FSTTransactionTests.mm 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877
  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)testEmptyDoc {
  276. FIRFirestore *firestore = [self firestore];
  277. FIRDocumentReference *doc = [[firestore collectionWithPath:@"abc"] documentWithAutoID];
  278. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  279. [firestore
  280. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **errorPointer) {
  281. FIRDocumentSnapshot *sfDocument __unused = [transaction getDocument:doc error:errorPointer];
  282. // NSLog(@"document data: %@", sfDocument.data);
  283. return @YES;
  284. }
  285. completion:^(id _Nullable result, NSError *_Nullable error) {
  286. XCTAssertEqualObjects(result, @YES);
  287. XCTAssertNil(error);
  288. [expectation fulfill];
  289. }];
  290. [self awaitExpectations];
  291. }
  292. - (void)testRunsTransactionOnExistingDoc {
  293. FIRFirestore *firestore = [self firestore];
  294. FSTTransactionTester *tt = [[FSTTransactionTester alloc] initWithDb:firestore testCase:self];
  295. [[[tt withExistingDoc] runWithStages:@[ delete1, delete1 ]] expectNoDoc];
  296. [[[tt withExistingDoc] runWithStages:@[ delete1, update2 ]]
  297. expectError:FIRFirestoreErrorCodeInvalidArgument];
  298. [[[tt withExistingDoc] runWithStages:@[ delete1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  299. [[[tt withExistingDoc] runWithStages:@[ update1, delete1 ]] expectNoDoc];
  300. [[[tt withExistingDoc] runWithStages:@[ update1, update2 ]] expectDoc:@{@"foo" : @"bar2"}];
  301. [[[tt withExistingDoc] runWithStages:@[ update1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  302. [[[tt withExistingDoc] runWithStages:@[ set1, delete1 ]] expectNoDoc];
  303. [[[tt withExistingDoc] runWithStages:@[ set1, update2 ]] expectDoc:@{@"foo" : @"bar2"}];
  304. [[[tt withExistingDoc] runWithStages:@[ set1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  305. }
  306. - (void)testRunsTransactionsOnNonexistentDoc {
  307. FIRFirestore *firestore = [self firestore];
  308. FSTTransactionTester *tt = [[FSTTransactionTester alloc] initWithDb:firestore testCase:self];
  309. [[[tt withNonexistentDoc] runWithStages:@[ delete1, delete1 ]] expectNoDoc];
  310. [[[tt withNonexistentDoc] runWithStages:@[ delete1, update2 ]]
  311. expectError:FIRFirestoreErrorCodeInvalidArgument];
  312. [[[tt withNonexistentDoc] runWithStages:@[ delete1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  313. [[[tt withNonexistentDoc] runWithStages:@[ update1, delete1 ]]
  314. expectError:FIRFirestoreErrorCodeNotFound];
  315. [[[tt withNonexistentDoc] runWithStages:@[ update1, update2 ]]
  316. expectError:FIRFirestoreErrorCodeNotFound];
  317. [[[tt withNonexistentDoc] runWithStages:@[ update1, set2 ]]
  318. expectError:FIRFirestoreErrorCodeNotFound];
  319. [[[tt withNonexistentDoc] runWithStages:@[ set1, delete1 ]] expectNoDoc];
  320. [[[tt withNonexistentDoc] runWithStages:@[ set1, update2 ]] expectDoc:@{@"foo" : @"bar2"}];
  321. [[[tt withNonexistentDoc] runWithStages:@[ set1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  322. }
  323. - (void)testSetDocumentWithMerge {
  324. FIRFirestore *firestore = [self firestore];
  325. FIRDocumentReference *doc = [[firestore collectionWithPath:@"towns"] documentWithAutoID];
  326. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  327. [firestore
  328. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **) {
  329. [transaction setData:@{@"a" : @"b", @"nested" : @{@"a" : @"b"}} forDocument:doc];
  330. [transaction setData:@{@"c" : @"d", @"nested" : @{@"c" : @"d"}} forDocument:doc merge:YES];
  331. return @YES;
  332. }
  333. completion:^(id _Nullable result, NSError *_Nullable error) {
  334. XCTAssertEqualObjects(result, @YES);
  335. XCTAssertNil(error);
  336. [expectation fulfill];
  337. }];
  338. [self awaitExpectations];
  339. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:doc];
  340. XCTAssertEqualObjects(snapshot.data,
  341. (@{@"a" : @"b", @"c" : @"d", @"nested" : @{@"a" : @"b", @"c" : @"d"}}));
  342. }
  343. - (void)testIncrementTransactionally {
  344. // A barrier to make sure every transaction reaches the same spot.
  345. dispatch_semaphore_t writeBarrier = dispatch_semaphore_create(0);
  346. auto counter = std::make_shared<std::atomic_int>(0);
  347. FIRFirestore *firestore = [self firestore];
  348. FIRDocumentReference *doc = [[firestore collectionWithPath:@"counters"] documentWithAutoID];
  349. [self writeDocumentRef:doc data:@{@"count" : @(5.0)}];
  350. // Skip backoff delays.
  351. [firestore workerQueue]->SkipDelaysForTimerId(TimerId::RetryTransaction);
  352. // Make 3 transactions that will all increment.
  353. int total = 3;
  354. for (int i = 0; i < total; i++) {
  355. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  356. [firestore
  357. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  358. FIRDocumentSnapshot *snapshot = [transaction getDocument:doc error:error];
  359. XCTAssertNil(*error);
  360. (*counter)++;
  361. // Once all of the transactions have read, allow the first write.
  362. if (*counter == total) {
  363. dispatch_semaphore_signal(writeBarrier);
  364. }
  365. dispatch_semaphore_wait(writeBarrier, DISPATCH_TIME_FOREVER);
  366. // Refill the barrier so that the other transactions and retries succeed.
  367. dispatch_semaphore_signal(writeBarrier);
  368. double newCount = ((NSNumber *)snapshot[@"count"]).doubleValue + 1.0;
  369. [transaction setData:@{@"count" : @(newCount)} forDocument:doc];
  370. return @YES;
  371. }
  372. completion:^(id, NSError *) {
  373. [expectation fulfill];
  374. }];
  375. }
  376. [self awaitExpectations];
  377. // Now all transaction should be completed, so check the result.
  378. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:doc];
  379. XCTAssertEqualObjects(snapshot[@"count"], @(5.0 + total));
  380. }
  381. - (void)testUpdateTransactionally {
  382. // A barrier to make sure every transaction reaches the same spot.
  383. dispatch_semaphore_t writeBarrier = dispatch_semaphore_create(0);
  384. auto counter = std::make_shared<std::atomic_int>(0);
  385. FIRFirestore *firestore = [self firestore];
  386. FIRDocumentReference *doc = [[firestore collectionWithPath:@"counters"] documentWithAutoID];
  387. [self writeDocumentRef:doc data:@{@"count" : @(5.0), @"other" : @"yes"}];
  388. // Skip backoff delays.
  389. [firestore workerQueue]->SkipDelaysForTimerId(TimerId::RetryTransaction);
  390. // Make 3 transactions that will all increment.
  391. int total = 3;
  392. for (int i = 0; i < total; i++) {
  393. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  394. [firestore
  395. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  396. int32_t nowStarted = ++(*counter);
  397. FIRDocumentSnapshot *snapshot = [transaction getDocument:doc error:error];
  398. XCTAssertNil(*error);
  399. // Once all of the transactions have read, allow the first write. There should be 3
  400. // initial transaction runs.
  401. if (nowStarted == total) {
  402. XCTAssertEqual(counter->load(), 3);
  403. dispatch_semaphore_signal(writeBarrier);
  404. }
  405. dispatch_semaphore_wait(writeBarrier, DISPATCH_TIME_FOREVER);
  406. // Refill the barrier so that the other transactions and retries succeed.
  407. dispatch_semaphore_signal(writeBarrier);
  408. double newCount = ((NSNumber *)snapshot[@"count"]).doubleValue + 1.0;
  409. [transaction updateData:@{@"count" : @(newCount)} forDocument:doc];
  410. return @YES;
  411. }
  412. completion:^(id, NSError *) {
  413. [expectation fulfill];
  414. }];
  415. }
  416. [self awaitExpectations];
  417. // There should be a maximum of 3 retries: once for the 2nd update, and twice for the 3rd update.
  418. XCTAssertLessThanOrEqual(counter->load(), 6);
  419. // Now all transaction should be completed, so check the result.
  420. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:doc];
  421. XCTAssertEqualObjects(snapshot[@"count"], @(5.0 + total));
  422. XCTAssertEqualObjects(@"yes", snapshot[@"other"]);
  423. }
  424. - (void)testRetriesWhenDocumentThatWasReadWithoutBeingWrittenChanges {
  425. FIRFirestore *firestore = [self firestore];
  426. FIRDocumentReference *doc1 = [[firestore collectionWithPath:@"counters"] documentWithAutoID];
  427. FIRDocumentReference *doc2 = [[firestore collectionWithPath:@"counters"] documentWithAutoID];
  428. auto counter = std::make_shared<std::atomic_int>(0);
  429. [self writeDocumentRef:doc1 data:@{@"count" : @(15.0)}];
  430. // Skip backoff delays.
  431. [firestore workerQueue]->SkipDelaysForTimerId(TimerId::RetryTransaction);
  432. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  433. [firestore
  434. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  435. ++(*counter);
  436. // Get the first doc.
  437. [transaction getDocument:doc1 error:error];
  438. XCTAssertNil(*error);
  439. // Do a write outside of the transaction. The first time the
  440. // transaction is tried, this will bump the version, which
  441. // will cause the write to doc2 to fail. The second time, it
  442. // will be a no-op and not bump the version.
  443. dispatch_semaphore_t writeSemaphore = dispatch_semaphore_create(0);
  444. [doc1 setData:@{
  445. @"count" : @(1234)
  446. }
  447. completion:^(NSError *) {
  448. dispatch_semaphore_signal(writeSemaphore);
  449. }];
  450. // We can block on it, because transactions run on a background queue.
  451. dispatch_semaphore_wait(writeSemaphore, DISPATCH_TIME_FOREVER);
  452. // Now try to update the other doc from within the transaction.
  453. // This should fail once, because we read 15 earlier.
  454. [transaction setData:@{@"count" : @(16)} forDocument:doc2];
  455. return nil;
  456. }
  457. completion:^(id, NSError *_Nullable error) {
  458. XCTAssertNil(error);
  459. XCTAssertEqual(counter->load(), 2);
  460. [expectation fulfill];
  461. }];
  462. [self awaitExpectations];
  463. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:doc1];
  464. XCTAssertEqualObjects(snapshot[@"count"], @(1234));
  465. }
  466. - (void)testReadingADocTwiceWithDifferentVersions {
  467. FIRFirestore *firestore = [self firestore];
  468. FIRDocumentReference *doc = [[firestore collectionWithPath:@"counters"] documentWithAutoID];
  469. auto counter = std::make_shared<std::atomic_int>(0);
  470. [self writeDocumentRef:doc data:@{@"count" : @(15.0)}];
  471. // Skip backoff delays.
  472. [firestore workerQueue]->SkipDelaysForTimerId(TimerId::RetryTransaction);
  473. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  474. [firestore
  475. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  476. ++(*counter);
  477. // Get the doc once.
  478. FIRDocumentSnapshot *snapshot = [transaction getDocument:doc error:error];
  479. XCTAssertNotNil(snapshot);
  480. XCTAssertNil(*error);
  481. // Do a write outside of the transaction. Because the transaction will retry, set the
  482. // document to a different value each time.
  483. dispatch_semaphore_t writeSemaphore = dispatch_semaphore_create(0);
  484. [doc setData:@{
  485. @"count" : @(1234 + (int)(*counter))
  486. }
  487. completion:^(NSError *) {
  488. dispatch_semaphore_signal(writeSemaphore);
  489. }];
  490. // We can block on it, because transactions run on a background queue.
  491. dispatch_semaphore_wait(writeSemaphore, DISPATCH_TIME_FOREVER);
  492. // Get the doc again in the transaction with the new version.
  493. snapshot = [transaction getDocument:doc error:error];
  494. // The get itself will fail, because we already read an earlier version of this document.
  495. // TODO(klimt): Perhaps we shouldn't fail reads for this, but should wait and fail the
  496. // whole transaction? It's an edge-case anyway, as developers shouldn't be reading the same
  497. // doc multiple times. But they need to handle read errors anyway.
  498. XCTAssertNil(snapshot);
  499. XCTAssertNotNil(*error);
  500. return nil;
  501. }
  502. completion:^(id, NSError *_Nullable error) {
  503. [expectation fulfill];
  504. XCTAssertNotNil(error);
  505. XCTAssertEqual(error.code, FIRFirestoreErrorCodeAborted);
  506. }];
  507. [self awaitExpectations];
  508. }
  509. - (void)testReadAndUpdateNonExistentDocumentWithExternalWrite {
  510. FIRFirestore *firestore = [self firestore];
  511. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  512. [firestore
  513. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  514. // Get and update a document that doesn't exist so that the transaction fails.
  515. FIRDocumentReference *doc =
  516. [[firestore collectionWithPath:@"nonexistent"] documentWithAutoID];
  517. [transaction getDocument:doc error:error];
  518. XCTAssertNil(*error);
  519. // Do a write outside of the transaction.
  520. dispatch_semaphore_t writeSemaphore = dispatch_semaphore_create(0);
  521. [doc setData:@{
  522. @"count" : @(1234)
  523. }
  524. completion:^(NSError *) {
  525. dispatch_semaphore_signal(writeSemaphore);
  526. }];
  527. // We can block on it, because transactions run on a background queue.
  528. dispatch_semaphore_wait(writeSemaphore, DISPATCH_TIME_FOREVER);
  529. // Now try to update the other doc from within the transaction.
  530. // This should fail, because the document didn't exist at the
  531. // start of the transaction.
  532. [transaction updateData:@{@"count" : @(16)} forDocument:doc];
  533. return nil;
  534. }
  535. completion:^(id, NSError *_Nullable error) {
  536. [expectation fulfill];
  537. XCTAssertNotNil(error);
  538. XCTAssertEqual(error.code, FIRFirestoreErrorCodeInvalidArgument);
  539. }];
  540. [self awaitExpectations];
  541. }
  542. - (void)testCanHaveGetsWithoutMutations {
  543. FIRFirestore *firestore = [self firestore];
  544. FIRDocumentReference *doc = [[firestore collectionWithPath:@"foo"] documentWithAutoID];
  545. FIRDocumentReference *doc2 = [[firestore collectionWithPath:@"foo"] documentWithAutoID];
  546. [self writeDocumentRef:doc data:@{@"foo" : @"bar"}];
  547. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  548. [firestore
  549. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  550. [transaction getDocument:doc2 error:error];
  551. [transaction getDocument:doc error:error];
  552. return nil;
  553. }
  554. completion:^(id, NSError *_Nullable error) {
  555. XCTAssertNil(error);
  556. [expectation fulfill];
  557. }];
  558. [self awaitExpectations];
  559. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:doc];
  560. XCTAssertEqualObjects(snapshot[@"foo"], @"bar");
  561. }
  562. - (void)testDoesNotRetryOnPermanentError {
  563. FIRFirestore *firestore = [self firestore];
  564. auto counter = std::make_shared<std::atomic_int>(0);
  565. // Make a transaction that should fail with a permanent error
  566. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  567. [firestore
  568. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  569. ++(*counter);
  570. // Get and update a document that doesn't exist so that the transaction fails.
  571. FIRDocumentReference *doc =
  572. [[firestore collectionWithPath:@"nonexistent"] documentWithAutoID];
  573. [transaction getDocument:doc error:error];
  574. [transaction updateData:@{@"count" : @(16)} forDocument:doc];
  575. return nil;
  576. }
  577. completion:^(id, NSError *_Nullable error) {
  578. [expectation fulfill];
  579. XCTAssertNotNil(error);
  580. XCTAssertEqual(error.code, FIRFirestoreErrorCodeInvalidArgument);
  581. XCTAssertEqual(counter->load(), 1);
  582. }];
  583. [self awaitExpectations];
  584. }
  585. - (void)testMakesDefaultMaxAttempts {
  586. FIRFirestore *firestore = [self firestore];
  587. FIRDocumentReference *doc1 = [[firestore collectionWithPath:@"counters"] documentWithAutoID];
  588. auto counter = std::make_shared<std::atomic_int>(0);
  589. [self writeDocumentRef:doc1 data:@{@"count" : @(15.0)}];
  590. // Skip backoff delays.
  591. [firestore workerQueue]->SkipDelaysForTimerId(TimerId::RetryTransaction);
  592. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  593. [firestore
  594. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  595. ++(*counter);
  596. // Get the first doc.
  597. [transaction getDocument:doc1 error:error];
  598. XCTAssertNil(*error);
  599. // Do a write outside of the transaction to cause the transaction to fail.
  600. dispatch_semaphore_t writeSemaphore = dispatch_semaphore_create(0);
  601. int newValue = 1234 + counter->load();
  602. [doc1 setData:@{
  603. @"count" : @(newValue)
  604. }
  605. completion:^(NSError *) {
  606. dispatch_semaphore_signal(writeSemaphore);
  607. }];
  608. // We can block on it, because transactions run on a background queue.
  609. dispatch_semaphore_wait(writeSemaphore, DISPATCH_TIME_FOREVER);
  610. return nil;
  611. }
  612. completion:^(id, NSError *_Nullable error) {
  613. [expectation fulfill];
  614. XCTAssertNotNil(error);
  615. XCTAssertEqual(error.code, FIRFirestoreErrorCodeFailedPrecondition);
  616. XCTAssertEqual(counter->load(), 5);
  617. }];
  618. [self awaitExpectations];
  619. }
  620. - (void)testSuccessWithNoTransactionOperations {
  621. FIRFirestore *firestore = [self firestore];
  622. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  623. [firestore
  624. runTransactionWithBlock:^id _Nullable(FIRTransaction *, NSError **) {
  625. return @"yes";
  626. }
  627. completion:^(id _Nullable result, NSError *_Nullable error) {
  628. XCTAssertEqualObjects(result, @"yes");
  629. XCTAssertNil(error);
  630. [expectation fulfill];
  631. }];
  632. [self awaitExpectations];
  633. }
  634. - (void)testCancellationOnError {
  635. FIRFirestore *firestore = [self firestore];
  636. FIRDocumentReference *doc = [[firestore collectionWithPath:@"towns"] documentWithAutoID];
  637. auto counter = std::make_shared<std::atomic_int>(0);
  638. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  639. [firestore
  640. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  641. ++(*counter);
  642. [transaction setData:@{@"foo" : @"bar"} forDocument:doc];
  643. if (error) {
  644. *error = [NSError errorWithDomain:NSCocoaErrorDomain code:35 userInfo:@{}];
  645. }
  646. return nil;
  647. }
  648. completion:^(id _Nullable result, NSError *_Nullable error) {
  649. XCTAssertNil(result);
  650. XCTAssertNotNil(error);
  651. XCTAssertEqual(error.code, 35);
  652. [expectation fulfill];
  653. }];
  654. [self awaitExpectations];
  655. XCTAssertEqual(counter->load(), 1);
  656. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:doc];
  657. XCTAssertFalse(snapshot.exists);
  658. }
  659. - (void)testUpdateFieldsWithDotsTransactionally {
  660. FIRDocumentReference *doc = [self documentRef];
  661. XCTestExpectation *expectation =
  662. [self expectationWithDescription:@"testUpdateFieldsWithDotsTransactionally"];
  663. [doc.firestore
  664. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  665. XCTAssertNil(*error);
  666. [transaction setData:@{@"a.b" : @"old", @"c.d" : @"old"} forDocument:doc];
  667. [transaction updateData:@{
  668. [[FIRFieldPath alloc] initWithFields:@[ @"a.b" ]] : @"new"
  669. }
  670. forDocument:doc];
  671. return nil;
  672. }
  673. completion:^(id, NSError *error) {
  674. XCTAssertNil(error);
  675. [doc getDocumentWithCompletion:^(FIRDocumentSnapshot *snapshot, NSError *error) {
  676. XCTAssertNil(error);
  677. XCTAssertEqualObjects(snapshot.data, (@{@"a.b" : @"new", @"c.d" : @"old"}));
  678. }];
  679. [expectation fulfill];
  680. }];
  681. [self awaitExpectations];
  682. }
  683. - (void)testUpdateNestedFieldsTransactionally {
  684. FIRDocumentReference *doc = [self documentRef];
  685. XCTestExpectation *expectation =
  686. [self expectationWithDescription:@"testUpdateNestedFieldsTransactionally"];
  687. [doc.firestore
  688. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  689. XCTAssertNil(*error);
  690. [transaction setData:@{
  691. @"a" : @{@"b" : @"old"},
  692. @"c" : @{@"d" : @"old"},
  693. @"e" : @{@"f" : @"old"}
  694. }
  695. forDocument:doc];
  696. [transaction updateData:@{
  697. @"a.b" : @"new",
  698. [[FIRFieldPath alloc] initWithFields:@[ @"c", @"d" ]] : @"new"
  699. }
  700. forDocument:doc];
  701. return nil;
  702. }
  703. completion:^(id, NSError *error) {
  704. XCTAssertNil(error);
  705. [doc getDocumentWithCompletion:^(FIRDocumentSnapshot *snapshot, NSError *error) {
  706. XCTAssertNil(error);
  707. XCTAssertEqualObjects(snapshot.data, (@{
  708. @"a" : @{@"b" : @"new"},
  709. @"c" : @{@"d" : @"new"},
  710. @"e" : @{@"f" : @"old"}
  711. }));
  712. }];
  713. [expectation fulfill];
  714. }];
  715. [self awaitExpectations];
  716. }
  717. - (void)runFailedPreconditionTransactionWithOptions:(FIRTransactionOptions *_Nullable)options
  718. expectNumAttempts:(int)expectedNumAttempts {
  719. // Note: The logic below to force retries is heavily based on
  720. // testRetriesWhenDocumentThatWasReadWithoutBeingWrittenChanges.
  721. FIRFirestore *firestore = [self firestore];
  722. FIRDocumentReference *doc = [[firestore collectionWithPath:@"counters"] documentWithAutoID];
  723. auto attemptCount = std::make_shared<std::atomic_int>(0);
  724. attemptCount->store(0);
  725. [self writeDocumentRef:doc data:@{@"count" : @"initial value"}];
  726. // Skip backoff delays.
  727. [firestore workerQueue]->SkipDelaysForTimerId(TimerId::RetryTransaction);
  728. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  729. [firestore runTransactionWithOptions:options
  730. block:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  731. ++(*attemptCount);
  732. [transaction getDocument:doc error:error];
  733. XCTAssertNil(*error);
  734. // Do a write outside of the transaction. This will force the transaction to be retried.
  735. dispatch_semaphore_t writeSemaphore = dispatch_semaphore_create(0);
  736. [doc setData:@{
  737. @"count" : @(attemptCount->load())
  738. }
  739. completion:^(NSError *) {
  740. dispatch_semaphore_signal(writeSemaphore);
  741. }];
  742. dispatch_semaphore_wait(writeSemaphore, DISPATCH_TIME_FOREVER);
  743. // Now try to update the doc from within the transaction.
  744. // This will fail since the document was modified outside of the transaction.
  745. [transaction setData:@{@"count" : @"this write should fail"} forDocument:doc];
  746. return nil;
  747. }
  748. completion:^(id, NSError *_Nullable error) {
  749. [self assertError:error
  750. message:@"the transaction should fail due to retries exhausted"
  751. code:FIRFirestoreErrorCodeFailedPrecondition];
  752. XCTAssertEqual(attemptCount->load(), expectedNumAttempts);
  753. [expectation fulfill];
  754. }];
  755. [self awaitExpectations];
  756. }
  757. - (void)testTransactionOptionsNil {
  758. [self runFailedPreconditionTransactionWithOptions:nil expectNumAttempts:5];
  759. }
  760. - (void)testTransactionOptionsMaxAttempts {
  761. FIRTransactionOptions *options = [[FIRTransactionOptions alloc] init];
  762. options.maxAttempts = 7;
  763. [self runFailedPreconditionTransactionWithOptions:options expectNumAttempts:7];
  764. }
  765. @end