FSTTransaction.mm 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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 =
  83. [NSError errorWithDomain:FIRFirestoreErrorDomain
  84. code:FIRFirestoreErrorCodeFailedPrecondition
  85. userInfo:@{
  86. NSLocalizedDescriptionKey :
  87. @"A document cannot be read twice within a single transaction."
  88. }];
  89. }
  90. return NO;
  91. }
  92. }
  93. - (void)lookupDocumentsForKeys:(const std::vector<DocumentKey> &)keys
  94. completion:(FSTVoidMaybeDocumentArrayErrorBlock)completion {
  95. [self ensureCommitNotCalled];
  96. if (self.mutations.count) {
  97. FSTThrowInvalidUsage(@"FIRIllegalStateException",
  98. @"All reads in a transaction must be done before any writes.");
  99. }
  100. [self.datastore lookupDocuments:keys
  101. completion:^(NSArray<FSTMaybeDocument *> *_Nullable documents,
  102. NSError *_Nullable error) {
  103. if (error) {
  104. completion(nil, error);
  105. return;
  106. }
  107. for (FSTMaybeDocument *doc in documents) {
  108. NSError *recordError = nil;
  109. if (![self recordVersionForDocument:doc error:&recordError]) {
  110. completion(nil, recordError);
  111. return;
  112. }
  113. }
  114. completion(documents, nil);
  115. }];
  116. }
  117. /** Stores mutations to be written when commitWithCompletion is called. */
  118. - (void)writeMutations:(NSArray<FSTMutation *> *)mutations {
  119. [self ensureCommitNotCalled];
  120. [self.mutations addObjectsFromArray:mutations];
  121. }
  122. /**
  123. * Returns version of this doc when it was read in this transaction as a precondition, or no
  124. * precondition if it was not read.
  125. */
  126. - (Precondition)preconditionForDocumentKey:(const DocumentKey &)key {
  127. const auto iter = _readVersions.find(key);
  128. if (iter == _readVersions.end()) {
  129. return Precondition::None();
  130. } else {
  131. return Precondition::UpdateTime(iter->second);
  132. }
  133. }
  134. /**
  135. * Returns the precondition for a document if the operation is an update, based on the provided
  136. * UpdateOptions. Will return none precondition if an error occurred, in which case it sets the
  137. * error parameter.
  138. */
  139. - (Precondition)preconditionForUpdateWithDocumentKey:(const DocumentKey &)key
  140. error:(NSError **)error {
  141. const auto iter = _readVersions.find(key);
  142. if (iter == _readVersions.end()) {
  143. // Document was not read, so we just use the preconditions for an update.
  144. return Precondition::Exists(true);
  145. }
  146. const SnapshotVersion &version = iter->second;
  147. if (version == SnapshotVersion::None()) {
  148. // The document was read, but doesn't exist.
  149. // Return an error because the precondition is impossible
  150. if (error) {
  151. *error = [NSError
  152. errorWithDomain:FIRFirestoreErrorDomain
  153. code:FIRFirestoreErrorCodeAborted
  154. userInfo:@{
  155. NSLocalizedDescriptionKey : @"Can't update a document that doesn't exist."
  156. }];
  157. }
  158. return Precondition::None();
  159. } else {
  160. // Document exists, just base precondition on document update time.
  161. return Precondition::UpdateTime(version);
  162. }
  163. }
  164. - (void)setData:(FSTParsedSetData *)data forDocument:(const DocumentKey &)key {
  165. [self writeMutations:[data mutationsWithKey:key
  166. precondition:[self preconditionForDocumentKey:key]]];
  167. }
  168. - (void)updateData:(FSTParsedUpdateData *)data forDocument:(const DocumentKey &)key {
  169. NSError *error = nil;
  170. const Precondition precondition = [self preconditionForUpdateWithDocumentKey:key error:&error];
  171. if (precondition.IsNone()) {
  172. HARD_ASSERT(error, "Got nil precondition, but error was not set");
  173. self.lastWriteError = error;
  174. } else {
  175. [self writeMutations:[data mutationsWithKey:key precondition:precondition]];
  176. }
  177. }
  178. - (void)deleteDocument:(const DocumentKey &)key {
  179. [self writeMutations:@[ [[FSTDeleteMutation alloc]
  180. initWithKey:key
  181. precondition:[self preconditionForDocumentKey:key]] ]];
  182. // Since the delete will be applied before all following writes, we need to ensure that the
  183. // precondition for the next write will be exists without timestamp.
  184. _readVersions[key] = SnapshotVersion::None();
  185. }
  186. - (void)commitWithCompletion:(FSTVoidErrorBlock)completion {
  187. [self ensureCommitNotCalled];
  188. // Once commitWithCompletion is called once, mark this object so it can't be used again.
  189. self.commitCalled = YES;
  190. // If there was an error writing, raise that error now
  191. if (self.lastWriteError) {
  192. completion(self.lastWriteError);
  193. return;
  194. }
  195. // Make a list of read documents that haven't been written.
  196. DocumentKeySet unwritten;
  197. for (const auto &kv : _readVersions) {
  198. unwritten = unwritten.insert(kv.first);
  199. };
  200. // For each mutation, note that the doc was written.
  201. for (FSTMutation *mutation in self.mutations) {
  202. unwritten = unwritten.erase(mutation.key);
  203. }
  204. if (!unwritten.empty()) {
  205. // TODO(klimt): This is a temporary restriction, until "verify" is supported on the backend.
  206. completion([NSError
  207. errorWithDomain:FIRFirestoreErrorDomain
  208. code:FIRFirestoreErrorCodeFailedPrecondition
  209. userInfo:@{
  210. NSLocalizedDescriptionKey : @"Every document read in a transaction must also be "
  211. @"written in that transaction."
  212. }]);
  213. } else {
  214. [self.datastore commitMutations:self.mutations
  215. completion:^(NSError *_Nullable error) {
  216. if (error) {
  217. completion(error);
  218. } else {
  219. completion(nil);
  220. }
  221. }];
  222. }
  223. }
  224. - (void)ensureCommitNotCalled {
  225. if (self.commitCalled) {
  226. FSTThrowInvalidUsage(
  227. @"FIRIllegalStateException",
  228. @"A transaction object cannot be used after its update block has completed.");
  229. }
  230. }
  231. @end
  232. NS_ASSUME_NONNULL_END