FSTTransactionTests.mm 34 KB

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