aboutsummaryrefslogtreecommitdiffhomepage
path: root/Firestore/Source/Model/FSTMutation.mm
blob: a61ee840d4f7f886a6b13b65ad695ac3e5f2dbb2 (plain)
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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
/*
 * Copyright 2017 Google
 *
 * 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 "Firestore/Source/Model/FSTMutation.h"

#import "FIRTimestamp.h"

#import "Firestore/Source/Core/FSTSnapshotVersion.h"
#import "Firestore/Source/Model/FSTDocument.h"
#import "Firestore/Source/Model/FSTDocumentKey.h"
#import "Firestore/Source/Model/FSTFieldValue.h"
#import "Firestore/Source/Util/FSTAssert.h"
#import "Firestore/Source/Util/FSTClasses.h"

#include "Firestore/core/src/firebase/firestore/model/field_path.h"

using firebase::firestore::model::FieldPath;

NS_ASSUME_NONNULL_BEGIN

#pragma mark - FSTFieldMask

@implementation FSTFieldMask {
  std::vector<FieldPath> _fields;
}

- (instancetype)initWithFields:(std::vector<FieldPath>)fields {
  if (self = [super init]) {
    _fields = std::move(fields);
  }
  return self;
}

- (BOOL)isEqual:(id)other {
  if (other == self) {
    return YES;
  }
  if (![other isKindOfClass:[FSTFieldMask class]]) {
    return NO;
  }

  FSTFieldMask *otherMask = (FSTFieldMask *)other;
  return _fields == otherMask->_fields;
}

- (NSUInteger)hash {
  NSUInteger hashResult = 0;
  for (const FieldPath &field : _fields) {
    hashResult = hashResult * 31u + field.Hash();
  }
  return hashResult;
}

- (const std::vector<FieldPath> &)fields {
  return _fields;
}
@end

#pragma mark - FSTServerTimestampTransform

@implementation FSTServerTimestampTransform

+ (instancetype)serverTimestampTransform {
  static FSTServerTimestampTransform *sharedInstance = nil;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    sharedInstance = [[FSTServerTimestampTransform alloc] init];
  });
  return sharedInstance;
}

- (BOOL)isEqual:(id)other {
  if (other == self) {
    return YES;
  }
  return [other isKindOfClass:[FSTServerTimestampTransform class]];
}

- (NSUInteger)hash {
  // arbitrary number since all instances are equal.
  return 37;
}

@end

#pragma mark - FSTFieldTransform

@implementation FSTFieldTransform {
  FieldPath _path;
}

- (instancetype)initWithPath:(FieldPath)path transform:(id<FSTTransformOperation>)transform {
  self = [super init];
  if (self) {
    _path = std::move(path);
    _transform = transform;
  }
  return self;
}

- (BOOL)isEqual:(id)other {
  if (other == self) return YES;
  if (![[other class] isEqual:[self class]]) return NO;
  FSTFieldTransform *otherFieldTransform = other;
  return self.path == otherFieldTransform.path &&
         [self.transform isEqual:otherFieldTransform.transform];
}

- (NSUInteger)hash {
  NSUInteger hash = self.path.Hash();
  hash = hash * 31 + [self.transform hash];
  return hash;
}

- (const firebase::firestore::model::FieldPath &)path {
  return _path;
}

@end

#pragma mark - FSTPrecondition

@implementation FSTPrecondition

+ (FSTPrecondition *)preconditionWithExists:(BOOL)exists {
  FSTPreconditionExists existsEnum = exists ? FSTPreconditionExistsYes : FSTPreconditionExistsNo;
  return [[FSTPrecondition alloc] initWithUpdateTime:nil exists:existsEnum];
}

+ (FSTPrecondition *)preconditionWithUpdateTime:(FSTSnapshotVersion *)updateTime {
  return [[FSTPrecondition alloc] initWithUpdateTime:updateTime exists:FSTPreconditionExistsNotSet];
}

+ (FSTPrecondition *)none {
  static dispatch_once_t onceToken;
  static FSTPrecondition *noPrecondition;
  dispatch_once(&onceToken, ^{
    noPrecondition =
        [[FSTPrecondition alloc] initWithUpdateTime:nil exists:FSTPreconditionExistsNotSet];
  });
  return noPrecondition;
}

- (instancetype)initWithUpdateTime:(FSTSnapshotVersion *_Nullable)updateTime
                            exists:(FSTPreconditionExists)exists {
  if (self = [super init]) {
    _updateTime = updateTime;
    _exists = exists;
  }
  return self;
}

- (BOOL)isValidForDocument:(FSTMaybeDocument *_Nullable)maybeDoc {
  if (self.updateTime) {
    return
        [maybeDoc isKindOfClass:[FSTDocument class]] && [maybeDoc.version isEqual:self.updateTime];
  } else if (self.exists != FSTPreconditionExistsNotSet) {
    if (self.exists == FSTPreconditionExistsYes) {
      return [maybeDoc isKindOfClass:[FSTDocument class]];
    } else {
      FSTAssert(self.exists == FSTPreconditionExistsNo, @"Invalid precondition");
      return maybeDoc == nil || [maybeDoc isKindOfClass:[FSTDeletedDocument class]];
    }
  } else {
    FSTAssert(self.isNone, @"Precondition should be empty");
    return YES;
  }
}

- (BOOL)isNone {
  return self.updateTime == nil && self.exists == FSTPreconditionExistsNotSet;
}

- (BOOL)isEqual:(id)other {
  if (self == other) {
    return YES;
  }

  if (![other isKindOfClass:[FSTPrecondition class]]) {
    return NO;
  }

  FSTPrecondition *otherPrecondition = (FSTPrecondition *)other;
  // Compare references to cover nil equality
  return (self.updateTime == otherPrecondition.updateTime ||
          [self.updateTime isEqual:otherPrecondition.updateTime]) &&
         self.exists == otherPrecondition.exists;
}

- (NSUInteger)hash {
  NSUInteger hash = [self.updateTime hash];
  hash = hash * 31 + self.exists;
  return hash;
}

- (NSString *)description {
  if (self.isNone) {
    return @"<FSTPrecondition <none>>";
  } else {
    NSString *existsString;
    switch (self.exists) {
      case FSTPreconditionExistsYes:
        existsString = @"yes";
        break;
      case FSTPreconditionExistsNo:
        existsString = @"no";
        break;
      default:
        existsString = @"<not-set>";
        break;
    }
    return [NSString stringWithFormat:@"<FSTPrecondition updateTime=%@ exists=%@>", self.updateTime,
                                      existsString];
  }
}

@end

#pragma mark - FSTMutationResult

@implementation FSTMutationResult

- (instancetype)initWithVersion:(FSTSnapshotVersion *_Nullable)version
               transformResults:(NSArray<FSTFieldValue *> *_Nullable)transformResults {
  if (self = [super init]) {
    _version = version;
    _transformResults = transformResults;
  }
  return self;
}

@end

#pragma mark - FSTMutation

@implementation FSTMutation

- (instancetype)initWithKey:(FSTDocumentKey *)key precondition:(FSTPrecondition *)precondition {
  if (self = [super init]) {
    _key = key;
    _precondition = precondition;
  }
  return self;
}

- (nullable FSTMaybeDocument *)applyTo:(nullable FSTMaybeDocument *)maybeDoc
                          baseDocument:(nullable FSTMaybeDocument *)baseDoc
                        localWriteTime:(FIRTimestamp *)localWriteTime
                        mutationResult:(nullable FSTMutationResult *)mutationResult {
  @throw FSTAbstractMethodException();  // NOLINT
}

- (nullable FSTMaybeDocument *)applyTo:(nullable FSTMaybeDocument *)maybeDoc
                          baseDocument:(nullable FSTMaybeDocument *)baseDoc
                        localWriteTime:(nullable FIRTimestamp *)localWriteTime {
  return
      [self applyTo:maybeDoc baseDocument:baseDoc localWriteTime:localWriteTime mutationResult:nil];
}

@end

#pragma mark - FSTSetMutation

@implementation FSTSetMutation

- (instancetype)initWithKey:(FSTDocumentKey *)key
                      value:(FSTObjectValue *)value
               precondition:(FSTPrecondition *)precondition {
  if (self = [super initWithKey:key precondition:precondition]) {
    _value = value;
  }
  return self;
}

- (NSString *)description {
  return [NSString stringWithFormat:@"<FSTSetMutation key=%@ value=%@ precondition=%@>", self.key,
                                    self.value, self.precondition];
}

- (BOOL)isEqual:(id)other {
  if (other == self) {
    return YES;
  }
  if (![other isKindOfClass:[FSTSetMutation class]]) {
    return NO;
  }

  FSTSetMutation *otherMutation = (FSTSetMutation *)other;
  return [self.key isEqual:otherMutation.key] && [self.value isEqual:otherMutation.value] &&
         [self.precondition isEqual:otherMutation.precondition];
}

- (NSUInteger)hash {
  NSUInteger result = [self.key hash];
  result = 31 * result + [self.precondition hash];
  result = 31 * result + [self.value hash];
  return result;
}

- (nullable FSTMaybeDocument *)applyTo:(nullable FSTMaybeDocument *)maybeDoc
                          baseDocument:(nullable FSTMaybeDocument *)baseDoc
                        localWriteTime:(FIRTimestamp *)localWriteTime
                        mutationResult:(nullable FSTMutationResult *)mutationResult {
  if (mutationResult) {
    FSTAssert(!mutationResult.transformResults, @"Transform results received by FSTSetMutation.");
  }

  if (![self.precondition isValidForDocument:maybeDoc]) {
    return maybeDoc;
  }

  BOOL hasLocalMutations = (mutationResult == nil);
  if (!maybeDoc || [maybeDoc isMemberOfClass:[FSTDeletedDocument class]]) {
    // If the document didn't exist before, create it.
    return [FSTDocument documentWithData:self.value
                                     key:self.key
                                 version:[FSTSnapshotVersion noVersion]
                       hasLocalMutations:hasLocalMutations];
  }

  FSTAssert([maybeDoc isMemberOfClass:[FSTDocument class]], @"Unknown MaybeDocument type %@",
            [maybeDoc class]);
  FSTDocument *doc = (FSTDocument *)maybeDoc;

  FSTAssert([doc.key isEqual:self.key], @"Can only set a document with the same key");
  return [FSTDocument documentWithData:self.value
                                   key:doc.key
                               version:doc.version
                     hasLocalMutations:hasLocalMutations];
}
@end

#pragma mark - FSTPatchMutation

@implementation FSTPatchMutation

- (instancetype)initWithKey:(FSTDocumentKey *)key
                  fieldMask:(FSTFieldMask *)fieldMask
                      value:(FSTObjectValue *)value
               precondition:(FSTPrecondition *)precondition {
  self = [super initWithKey:key precondition:precondition];
  if (self) {
    _fieldMask = fieldMask;
    _value = value;
  }
  return self;
}

- (BOOL)isEqual:(id)other {
  if (other == self) {
    return YES;
  }
  if (![other isKindOfClass:[FSTPatchMutation class]]) {
    return NO;
  }

  FSTPatchMutation *otherMutation = (FSTPatchMutation *)other;
  return [self.key isEqual:otherMutation.key] && [self.fieldMask isEqual:otherMutation.fieldMask] &&
         [self.value isEqual:otherMutation.value] &&
         [self.precondition isEqual:otherMutation.precondition];
}

- (NSUInteger)hash {
  NSUInteger result = [self.key hash];
  result = 31 * result + [self.precondition hash];
  result = 31 * result + [self.fieldMask hash];
  result = 31 * result + [self.value hash];
  return result;
}

- (NSString *)description {
  return [NSString stringWithFormat:@"<FSTPatchMutation key=%@ mask=%@ value=%@ precondition=%@>",
                                    self.key, self.fieldMask, self.value, self.precondition];
}

- (nullable FSTMaybeDocument *)applyTo:(nullable FSTMaybeDocument *)maybeDoc
                          baseDocument:(nullable FSTMaybeDocument *)baseDoc
                        localWriteTime:(FIRTimestamp *)localWriteTime
                        mutationResult:(nullable FSTMutationResult *)mutationResult {
  if (mutationResult) {
    FSTAssert(!mutationResult.transformResults, @"Transform results received by FSTPatchMutation.");
  }

  if (![self.precondition isValidForDocument:maybeDoc]) {
    return maybeDoc;
  }

  BOOL hasLocalMutations = (mutationResult == nil);
  if (!maybeDoc || [maybeDoc isMemberOfClass:[FSTDeletedDocument class]]) {
    // Precondition applied, so create the document if necessary
    FSTDocumentKey *key = maybeDoc ? maybeDoc.key : self.key;
    FSTSnapshotVersion *version = maybeDoc ? maybeDoc.version : [FSTSnapshotVersion noVersion];
    maybeDoc = [FSTDocument documentWithData:[FSTObjectValue objectValue]
                                         key:key
                                     version:version
                           hasLocalMutations:hasLocalMutations];
  }

  FSTAssert([maybeDoc isMemberOfClass:[FSTDocument class]], @"Unknown MaybeDocument type %@",
            [maybeDoc class]);
  FSTDocument *doc = (FSTDocument *)maybeDoc;

  FSTAssert([doc.key isEqual:self.key], @"Can only patch a document with the same key");

  FSTObjectValue *newData = [self patchObjectValue:doc.data];
  return [FSTDocument documentWithData:newData
                                   key:doc.key
                               version:doc.version
                     hasLocalMutations:hasLocalMutations];
}

- (FSTObjectValue *)patchObjectValue:(FSTObjectValue *)objectValue {
  FSTObjectValue *result = objectValue;
  for (const FieldPath &fieldPath : self.fieldMask.fields) {
    FSTFieldValue *newValue = [self.value valueForPath:fieldPath];
    if (newValue) {
      result = [result objectBySettingValue:newValue forPath:fieldPath];
    } else {
      result = [result objectByDeletingPath:fieldPath];
    }
  }
  return result;
}

@end

@implementation FSTTransformMutation

- (instancetype)initWithKey:(FSTDocumentKey *)key
            fieldTransforms:(NSArray<FSTFieldTransform *> *)fieldTransforms {
  // NOTE: We set a precondition of exists: true as a safety-check, since we always combine
  // FSTTransformMutations with a FSTSetMutation or FSTPatchMutation which (if successful) should
  // end up with an existing document.
  if (self = [super initWithKey:key precondition:[FSTPrecondition preconditionWithExists:YES]]) {
    _fieldTransforms = fieldTransforms;
  }
  return self;
}

- (BOOL)isEqual:(id)other {
  if (other == self) {
    return YES;
  }
  if (![other isKindOfClass:[FSTTransformMutation class]]) {
    return NO;
  }

  FSTTransformMutation *otherMutation = (FSTTransformMutation *)other;
  return [self.key isEqual:otherMutation.key] &&
         [self.fieldTransforms isEqual:otherMutation.fieldTransforms] &&
         [self.precondition isEqual:otherMutation.precondition];
}

- (NSUInteger)hash {
  NSUInteger result = [self.key hash];
  result = 31 * result + [self.precondition hash];
  result = 31 * result + [self.fieldTransforms hash];
  return result;
}

- (NSString *)description {
  return [NSString stringWithFormat:@"<FSTTransformMutation key=%@ transforms=%@ precondition=%@>",
                                    self.key, self.fieldTransforms, self.precondition];
}

- (nullable FSTMaybeDocument *)applyTo:(nullable FSTMaybeDocument *)maybeDoc
                          baseDocument:(nullable FSTMaybeDocument *)baseDoc
                        localWriteTime:(FIRTimestamp *)localWriteTime
                        mutationResult:(nullable FSTMutationResult *)mutationResult {
  if (mutationResult) {
    FSTAssert(mutationResult.transformResults,
              @"Transform results missing for FSTTransformMutation.");
  }

  if (![self.precondition isValidForDocument:maybeDoc]) {
    return maybeDoc;
  }

  // We only support transforms with precondition exists, so we can only apply it to an existing
  // document
  FSTAssert([maybeDoc isMemberOfClass:[FSTDocument class]], @"Unknown MaybeDocument type %@",
            [maybeDoc class]);
  FSTDocument *doc = (FSTDocument *)maybeDoc;

  FSTAssert([doc.key isEqual:self.key], @"Can only patch a document with the same key");

  BOOL hasLocalMutations = (mutationResult == nil);
  NSArray<FSTFieldValue *> *transformResults =
      mutationResult
          ? mutationResult.transformResults
          : [self localTransformResultsWithBaseDocument:baseDoc writeTime:localWriteTime];
  FSTObjectValue *newData = [self transformObject:doc.data transformResults:transformResults];
  return [FSTDocument documentWithData:newData
                                   key:doc.key
                               version:doc.version
                     hasLocalMutations:hasLocalMutations];
}

/**
 * Creates an array of "transform results" (a transform result is a field value representing the
 * result of applying a transform) for use when applying an FSTTransformMutation locally.
 *
 * @param baseDocument The document prior to applying this mutation batch.
 * @param localWriteTime The local time of the transform mutation (used to generate
 * FSTServerTimestampValues).
 * @return The transform results array.
 */
