aboutsummaryrefslogtreecommitdiffhomepage
path: root/Firestore/Example/Tests/Util/FSTHelpers.mm
blob: 58513b0c0fa4558a45a690533fd1912b52e4e481 (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
/*
 * 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/Example/Tests/Util/FSTHelpers.h"

#import <FirebaseFirestore/FIRFieldPath.h>
#import <FirebaseFirestore/FIRGeoPoint.h>
#import <FirebaseFirestore/FIRTimestamp.h>

#include <cinttypes>
#include <list>
#include <unordered_map>
#include <utility>
#include <vector>

#import "Firestore/Source/API/FIRFieldPath+Internal.h"
#import "Firestore/Source/API/FSTUserDataConverter.h"
#import "Firestore/Source/Core/FSTQuery.h"
#import "Firestore/Source/Core/FSTView.h"
#import "Firestore/Source/Core/FSTViewSnapshot.h"
#import "Firestore/Source/Local/FSTLocalViewChanges.h"
#import "Firestore/Source/Local/FSTQueryData.h"
#import "Firestore/Source/Model/FSTDocument.h"
#import "Firestore/Source/Model/FSTDocumentKey.h"
#import "Firestore/Source/Model/FSTDocumentSet.h"
#import "Firestore/Source/Model/FSTFieldValue.h"
#import "Firestore/Source/Model/FSTMutation.h"
#import "Firestore/Source/Remote/FSTRemoteEvent.h"
#import "Firestore/Source/Remote/FSTWatchChange.h"

#include "Firestore/core/src/firebase/firestore/model/database_id.h"
#include "Firestore/core/src/firebase/firestore/model/document_key.h"
#include "Firestore/core/src/firebase/firestore/model/document_key_set.h"
#include "Firestore/core/src/firebase/firestore/model/field_mask.h"
#include "Firestore/core/src/firebase/firestore/model/field_transform.h"
#include "Firestore/core/src/firebase/firestore/model/field_value.h"
#include "Firestore/core/src/firebase/firestore/model/precondition.h"
#include "Firestore/core/src/firebase/firestore/model/resource_path.h"
#include "Firestore/core/src/firebase/firestore/model/transform_operations.h"
#include "Firestore/core/src/firebase/firestore/util/string_apple.h"
#include "Firestore/core/test/firebase/firestore/testutil/testutil.h"
#include "absl/memory/memory.h"

namespace util = firebase::firestore::util;
namespace testutil = firebase::firestore::testutil;
using firebase::firestore::model::DatabaseId;
using firebase::firestore::model::DocumentKey;
using firebase::firestore::model::DocumentKeySet;
using firebase::firestore::model::FieldMask;
using firebase::firestore::model::FieldPath;
using firebase::firestore::model::FieldTransform;
using firebase::firestore::model::FieldValue;
using firebase::firestore::model::Precondition;
using firebase::firestore::model::ResourcePath;
using firebase::firestore::model::ServerTimestampTransform;
using firebase::firestore::model::SnapshotVersion;
using firebase::firestore::model::TransformOperation;

NS_ASSUME_NONNULL_BEGIN

/** A string sentinel that can be used with FSTTestPatchMutation() to mark a field for deletion. */
static NSString *const kDeleteSentinel = @"<DELETE>";

FIRTimestamp *FSTTestTimestamp(int year, int month, int day, int hour, int minute, int second) {
  NSDate *date = FSTTestDate(year, month, day, hour, minute, second);
  return [FIRTimestamp timestampWithDate:date];
}

NSDate *FSTTestDate(int year, int month, int day, int hour, int minute, int second) {
  NSDateComponents *comps = FSTTestDateComponents(year, month, day, hour, minute, second);
  return [[NSCalendar currentCalendar] dateFromComponents:comps];
}

NSData *FSTTestData(int bytes, ...) {
  va_list args;
  va_start(args, bytes); /* Initialize the argument list. */

  NSMutableData *data = [NSMutableData data];

  int next = bytes;
  while (next >= 0) {
    uint8_t byte = (uint8_t)next;
    [data appendBytes:&byte length:1];
    next = va_arg(args, int);
  }

  va_end(args);
  return [data copy];
}

FIRGeoPoint *FSTTestGeoPoint(double latitude, double longitude) {
  return [[FIRGeoPoint alloc] initWithLatitude:latitude longitude:longitude];
}

NSDateComponents *FSTTestDateComponents(
    int year, int month, int day, int hour, int minute, int second) {
  NSDateComponents *comps = [[NSDateComponents alloc] init];
  comps.year = year;
  comps.month = month;
  comps.day = day;
  comps.hour = hour;
  comps.minute = minute;
  comps.second = second;

  // Force time zone to UTC to avoid these values changing due to daylight saving.
  comps.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
  return comps;
}

FSTUserDataConverter *FSTTestUserDataConverter() {
  // This owns the DatabaseIds since we do not have FirestoreClient instance to own them.
  static DatabaseId database_id{"project", DatabaseId::kDefault};
  FSTUserDataConverter *converter =
      [[FSTUserDataConverter alloc] initWithDatabaseID:&database_id
                                          preConverter:^id _Nullable(id _Nullable input) {
                                            return input;
                                          }];
  return converter;
}

FSTFieldValue *FSTTestFieldValue(id _Nullable value) {
  FSTUserDataConverter *converter = FSTTestUserDataConverter();
  // HACK: We use parsedQueryValue: since it accepts scalars as well as arrays / objects, and
  // our tests currently use FSTTestFieldValue() pretty generically so we don't know the intent.
  return [converter parsedQueryValue:value];
}

FSTObjectValue *FSTTestObjectValue(NSDictionary<NSString *, id> *data) {
  FSTFieldValue *wrapped = FSTTestFieldValue(data);
  HARD_ASSERT([wrapped isKindOfClass:[FSTObjectValue class]], "Unsupported value: %s", data);
  return (FSTObjectValue *)wrapped;
}

FSTDocumentKey *FSTTestDocKey(NSString *path) {
  return [FSTDocumentKey keyWithPathString:path];
}

FSTDocument *FSTTestDoc(const absl::string_view path,
                        FSTTestSnapshotVersion version,
                        NSDictionary<NSString *, id> *data,
                        BOOL hasMutations) {
  DocumentKey key = testutil::Key(path);
  return [FSTDocument documentWithData:FSTTestObjectValue(data)
                                   key:key
                               version:testutil::Version(version)
                     hasLocalMutations:hasMutations];
}

FSTDeletedDocument *FSTTestDeletedDoc(const absl::string_view path,
                                      FSTTestSnapshotVersion version) {
  DocumentKey key = testutil::Key(path);
  return [FSTDeletedDocument documentWithKey:key version:testutil::Version(version)];
}

FSTDocumentKeyReference *FSTTestRef(const absl::string_view projectID,
                                    const absl::string_view database,
                                    NSString *path) {
  // This owns the DatabaseIds since we do not have FirestoreClient instance to own them.
  static std::list<DatabaseId> database_ids;
  database_ids.emplace_back(projectID, database);
  return [[FSTDocumentKeyReference alloc] initWithKey:FSTTestDocKey(path)
                                           databaseID:&database_ids.back()];
}

FSTQuery *FSTTestQuery(const absl::string_view path) {
  return [FSTQuery queryWithPath:testutil::Resource(path)];
}

FSTFilter *FSTTestFilter(const absl::string_view field, NSString *opString, id value) {
  const FieldPath path = testutil::Field(field);
  FSTRelationFilterOperator op;
  if ([opString isEqualToString:@"<"]) {
    op = FSTRelationFilterOperatorLessThan;
  } else if ([opString isEqualToString:@"<="]) {
    op = FSTRelationFilterOperatorLessThanOrEqual;
  } else if ([opString isEqualToString:@"=="]) {
    op = FSTRelationFilterOperatorEqual;
  } else if ([opString isEqualToString:@">="]) {
    op = FSTRelationFilterOperatorGreaterThanOrEqual;
  } else if ([opString isEqualToString:@">"]) {
    op = FSTRelationFilterOperatorGreaterThan;
  } else if ([opString isEqualToString:@"array_contains"]) {
    op = FSTRelationFilterOperatorArrayContains;
  } else {
    HARD_FAIL("Unsupported operator type: %s", opString);
  }

  FSTFieldValue *data = FSTTestFieldValue(value);

  return [FSTFilter filterWithField:path filterOperator:op value:data];
}

FSTSortOrder *FSTTestOrderBy(const absl::string_view field, NSString *direction) {
  const FieldPath path = testutil::Field(field);
  BOOL ascending;
  if ([direction isEqualToString:@"asc"]) {
    ascending = YES;
  } else if ([direction isEqualToString:@"desc"]) {
    ascending = NO;
  } else {
    HARD_FAIL("Unsupported direction: %s", direction);
  }
  return [FSTSortOrder sortOrderWithFieldPath:path ascending:ascending];
}

NSComparator FSTTestDocComparator(const absl::string_view fieldPath) {
  FSTQuery *query = [FSTTestQuery("docs")
      queryByAddingSortOrder:[FSTSortOrder sortOrderWithFieldPath:testutil::Field(fieldPath)
                                                        ascending:YES]];
  return [query comparator];
}

FSTDocumentSet *FSTTestDocSet(NSComparator comp, NSArray<FSTDocument *> *docs) {
  FSTDocumentSet *docSet = [FSTDocumentSet documentSetWithComparator:comp];
  for (FSTDocument *doc in docs) {
    docSet = [docSet documentSetByAddingDocument:doc];
  }
  return docSet;
}

FSTSetMutation *FSTTestSetMutation(NSString *path, NSDictionary<NSString *, id> *values) {
  return [[FSTSetMutation alloc] initWithKey:FSTTestDocKey(path)
                                       value:FSTTestObjectValue(values)
                                precondition:Precondition::None()];
}

FSTPatchMutation *FSTTestPatchMutation(const absl::string_view path,
                                       NSDictionary<NSString *, id> *values,
                                       const std::vector<FieldPath> &updateMask) {
  BOOL merge = !updateMask.empty();

  __block FSTObjectValue *objectValue = [FSTObjectValue objectValue];
  __block std::vector<FieldPath> fieldMaskPaths;
  [values enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *stop) {
    const FieldPath path = testutil::Field(util::MakeStringView(key));
    fieldMaskPaths.push_back(path);
    if (![value isEqual:kDeleteSentinel]) {
      FSTFieldValue *parsedValue = FSTTestFieldValue(value);
      objectValue = [objectValue objectBySettingValue:parsedValue forPath:path];
    }
  }];

  DocumentKey key = testutil::Key(path);
  FieldMask mask(merge ? updateMask : fieldMaskPaths);
  return [[FSTPatchMutation alloc] initWithKey:key
                                     fieldMask:mask
                                         value:objectValue
                                  precondition:Precondition::Exists(true)];
}

