FSTTransactionTests.mm 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  1. /*
  2. * Copyright 2017 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import <FirebaseFirestore/FirebaseFirestore.h>
  17. #import <XCTest/XCTest.h>
  18. #include <atomic>
  19. #import "Firestore/Example/Tests/Util/FSTIntegrationTestCase.h"
  20. #import "Firestore/Source/API/FIRFirestore+Internal.h"
  21. using firebase::firestore::util::TimerId;
  22. @interface FSTTransactionTests : FSTIntegrationTestCase
  23. @end
  24. /**
  25. * This category is to handle the use of assertions in `FSTTransactionTester`, since XCTest
  26. * assertions do not work in classes that don't extend XCTestCase.
  27. */
  28. @interface FSTTransactionTests (Assertions)
  29. - (void)assertExistsWithSnapshot:(FIRDocumentSnapshot *)snapshot error:(NSError *)error;
  30. - (void)assertDoesNotExistWithSnapshot:(FIRDocumentSnapshot *)snapshot error:(NSError *)error;
  31. - (void)assertNilError:(NSError *)error message:(NSString *)message;
  32. - (void)assertError:(NSError *)error message:(NSString *)message code:(NSInteger)code;
  33. - (void)assertSnapshot:(FIRDocumentSnapshot *)snapshot
  34. equalsObject:(NSObject *)expected
  35. error:(NSError *)error;
  36. @end
  37. @implementation FSTTransactionTests (Assertions)
  38. - (void)assertExistsWithSnapshot:(FIRDocumentSnapshot *)snapshot error:(NSError *)error {
  39. XCTAssertNil(error);
  40. XCTAssertTrue(snapshot.exists);
  41. }
  42. - (void)assertDoesNotExistWithSnapshot:(FIRDocumentSnapshot *)snapshot error:(NSError *)error {
  43. XCTAssertNil(error);
  44. XCTAssertFalse(snapshot.exists);
  45. }
  46. - (void)assertNilError:(NSError *)error message:(NSString *)message {
  47. XCTAssertNil(error, @"%@", message);
  48. }
  49. - (void)assertError:(NSError *)error message:(NSString *)message code:(NSInteger)code {
  50. XCTAssertNotNil(error, @"%@", message);
  51. XCTAssertEqual(error.code, code, @"%@", message);
  52. }
  53. - (void)assertSnapshot:(FIRDocumentSnapshot *)snapshot
  54. equalsObject:(NSObject *)expected
  55. error:(NSError *)error {
  56. XCTAssertNil(error);
  57. XCTAssertTrue(snapshot.exists);
  58. XCTAssertEqualObjects(expected, snapshot.data);
  59. }
  60. @end
  61. typedef void (^TransactionStage)(FIRTransaction *, FIRDocumentReference *);
  62. /**
  63. * The transaction stages that follow are postfixed by numbers to indicate the calling order. For
  64. * example, calling `set1` followed by `set2` should result in the document being set to the value
  65. * specified by `set2`.
  66. */
  67. TransactionStage delete1 = ^(FIRTransaction *transaction, FIRDocumentReference *doc) {
  68. [transaction deleteDocument:doc];
  69. };
  70. TransactionStage update1 = ^(FIRTransaction *transaction, FIRDocumentReference *doc) {
  71. [transaction updateData:@{@"foo" : @"bar1"} forDocument:doc];
  72. };
  73. TransactionStage update2 = ^(FIRTransaction *transaction, FIRDocumentReference *doc) {
  74. [transaction updateData:@{@"foo" : @"bar2"} forDocument:doc];
  75. };
  76. TransactionStage update3 = ^(FIRTransaction *transaction, FIRDocumentReference *doc) {
  77. [transaction updateData:@{} forDocument:doc];
  78. };
  79. TransactionStage set1 = ^(FIRTransaction *transaction, FIRDocumentReference *doc) {
  80. [transaction setData:@{@"foo" : @"bar1"} forDocument:doc];
  81. };
  82. TransactionStage set2 = ^(FIRTransaction *transaction, FIRDocumentReference *doc) {
  83. [transaction setData:@{@"foo" : @"bar2"} forDocument:doc];
  84. };
  85. TransactionStage get = ^(FIRTransaction *transaction, FIRDocumentReference *doc) {
  86. NSError *error = nil;
  87. [transaction getDocument:doc error:&error];
  88. };
  89. /**
  90. * Used for testing that all possible combinations of executing transactions result in the desired
  91. * document value or error.
  92. *
  93. * `runWithStages`, `withExistingDoc`, and `withNonexistentDoc` don't actually do anything except
  94. * assign variables into `FSTTransactionTester`.
  95. *
  96. * `expectDoc`, `expectNoDoc`, and `expectError` will trigger the transaction to run and assert
  97. * that the end result matches the input.
  98. */
  99. @interface FSTTransactionTester : NSObject
  100. - (FSTTransactionTester *)withExistingDoc;
  101. - (FSTTransactionTester *)withNonexistentDoc;
  102. - (FSTTransactionTester *)runWithStages:(NSArray<TransactionStage> *)stages;
  103. - (void)expectDoc:(NSObject *)expected;
  104. - (void)expectNoDoc;
  105. - (void)expectError:(FIRFirestoreErrorCode)expected;
  106. @property(atomic, strong, readwrite) NSArray<TransactionStage> *stages;
  107. @property(atomic, strong, readwrite) FIRDocumentReference *docRef;
  108. @property(atomic, assign, readwrite) BOOL fromExistingDoc;
  109. @end
  110. @implementation FSTTransactionTester {
  111. FIRFirestore *_db;
  112. FSTTransactionTests *_testCase;
  113. NSMutableArray<XCTestExpectation *> *_testExpectations;
  114. }
  115. - (instancetype)initWithDb:(FIRFirestore *)db testCase:(FSTTransactionTests *)testCase {
  116. self = [super init];
  117. if (self) {
  118. _db = db;
  119. _stages = [NSArray array];
  120. _testCase = testCase;
  121. _testExpectations = [NSMutableArray array];
  122. }
  123. return self;
  124. }
  125. - (FSTTransactionTester *)withExistingDoc {
  126. self.fromExistingDoc = YES;
  127. return self;
  128. }
  129. - (FSTTransactionTester *)withNonexistentDoc {
  130. self.fromExistingDoc = NO;
  131. return self;
  132. }
  133. - (FSTTransactionTester *)runWithStages:(NSArray<TransactionStage> *)stages {
  134. self.stages = stages;
  135. return self;
  136. }
  137. - (void)expectDoc:(NSObject *)expected {
  138. [self prepareDoc];
  139. [self runSuccessfulTransaction];
  140. XCTestExpectation *expectation = [_testCase expectationWithDescription:@"expectDoc"];
  141. [self.docRef getDocumentWithCompletion:^(FIRDocumentSnapshot *snapshot, NSError *error) {
  142. [self->_testCase assertSnapshot:snapshot equalsObject:expected error:error];
  143. [expectation fulfill];
  144. }];
  145. [_testCase awaitExpectations];
  146. [self cleanupTester];
  147. }
  148. - (void)expectNoDoc {
  149. [self prepareDoc];
  150. [self runSuccessfulTransaction];
  151. XCTestExpectation *expectation = [_testCase expectationWithDescription:@"expectNoDoc"];
  152. [self.docRef getDocumentWithCompletion:^(FIRDocumentSnapshot *snapshot, NSError *error) {
  153. [self->_testCase assertDoesNotExistWithSnapshot:snapshot error:error];
  154. [expectation fulfill];
  155. }];
  156. [_testCase awaitExpectations];
  157. [self cleanupTester];
  158. }
  159. - (void)expectError:(FIRFirestoreErrorCode)expected {
  160. [self prepareDoc];
  161. [self runFailingTransactionWithError:expected];
  162. [self cleanupTester];
  163. }
  164. - (void)prepareDoc {
  165. self.docRef = [[_db collectionWithPath:@"nonexistent"] documentWithAutoID];
  166. if (_fromExistingDoc) {
  167. NSError *setError = [self writeDocumentRef:self.docRef data:@{@"foo" : @"bar"}];
  168. NSString *message = [NSString stringWithFormat:@"Failed set at %@", [self stageNames]];
  169. [_testCase assertNilError:setError message:message];
  170. }
  171. }
  172. - (NSError *)writeDocumentRef:(FIRDocumentReference *)ref
  173. data:(NSDictionary<NSString *, id> *)data {
  174. __block NSError *errorResult;
  175. XCTestExpectation *expectation = [_testCase expectationWithDescription:@"prepareDoc:set"];
  176. [ref setData:data
  177. completion:^(NSError *error) {
  178. errorResult = error;
  179. [expectation fulfill];
  180. }];
  181. [_testCase awaitExpectations];
  182. return errorResult;
  183. }
  184. - (void)runSuccessfulTransaction {
  185. XCTestExpectation *expectation =
  186. [_testCase expectationWithDescription:@"runSuccessfulTransaction"];
  187. [_db
  188. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **) {
  189. for (TransactionStage stage in self.stages) {
  190. stage(transaction, self.docRef);
  191. }
  192. return @YES;
  193. }
  194. completion:^(id, NSError *error) {
  195. [expectation fulfill];
  196. NSString *message =
  197. [NSString stringWithFormat:@"Expected the sequence %@, to succeed, but got %d.",
  198. [self stageNames], (int)[error code]];
  199. [self->_testCase assertNilError:error message:message];
  200. }];
  201. [_testCase awaitExpectations];
  202. }
  203. - (void)runFailingTransactionWithError:(FIRFirestoreErrorCode)expected {
  204. (void)expected;
  205. XCTestExpectation *expectation =
  206. [_testCase expectationWithDescription:@"runFailingTransactionWithError"];
  207. [_db
  208. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **) {
  209. for (TransactionStage stage in self.stages) {
  210. stage(transaction, self.docRef);
  211. }
  212. return @YES;
  213. }
  214. completion:^(id, NSError *_Nullable error) {
  215. [expectation fulfill];
  216. NSString *message =
  217. [NSString stringWithFormat:@"Expected the sequence (%@), to fail, but it didn't.",
  218. [self stageNames]];
  219. [self->_testCase assertError:error message:message code:expected];
  220. }];
  221. [_testCase awaitExpectations];
  222. }
  223. - (void)cleanupTester {
  224. self.stages = [NSArray array];
  225. // Set the docRef to something else to lose the original reference.
  226. self.docRef = [[self->_db collectionWithPath:@"reset"] documentWithAutoID];
  227. }
  228. - (NSString *)stageNames {
  229. NSMutableArray<NSString *> *seqList = [NSMutableArray array];
  230. for (TransactionStage stage in self.stages) {
  231. if (stage == delete1) {
  232. [seqList addObject:@"delete"];
  233. } else if (stage == update1 || stage == update2 || stage == update3) {
  234. [seqList addObject:@"update"];
  235. } else if (stage == set1 || stage == set2) {
  236. [seqList addObject:@"set"];
  237. } else if (stage == get) {
  238. [seqList addObject:@"get"];
  239. }
  240. }
  241. return [seqList description];
  242. }
  243. @end
  244. @implementation FSTTransactionTests
  245. - (void)testRunsTransactionsAfterGettingExistingDoc {
  246. FIRFirestore *firestore = [self firestore];
  247. FSTTransactionTester *tt = [[FSTTransactionTester alloc] initWithDb:firestore testCase:self];
  248. [[[tt withExistingDoc] runWithStages:@[ get, delete1, delete1 ]] expectNoDoc];
  249. [[[tt withExistingDoc] runWithStages:@[ get, delete1, update2 ]]
  250. expectError:FIRFirestoreErrorCodeInvalidArgument];
  251. [[[tt withExistingDoc] runWithStages:@[ get, delete1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  252. [[[tt withExistingDoc] runWithStages:@[ get, update1, delete1 ]] expectNoDoc];
  253. [[[tt withExistingDoc] runWithStages:@[ get, update1, update2 ]] expectDoc:@{@"foo" : @"bar2"}];
  254. [[[tt withExistingDoc] runWithStages:@[ get, update1, update2, update3 ]]
  255. expectDoc:@{@"foo" : @"bar2"}];
  256. [[[tt withExistingDoc] runWithStages:@[ get, update1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  257. [[[tt withExistingDoc] runWithStages:@[ get, set1, delete1 ]] expectNoDoc];
  258. [[[tt withExistingDoc] runWithStages:@[ get, set1, update2 ]] expectDoc:@{@"foo" : @"bar2"}];
  259. [[[tt withExistingDoc] runWithStages:@[ get, set1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  260. }
  261. - (void)testRunsTransactionsAfterGettingNonexistentDoc {
  262. FIRFirestore *firestore = [self firestore];
  263. FSTTransactionTester *tt = [[FSTTransactionTester alloc] initWithDb:firestore testCase:self];
  264. [[[tt withNonexistentDoc] runWithStages:@[ get, delete1, delete1 ]] expectNoDoc];
  265. [[[tt withNonexistentDoc] runWithStages:@[ get, delete1, update2 ]]
  266. expectError:FIRFirestoreErrorCodeInvalidArgument];
  267. [[[tt withNonexistentDoc] runWithStages:@[ get, delete1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  268. [[[tt withNonexistentDoc] runWithStages:@[ get, update1, delete1 ]]
  269. expectError:FIRFirestoreErrorCodeInvalidArgument];
  270. [[[tt withNonexistentDoc] runWithStages:@[ get, update1, update2 ]]
  271. expectError:FIRFirestoreErrorCodeInvalidArgument];
  272. [[[tt withNonexistentDoc] runWithStages:@[ get, update1, set2 ]]
  273. expectError:FIRFirestoreErrorCodeInvalidArgument];
  274. [[[tt withNonexistentDoc] runWithStages:@[ get, set1, delete1 ]] expectNoDoc];
  275. [[[tt withNonexistentDoc] runWithStages:@[ get, set1, update2 ]] expectDoc:@{@"foo" : @"bar2"}];
  276. [[[tt withNonexistentDoc] runWithStages:@[ get, set1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  277. }
  278. - (void)testRunsTransactionOnExistingDoc {
  279. FIRFirestore *firestore = [self firestore];
  280. FSTTransactionTester *tt = [[FSTTransactionTester alloc] initWithDb:firestore testCase:self];
  281. [[[tt withExistingDoc] runWithStages:@[ delete1, delete1 ]] expectNoDoc];
  282. [[[tt withExistingDoc] runWithStages:@[ delete1, update2 ]]
  283. expectError:FIRFirestoreErrorCodeInvalidArgument];
  284. [[[tt withExistingDoc] runWithStages:@[ delete1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  285. [[[tt withExistingDoc] runWithStages:@[ update1, delete1 ]] expectNoDoc];
  286. [[[tt withExistingDoc] runWithStages:@[ update1, update2 ]] expectDoc:@{@"foo" : @"bar2"}];
  287. [[[tt withExistingDoc] runWithStages:@[ update1, update2, update3 ]]
  288. expectDoc:@{@"foo" : @"bar2"}];
  289. [[[tt withExistingDoc] runWithStages:@[ update1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  290. [[[tt withExistingDoc] runWithStages:@[ set1, delete1 ]] expectNoDoc];
  291. [[[tt withExistingDoc] runWithStages:@[ set1, update2 ]] expectDoc:@{@"foo" : @"bar2"}];
  292. [[[tt withExistingDoc] runWithStages:@[ set1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  293. }
  294. - (void)testRunsTransactionsOnNonexistentDoc {
  295. FIRFirestore *firestore = [self firestore];
  296. FSTTransactionTester *tt = [[FSTTransactionTester alloc] initWithDb:firestore testCase:self];
  297. [[[tt withNonexistentDoc] runWithStages:@[ delete1, delete1 ]] expectNoDoc];
  298. [[[tt withNonexistentDoc] runWithStages:@[ delete1, update2 ]]
  299. expectError:FIRFirestoreErrorCodeInvalidArgument];
  300. [[[tt withNonexistentDoc] runWithStages:@[ delete1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  301. [[[tt withNonexistentDoc] runWithStages:@[ update1, delete1 ]]
  302. expectError:FIRFirestoreErrorCodeNotFound];
  303. [[[tt withNonexistentDoc] runWithStages:@[ update1, update2 ]]
  304. expectError:FIRFirestoreErrorCodeNotFound];
  305. [[[tt withNonexistentDoc] runWithStages:@[ update1, set2 ]]
  306. expectError:FIRFirestoreErrorCodeNotFound];
  307. [[[tt withNonexistentDoc] runWithStages:@[ set1, delete1 ]] expectNoDoc];
  308. [[[tt withNonexistentDoc] runWithStages:@[ set1, update2 ]] expectDoc:@{@"foo" : @"bar2"}];
  309. [[[tt withNonexistentDoc] runWithStages:@[ set1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  310. }
  311. - (void)testSetDocumentWithMerge {
  312. FIRFirestore *firestore = [self firestore];
  313. FIRDocumentReference *doc = [[firestore collectionWithPath:@"towns"] documentWithAutoID];
  314. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  315. [firestore
  316. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **) {
  317. [transaction setData:@{@"a" : @"b", @"nested" : @{@"a" : @"b"}} forDocument:doc];
  318. [transaction setData:@{@"c" : @"d", @"nested" : @{@"c" : @"d"}} forDocument:doc merge:YES];
  319. return @YES;
  320. }
  321. completion:^(id _Nullable result, NSError *_Nullable error) {
  322. XCTAssertEqualObjects(result, @YES);
  323. XCTAssertNil(error);
  324. [expectation fulfill];
  325. }];
  326. [self awaitExpectations];
  327. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:doc];
  328. XCTAssertEqualObjects(snapshot.data,
  329. (@{@"a" : @"b", @"c" : @"d", @"nested" : @{@"a" : @"b", @"c" : @"d"}}));
  330. }
  331. - (void)testIncrementTransactionally {
  332. // A barrier to make sure every transaction reaches the same spot.
  333. dispatch_semaphore_t writeBarrier = dispatch_semaphore_create(0);
  334. auto counter = std::make_shared<std::atomic_int>(0);
  335. FIRFirestore *firestore = [self firestore];
  336. FIRDocumentReference *doc = [[firestore collectionWithPath:@"counters"] documentWithAutoID];
  337. [self writeDocumentRef:doc data:@{@"count" : @(5.0)}];
  338. // Skip backoff delays.
  339. [firestore workerQueue]->SkipDelaysForTimerId(TimerId::RetryTransaction);
  340. // Make 3 transactions that will all increment.
  341. int total = 3;
  342. for (int i = 0; i < total; i++) {
  343. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  344. [firestore
  345. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  346. FIRDocumentSnapshot *snapshot = [transaction getDocument:doc error:error];
  347. XCTAssertNil(*error);
  348. (*counter)++;
  349. // Once all of the transactions have read, allow the first write.
  350. if (*counter == total) {
  351. dispatch_semaphore_signal(writeBarrier);
  352. }
  353. dispatch_semaphore_wait(writeBarrier, DISPATCH_TIME_FOREVER);
  354. // Refill the barrier so that the other transactions and retries succeed.
  355. dispatch_semaphore_signal(writeBarrier);
  356. double newCount = ((NSNumber *)snapshot[@"count"]).doubleValue + 1.0;
  357. [transaction setData:@{@"count" : @(newCount)} forDocument:doc];
  358. return @YES;
  359. }
  360. completion:^(id, NSError *) {
  361. [expectation fulfill];
  362. }];
  363. }
  364. [self awaitExpectations];
  365. // Now all transaction should be completed, so check the result.
  366. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:doc];
  367. XCTAssertEqualObjects(snapshot[@"count"], @(5.0 + total));
  368. }
  369. - (void)testUpdateTransactionally {
  370. // A barrier to make sure every transaction reaches the same spot.
  371. dispatch_semaphore_t writeBarrier = dispatch_semaphore_create(0);
  372. auto counter = std::make_shared<std::atomic_int>(0);
  373. FIRFirestore *firestore = [self firestore];
  374. FIRDocumentReference *doc = [[firestore collectionWithPath:@"counters"] documentWithAutoID];
  375. [self writeDocumentRef:doc data:@{@"count" : @(5.0), @"other" : @"yes"}];
  376. // Skip backoff delays.
  377. [firestore workerQueue]->SkipDelaysForTimerId(TimerId::RetryTransaction);
  378. // Make 3 transactions that will all increment.
  379. int total = 3;
  380. for (int i = 0; i < total; i++) {
  381. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  382. [firestore
  383. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  384. int32_t nowStarted = ++(*counter);
  385. FIRDocumentSnapshot *snapshot = [transaction getDocument:doc error:error];
  386. XCTAssertNil(*error);
  387. // Once all of the transactions have read, allow the first write. There should be 3
  388. // initial transaction runs.
  389. if (nowStarted == total) {
  390. XCTAssertEqual(counter->load(), 3);
  391. dispatch_semaphore_signal(writeBarrier);
  392. }
  393. dispatch_semaphore_wait(writeBarrier, DISPATCH_TIME_FOREVER);
  394. // Refill the barrier so that the other transactions and retries succeed.
  395. dispatch_semaphore_signal(writeBarrier);
  396. double newCount = ((NSNumber *)snapshot[@"count"]).doubleValue + 1.0;
  397. [transaction updateData:@{@"count" : @(newCount)} forDocument:doc];
  398. return @YES;
  399. }
  400. completion:^(id, NSError *) {
  401. [expectation fulfill];
  402. }];
  403. }
  404. [self awaitExpectations];
  405. // There should be a maximum of 3 retries: once for the 2nd update, and twice for the 3rd update.
  406. XCTAssertLessThanOrEqual(counter->load(), 6);
  407. // Now all transaction should be completed, so check the result.
  408. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:doc];
  409. XCTAssertEqualObjects(snapshot[@"count"], @(5.0 + total));
  410. XCTAssertEqualObjects(@"yes", snapshot[@"other"]);
  411. }
  412. - (void)testRetriesWhenDocumentThatWasReadWithoutBeingWrittenChanges {
  413. FIRFirestore *firestore = [self firestore];
  414. FIRDocumentReference *doc1 = [[firestore collectionWithPath:@"counters"] documentWithAutoID];
  415. FIRDocumentReference *doc2 = [[firestore collectionWithPath:@"counters"] documentWithAutoID];
  416. auto counter = std::make_shared<std::atomic_int>(0);
  417. [self writeDocumentRef:doc1 data:@{@"count" : @(15.0)}];
  418. // Skip backoff delays.
  419. [firestore workerQueue]->SkipDelaysForTimerId(TimerId::RetryTransaction);
  420. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  421. [firestore
  422. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  423. ++(*counter);
  424. // Get the first doc.
  425. [transaction getDocument:doc1 error:error];
  426. XCTAssertNil(*error);
  427. // Do a write outside of the transaction. The first time the
  428. // transaction is tried, this will bump the version, which
  429. // will cause the write to doc2 to fail. The second time, it
  430. // will be a no-op and not bump the version.
  431. dispatch_semaphore_t writeSemaphore = dispatch_semaphore_create(0);
  432. [doc1 setData:@{
  433. @"count" : @(1234)
  434. }
  435. completion:^(NSError *) {
  436. dispatch_semaphore_signal(writeSemaphore);
  437. }];
  438. // We can block on it, because transactions run on a background queue.
  439. dispatch_semaphore_wait(writeSemaphore, DISPATCH_TIME_FOREVER);
  440. // Now try to update the other doc from within the transaction.
  441. // This should fail once, because we read 15 earlier.
  442. [transaction setData:@{@"count" : @(16)} forDocument:doc2];
  443. return nil;
  444. }
  445. completion:^(id, NSError *_Nullable error) {
  446. XCTAssertNil(error);
  447. XCTAssertEqual(counter->load(), 2);
  448. [expectation fulfill];
  449. }];
  450. [self awaitExpectations];
  451. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:doc1];
  452. XCTAssertEqualObjects(snapshot[@"count"], @(1234));
  453. }
  454. - (void)testReadingADocTwiceWithDifferentVersions {
  455. FIRFirestore *firestore = [self firestore];
  456. FIRDocumentReference *doc = [[firestore collectionWithPath:@"counters"] documentWithAutoID];
  457. auto counter = std::make_shared<std::atomic_int>(0);
  458. [self writeDocumentRef:doc data:@{@"count" : @(15.0)}];
  459. // Skip backoff delays.
  460. [firestore workerQueue]->SkipDelaysForTimerId(TimerId::RetryTransaction);
  461. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  462. [firestore
  463. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  464. ++(*counter);
  465. // Get the doc once.
  466. FIRDocumentSnapshot *snapshot = [transaction getDocument:doc error:error];
  467. XCTAssertNil(*error);
  468. // Do a write outside of the transaction. Because the transaction will retry, set the
  469. // document to a different value each time.
  470. dispatch_semaphore_t writeSemaphore = dispatch_semaphore_create(0);
  471. [doc setData:@{
  472. @"count" : @(1234 + (int)(*counter))
  473. }
  474. completion:^(NSError *) {
  475. dispatch_semaphore_signal(writeSemaphore);
  476. }];
  477. // We can block on it, because transactions run on a background queue.
  478. dispatch_semaphore_wait(writeSemaphore, DISPATCH_TIME_FOREVER);
  479. // Get the doc again in the transaction with the new version.
  480. snapshot = [transaction getDocument:doc error:error];
  481. // The get itself will fail, because we already read an earlier version of this document.
  482. // TODO(klimt): Perhaps we shouldn't fail reads for this, but should wait and fail the
  483. // whole transaction? It's an edge-case anyway, as developers shouldn't be reading the same
  484. // doc multiple times. But they need to handle read errors anyway.
  485. XCTAssertNotNil(*error);
  486. return nil;
  487. }
  488. completion:^(id, NSError *_Nullable error) {
  489. [expectation fulfill];
  490. XCTAssertNotNil(error);
  491. XCTAssertEqual(error.code, FIRFirestoreErrorCodeAborted);
  492. }];
  493. [self awaitExpectations];
  494. }
  495. - (void)testReadAndUpdateNonExistentDocumentWithExternalWrite {
  496. FIRFirestore *firestore = [self firestore];
  497. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  498. [firestore
  499. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  500. // Get and update a document that doesn't exist so that the transaction fails.
  501. FIRDocumentReference *doc =
  502. [[firestore collectionWithPath:@"nonexistent"] documentWithAutoID];
  503. [transaction getDocument:doc error:error];
  504. XCTAssertNil(*error);
  505. // Do a write outside of the transaction.
  506. dispatch_semaphore_t writeSemaphore = dispatch_semaphore_create(0);
  507. [doc setData:@{
  508. @"count" : @(1234)
  509. }
  510. completion:^(NSError *) {
  511. dispatch_semaphore_signal(writeSemaphore);
  512. }];
  513. // We can block on it, because transactions run on a background queue.
  514. dispatch_semaphore_wait(writeSemaphore, DISPATCH_TIME_FOREVER);
  515. // Now try to update the other doc from within the transaction.
  516. // This should fail, because the document didn't exist at the
  517. // start of the transaction.
  518. [transaction updateData:@{@"count" : @(16)} forDocument:doc];
  519. return nil;
  520. }
  521. completion:^(id, NSError *_Nullable error) {
  522. [expectation fulfill];
  523. XCTAssertNotNil(error);
  524. XCTAssertEqual(error.code, FIRFirestoreErrorCodeInvalidArgument);
  525. }];
  526. [self awaitExpectations];
  527. }
  528. - (void)testCanHaveGetsWithoutMutations {
  529. FIRFirestore *firestore = [self firestore];
  530. FIRDocumentReference *doc = [[firestore collectionWithPath:@"foo"] documentWithAutoID];
  531. FIRDocumentReference *doc2 = [[firestore collectionWithPath:@"foo"] documentWithAutoID];
  532. [self writeDocumentRef:doc data:@{@"foo" : @"bar"}];
  533. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  534. [firestore
  535. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  536. [transaction getDocument:doc2 error:error];
  537. [transaction getDocument:doc error:error];
  538. return nil;
  539. }
  540. completion:^(id, NSError *_Nullable error) {
  541. XCTAssertNil(error);
  542. [expectation fulfill];
  543. }];
  544. [self awaitExpectations];
  545. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:doc];
  546. XCTAssertEqualObjects(snapshot[@"foo"], @"bar");
  547. }
  548. - (void)testDoesNotRetryOnPermanentError {
  549. FIRFirestore *firestore = [self firestore];
  550. auto counter = std::make_shared<std::atomic_int>(0);
  551. // Make a transaction that should fail with a permanent error
  552. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  553. [firestore
  554. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  555. ++(*counter);
  556. // Get and update a document that doesn't exist so that the transaction fails.
  557. FIRDocumentReference *doc =
  558. [[firestore collectionWithPath:@"nonexistent"] documentWithAutoID];
  559. [transaction getDocument:doc error:error];
  560. [transaction updateData:@{@"count" : @(16)} forDocument:doc];
  561. return nil;
  562. }
  563. completion:^(id, NSError *_Nullable error) {
  564. [expectation fulfill];
  565. XCTAssertNotNil(error);
  566. XCTAssertEqual(error.code, FIRFirestoreErrorCodeInvalidArgument);
  567. XCTAssertEqual(counter->load(), 1);
  568. }];
  569. [self awaitExpectations];
  570. }
  571. - (void)testMakesDefaultMaxAttempts {
  572. FIRFirestore *firestore = [self firestore];
  573. FIRDocumentReference *doc1 = [[firestore collectionWithPath:@"counters"] documentWithAutoID];
  574. auto counter = std::make_shared<std::atomic_int>(0);
  575. [self writeDocumentRef:doc1 data:@{@"count" : @(15.0)}];
  576. // Skip backoff delays.
  577. [firestore workerQueue]->SkipDelaysForTimerId(TimerId::RetryTransaction);
  578. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  579. [firestore
  580. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  581. ++(*counter);
  582. // Get the first doc.
  583. [transaction getDocument:doc1 error:error];
  584. XCTAssertNil(*error);
  585. // Do a write outside of the transaction to cause the transaction to fail.
  586. dispatch_semaphore_t writeSemaphore = dispatch_semaphore_create(0);
  587. int newValue = 1234 + counter->load();
  588. [doc1 setData:@{
  589. @"count" : @(newValue)
  590. }
  591. completion:^(NSError *) {
  592. dispatch_semaphore_signal(writeSemaphore);
  593. }];
  594. // We can block on it, because transactions run on a background queue.
  595. dispatch_semaphore_wait(writeSemaphore, DISPATCH_TIME_FOREVER);
  596. return nil;
  597. }
  598. completion:^(id, NSError *_Nullable error) {
  599. [expectation fulfill];
  600. XCTAssertNotNil(error);
  601. XCTAssertEqual(error.code, FIRFirestoreErrorCodeFailedPrecondition);
  602. XCTAssertEqual(counter->load(), 5);
  603. }];
  604. [self awaitExpectations];
  605. }
  606. - (void)testSuccessWithNoTransactionOperations {
  607. FIRFirestore *firestore = [self firestore];
  608. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  609. [firestore
  610. runTransactionWithBlock:^id _Nullable(FIRTransaction *, NSError **) {
  611. return @"yes";
  612. }
  613. completion:^(id _Nullable result, NSError *_Nullable error) {
  614. XCTAssertEqualObjects(result, @"yes");
  615. XCTAssertNil(error);
  616. [expectation fulfill];
  617. }];
  618. [self awaitExpectations];
  619. }
  620. - (void)testCancellationOnError {
  621. FIRFirestore *firestore = [self firestore];
  622. FIRDocumentReference *doc = [[firestore collectionWithPath:@"towns"] documentWithAutoID];
  623. auto counter = std::make_shared<std::atomic_int>(0);
  624. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  625. [firestore
  626. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  627. ++(*counter);
  628. [transaction setData:@{@"foo" : @"bar"} forDocument:doc];
  629. if (error) {
  630. *error = [NSError errorWithDomain:NSCocoaErrorDomain code:35 userInfo:@{}];
  631. }
  632. return nil;
  633. }
  634. completion:^(id _Nullable result, NSError *_Nullable error) {
  635. XCTAssertNil(result);
  636. XCTAssertNotNil(error);
  637. XCTAssertEqual(error.code, 35);
  638. [expectation fulfill];
  639. }];
  640. [self awaitExpectations];
  641. XCTAssertEqual(counter->load(), 1);
  642. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:doc];
  643. XCTAssertFalse(snapshot.exists);
  644. }
  645. - (void)testUpdateFieldsWithDotsTransactionally {
  646. FIRDocumentReference *doc = [self documentRef];
  647. XCTestExpectation *expectation =
  648. [self expectationWithDescription:@"testUpdateFieldsWithDotsTransactionally"];
  649. [doc.firestore
  650. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  651. XCTAssertNil(*error);
  652. [transaction setData:@{@"a.b" : @"old", @"c.d" : @"old"} forDocument:doc];
  653. [transaction updateData:@{
  654. [[FIRFieldPath alloc] initWithFields:@[ @"a.b" ]] : @"new"
  655. }
  656. forDocument:doc];
  657. return nil;
  658. }
  659. completion:^(id, NSError *error) {
  660. XCTAssertNil(error);
  661. [doc getDocumentWithCompletion:^(FIRDocumentSnapshot *snapshot, NSError *error) {
  662. XCTAssertNil(error);
  663. XCTAssertEqualObjects(snapshot.data, (@{@"a.b" : @"new", @"c.d" : @"old"}));
  664. }];
  665. [expectation fulfill];
  666. }];
  667. [self awaitExpectations];
  668. }
  669. - (void)testUpdateNestedFieldsTransactionally {
  670. FIRDocumentReference *doc = [self documentRef];
  671. XCTestExpectation *expectation =
  672. [self expectationWithDescription:@"testUpdateNestedFieldsTransactionally"];
  673. [doc.firestore
  674. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  675. XCTAssertNil(*error);
  676. [transaction setData:@{
  677. @"a" : @{@"b" : @"old"},
  678. @"c" : @{@"d" : @"old"},
  679. @"e" : @{@"f" : @"old"}
  680. }
  681. forDocument:doc];
  682. [transaction updateData:@{
  683. @"a.b" : @"new",
  684. [[FIRFieldPath alloc] initWithFields:@[ @"c", @"d" ]] : @"new"
  685. }
  686. forDocument:doc];
  687. return nil;
  688. }
  689. completion:^(id, NSError *error) {
  690. XCTAssertNil(error);
  691. [doc getDocumentWithCompletion:^(FIRDocumentSnapshot *snapshot, NSError *error) {
  692. XCTAssertNil(error);
  693. XCTAssertEqualObjects(snapshot.data, (@{
  694. @"a" : @{@"b" : @"new"},
  695. @"c" : @{@"d" : @"new"},
  696. @"e" : @{@"f" : @"old"}
  697. }));
  698. }];
  699. [expectation fulfill];
  700. }];
  701. [self awaitExpectations];
  702. }
  703. @end