FSTTransaction.mm 9.4 KB

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