FSTTransformMutation *FSTTestTransformMutation(NSString *path, NSDictionary<NSString *, id> *data) {
  FSTDocumentKey *key = [FSTDocumentKey keyWithPath:testutil::Resource(util::MakeStringView(path))];
  FSTUserDataConverter *converter = FSTTestUserDataConverter();
  FSTParsedUpdateData *result = [converter parsedUpdateData:data];
  HARD_ASSERT(result.data.value.count == 0,
              "FSTTestTransformMutation() only expects transforms; no other data");
  return [[FSTTransformMutation alloc] initWithKey:key
                                   fieldTransforms:std::move(result.fieldTransforms)];
}

FSTDeleteMutation *FSTTestDeleteMutation(NSString *path) {
  return
      [[FSTDeleteMutation alloc] initWithKey:FSTTestDocKey(path) precondition:Precondition::None()];
}

FSTMaybeDocumentDictionary *FSTTestDocUpdates(NSArray<FSTMaybeDocument *> *docs) {
  FSTMaybeDocumentDictionary *updates = [FSTMaybeDocumentDictionary maybeDocumentDictionary];
  for (FSTMaybeDocument *doc in docs) {
    updates = [updates dictionaryBySettingObject:doc forKey:doc.key];
  }
  return updates;
}

FSTViewSnapshot *_Nullable FSTTestApplyChanges(FSTView *view,
                                               NSArray<FSTMaybeDocument *> *docs,
                                               FSTTargetChange *_Nullable targetChange) {
  return [view applyChangesToDocuments:[view computeChangesWithDocuments:FSTTestDocUpdates(docs)]
                          targetChange:targetChange]
      .snapshot;
}

