forked from couchbaselabs/TouchDB-iOS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TDPusher.m
441 lines (380 loc) · 17.1 KB
/
TDPusher.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
//
// TDPusher.m
// TouchDB
//
// Created by Jens Alfke on 12/5/11.
// Copyright (c) 2011 Couchbase, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
#import "TDPusher.h"
#import <TouchDB/TD_Database.h>
#import "TD_Database+Insertion.h"
#import <TouchDB/TD_Revision.h>
#import "TDBatcher.h"
#import "TDMultipartUploader.h"
#import "TDInternal.h"
#import "TDMisc.h"
#import "TDCanonicalJSON.h"
static int findCommonAncestor(TD_Revision* rev, NSArray* possibleIDs);
@interface TDPusher ()
- (BOOL) uploadMultipartRevision: (TD_Revision*)rev;
@end
@implementation TDPusher
@synthesize createTarget=_createTarget;
- (BOOL) isPush {
return YES;
}
- (TD_FilterBlock) filter {
if (!_filterName)
return NULL;
TD_FilterBlock filter = [_db filterNamed: _filterName];
if (!filter) {
Warn(@"%@: No TDFilterBlock registered for filter '%@'", self, _filterName);
if (!_error) {
NSDictionary* info = $dict({NSLocalizedFailureReasonErrorKey, @"Unknown filter"});
self.error = [NSError errorWithDomain: TDHTTPErrorDomain
code: kTDStatusNotFound
userInfo: info];
}
[self stop];
}
return filter;
}
// This is called before beginReplicating, if the target db might not exist
- (void) maybeCreateRemoteDB {
if (!_createTarget)
return;
LogTo(Sync, @"Remote db might not exist; creating it...");
_creatingTarget = YES;
[self asyncTaskStarted];
[self sendAsyncRequest: @"PUT" path: @"" body: nil onCompletion: ^(id result, NSError* error) {
_creatingTarget = NO;
if (error && error.code != kTDStatusDuplicate) {
LogTo(Sync, @"Failed to create remote db: %@", error);
self.error = error;
[self stop];
} else {
LogTo(Sync, @"Created remote db");
_createTarget = NO; // remember that I created the target
[self beginReplicating];
}
[self asyncTasksFinished: 1];
}];
}
- (void) beginReplicating {
// If we're still waiting to create the remote db, do nothing now. (This method will be
// re-invoked after that request finishes; see -maybeCreateRemoteDB above.)
if (_creatingTarget)
return;
TD_FilterBlock filter = NULL;
if (_filterName) {
filter = self.filter;
if (!filter)
return; // missing filter block
}
// Include conflicts so all conflicting revisions are replicated too
TDChangesOptions options = kDefaultTDChangesOptions;
options.includeConflicts = YES;
// Process existing changes since the last push:
[self addRevsToInbox: [_db changesSinceSequence: [_lastSequence longLongValue]
options: &options
filter: filter
params: _filterParameters]];
[_batcher flush]; // process up to the first 100 revs
// Now listen for future changes (in continuous mode):
if (_continuous && !_observing) {
_observing = YES;
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(dbChanged:)
name: TD_DatabaseChangeNotification object: _db];
}
#ifdef GNUSTEP // TODO: Multipart upload on GNUstep
_dontSendMultipart = YES;
#endif
}
- (void) stopObserving {
if (_observing) {
_observing = NO;
[[NSNotificationCenter defaultCenter] removeObserver: self
name: TD_DatabaseChangeNotification
object: _db];
}
}
- (void) retry {
// This is called if I've gone idle but some revisions failed to be pushed.
// I should start the _changes feed over again, so I can retry all the revisions.
[super retry];
[self beginReplicating];
}
- (BOOL) goOffline {
if (![super goOffline])
return NO;
[self stopObserving];
return YES;
}
- (void) stop {
_uploaderQueue = nil;
_uploading = NO;
[self stopObserving];
[super stop];
}
- (void) dbChanged: (NSNotification*)n {
NSDictionary* userInfo = n.userInfo;
// Skip revisions that originally came from the database I'm syncing to:
if ([userInfo[@"source"] isEqual: _remote])
return;
TD_Revision* rev = userInfo[@"rev"];
if (_filterName) {
TD_FilterBlock filter = self.filter;
if (!filter || !filter(rev, _filterParameters))
return;
}
[self addToInbox: rev];
}
- (void) processInbox: (TD_RevisionList*)changes {
// Generate a set of doc/rev IDs in the JSON format that _revs_diff wants:
// <http://wiki.apache.org/couchdb/HttpPostRevsDiff>
NSMutableDictionary* diffs = $mdict();
for (TD_Revision* rev in changes) {
NSString* docID = rev.docID;
NSMutableArray* revs = diffs[docID];
if (!revs) {
revs = $marray();
diffs[docID] = revs;
}
[revs addObject: rev.revID];
}
// Call _revs_diff on the target db:
[self asyncTaskStarted];
[self sendAsyncRequest: @"POST" path: @"_revs_diff" body: diffs
onCompletion:^(NSDictionary* results, NSError* error) {
if (error) {
self.error = error;
[self revisionFailed];
} else if (results.count) {
// Go through the list of local changes again, selecting the ones the destination server
// said were missing and mapping them to a JSON dictionary in the form _bulk_docs wants:
__block SequenceNumber lastInboxSequence = 0;
NSArray* docsToSend = [changes.allRevisions my_map: ^id(TD_Revision* rev) {
NSDictionary* properties;
@autoreleasepool {
// Is this revision in the server's 'missing' list?
NSDictionary* revResults = results[rev.docID];
NSArray* missing = revResults[@"missing"];
if (![missing containsObject: [rev revID]])
return nil;
// Get the revision's properties:
TDContentOptions options = kTDIncludeAttachments | kTDIncludeRevs;
if (!_dontSendMultipart)
options |= kTDBigAttachmentsFollow;
if ([_db loadRevisionBody: rev options: options] >= 300) {
Warn(@"%@: Couldn't get local contents of %@", self, rev);
[self revisionFailed];
return nil;
}
properties = rev.properties;
Assert(properties[@"_revisions"]);
// Strip any attachments already known to the target db:
if (properties[@"_attachments"]) {
// Look for the latest common ancestor and stub out older attachments:
NSArray* possible = revResults[@"possible_ancestors"];
int minRevPos = findCommonAncestor(rev, possible);
[TD_Database stubOutAttachmentsIn: rev beforeRevPos: minRevPos + 1
attachmentsFollow: NO];
properties = rev.properties;
// If the rev has huge attachments, send it under separate cover:
if (!_dontSendMultipart && [self uploadMultipartRevision: rev])
return nil;
}
// (to survive impending autorelease-pool drain)
}
lastInboxSequence = rev.sequence;
Assert(properties[@"_id"]);
return properties;
}];
// Post the revisions to the destination:
[self uploadBulkDocs: docsToSend changes: changes lastSequence: lastInboxSequence];
} else {
// If none of the revisions are new to the remote, just bump the lastSequence:
self.lastSequence = $sprintf(@"%lld", [changes.allRevisions.lastObject sequence]);
}
[self asyncTasksFinished: 1];
}];
}
// Post the revisions to the destination. "new_edits":false means that the server should
// use the given _rev IDs instead of making up new ones.
- (void) uploadBulkDocs: (NSArray*)docsToSend
changes: (TD_RevisionList*)changes
lastSequence: (SequenceNumber)lastInboxSequence
{
NSUInteger numDocsToSend = docsToSend.count;
if (numDocsToSend == 0)
return;
LogTo(Sync, @"%@: Sending %u revisions", self, (unsigned)numDocsToSend);
LogTo(SyncVerbose, @"%@: Sending %@", self, changes.allRevisions);
self.changesTotal += numDocsToSend;
[self asyncTaskStarted];
[self sendAsyncRequest: @"POST"
path: @"_bulk_docs"
body: $dict({@"docs", docsToSend},
{@"new_edits", $false})
onCompletion: ^(NSDictionary* response, NSError *error) {
if (!error) {
// _bulk_docs response is really an array, not a dictionary!
for (NSDictionary* item in $castIf(NSArray, response)) {
if (item[@"error"]) {
// One of the docs failed to save:
Warn(@"%@: _bulk_docs got an error: %@", self, item);
TDStatus status = kTDStatusUpstreamError;
if ($equal(item[@"error"], @"unauthorized"))
status = kTDStatusUnauthorized;
NSString* docID = item[@"id"];
NSURL* url = docID ? [_remote URLByAppendingPathComponent: docID] : nil;
error = TDStatusToNSError(status, url);
}
}
}
if (error) {
self.error = error;
[self revisionFailed];
} else {
LogTo(SyncVerbose, @"%@: Sent %@", self, changes.allRevisions);
self.lastSequence = $sprintf(@"%lld", lastInboxSequence);
}
self.changesProcessed += numDocsToSend;
[self asyncTasksFinished: 1];
}
];
}
- (BOOL) uploadMultipartRevision: (TD_Revision*)rev {
// Find all the attachments with "follows" instead of a body, and put 'em in a multipart stream.
// It's important to scan the _attachments entries in the same order in which they will appear
// in the JSON, because CouchDB expects the MIME bodies to appear in that same order (see #133).
TDMultipartWriter* bodyStream = nil;
NSDictionary* attachments = rev[@"_attachments"];
for (NSString* attachmentName in [TDCanonicalJSON orderedKeys: attachments]) {
NSDictionary* attachment = attachments[attachmentName];
if (attachment[@"follows"]) {
if (!bodyStream) {
// Create the HTTP multipart stream:
bodyStream = [[TDMultipartWriter alloc] initWithContentType: @"multipart/related"
boundary: nil];
[bodyStream setNextPartsHeaders: $dict({@"Content-Type", @"application/json"})];
// Use canonical JSON encoder so that _attachments keys will be written in the
// same order that this for loop is processing the attachments.
NSData* json = [TDCanonicalJSON canonicalData: rev.properties];
[bodyStream addData: json];
}
NSString* disposition = $sprintf(@"attachment; filename=%@", TDQuoteString(attachmentName));
NSString* contentType = attachment[@"type"];
NSString* contentEncoding = attachment[@"encoding"];
[bodyStream setNextPartsHeaders: $dict({@"Content-Disposition", disposition},
{@"Content-Type", contentType},
{@"Content-Encoding", contentEncoding})];
[bodyStream addFileURL: [_db fileForAttachmentDict: attachment]];
}
}
if (!bodyStream)
return NO;
// OK, we are going to upload this on its own:
self.changesTotal++;
[self asyncTaskStarted];
NSString* path = $sprintf(@"%@?new_edits=false", TDEscapeID(rev.docID));
__block TDMultipartUploader* uploader = [[TDMultipartUploader alloc]
initWithURL: TDAppendToURL(_remote, path)
streamer: bodyStream
requestHeaders: self.requestHeaders
onCompletion: ^(id response, NSError *error) {
if (error) {
if ($equal(error.domain, TDHTTPErrorDomain)
&& error.code == kTDStatusUnsupportedType) {
// Server doesn't like multipart, eh? Fall back to JSON.
_dontSendMultipart = YES;
[self uploadJSONRevision: rev];
} else {
self.error = error;
[self revisionFailed];
}
} else {
LogTo(SyncVerbose, @"%@: Sent %@, response=%@", self, rev, response);
self.lastSequence = $sprintf(@"%lld", rev.sequence);
}
self.changesProcessed++;
[self asyncTasksFinished: 1];
[self removeRemoteRequest: uploader];
_uploading = NO;
[self startNextUpload];
}
];
uploader.authorizer = _authorizer;
[self addRemoteRequest: uploader];
LogTo(SyncVerbose, @"%@: Queuing %@ (multipart, %lldkb)", self, uploader, bodyStream.length/1024);
if (!_uploaderQueue)
_uploaderQueue = [[NSMutableArray alloc] init];
[_uploaderQueue addObject: uploader];
[self startNextUpload];
return YES;
}
// Fallback to upload a revision if uploadMultipartRevision failed due to the server's rejecting
// multipart format.
- (void) uploadJSONRevision: (TD_Revision*)rev {
// Get the revision's properties:
NSError* error;
if (![_db inlineFollowingAttachmentsIn: rev error: &error]) {
self.error = error;
[self revisionFailed];
return;
}
[self asyncTaskStarted];
NSString* path = $sprintf(@"%@?new_edits=false", TDEscapeID(rev.docID));
[self sendAsyncRequest: @"PUT"
path: path
body: rev.properties
onCompletion: ^(id response, NSError *error) {
if (error) {
self.error = error;
[self revisionFailed];
} else {
LogTo(SyncVerbose, @"%@: Sent %@ (JSON), response=%@", self, rev, response);
self.lastSequence = $sprintf(@"%lld", rev.sequence);
}
[self asyncTasksFinished: 1];
}];
}
- (void) startNextUpload {
if (!_uploading && _uploaderQueue.count > 0) {
_uploading = YES;
TDMultipartUploader* uploader = _uploaderQueue[0];
LogTo(SyncVerbose, @"%@: Starting %@", self, uploader);
[uploader start];
[_uploaderQueue removeObjectAtIndex: 0];
}
}
// Given a revision and an array of revIDs, finds the latest common ancestor revID
// and returns its generation #. If there is none, returns 0.
static int findCommonAncestor(TD_Revision* rev, NSArray* possibleRevIDs) {
if (possibleRevIDs.count == 0)
return 0;
NSArray* history = [TD_Database parseCouchDBRevisionHistory: rev.properties];
NSString* ancestorID = [history firstObjectCommonWithArray: possibleRevIDs];
if (!ancestorID)
return 0;
int generation;
if (![TD_Revision parseRevID: ancestorID intoGeneration: &generation andSuffix: NULL])
generation = 0;
return generation;
}
@end
TestCase(TDPusher_findCommonAncestor) {
NSDictionary* revDict = $dict({@"ids", @[@"second", @"first"]}, {@"start", @2});
TD_Revision* rev = [TD_Revision revisionWithProperties: $dict({@"_revisions", revDict})];
CAssertEq(findCommonAncestor(rev, @[]), 0);
CAssertEq(findCommonAncestor(rev, @[@"3-noway", @"1-nope"]), 0);
CAssertEq(findCommonAncestor(rev, @[@"3-noway", @"1-first"]), 1);
CAssertEq(findCommonAncestor(rev, @[@"3-noway", @"2-second", @"1-first"]), 2);
}