FSTTransactionTests.mm 32 KB

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