@implementation FSTTestTargetMetadataProvider {
  std::unordered_map<FSTTargetID, DocumentKeySet> _syncedKeys;
  std::unordered_map<FSTTargetID, FSTQueryData *> _queryData;
}

+ (instancetype)providerWithSingleResultForKey:(DocumentKey)documentKey
                                       targets:(NSArray<FSTBoxedTargetID *> *)targets {
  FSTTestTargetMetadataProvider *metadataProvider = [FSTTestTargetMetadataProvider new];
  FSTQuery *query = [FSTQuery queryWithPath:documentKey.path()];

  for (FSTBoxedTargetID *targetID in targets) {
    FSTQueryData *queryData = [[FSTQueryData alloc] initWithQuery:query
                                                         targetID:targetID.intValue
                                             listenSequenceNumber:0
                                                          purpose:FSTQueryPurposeListen];
    [metadataProvider setSyncedKeys:DocumentKeySet{documentKey} forQueryData:queryData];
  }

  return metadataProvider;
}

+ (instancetype)providerWithEmptyResultForKey:(DocumentKey)documentKey
                                      targets:(NSArray<FSTBoxedTargetID *> *)targets {
  FSTTestTargetMetadataProvider *metadataProvider = [FSTTestTargetMetadataProvider new];
  FSTQuery *query = [FSTQuery queryWithPath:documentKey.path()];

  for (FSTBoxedTargetID *targetID in targets) {
    FSTQueryData *queryData = [[FSTQueryData alloc] initWithQuery:query
                                                         targetID:targetID.intValue
                                             listenSequenceNumber:0
                                                          purpose:FSTQueryPurposeListen];
    [metadataProvider setSyncedKeys:DocumentKeySet {} forQueryData:queryData];
  }

  return metadataProvider;
}