- (NSArray<FSTFieldValue *> *)localTransformResultsWithBaseDocument:
                                  (FSTMaybeDocument *_Nullable)baseDocument
                                                          writeTime:(FIRTimestamp *)localWriteTime {
  NSMutableArray<FSTFieldValue *> *transformResults = [NSMutableArray array];
  for (FSTFieldTransform *fieldTransform in self.fieldTransforms) {
    if ([fieldTransform.transform isKindOfClass:[FSTServerTimestampTransform class]]) {
      FSTFieldValue *previousValue = nil;

      if ([baseDocument isMemberOfClass:[FSTDocument class]]) {
        previousValue = [((FSTDocument *)baseDocument) fieldForPath:fieldTransform.path];
      }

      [transformResults
          addObject:[FSTServerTimestampValue serverTimestampValueWithLocalWriteTime:localWriteTime
                                                                      previousValue:previousValue]];
    } else {
      FSTFail(@"Encountered unknown transform: %@", fieldTransform);
    }
  }
  return transformResults;
}

- (FSTObjectValue *)transformObject:(FSTObjectValue *)objectValue
                   transformResults:(NSArray<FSTFieldValue *> *)transformResults {
  FSTAssert(transformResults.count == self.fieldTransforms.count,
            @"Transform results length mismatch.");

  for (NSUInteger i = 0; i < self.fieldTransforms.count; i++) {
    FSTFieldTransform *fieldTransform = self.fieldTransforms[i];
    id<FSTTransformOperation> transform = fieldTransform.transform;
    FieldPath fieldPath = fieldTransform.path;
    if ([transform isKindOfClass:[FSTServerTimestampTransform class]]) {
      objectValue = [objectValue objectBySettingValue:transformResults[i] forPath:fieldPath];
    } else {
      FSTFail(@"Encountered unknown transform: %@", transform);
    }
  }
  return objectValue;
}

