FSTTransaction.mm 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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 "Firestore/Source/Core/FSTTransaction.h"
  17. #include <map>
  18. #include <vector>
  19. #import <GRPCClient/GRPCCall.h>
  20. #import "FIRFirestoreErrors.h"
  21. #import "FIRSetOptions.h"
  22. #import "Firestore/Source/API/FSTUserDataConverter.h"
  23. #import "Firestore/Source/Core/FSTSnapshotVersion.h"
  24. #import "Firestore/Source/Model/FSTDocument.h"
  25. #import "Firestore/Source/Model/FSTDocumentKeySet.h"
  26. #import "Firestore/Source/Model/FSTMutation.h"
  27. #import "Firestore/Source/Remote/FSTDatastore.h"
  28. #import "Firestore/Source/Util/FSTAssert.h"
  29. #import "Firestore/Source/Util/FSTUsageValidation.h"
  30. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  31. using firebase::firestore::model::DocumentKey;
  32. NS_ASSUME_NONNULL_BEGIN
  33. #pragma mark - FSTTransaction
  34. @interface FSTTransaction ()
  35. @property(nonatomic, strong, readonly) FSTDatastore *datastore;
  36. @property(nonatomic, strong, readonly) NSMutableArray *mutations;
  37. @property(nonatomic, assign) BOOL commitCalled;
  38. /**
  39. * An error that may have occurred as a consequence of a write. If set, needs to be raised in the
  40. * completion handler instead of trying to commit.
  41. */
  42. @property(nonatomic, strong, nullable) NSError *lastWriteError;
  43. @end
  44. @implementation FSTTransaction {
  45. std::map<DocumentKey, FSTSnapshotVersion *> _readVersions;
  46. }
  47. + (instancetype)transactionWithDatastore:(FSTDatastore *)datastore {
  48. return [[FSTTransaction alloc] initWithDatastore:datastore];
  49. }
  50. - (instancetype)initWithDatastore:(FSTDatastore *)datastore {
  51. self = [super init];
  52. if (self) {
  53. _datastore = datastore;
  54. _mutations = [NSMutableArray array];
  55. _commitCalled = NO;
  56. }
  57. return self;
  58. }
  59. /**
  60. * Every time a document is read, this should be called to record its version. If we read two
  61. * different versions of the same document, this will return an error through its out parameter.
  62. * When the transaction is committed, the versions recorded will be set as preconditions on the
  63. * writes sent to the backend.
  64. */
  65. - (BOOL)recordVersionForDocument:(FSTMaybeDocument *)doc error:(NSError **)error {
  66. FSTAssert(error != nil, @"nil error parameter");
  67. *error = nil;
  68. FSTSnapshotVersion *docVersion = doc.version;
  69. if ([doc isKindOfClass:[FSTDeletedDocument class]]) {
  70. // For deleted docs, we must record an explicit no version to build the right precondition
  71. // when writing.
  72. docVersion = [FSTSnapshotVersion noVersion];
  73. }
  74. if (_readVersions.find(doc.key) == _readVersions.end()) {
  75. _readVersions[doc.key] = docVersion;
  76. return YES;
  77. } else {
  78. if (error) {
  79. *error =
  80. [NSError errorWithDomain:FIRFirestoreErrorDomain
  81. code:FIRFirestoreErrorCodeFailedPrecondition
  82. userInfo:@{
  83. NSLocalizedDescriptionKey :
  84. @"A document cannot be read twice within a single transaction."
  85. }];
  86. }
  87. return NO;
  88. }
  89. }
  90. - (void)lookupDocumentsForKeys:(const std::vector<DocumentKey> &)keys
  91. completion:(FSTVoidMaybeDocumentArrayErrorBlock)completion {
  92. [self ensureCommitNotCalled];
  93. if (self.mutations.count) {
  94. FSTThrowInvalidUsage(@"FIRIllegalStateException",
  95. @"All reads in a transaction must be done before any writes.");
  96. }
  97. [self.datastore lookupDocuments:keys
  98. completion:^(NSArray<FSTMaybeDocument *> *_Nullable documents,
  99. NSError *_Nullable error) {
  100. if (error) {
  101. completion(nil, error);
  102. return;
  103. }
  104. for (FSTMaybeDocument *doc in documents) {
  105. NSError *recordError = nil;
  106. if (![self recordVersionForDocument:doc error:&recordError]) {
  107. completion(nil, recordError);
  108. return;
  109. }
  110. }
  111. completion(documents, nil);
  112. }];
  113. }
  114. /** Stores mutations to be written when commitWithCompletion is called. */
  115. - (void)writeMutations:(NSArray<FSTMutation *> *)mutations {
  116. [self ensureCommitNotCalled];
  117. [self.mutations addObjectsFromArray:mutations];
  118. }
  119. /**
  120. * Returns version of this doc when it was read in this transaction as a precondition, or no
  121. * precondition if it was not read.
  122. */
  123. - (FSTPrecondition *)preconditionForDocumentKey:(const DocumentKey &)key {
  124. const auto iter = _readVersions.find(key);
  125. if (iter == _readVersions.end()) {
  126. return [FSTPrecondition none];
  127. } else {
  128. return [FSTPrecondition preconditionWithUpdateTime:iter->second];
  129. }
  130. }
  131. /**
  132. * Returns the precondition for a document if the operation is an update, based on the provided
  133. * UpdateOptions. Will return nil if an error occurred, in which case it sets the error parameter.
  134. */
  135. - (nullable FSTPrecondition *)preconditionForUpdateWithDocumentKey:(const DocumentKey &)key
  136. error:(NSError **)error {
  137. const auto iter = _readVersions.find(key);
  138. if (iter == _readVersions.end()) {
  139. // Document was not read, so we just use the preconditions for an update.
  140. return [FSTPrecondition preconditionWithExists:YES];
  141. }
  142. FSTSnapshotVersion *version = iter->second;
  143. if ([version isEqual:[FSTSnapshotVersion noVersion]]) {
  144. // The document was read, but doesn't exist.
  145. // Return an error because the precondition is impossible
  146. if (error) {
  147. *error = [NSError
  148. errorWithDomain:FIRFirestoreErrorDomain
  149. code:FIRFirestoreErrorCodeAborted
  150. userInfo:@{
  151. NSLocalizedDescriptionKey : @"Can't update a document that doesn't exist."
  152. }];
  153. }
  154. return nil;
  155. } else {
  156. // Document exists, just base precondition on document update time.
  157. return [FSTPrecondition preconditionWithUpdateTime:version];
  158. }
  159. }
  160. - (void)setData:(FSTParsedSetData *)data forDocument:(const DocumentKey &)key {
  161. [self writeMutations:[data mutationsWithKey:key
  162. precondition:[self preconditionForDocumentKey:key]]];
  163. }
  164. - (void)updateData:(FSTParsedUpdateData *)data forDocument:(const DocumentKey &)key {
  165. NSError *error = nil;
  166. FSTPrecondition *_Nullable precondition =
  167. [self preconditionForUpdateWithDocumentKey:key error:&error];
  168. if (precondition) {
  169. [self writeMutations:[data mutationsWithKey:key precondition:precondition]];
  170. } else {
  171. FSTAssert(error, @"Got nil precondition, but error was not set");
  172. self.lastWriteError = error;
  173. }
  174. }
  175. - (void)deleteDocument:(const DocumentKey &)key {
  176. [self writeMutations:@[ [[FSTDeleteMutation alloc]
  177. initWithKey:key
  178. precondition:[self preconditionForDocumentKey:key]] ]];
  179. // Since the delete will be applied before all following writes, we need to ensure that the
  180. // precondition for the next write will be exists: false.
  181. _readVersions[key] = [FSTSnapshotVersion noVersion];
  182. }
  183. - (void)commitWithCompletion:(FSTVoidErrorBlock)completion {
  184. [self ensureCommitNotCalled];
  185. // Once commitWithCompletion is called once, mark this object so it can't be used again.
  186. self.commitCalled = YES;
  187. // If there was an error writing, raise that error now
  188. if (self.lastWriteError) {
  189. completion(self.lastWriteError);
  190. return;
  191. }
  192. // Make a list of read documents that haven't been written.
  193. FSTDocumentKeySet *unwritten = [FSTDocumentKeySet keySet];
  194. for (const auto &kv : _readVersions) {
  195. unwritten = [unwritten setByAddingObject:kv.first];
  196. };
  197. // For each mutation, note that the doc was written.
  198. for (FSTMutation *mutation in self.mutations) {
  199. unwritten = [unwritten setByRemovingObject:mutation.key];
  200. }
  201. if (unwritten.count) {
  202. // TODO(klimt): This is a temporary restriction, until "verify" is supported on the backend.
  203. completion([NSError
  204. errorWithDomain:FIRFirestoreErrorDomain
  205. code:FIRFirestoreErrorCodeFailedPrecondition
  206. userInfo:@{
  207. NSLocalizedDescriptionKey : @"Every document read in a transaction must also be "
  208. @"written in that transaction."
  209. }]);
  210. } else {
  211. [self.datastore commitMutations:self.mutations
  212. completion:^(NSError *_Nullable error) {
  213. if (error) {
  214. completion(error);
  215. } else {
  216. completion(nil);
  217. }
  218. }];
  219. }
  220. }
  221. - (void)ensureCommitNotCalled {
  222. if (self.commitCalled) {
  223. FSTThrowInvalidUsage(
  224. @"FIRIllegalStateException",
  225. @"A transaction object cannot be used after its update block has completed.");
  226. }
  227. }
  228. @end
  229. NS_ASSUME_NONNULL_END