- (void)setSyncedKeys:(DocumentKeySet)keys forQueryData:(FSTQueryData *)queryData {
  _syncedKeys[queryData.targetID] = keys;
  _queryData[queryData.targetID] = queryData;
}

- (DocumentKeySet)remoteKeysForTarget:(FSTBoxedTargetID *)targetID {
  auto it = _syncedKeys.find(targetID.intValue);
  HARD_ASSERT(it != _syncedKeys.end(), "Cannot process unknown target %s", targetID.intValue);
  return it->second;
}

- (nullable FSTQueryData *)queryDataForTarget:(FSTBoxedTargetID *)targetID {
  auto it = _queryData.find(targetID.intValue);
  HARD_ASSERT(it != _queryData.end(), "Cannot process unknown target %s", targetID.intValue);
  return it->second;
}

@end

FSTRemoteEvent *FSTTestAddedRemoteEvent(FSTMaybeDocument *doc,
                                        NSArray<FSTBoxedTargetID *> *addedToTargets) {
  HARD_ASSERT(![doc isKindOfClass:[FSTDocument class]] || ![(FSTDocument *)doc hasLocalMutations],
              "Docs from remote updates shouldn't have local changes.");
  FSTDocumentWatchChange *change =
      [[FSTDocumentWatchChange alloc] initWithUpdatedTargetIDs:addedToTargets
                                              removedTargetIDs:{}
                                                   documentKey:doc.key
                                                      document:doc];
  FSTWatchChangeAggregator *aggregator = [[FSTWatchChangeAggregator alloc]
      initWithTargetMetadataProvider:[FSTTestTargetMetadataProvider
                                         providerWithEmptyResultForKey:doc.key
                                                               targets:addedToTargets]];
  [aggregator handleDocumentChange:change];
  return [aggregator remoteEventAtSnapshotVersion:doc.version];
}