@end

#pragma mark - FSTDeleteMutation

@implementation FSTDeleteMutation

- (BOOL)isEqual:(id)other {
  if (other == self) {
    return YES;
  }
  if (![other isKindOfClass:[FSTDeleteMutation class]]) {
    return NO;
  }

  FSTDeleteMutation *otherMutation = (FSTDeleteMutation *)other;
  return [self.key isEqual:otherMutation.key] &&
         [self.precondition isEqual:otherMutation.precondition];
}

- (NSUInteger)hash {
  NSUInteger result = [self.key hash];
  result = 31 * result + [self.precondition hash];
  return result;
}

- (NSString *)description {
  return [NSString
      stringWithFormat:@"<FSTDeleteMutation key=%@ precondition=%@>", self.key, self.precondition];
}

- (nullable FSTMaybeDocument *)applyTo:(nullable FSTMaybeDocument *)maybeDoc
                          baseDocument:(nullable FSTMaybeDocument *)baseDoc
                        localWriteTime:(FIRTimestamp *)localWriteTime
                        mutationResult:(nullable FSTMutationResult *)mutationResult {
  if (mutationResult) {
    FSTAssert(!mutationResult.transformResults,
              @"Transform results received by FSTDeleteMutation.");
  }

  if (![self.precondition isValidForDocument:maybeDoc]) {
    return maybeDoc;
  }

  if (maybeDoc) {
    FSTAssert([maybeDoc.key isEqual:self.key], @"Can only delete a document with the same key");
  }

  return [FSTDeletedDocument documentWithKey:self.key version:[FSTSnapshotVersion noVersion]];
}

@end

NS_ASSUME_NONNULL_END