FSTTransactionTests.mm 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  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;
  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 {
  50. XCTAssertNotNil(error, @"%@", message);
  51. }
  52. - (void)assertSnapshot:(FIRDocumentSnapshot *)snapshot
  53. equalsObject:(NSObject *)expected
  54. error:(NSError *)error {
  55. XCTAssertNil(error);
  56. XCTAssertTrue(snapshot.exists);
  57. XCTAssertEqualObjects(expected, snapshot.data);
  58. }
  59. @end
  60. typedef void (^TransactionStage)(FIRTransaction *, FIRDocumentReference *);
  61. /**
  62. * The transaction stages that follow are postfixed by numbers to indicate the calling order. For
  63. * example, calling `set1` followed by `set2` should result in the document being set to the value
  64. * specified by `set2`.
  65. */
  66. TransactionStage delete1 = ^(FIRTransaction *transaction, FIRDocumentReference *doc) {
  67. [transaction deleteDocument:doc];
  68. };
  69. TransactionStage update1 = ^(FIRTransaction *transaction, FIRDocumentReference *doc) {
  70. [transaction updateData:@{@"foo" : @"bar1"} forDocument:doc];
  71. };
  72. TransactionStage update2 = ^(FIRTransaction *transaction, FIRDocumentReference *doc) {
  73. [transaction updateData:@{@"foo" : @"bar2"} forDocument:doc];
  74. };
  75. TransactionStage set1 = ^(FIRTransaction *transaction, FIRDocumentReference *doc) {
  76. [transaction setData:@{@"foo" : @"bar1"} forDocument:doc];
  77. };
  78. TransactionStage set2 = ^(FIRTransaction *transaction, FIRDocumentReference *doc) {
  79. [transaction setData:@{@"foo" : @"bar2"} forDocument:doc];
  80. };
  81. TransactionStage get = ^(FIRTransaction *transaction, FIRDocumentReference *doc) {
  82. NSError *error = nil;
  83. [transaction getDocument:doc error:&error];
  84. };
  85. /**
  86. * Used for testing that all possible combinations of executing transactions result in the desired
  87. * document value or error.
  88. *
  89. * `runWithStages`, `withExistingDoc`, and `withNonexistentDoc` don't actually do anything except
  90. * assign variables into `FSTTransactionTester`.
  91. *
  92. * `expectDoc`, `expectNoDoc`, and `expectError` will trigger the transaction to run and assert
  93. * that the end result matches the input.
  94. */
  95. @interface FSTTransactionTester : NSObject
  96. - (FSTTransactionTester *)withExistingDoc;
  97. - (FSTTransactionTester *)withNonexistentDoc;
  98. - (FSTTransactionTester *)runWithStages:(NSArray<TransactionStage> *)stages;
  99. - (void)expectDoc:(NSObject *)expected;
  100. - (void)expectNoDoc;
  101. - (void)expectError:(FIRFirestoreErrorCode)expected;
  102. @end
  103. @implementation FSTTransactionTester {
  104. FIRFirestore *_db;
  105. FIRDocumentReference *_docRef;
  106. BOOL _fromExistingDoc;
  107. NSArray<TransactionStage> *_stages;
  108. FSTTransactionTests *_testCase;
  109. NSMutableArray<XCTestExpectation *> *_testExpectations;
  110. }
  111. - (instancetype)initWithDb:(FIRFirestore *)db testCase:(FSTTransactionTests *)testCase {
  112. self = [super init];
  113. if (self) {
  114. _db = db;
  115. _stages = [NSArray array];
  116. _testCase = testCase;
  117. _testExpectations = [NSMutableArray array];
  118. }
  119. return self;
  120. }
  121. - (FSTTransactionTester *)withExistingDoc {
  122. _fromExistingDoc = YES;
  123. return self;
  124. }
  125. - (FSTTransactionTester *)withNonexistentDoc {
  126. _fromExistingDoc = NO;
  127. return self;
  128. }
  129. - (FSTTransactionTester *)runWithStages:(NSArray<TransactionStage> *)stages {
  130. _stages = stages;
  131. return self;
  132. }
  133. - (void)expectDoc:(NSObject *)expected {
  134. [self prepareDoc];
  135. [self runSuccessfulTransaction];
  136. XCTestExpectation *expectation = [_testCase expectationWithDescription:@"expectDoc"];
  137. [_docRef getDocumentWithCompletion:^(FIRDocumentSnapshot *snapshot, NSError *error) {
  138. [self->_testCase assertSnapshot:snapshot equalsObject:expected error:error];
  139. [expectation fulfill];
  140. }];
  141. [_testCase awaitExpectations];
  142. [self cleanupTester];
  143. }
  144. - (void)expectNoDoc {
  145. [self prepareDoc];
  146. [self runSuccessfulTransaction];
  147. XCTestExpectation *expectation = [_testCase expectationWithDescription:@"expectNoDoc"];
  148. [_docRef getDocumentWithCompletion:^(FIRDocumentSnapshot *snapshot, NSError *error) {
  149. [self->_testCase assertDoesNotExistWithSnapshot:snapshot error:error];
  150. [expectation fulfill];
  151. }];
  152. [_testCase awaitExpectations];
  153. [self cleanupTester];
  154. }
  155. - (void)expectError:(FIRFirestoreErrorCode)expected {
  156. [self prepareDoc];
  157. [self runFailingTransactionWithError:expected];
  158. [self cleanupTester];
  159. }
  160. - (void)prepareDoc {
  161. _docRef = [[_db collectionWithPath:@"nonexistent"] documentWithAutoID];
  162. if (_fromExistingDoc) {
  163. NSError *setError = [self writeDocumentRef:_docRef data:@{@"foo" : @"bar"}];
  164. NSString *message = [NSString stringWithFormat:@"Failed set at %@", [self stageNames]];
  165. [_testCase assertNilError:setError message:message];
  166. XCTestExpectation *expectation = [_testCase expectationWithDescription:@"prepareDoc:get"];
  167. [_docRef getDocumentWithCompletion:^(FIRDocumentSnapshot *snapshot, NSError *error) {
  168. [self->_testCase assertExistsWithSnapshot:snapshot error:error];
  169. [expectation fulfill];
  170. }];
  171. [_testCase awaitExpectations];
  172. }
  173. }
  174. - (NSError *)writeDocumentRef:(FIRDocumentReference *)ref
  175. data:(NSDictionary<NSString *, id> *)data {
  176. __block NSError *errorResult;
  177. XCTestExpectation *expectation = [_testCase expectationWithDescription:@"prepareDoc:set"];
  178. [_docRef setData:data
  179. completion:^(NSError *error) {
  180. errorResult = error;
  181. [expectation fulfill];
  182. }];
  183. [_testCase awaitExpectations];
  184. return errorResult;
  185. }
  186. - (void)runSuccessfulTransaction {
  187. XCTestExpectation *expectation =
  188. [_testCase expectationWithDescription:@"runSuccessfulTransaction"];
  189. [_db
  190. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  191. for (TransactionStage stage in self->_stages) {
  192. stage(transaction, self->_docRef);
  193. }
  194. return @YES;
  195. }
  196. completion:^(id _Nullable result, NSError *_Nullable error) {
  197. [expectation fulfill];
  198. NSString *message =
  199. [NSString stringWithFormat:@"Expected the sequence %@, to succeed, but got %d.",
  200. [self stageNames], (int)[error code]];
  201. [self->_testCase assertNilError:error message:message];
  202. }];
  203. [_testCase awaitExpectations];
  204. }
  205. - (void)runFailingTransactionWithError:(FIRFirestoreErrorCode)expected {
  206. XCTestExpectation *expectation =
  207. [_testCase expectationWithDescription:@"runFailingTransactionWithError"];
  208. [_db
  209. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  210. for (TransactionStage stage in self->_stages) {
  211. stage(transaction, self->_docRef);
  212. }
  213. return @YES;
  214. }
  215. completion:^(id _Nullable result, NSError *_Nullable error) {
  216. [expectation fulfill];
  217. NSString *message =
  218. [NSString stringWithFormat:@"Expected the sequence (%@), to fail, but it didn't.",
  219. [self stageNames]];
  220. [self->_testCase assertError:error message:message];
  221. }];
  222. [_testCase awaitExpectations];
  223. }
  224. - (void)cleanupTester {
  225. _stages = [NSArray array];
  226. // Set the docRef to something else to lose the original reference.
  227. _docRef = [[self->_db collectionWithPath:@"reset"] documentWithAutoID];
  228. }
  229. - (NSString *)stageNames {
  230. NSMutableArray<NSString *> *seqList = [NSMutableArray array];
  231. for (TransactionStage stage in _stages) {
  232. if (stage == delete1) {
  233. [seqList addObject:@"delete"];
  234. } else if (stage == update1 || stage == update2) {
  235. [seqList addObject:@"update"];
  236. } else if (stage == set1 || stage == set2) {
  237. [seqList addObject:@"set"];
  238. } else if (stage == get) {
  239. [seqList addObject:@"get"];
  240. }
  241. }
  242. return [seqList description];
  243. }
  244. @end
  245. @implementation FSTTransactionTests
  246. - (void)testRunsTransactionsAfterGettingExistingDoc {
  247. FIRFirestore *firestore = [self firestore];
  248. FSTTransactionTester *tt = [[FSTTransactionTester alloc] initWithDb:firestore testCase:self];
  249. [[[tt withExistingDoc] runWithStages:@[ get, delete1, delete1 ]] expectNoDoc];
  250. [[[tt withExistingDoc] runWithStages:@[ get, delete1, update2 ]]
  251. expectError:FIRFirestoreErrorCodeInvalidArgument];
  252. [[[tt withExistingDoc] runWithStages:@[ get, delete1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  253. [[[tt withExistingDoc] runWithStages:@[ get, update1, delete1 ]] expectNoDoc];
  254. [[[tt withExistingDoc] runWithStages:@[ get, update1, update2 ]] expectDoc:@{@"foo" : @"bar2"}];
  255. [[[tt withExistingDoc] runWithStages:@[ get, update1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  256. [[[tt withExistingDoc] runWithStages:@[ get, set1, delete1 ]] expectNoDoc];
  257. [[[tt withExistingDoc] runWithStages:@[ get, set1, update2 ]] expectDoc:@{@"foo" : @"bar2"}];
  258. [[[tt withExistingDoc] runWithStages:@[ get, set1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  259. }
  260. - (void)testRunsTransactionsAfterGettingNonexistentDoc {
  261. FIRFirestore *firestore = [self firestore];
  262. FSTTransactionTester *tt = [[FSTTransactionTester alloc] initWithDb:firestore testCase:self];
  263. [[[tt withNonexistentDoc] runWithStages:@[ get, delete1, delete1 ]] expectNoDoc];
  264. [[[tt withNonexistentDoc] runWithStages:@[ get, delete1, update2 ]]
  265. expectError:FIRFirestoreErrorCodeInvalidArgument];
  266. [[[tt withNonexistentDoc] runWithStages:@[ get, delete1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  267. [[[tt withNonexistentDoc] runWithStages:@[ get, update1, delete1 ]]
  268. expectError:FIRFirestoreErrorCodeInvalidArgument];
  269. [[[tt withNonexistentDoc] runWithStages:@[ get, update1, update2 ]]
  270. expectError:FIRFirestoreErrorCodeInvalidArgument];
  271. [[[tt withNonexistentDoc] runWithStages:@[ get, update1, set2 ]]
  272. expectError:FIRFirestoreErrorCodeInvalidArgument];
  273. [[[tt withNonexistentDoc] runWithStages:@[ get, set1, delete1 ]] expectNoDoc];
  274. [[[tt withNonexistentDoc] runWithStages:@[ get, set1, update2 ]] expectDoc:@{@"foo" : @"bar2"}];
  275. [[[tt withNonexistentDoc] runWithStages:@[ get, set1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  276. }
  277. - (void)testRunsTransactionOnExistingDoc {
  278. FIRFirestore *firestore = [self firestore];
  279. FSTTransactionTester *tt = [[FSTTransactionTester alloc] initWithDb:firestore testCase:self];
  280. [[[tt withExistingDoc] runWithStages:@[ delete1, delete1 ]] expectNoDoc];
  281. [[[tt withExistingDoc] runWithStages:@[ delete1, update2 ]]
  282. expectError:FIRFirestoreErrorCodeInvalidArgument];
  283. [[[tt withExistingDoc] runWithStages:@[ delete1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  284. [[[tt withExistingDoc] runWithStages:@[ update1, delete1 ]] expectNoDoc];
  285. [[[tt withExistingDoc] runWithStages:@[ update1, update2 ]] expectDoc:@{@"foo" : @"bar2"}];
  286. [[[tt withExistingDoc] runWithStages:@[ update1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  287. [[[tt withExistingDoc] runWithStages:@[ set1, delete1 ]] expectNoDoc];
  288. [[[tt withExistingDoc] runWithStages:@[ set1, update2 ]] expectDoc:@{@"foo" : @"bar2"}];
  289. [[[tt withExistingDoc] runWithStages:@[ set1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  290. }
  291. - (void)testRunsTransactionsOnNonexistentDoc {
  292. FIRFirestore *firestore = [self firestore];
  293. FSTTransactionTester *tt = [[FSTTransactionTester alloc] initWithDb:firestore testCase:self];
  294. [[[tt withNonexistentDoc] runWithStages:@[ delete1, delete1 ]] expectNoDoc];
  295. [[[tt withNonexistentDoc] runWithStages:@[ delete1, update2 ]]
  296. expectError:FIRFirestoreErrorCodeInvalidArgument];
  297. [[[tt withNonexistentDoc] runWithStages:@[ delete1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  298. [[[tt withNonexistentDoc] runWithStages:@[ update1, delete1 ]]
  299. expectError:FIRFirestoreErrorCodeNotFound];
  300. [[[tt withNonexistentDoc] runWithStages:@[ update1, update2 ]]
  301. expectError:FIRFirestoreErrorCodeNotFound];
  302. [[[tt withNonexistentDoc] runWithStages:@[ update1, set2 ]]
  303. expectError:FIRFirestoreErrorCodeNotFound];
  304. [[[tt withNonexistentDoc] runWithStages:@[ set1, delete1 ]] expectNoDoc];
  305. [[[tt withNonexistentDoc] runWithStages:@[ set1, update2 ]] expectDoc:@{@"foo" : @"bar2"}];
  306. [[[tt withNonexistentDoc] runWithStages:@[ set1, set2 ]] expectDoc:@{@"foo" : @"bar2"}];
  307. }
  308. - (void)testSetDocumentWithMerge {
  309. FIRFirestore *firestore = [self firestore];
  310. FIRDocumentReference *doc = [[firestore collectionWithPath:@"towns"] documentWithAutoID];
  311. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  312. [firestore
  313. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  314. [transaction setData:@{@"a" : @"b", @"nested" : @{@"a" : @"b"}} forDocument:doc];
  315. [transaction setData:@{@"c" : @"d", @"nested" : @{@"c" : @"d"}} forDocument:doc merge:YES];
  316. return @YES;
  317. }
  318. completion:^(id _Nullable result, NSError *_Nullable error) {
  319. XCTAssertEqualObjects(result, @YES);
  320. XCTAssertNil(error);
  321. [expectation fulfill];
  322. }];
  323. [self awaitExpectations];
  324. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:doc];
  325. XCTAssertEqualObjects(snapshot.data,
  326. (@{@"a" : @"b", @"c" : @"d", @"nested" : @{@"a" : @"b", @"c" : @"d"}}));
  327. }
  328. - (void)testIncrementTransactionally {
  329. // A barrier to make sure every transaction reaches the same spot.
  330. dispatch_semaphore_t writeBarrier = dispatch_semaphore_create(0);
  331. auto counter = std::make_shared<std::atomic_int>(0);
  332. FIRFirestore *firestore = [self firestore];
  333. FIRDocumentReference *doc = [[firestore collectionWithPath:@"counters"] documentWithAutoID];
  334. [self writeDocumentRef:doc data:@{@"count" : @(5.0)}];
  335. // Skip backoff delays.
  336. [firestore workerQueue]->SkipDelaysForTimerId(TimerId::RetryTransaction);
  337. // Make 3 transactions that will all increment.
  338. int total = 3;
  339. for (int i = 0; i < total; i++) {
  340. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  341. [firestore
  342. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  343. FIRDocumentSnapshot *snapshot = [transaction getDocument:doc error:error];
  344. XCTAssertNil(*error);
  345. (*counter)++;
  346. // Once all of the transactions have read, allow the first write.
  347. if (*counter == total) {
  348. dispatch_semaphore_signal(writeBarrier);
  349. }
  350. dispatch_semaphore_wait(writeBarrier, DISPATCH_TIME_FOREVER);
  351. // Refill the barrier so that the other transactions and retries succeed.
  352. dispatch_semaphore_signal(writeBarrier);
  353. double newCount = ((NSNumber *)snapshot[@"count"]).doubleValue + 1.0;
  354. [transaction setData:@{@"count" : @(newCount)} forDocument:doc];
  355. return @YES;
  356. }
  357. completion:^(id _Nullable result, NSError *_Nullable error) {
  358. [expectation fulfill];
  359. }];
  360. }
  361. [self awaitExpectations];
  362. // Now all transaction should be completed, so check the result.
  363. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:doc];
  364. XCTAssertEqualObjects(snapshot[@"count"], @(5.0 + total));
  365. }
  366. - (void)testUpdateTransactionally {
  367. // A barrier to make sure every transaction reaches the same spot.
  368. dispatch_semaphore_t writeBarrier = dispatch_semaphore_create(0);
  369. auto counter = std::make_shared<std::atomic_int>(0);
  370. FIRFirestore *firestore = [self firestore];
  371. FIRDocumentReference *doc = [[firestore collectionWithPath:@"counters"] documentWithAutoID];
  372. [self writeDocumentRef:doc data:@{@"count" : @(5.0), @"other" : @"yes"}];
  373. // Skip backoff delays.
  374. [firestore workerQueue]->SkipDelaysForTimerId(TimerId::RetryTransaction);
  375. // Make 3 transactions that will all increment.
  376. int total = 3;
  377. for (int i = 0; i < total; i++) {
  378. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  379. [firestore
  380. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  381. int32_t nowStarted = ++(*counter);
  382. FIRDocumentSnapshot *snapshot = [transaction getDocument:doc error:error];
  383. XCTAssertNil(*error);
  384. // Once all of the transactions have read, allow the first write. There should be 3
  385. // initial transaction runs.
  386. if (nowStarted == total) {
  387. XCTAssertEqual(counter->load(), 3);
  388. dispatch_semaphore_signal(writeBarrier);
  389. }
  390. dispatch_semaphore_wait(writeBarrier, DISPATCH_TIME_FOREVER);
  391. // Refill the barrier so that the other transactions and retries succeed.
  392. dispatch_semaphore_signal(writeBarrier);
  393. double newCount = ((NSNumber *)snapshot[@"count"]).doubleValue + 1.0;
  394. [transaction updateData:@{@"count" : @(newCount)} forDocument:doc];
  395. return @YES;
  396. }
  397. completion:^(id _Nullable result, NSError *_Nullable error) {
  398. [expectation fulfill];
  399. }];
  400. }
  401. [self awaitExpectations];
  402. // There should be a maximum of 3 retries: once for the 2nd update, and twice for the 3rd update.
  403. XCTAssertLessThanOrEqual(counter->load(), 6);
  404. // Now all transaction should be completed, so check the result.
  405. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:doc];
  406. XCTAssertEqualObjects(snapshot[@"count"], @(5.0 + total));
  407. XCTAssertEqualObjects(@"yes", snapshot[@"other"]);
  408. }
  409. - (void)testRetriesWhenDocumentThatWasReadWithoutBeingWrittenChanges {
  410. FIRFirestore *firestore = [self firestore];
  411. FIRDocumentReference *doc1 = [[firestore collectionWithPath:@"counters"] documentWithAutoID];
  412. FIRDocumentReference *doc2 = [[firestore collectionWithPath:@"counters"] documentWithAutoID];
  413. auto counter = std::make_shared<std::atomic_int>(0);
  414. [self writeDocumentRef:doc1 data:@{@"count" : @(15.0)}];
  415. // Skip backoff delays.
  416. [firestore workerQueue]->SkipDelaysForTimerId(TimerId::RetryTransaction);
  417. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  418. [firestore
  419. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  420. ++(*counter);
  421. // Get the first doc.
  422. [transaction getDocument:doc1 error:error];
  423. XCTAssertNil(*error);
  424. // Do a write outside of the transaction. The first time the
  425. // transaction is tried, this will bump the version, which
  426. // will cause the write to doc2 to fail. The second time, it
  427. // will be a no-op and not bump the version.
  428. dispatch_semaphore_t writeSemaphore = dispatch_semaphore_create(0);
  429. [doc1 setData:@{
  430. @"count" : @(1234)
  431. }
  432. completion:^(NSError *_Nullable error) {
  433. dispatch_semaphore_signal(writeSemaphore);
  434. }];
  435. // We can block on it, because transactions run on a background queue.
  436. dispatch_semaphore_wait(writeSemaphore, DISPATCH_TIME_FOREVER);
  437. // Now try to update the other doc from within the transaction.
  438. // This should fail once, because we read 15 earlier.
  439. [transaction setData:@{@"count" : @(16)} forDocument:doc2];
  440. return nil;
  441. }
  442. completion:^(id _Nullable result, NSError *_Nullable error) {
  443. XCTAssertNil(error);
  444. XCTAssertEqual(counter->load(), 2);
  445. [expectation fulfill];
  446. }];
  447. [self awaitExpectations];
  448. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:doc1];
  449. XCTAssertEqualObjects(snapshot[@"count"], @(1234));
  450. }
  451. - (void)testReadingADocTwiceWithDifferentVersions {
  452. FIRFirestore *firestore = [self firestore];
  453. FIRDocumentReference *doc = [[firestore collectionWithPath:@"counters"] documentWithAutoID];
  454. auto counter = std::make_shared<std::atomic_int>(0);
  455. [self writeDocumentRef:doc data:@{@"count" : @(15.0)}];
  456. // Skip backoff delays.
  457. [firestore workerQueue]->SkipDelaysForTimerId(TimerId::RetryTransaction);
  458. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  459. [firestore
  460. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  461. ++(*counter);
  462. // Get the doc once.
  463. FIRDocumentSnapshot *snapshot = [transaction getDocument:doc error:error];
  464. XCTAssertNil(*error);
  465. // Do a write outside of the transaction. Because the transaction will retry, set the
  466. // document to a different value each time.
  467. dispatch_semaphore_t writeSemaphore = dispatch_semaphore_create(0);
  468. [doc setData:@{
  469. @"count" : @(1234 + (int)(*counter))
  470. }
  471. completion:^(NSError *_Nullable error) {
  472. dispatch_semaphore_signal(writeSemaphore);
  473. }];
  474. // We can block on it, because transactions run on a background queue.
  475. dispatch_semaphore_wait(writeSemaphore, DISPATCH_TIME_FOREVER);
  476. // Get the doc again in the transaction with the new version.
  477. snapshot = [transaction getDocument:doc error:error];
  478. // The get itself will fail, because we already read an earlier version of this document.
  479. // TODO(klimt): Perhaps we shouldn't fail reads for this, but should wait and fail the
  480. // whole transaction? It's an edge-case anyway, as developers shouldn't be reading the same
  481. // doc multiple times. But they need to handle read errors anyway.
  482. XCTAssertNotNil(*error);
  483. return nil;
  484. }
  485. completion:^(id _Nullable result, 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 *_Nullable error) {
  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 _Nullable result, 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 _Nullable result, 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 _Nullable result, 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)testSuccessWithNoTransactionOperations {
  569. FIRFirestore *firestore = [self firestore];
  570. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  571. [firestore
  572. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  573. return @"yes";
  574. }
  575. completion:^(id _Nullable result, NSError *_Nullable error) {
  576. XCTAssertEqualObjects(result, @"yes");
  577. XCTAssertNil(error);
  578. [expectation fulfill];
  579. }];
  580. [self awaitExpectations];
  581. }
  582. - (void)testCancellationOnError {
  583. FIRFirestore *firestore = [self firestore];
  584. FIRDocumentReference *doc = [[firestore collectionWithPath:@"towns"] documentWithAutoID];
  585. auto counter = std::make_shared<std::atomic_int>(0);
  586. XCTestExpectation *expectation = [self expectationWithDescription:@"transaction"];
  587. [firestore
  588. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  589. ++(*counter);
  590. [transaction setData:@{@"foo" : @"bar"} forDocument:doc];
  591. if (error) {
  592. *error = [NSError errorWithDomain:NSCocoaErrorDomain code:35 userInfo:@{}];
  593. }
  594. return nil;
  595. }
  596. completion:^(id _Nullable result, NSError *_Nullable error) {
  597. XCTAssertNil(result);
  598. XCTAssertNotNil(error);
  599. XCTAssertEqual(error.code, 35);
  600. [expectation fulfill];
  601. }];
  602. [self awaitExpectations];
  603. XCTAssertEqual(counter->load(), 1);
  604. FIRDocumentSnapshot *snapshot = [self readDocumentForRef:doc];
  605. XCTAssertFalse(snapshot.exists);
  606. }
  607. - (void)testUpdateFieldsWithDotsTransactionally {
  608. FIRDocumentReference *doc = [self documentRef];
  609. XCTestExpectation *expectation =
  610. [self expectationWithDescription:@"testUpdateFieldsWithDotsTransactionally"];
  611. [doc.firestore
  612. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  613. XCTAssertNil(*error);
  614. [transaction setData:@{@"a.b" : @"old", @"c.d" : @"old"} forDocument:doc];
  615. [transaction updateData:@{
  616. [[FIRFieldPath alloc] initWithFields:@[ @"a.b" ]] : @"new"
  617. }
  618. forDocument:doc];
  619. return nil;
  620. }
  621. completion:^(id result, NSError *error) {
  622. XCTAssertNil(error);
  623. [doc getDocumentWithCompletion:^(FIRDocumentSnapshot *snapshot, NSError *error) {
  624. XCTAssertNil(error);
  625. XCTAssertEqualObjects(snapshot.data, (@{@"a.b" : @"new", @"c.d" : @"old"}));
  626. }];
  627. [expectation fulfill];
  628. }];
  629. [self awaitExpectations];
  630. }
  631. - (void)testUpdateNestedFieldsTransactionally {
  632. FIRDocumentReference *doc = [self documentRef];
  633. XCTestExpectation *expectation =
  634. [self expectationWithDescription:@"testUpdateNestedFieldsTransactionally"];
  635. [doc.firestore
  636. runTransactionWithBlock:^id _Nullable(FIRTransaction *transaction, NSError **error) {
  637. XCTAssertNil(*error);
  638. [transaction setData:@{
  639. @"a" : @{@"b" : @"old"},
  640. @"c" : @{@"d" : @"old"},
  641. @"e" : @{@"f" : @"old"}
  642. }
  643. forDocument:doc];
  644. [transaction updateData:@{
  645. @"a.b" : @"new",
  646. [[FIRFieldPath alloc] initWithFields:@[ @"c", @"d" ]] : @"new"
  647. }
  648. forDocument:doc];
  649. return nil;
  650. }
  651. completion:^(id result, NSError *error) {
  652. XCTAssertNil(error);
  653. [doc getDocumentWithCompletion:^(FIRDocumentSnapshot *snapshot, NSError *error) {
  654. XCTAssertNil(error);
  655. XCTAssertEqualObjects(snapshot.data, (@{
  656. @"a" : @{@"b" : @"new"},
  657. @"c" : @{@"d" : @"new"},
  658. @"e" : @{@"f" : @"old"}
  659. }));
  660. }];
  661. [expectation fulfill];
  662. }];
  663. [self awaitExpectations];
  664. }
  665. @end