FSTRemoteEvent *FSTTestUpdateRemoteEvent(FSTMaybeDocument *doc,
                                         NSArray<FSTBoxedTargetID *> *updatedInTargets,
                                         NSArray<FSTBoxedTargetID *> *removedFromTargets) {
  HARD_ASSERT(![doc isKindOfClass:[FSTDocument class]] || ![(FSTDocument *)doc hasLocalMutations],
              "Docs from remote updates shouldn't have local changes.");
  FSTDocumentWatchChange *change =
      [[FSTDocumentWatchChange alloc] initWithUpdatedTargetIDs:updatedInTargets
                                              removedTargetIDs:removedFromTargets
                                                   documentKey:doc.key
                                                      document:doc];
  NSArray<FSTBoxedTargetID *> *targets =
      [updatedInTargets arrayByAddingObjectsFromArray:removedFromTargets];
  FSTWatchChangeAggregator *aggregator = [[FSTWatchChangeAggregator alloc]
      initWithTargetMetadataProvider:[FSTTestTargetMetadataProvider
                                         providerWithSingleResultForKey:doc.key
                                                                targets:targets]];
  [aggregator handleDocumentChange:change];
  return [aggregator remoteEventAtSnapshotVersion:doc.version];
}

FSTTargetChange *FSTTestTargetChangeMarkCurrent() {
  return [[FSTTargetChange alloc] initWithResumeToken:[NSData data]
      current:YES
      addedDocuments:DocumentKeySet {}
      modifiedDocuments:DocumentKeySet {}
      removedDocuments:DocumentKeySet{}];
}

FSTTargetChange *FSTTestTargetChangeAckDocuments(DocumentKeySet docs) {
  return [[FSTTargetChange alloc] initWithResumeToken:[NSData data]
                                              current:YES
                                       addedDocuments:docs
                                    modifiedDocuments:DocumentKeySet {}
                                     removedDocuments:DocumentKeySet{}];
}

FSTTargetChange *FSTTestTargetChange(DocumentKeySet added,
                                     DocumentKeySet modified,
                                     DocumentKeySet removed,
                                     NSData *resumeToken,
                                     BOOL current) {
  return [[FSTTargetChange alloc] initWithResumeToken:resumeToken
                                              current:current
                                       addedDocuments:added
                                    modifiedDocuments:modified
                                     removedDocuments:removed];
}

/** Creates a resume token to match the given snapshot version. */
NSData *_Nullable FSTTestResumeTokenFromSnapshotVersion(FSTTestSnapshotVersion snapshotVersion) {
  if (snapshotVersion == 0) {
    return nil;
  }

  NSString *snapshotString = [NSString stringWithFormat:@"snapshot-%" PRId64, snapshotVersion];
  return [snapshotString dataUsingEncoding:NSUTF8StringEncoding];
}

FSTLocalViewChanges *FSTTestViewChanges(FSTQuery *query,
                                        NSArray<NSString *> *addedKeys,
                                        NSArray<NSString *> *removedKeys) {
  DocumentKeySet added;
  for (NSString *keyPath in addedKeys) {
    added = added.insert(testutil::Key(util::MakeStringView(keyPath)));
  }
  DocumentKeySet removed;
  for (NSString *keyPath in removedKeys) {
    removed = removed.insert(testutil::Key(util::MakeStringView(keyPath)));
  }
  return [FSTLocalViewChanges changesForQuery:query
                                    addedKeys:std::move(added)
                                  removedKeys:std::move(removed)];
}

NS_ASSUME_NONNULL_END