This repository has been archived by the owner on Mar 9, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 143
/
TDRouter+Handlers.m
573 lines (482 loc) · 19.6 KB
/
TDRouter+Handlers.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
//
// TDRouter+Handlers.m
// TouchDB
//
// Created by Jens Alfke on 1/5/12.
// Copyright (c) 2012 Couchbase, Inc. All rights reserved.
//
#import "TDRouter.h"
#import "TDDatabase.h"
#import "TDView.h"
#import "TDBody.h"
#import "TDRevision.h"
#import "TDServer.h"
#import "TDReplicator.h"
@interface TDRouter ()
- (TDStatus) update: (TDDatabase*)db docID: (NSString*)docID json: (NSData*)json
deleting: (BOOL)deleting;
@end
@implementation TDRouter (Handlers)
#pragma mark - SERVER REQUESTS:
- (TDStatus) do_GETRoot {
NSDictionary* info = $dict({@"TouchDB", @"Welcome"},
{@"couchdb", @"Welcome"}, // for compatibility
{@"version", kTDVersionString});
_response.body = [TDBody bodyWithProperties: info];
return 200;
}
- (TDStatus) do_GET_all_dbs {
NSArray* dbs = _server.allDatabaseNames ?: $array();
_response.body = [[[TDBody alloc] initWithArray: dbs] autorelease];
return 200;
}
- (TDStatus) do_POST_replicate {
// Extract the parameters from the JSON request body:
// http://wiki.apache.org/couchdb/Replication
id body = [NSJSONSerialization JSONObjectWithData: _request.HTTPBody options: 0 error: nil];
if (![body isKindOfClass: [NSDictionary class]])
return 400;
NSString* source = $castIf(NSString, [body objectForKey: @"source"]);
NSString* target = $castIf(NSString, [body objectForKey: @"target"]);
BOOL createTarget = [$castIf(NSNumber, [body objectForKey: @"create_target"]) boolValue];
BOOL continuous = [$castIf(NSNumber, [body objectForKey: @"continuous"]) boolValue];
BOOL cancel = [$castIf(NSNumber, [body objectForKey: @"cancel"]) boolValue];
// Map the 'source' and 'target' JSON params to a local database and remote URL:
if (!source || !target)
return 400;
BOOL push = NO;
TDDatabase* db = [_server existingDatabaseNamed: source];
NSString* remoteStr;
if (db) {
remoteStr = target;
push = YES;
} else {
remoteStr = source;
if (createTarget && !cancel) {
db = [_server databaseNamed: target];
if (![db open])
return 500;
} else {
db = [_server existingDatabaseNamed: target];
}
if (!db)
return 404;
}
NSURL* remote = [NSURL URLWithString: remoteStr];
if (!remote || ![remote.scheme hasPrefix: @"http"])
return 400;
if (!cancel) {
// Start replication:
TDReplicator* repl = [db replicateWithRemoteURL: remote push: push continuous: continuous];
if (!repl)
return 500;
_response.bodyObject = $dict({@"session_id", repl.sessionID});
} else {
// Cancel replication:
TDReplicator* repl = [db activeReplicatorWithRemoteURL: remote push: push];
if (!repl)
return 404;
[repl stop];
}
return 200;
}
- (TDStatus) do_GET_uuids {
int count = MIN(1000, [self intQuery: @"count" defaultValue: 1]);
NSMutableArray* uuids = [NSMutableArray arrayWithCapacity: count];
for (int i=0; i<count; i++)
[uuids addObject: [TDDatabase generateDocumentID]];
_response.bodyObject = $dict({@"uuids", uuids});
return 200;
}
- (TDStatus) do_GET_active_tasks {
// http://wiki.apache.org/couchdb/HttpGetActiveTasks
NSMutableArray* activity = $marray();
for (TDDatabase* db in _server.allOpenDatabases) {
for (TDReplicator* repl in db.activeReplicators) {
NSString* source = repl.remote.absoluteString;
NSString* target = db.name;
if (repl.isPush) {
NSString* temp = source;
source = target;
target = temp;
}
NSUInteger processed = repl.changesProcessed;
NSUInteger total = repl.changesTotal;
NSString* status = $sprintf(@"Processed %u / %u changes",
(unsigned)processed, (unsigned)total);
long progress = (total > 0) ? lroundf(100*(processed / (float)total)) : 0;
[activity addObject: $dict({@"type", @"Replication"},
{@"task", repl.sessionID},
{@"source", source},
{@"target", target},
{@"status", status},
{@"progress", $object(progress)})];
}
}
_response.body = [[[TDBody alloc] initWithArray: activity] autorelease];
return 200;
}
#pragma mark - DATABASE REQUESTS:
- (TDStatus) do_GET: (TDDatabase*)db {
// http://wiki.apache.org/couchdb/HTTP_database_API#Database_Information
TDStatus status = [self openDB];
if (status >= 300)
return status;
NSUInteger num_docs = db.documentCount;
SequenceNumber update_seq = db.lastSequence;
if (num_docs == NSNotFound || update_seq == NSNotFound)
return 500;
_response.bodyObject = $dict({@"db_name", db.name},
{@"doc_count", $object(num_docs)},
{@"update_seq", $object(update_seq)});
return 200;
}
- (TDStatus) do_PUT: (TDDatabase*)db {
if (db.exists)
return 412;
if (![db open])
return 500;
[_response setValue: _request.URL.absoluteString ofHeader: @"Location"];
return 201;
}
- (TDStatus) do_DELETE: (TDDatabase*)db {
if ([self query: @"rev"])
return 400; // CouchDB checks for this; probably meant to be a document deletion
return [_server deleteDatabaseNamed: db.name] ? 200 : 404;
}
- (TDStatus) do_POST: (TDDatabase*)db {
TDStatus status = [self openDB];
if (status >= 300)
return status;
return [self update: db docID: nil json: _request.HTTPBody deleting: NO];
}
- (TDStatus) do_GET_all_docs: (TDDatabase*)db {
TDQueryOptions options;
if (![self getQueryOptions: &options])
return 400;
NSDictionary* result = [db getAllDocs: &options];
if (!result)
return 500;
_response.bodyObject = result;
return 200;
}
- (TDStatus) do_POST_all_docs: (TDDatabase*)db {
// http://wiki.apache.org/couchdb/HTTP_Bulk_Document_API
TDQueryOptions options;
if (![self getQueryOptions: &options])
return 400;
NSDictionary* body = [NSJSONSerialization JSONObjectWithData: _request.HTTPBody
options: 0 error: nil];
if (![body isKindOfClass: [NSDictionary class]])
return 400;
NSArray* docIDs = [body objectForKey: @"keys"];
if (![docIDs isKindOfClass: [NSArray class]])
return 400;
NSDictionary* result = [db getDocsWithIDs: docIDs options: &options];
if (!result)
return 500;
_response.bodyObject = result;
return 200;
}
- (TDStatus) do_POST_compact: (TDDatabase*)db {
return [db compact];
}
- (TDStatus) do_POST_ensure_full_commit: (TDDatabase*)db {
return 200;
}
#pragma mark - CHANGES:
- (NSDictionary*) changeDictForRev: (TDRevision*)rev {
return $dict({@"seq", $object(rev.sequence)},
{@"id", rev.docID},
{@"changes", $marray($dict({@"rev", rev.revID}))},
{@"deleted", rev.deleted ? $true : nil},
{@"doc", (_changesIncludeDocs ? rev.properties : nil)});
}
- (NSDictionary*) responseBodyForChanges: (NSArray*)changes since: (UInt64)since {
NSArray* results = [changes my_map: ^(id rev) {return [self changeDictForRev: rev];}];
if (changes.count > 0)
since = [[changes lastObject] sequence];
return $dict({@"results", results}, {@"last_seq", $object(since)});
}
- (NSDictionary*) responseBodyForChangesWithConflicts: (NSArray*)changes since: (UInt64)since {
// Assumes the changes are grouped by docID so that conflicts will be adjacent.
NSMutableArray* entries = [NSMutableArray arrayWithCapacity: changes.count];
NSString* lastDocID = nil;
NSDictionary* lastEntry = nil;
for (TDRevision* rev in changes) {
NSString* docID = rev.docID;
if ($equal(docID, lastDocID)) {
[[lastEntry objectForKey: @"changes"] addObject: $dict({@"rev", rev.revID})];
} else {
lastEntry = [self changeDictForRev: rev];
[entries addObject: lastEntry];
lastDocID = docID;
}
}
// After collecting revisions, sort by sequence:
[entries sortUsingComparator: ^NSComparisonResult(id e1, id e2) {
return [[e1 objectForKey: @"seq"] longLongValue] - [[e2 objectForKey: @"seq"] longLongValue];
}];
return $dict({@"results", entries}, {@"last_seq", $object(since)});
}
- (void) sendContinuousChange: (TDRevision*)rev {
NSDictionary* changeDict = [self changeDictForRev: rev];
NSMutableData* json = [[NSJSONSerialization dataWithJSONObject: changeDict
options: 0 error: nil] mutableCopy];
[json appendBytes: @"\n" length: 1];
_onDataAvailable(json);
[json release];
}
- (void) dbChanged: (NSNotification*)n {
TDRevision* rev = [n.userInfo objectForKey: @"rev"];
if (_changesFilter && !_changesFilter(rev))
return;
if (_longpoll) {
Log(@"TDRouter: Sending longpoll response");
[self sendResponse];
NSDictionary* body = [self responseBodyForChanges: $array(rev) since: 0];
_onDataAvailable([NSJSONSerialization dataWithJSONObject: body
options: 0 error: nil]);
_onFinished();
[self stop];
} else {
Log(@"TDRouter: Sending continous change chunk");
[self sendContinuousChange: rev];
}
}
- (TDStatus) do_GET_changes: (TDDatabase*)db {
// http://wiki.apache.org/couchdb/HTTP_database_API#Changes
TDChangesOptions options = kDefaultTDChangesOptions;
_changesIncludeDocs = [self boolQuery: @"include_docs"];
options.includeDocs = _changesIncludeDocs;
options.includeConflicts = $equal([self query: @"style"], @"all_docs");
options.contentOptions = [self contentOptions];
options.sortBySequence = !options.includeConflicts;
options.limit = [self intQuery: @"limit" defaultValue: options.limit];
int since = [[self query: @"since"] intValue];
NSString* filterName = [self query: @"filter"];
if (filterName) {
_changesFilter = [[_db filterNamed: filterName] retain];
if (!_changesFilter)
return 404;
}
TDRevisionList* changes = [db changesSinceSequence: since
options: &options
filter: _changesFilter];
if (!changes)
return 500;
NSString* feed = [self query: @"feed"];
_longpoll = $equal(feed, @"longpoll");
BOOL continuous = !_longpoll && $equal(feed, @"continuous");
if (continuous || (_longpoll && changes.count==0)) {
if (continuous) {
[self sendResponse];
for (TDRevision* rev in changes)
[self sendContinuousChange: rev];
}
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(dbChanged:)
name: TDDatabaseChangeNotification
object: db];
// Don't close connection; more data to come
_waiting = YES;
return 0;
} else {
if (options.includeConflicts)
_response.bodyObject = [self responseBodyForChangesWithConflicts: changes.allRevisions
since: since];
else
_response.bodyObject = [self responseBodyForChanges: changes.allRevisions since: since];
return 200;
}
}
#pragma mark - DOCUMENT REQUESTS:
- (NSString*) setResponseEtag: (TDRevision*)rev {
NSString* eTag = $sprintf(@"\"%@\"", rev.revID);
[_response setValue: eTag ofHeader: @"Etag"];
return eTag;
}
- (TDStatus) do_GET: (TDDatabase*)db docID: (NSString*)docID {
// http://wiki.apache.org/couchdb/HTTP_Document_API#GET
TDRevision* rev = [db getDocumentWithID: docID
revisionID: [self query: @"rev"] // often nil
options: [self contentOptions]];
if (!rev)
return 404;
// Check for conditional GET:
NSString* eTag = [self setResponseEtag: rev];
if ($equal(eTag, [_request valueForHTTPHeaderField: @"If-None-Match"]))
return 304;
_response.body = rev.body;
return 200;
}
- (TDStatus) do_GET: (TDDatabase*)db docID: (NSString*)docID attachment: (NSString*)attachment {
//OPT: This gets the JSON body too, which is a waste. Could add a 'withBody:' attribute?
TDRevision* rev = [db getDocumentWithID: docID
revisionID: [self query: @"rev"] // often nil
options: 0];
if (!rev)
return 404;
// Check for conditional GET:
NSString* eTag = [self setResponseEtag: rev];
if ($equal(eTag, [_request valueForHTTPHeaderField: @"If-None-Match"]))
return 304;
NSString* type = nil;
TDStatus status;
NSData* contents = [_db getAttachmentForSequence: rev.sequence
named: attachment
type: &type
status: &status];
if (!contents)
return status;
if (type)
[_response setValue: type ofHeader: @"Content-Type"];
_response.body = [TDBody bodyWithJSON: contents]; //FIX: This is a lie, it's not JSON
return 200;
}
- (TDStatus) update: (TDDatabase*)db
docID: (NSString*)docID
json: (NSData*)json
deleting: (BOOL)deleting
{
BOOL posting = (docID == nil);
TDBody* body = json ? [TDBody bodyWithJSON: json] : nil;
NSString* prevRevID;
if (!deleting) {
deleting = $castIf(NSNumber, [body propertyForKey: @"_deleted"]).boolValue;
if (!docID) {
// POST's doc ID may come from the _id field of the JSON body, else generate a random one.
docID = [body propertyForKey: @"_id"];
if (!docID) {
if (deleting)
return 400;
docID = [TDDatabase generateDocumentID];
}
}
// PUT's revision ID comes from the JSON body.
prevRevID = [body propertyForKey: @"_rev"];
} else {
// DELETE's revision ID can come either from the ?rev= query param or an If-Match header.
prevRevID = [self query: @"rev"];
if (!prevRevID) {
NSString* ifMatch = [_request valueForHTTPHeaderField: @"If-Match"];
if (ifMatch) {
// Value of If-Match is an ETag, so have to trim the quotes around it:
if (ifMatch.length > 2 && [ifMatch hasPrefix: @"\""] && [ifMatch hasSuffix: @"\""])
prevRevID = [ifMatch substringWithRange: NSMakeRange(1, ifMatch.length-2)];
else
return 400;
}
}
}
TDRevision* rev = [[[TDRevision alloc] initWithDocID: docID revID: nil deleted: deleting]
autorelease];
if (!rev)
return 400;
rev.body = body;
TDStatus status;
rev = [db putRevision: rev prevRevisionID: prevRevID status: &status];
if (status < 300) {
[self setResponseEtag: rev];
if (!deleting) {
NSURL* url = _request.URL;
if (posting)
url = [url URLByAppendingPathComponent: docID];
[_response.headers setObject: url.absoluteString forKey: @"Location"];
}
_response.bodyObject = $dict({@"ok", $true},
{@"id", rev.docID},
{@"rev", rev.revID});
}
return status;
}
- (TDStatus) do_PUT: (TDDatabase*)db docID: (NSString*)docID {
NSData* json = _request.HTTPBody;
if (!json)
return 400;
if (![self query: @"new_edits"] || [self boolQuery: @"new_edits"]) {
// Regular PUT:
return [self update: db docID: docID json: json deleting: NO];
} else {
// PUT with new_edits=false -- forcible insertion of existing revision:
TDBody* body = [TDBody bodyWithJSON: json];
TDRevision* rev = [[[TDRevision alloc] initWithBody: body] autorelease];
if (!rev || !$equal(rev.docID, docID) || !rev.revID)
return 400;
NSArray* history = [TDDatabase parseCouchDBRevisionHistory: body.properties];
if (!history)
history = $array(rev.revID);
return [_db forceInsert: rev revisionHistory: history source: nil];
}
}
- (TDStatus) do_DELETE: (TDDatabase*)db docID: (NSString*)docID {
return [self update: db docID: docID json: nil deleting: YES];
}
#pragma mark - VIEW QUERIES:
- (TDStatus) do_GET: (TDDatabase*)db designDocID: (NSString*)designDoc view: (NSString*)viewName {
viewName = $sprintf(@"%@/%@", designDoc, viewName);
TDView* view = [db existingViewNamed: viewName];
if (!view)
return 404;
TDQueryOptions options;
if (![self getQueryOptions: &options])
return 400;
TDStatus status;
NSArray* rows = [view queryWithOptions: &options status: &status];
if (!rows)
return status;
id updateSeq = options.updateSeq ? $object(view.lastSequenceIndexed) : nil;
_response.bodyObject = $dict({@"rows", rows},
{@"total_rows", $object(rows.count)},
{@"offset", $object(options.skip)},
{@"update_seq", updateSeq});
return 200;
}
- (TDStatus) do_POST_temp_view: (TDDatabase*)db {
if (![[_request valueForHTTPHeaderField: @"Content-Type"] hasPrefix: @"application/json"])
return 415;
TDBody* requestBody = [TDBody bodyWithJSON: _request.HTTPBody];
NSDictionary* props = requestBody.properties;
if (!props)
return 400;
TDQueryOptions options;
if (![self getQueryOptions: &options])
return 400;
TDView* view = [_db viewNamed: @"@@TEMP@@"];
if (!view)
return 500;
@try {
NSString* language = [props objectForKey: @"language"] ?: @"javascript";
NSString* mapSource = [props objectForKey: @"map"];
TDMapBlock mapBlock = [[TDView compiler] compileMapFunction: mapSource language: language];
if (!mapBlock) {
Warn(@"Unknown map function source: %@", mapSource);
return 500;
}
NSString* reduceSource = [props objectForKey: @"reduce"];
TDReduceBlock reduceBlock = NULL;
if (reduceSource) {
reduceBlock =[[TDView compiler] compileReduceFunction: reduceSource language: language];
if (!reduceBlock) {
Warn(@"Unknown reduce function source: %@", reduceSource);
return 500;
}
}
[view setMapBlock: mapBlock reduceBlock: reduceBlock version: @"1"];
if (reduceBlock)
options.reduce = YES;
TDStatus status;
NSArray* rows = [view queryWithOptions: &options status: &status];
if (!rows)
return status;
id updateSeq = options.updateSeq ? $object(view.lastSequenceIndexed) : nil;
_response.bodyObject = $dict({@"rows", rows},
{@"total_rows", $object(rows.count)},
{@"offset", $object(options.skip)},
{@"update_seq", updateSeq});
return 200;
} @finally {
[view deleteView];
}
}
@end