FWriteTree.m 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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 "FWriteTree.h"
  17. #import "FImmutableTree.h"
  18. #import "FPath.h"
  19. #import "FNode.h"
  20. #import "FWriteTreeRef.h"
  21. #import "FChildrenNode.h"
  22. #import "FNamedNode.h"
  23. #import "FWriteRecord.h"
  24. #import "FEmptyNode.h"
  25. #import "FIndex.h"
  26. #import "FCompoundWrite.h"
  27. #import "FCacheNode.h"
  28. @interface FWriteTree ()
  29. /**
  30. * A tree tracking the results of applying all visible writes. This does not include transactions with
  31. * applyLocally=false or writes that are completely shadowed by other writes.
  32. * Contains id<FNode> as values.
  33. */
  34. @property (nonatomic, strong) FCompoundWrite *visibleWrites;
  35. /**
  36. * A list of pending writes, regardless of visibility and shadowed-ness. Used to calcuate arbitrary
  37. * sets of the changed data, such as hidden writes (from transactions) or changes with certain writes excluded (also
  38. * used by transactions).
  39. * Contains FWriteRecords.
  40. */
  41. @property (nonatomic, strong) NSMutableArray *allWrites;
  42. @property (nonatomic) NSInteger lastWriteId;
  43. @end
  44. /**
  45. * FWriteTree tracks all pending user-initiated writes and has methods to calcuate the result of merging them with
  46. * underlying server data (to create "event cache" data). Pending writes are added with addOverwriteAtPath: and
  47. * addMergeAtPath: and removed with removeWriteId:.
  48. */
  49. @implementation FWriteTree
  50. @synthesize allWrites;
  51. @synthesize lastWriteId;
  52. - (id) init {
  53. self = [super init];
  54. if (self) {
  55. self.visibleWrites = [FCompoundWrite emptyWrite];
  56. self.allWrites = [[NSMutableArray alloc] init];
  57. self.lastWriteId = -1;
  58. }
  59. return self;
  60. }
  61. /**
  62. * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.
  63. */
  64. - (FWriteTreeRef *) childWritesForPath:(FPath *)path {
  65. return [[FWriteTreeRef alloc] initWithPath:path writeTree:self];
  66. }
  67. /**
  68. * Record a new overwrite from user code.
  69. * @param visible Is set to false by some transactions. It should be excluded from event caches.
  70. */
  71. - (void) addOverwriteAtPath:(FPath *)path newData:(id <FNode>)newData writeId:(NSInteger)writeId isVisible:(BOOL)visible {
  72. NSAssert(writeId > self.lastWriteId, @"Stacking an older write on top of a newer one");
  73. FWriteRecord *record = [[FWriteRecord alloc] initWithPath:path overwrite:newData writeId:writeId visible:visible];
  74. [self.allWrites addObject:record];
  75. if (visible) {
  76. self.visibleWrites = [self.visibleWrites addWrite:newData atPath:path];
  77. }
  78. self.lastWriteId = writeId;
  79. }
  80. /**
  81. * Record a new merge from user code.
  82. * @param changedChildren maps NSString -> id<FNode>
  83. */
  84. - (void) addMergeAtPath:(FPath *)path changedChildren:(FCompoundWrite *)changedChildren writeId:(NSInteger)writeId {
  85. NSAssert(writeId > self.lastWriteId, @"Stacking an older merge on top of newer one");
  86. FWriteRecord *record = [[FWriteRecord alloc] initWithPath:path merge:changedChildren writeId:writeId];
  87. [self.allWrites addObject:record];
  88. self.visibleWrites = [self.visibleWrites addCompoundWrite:changedChildren atPath:path];
  89. self.lastWriteId = writeId;
  90. }
  91. - (FWriteRecord *)writeForId:(NSInteger)writeId {
  92. NSUInteger index = [self.allWrites indexOfObjectPassingTest:^BOOL(FWriteRecord *write, NSUInteger idx, BOOL *stop) {
  93. return write.writeId == writeId;
  94. }];
  95. return (index == NSNotFound) ? nil : self.allWrites[index];
  96. }
  97. /**
  98. * Remove a write (either an overwrite or merge) that has been successfully acknowledged by the server. Recalculates the
  99. * tree if necessary. We return the path of the write and whether it may have been visible, meaning views need to
  100. * reevaluate.
  101. *
  102. * @return YES if the write may have been visible (meaning we'll need to reevaluate / raise events as a result).
  103. */
  104. - (BOOL) removeWriteId:(NSInteger)writeId {
  105. NSUInteger index = [self.allWrites indexOfObjectPassingTest:^BOOL(FWriteRecord *record, NSUInteger idx, BOOL *stop) {
  106. if (record.writeId == writeId) {
  107. return YES;
  108. } else {
  109. return NO;
  110. }
  111. }];
  112. NSAssert(index != NSNotFound, @"[FWriteTree removeWriteId:] called with nonexistent writeId.");
  113. FWriteRecord *writeToRemove = self.allWrites[index];
  114. [self.allWrites removeObjectAtIndex:index];
  115. BOOL removedWriteWasVisible = writeToRemove.visible;
  116. BOOL removedWriteOverlapsWithOtherWrites = NO;
  117. NSInteger i = [self.allWrites count] - 1;
  118. while (removedWriteWasVisible && i >= 0) {
  119. FWriteRecord *currentWrite = [self.allWrites objectAtIndex:i];
  120. if (currentWrite.visible) {
  121. if (i >= index && [self record:currentWrite containsPath:writeToRemove.path]) {
  122. // The removed write was completely shadowed by a subsequent write.
  123. removedWriteWasVisible = NO;
  124. } else if ([writeToRemove.path contains:currentWrite.path]) {
  125. // Either we're covering some writes or they're covering part of us (depending on which came first).
  126. removedWriteOverlapsWithOtherWrites = YES;
  127. }
  128. }
  129. i--;
  130. }
  131. if (!removedWriteWasVisible) {
  132. return NO;
  133. } else if (removedWriteOverlapsWithOtherWrites) {
  134. // There's some shadowing going on. Just rebuild the visible writes from scratch.
  135. [self resetTree];
  136. return YES;
  137. } else {
  138. // There's no shadowing. We can safely just remove the write(s) from visibleWrites.
  139. if ([writeToRemove isOverwrite]) {
  140. self.visibleWrites = [self.visibleWrites removeWriteAtPath:writeToRemove.path];
  141. } else {
  142. FCompoundWrite *merge = writeToRemove.merge;
  143. [merge enumerateWrites:^(FPath *path, id<FNode> node, BOOL *stop) {
  144. self.visibleWrites = [self.visibleWrites removeWriteAtPath:[writeToRemove.path child:path]];
  145. }];
  146. }
  147. return YES;
  148. }
  149. }
  150. - (NSArray *) removeAllWrites {
  151. NSArray *writes = self.allWrites;
  152. self.visibleWrites = [FCompoundWrite emptyWrite];
  153. self.allWrites = [NSMutableArray array];
  154. return writes;
  155. }
  156. /**
  157. * @return A complete snapshot for the given path if there's visible write data at that path, else nil.
  158. * No server data is considered.
  159. */
  160. - (id <FNode>) completeWriteDataAtPath:(FPath *)path {
  161. return [self.visibleWrites completeNodeAtPath:path];
  162. }
  163. /**
  164. * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden
  165. * writes), attempt to calculate a complete snapshot for the given path
  166. * @param includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false
  167. */
  168. - (id <FNode>) calculateCompleteEventCacheAtPath:(FPath *)treePath completeServerCache:(id <FNode>)completeServerCache
  169. excludeWriteIds:(NSArray *)writeIdsToExclude includeHiddenWrites:(BOOL)includeHiddenWrites {
  170. if (writeIdsToExclude == nil && !includeHiddenWrites) {
  171. id<FNode> shadowingNode = [self.visibleWrites completeNodeAtPath:treePath];
  172. if (shadowingNode != nil) {
  173. return shadowingNode;
  174. } else {
  175. // No cache here. Can't claim complete knowledge.
  176. FCompoundWrite *subMerge = [self.visibleWrites childCompoundWriteAtPath:treePath];
  177. if (subMerge.isEmpty) {
  178. return completeServerCache;
  179. } else if (completeServerCache == nil && ![subMerge hasCompleteWriteAtPath:[FPath empty]]) {
  180. // We wouldn't have a complete snapshot since there's no underlying data and no complete shadow
  181. return nil;
  182. } else {
  183. id<FNode> layeredCache = completeServerCache != nil ? completeServerCache : [FEmptyNode emptyNode];
  184. return [subMerge applyToNode:layeredCache];
  185. }
  186. }
  187. } else {
  188. FCompoundWrite *merge = [self.visibleWrites childCompoundWriteAtPath:treePath];
  189. if (!includeHiddenWrites && merge.isEmpty) {
  190. return completeServerCache;
  191. } else {
  192. // If the server cache is null and we don't have a complete cache, we need to return nil
  193. if (!includeHiddenWrites && completeServerCache == nil && ![merge hasCompleteWriteAtPath:[FPath empty]]) {
  194. return nil;
  195. } else {
  196. BOOL (^filter) (FWriteRecord *) = ^(FWriteRecord *record) {
  197. return (BOOL) ((record.visible || includeHiddenWrites) &&
  198. (writeIdsToExclude == nil || ![writeIdsToExclude containsObject:[NSNumber numberWithInteger:record.writeId]]) &&
  199. ([record.path contains:treePath] || [treePath contains:record.path]));
  200. };
  201. FCompoundWrite *mergeAtPath = [FWriteTree layerTreeFromWrites:self.allWrites filter:filter treeRoot:treePath];
  202. id<FNode> layeredCache = completeServerCache ? completeServerCache : [FEmptyNode emptyNode];
  203. return [mergeAtPath applyToNode:layeredCache];
  204. }
  205. }
  206. }
  207. }
  208. /**
  209. * With optional, underlying server data, attempt to return a children node of children that we have complete data for.
  210. * Used when creating new views, to pre-fill their complete event children snapshot.
  211. */
  212. - (FChildrenNode *) calculateCompleteEventChildrenAtPath:(FPath *)treePath
  213. completeServerChildren:(id<FNode>)completeServerChildren {
  214. __block id<FNode> completeChildren = [FEmptyNode emptyNode];
  215. id<FNode> topLevelSet = [self.visibleWrites completeNodeAtPath:treePath];
  216. if (topLevelSet != nil) {
  217. if (![topLevelSet isLeafNode]) {
  218. // We're shadowing everything. Return the children.
  219. FChildrenNode *topChildrenNode = topLevelSet;
  220. [topChildrenNode enumerateChildrenUsingBlock:^(NSString *key, id<FNode> node, BOOL *stop) {
  221. completeChildren = [completeChildren updateImmediateChild:key withNewChild:node];
  222. }];
  223. }
  224. return completeChildren;
  225. } else {
  226. // Layer any children we have on top of this
  227. // We know we don't have a top-level set, so just enumerate existing children, and apply any updates
  228. FCompoundWrite *merge = [self.visibleWrites childCompoundWriteAtPath:treePath];
  229. [completeServerChildren enumerateChildrenUsingBlock:^(NSString *key, id<FNode> node, BOOL *stop) {
  230. FCompoundWrite *childMerge = [merge childCompoundWriteAtPath:[[FPath alloc] initWith:key]];
  231. id<FNode> newChildNode = [childMerge applyToNode:node];
  232. completeChildren = [completeChildren updateImmediateChild:key withNewChild:newChildNode];
  233. }];
  234. // Add any complete children we have from the set.
  235. for (FNamedNode *node in merge.completeChildren) {
  236. completeChildren = [completeChildren updateImmediateChild:node.name withNewChild:node.node];
  237. }
  238. return completeChildren;
  239. }
  240. }
  241. /**
  242. * Given that the underlying server data has updated, determine what, if anything, needs to be applied to the event cache.
  243. *
  244. * Possibilities
  245. *
  246. * 1. No write are shadowing. Events should be raised, the snap to be applied comes from the server data.
  247. *
  248. * 2. Some write is completely shadowing. No events to be raised.
  249. *
  250. * 3. Is partially shadowed. Events ..
  251. *
  252. * Either existingEventSnap or existingServerSnap must exist.
  253. */
  254. - (id <FNode>) calculateEventCacheAfterServerOverwriteAtPath:(FPath *)treePath childPath:(FPath *)childPath existingEventSnap:(id <FNode>)existingEventSnap existingServerSnap:(id <FNode>)existingServerSnap {
  255. NSAssert(existingEventSnap != nil || existingServerSnap != nil,
  256. @"Either existingEventSnap or existingServerSanp must exist.");
  257. FPath *path = [treePath child:childPath];
  258. if ([self.visibleWrites hasCompleteWriteAtPath:path]) {
  259. // At this point we can probably guarantee that we're in case 2, meaning no events
  260. // May need to check visibility while doing the findRootMostValueAndPath call
  261. return nil;
  262. } else {
  263. // This could be more efficient if the serverNode + updates doesn't change the eventSnap
  264. // However this is tricky to find out, since user updates don't necessary change the server
  265. // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server
  266. // adds nodes, but doesn't change any existing writes. It is therefore not enough to
  267. // only check if the updates change the serverNode.
  268. // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?
  269. FCompoundWrite *childMerge = [self.visibleWrites childCompoundWriteAtPath:path];
  270. if (childMerge.isEmpty) {
  271. // We're not shadowing at all. Case 1
  272. return [existingServerSnap getChild:childPath];
  273. } else {
  274. return [childMerge applyToNode:[existingServerSnap getChild:childPath]];
  275. }
  276. }
  277. }
  278. /**
  279. * Returns a complete child for a given server snap after applying all user writes or nil if there is no complete child
  280. * for this child key.
  281. */
  282. - (id<FNode>) calculateCompleteChildAtPath:(FPath *)treePath childKey:(NSString *)childKey cache:(FCacheNode *)existingServerCache {
  283. FPath *path = [treePath childFromString:childKey];
  284. id<FNode> shadowingNode = [self.visibleWrites completeNodeAtPath:path];
  285. if (shadowingNode != nil) {
  286. return shadowingNode;
  287. } else {
  288. if ([existingServerCache isCompleteForChild:childKey]) {
  289. FCompoundWrite *childMerge = [self.visibleWrites childCompoundWriteAtPath:path];
  290. return [childMerge applyToNode:[existingServerCache.node getImmediateChild:childKey]];
  291. } else {
  292. return nil;
  293. }
  294. }
  295. }
  296. /**
  297. * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at
  298. * a higher path, this will return the child of that write relative to the write and this path.
  299. * Returns null if there is no write at this path.
  300. */
  301. - (id<FNode>) shadowingWriteAtPath:(FPath *)path {
  302. return [self.visibleWrites completeNodeAtPath:path];
  303. }
  304. /**
  305. * This method is used when processing child remove events on a query. If we can, we pull in children that were outside
  306. * the window, but may now be in the window.
  307. */
  308. - (FNamedNode *)calculateNextNodeAfterPost:(FNamedNode *)post
  309. atPath:(FPath *)treePath
  310. completeServerData:(id<FNode>)completeServerData
  311. reverse:(BOOL)reverse
  312. index:(id<FIndex>)index
  313. {
  314. __block id<FNode> toIterate;
  315. FCompoundWrite *merge = [self.visibleWrites childCompoundWriteAtPath:treePath];
  316. id<FNode> shadowingNode = [merge completeNodeAtPath:[FPath empty]];
  317. if (shadowingNode != nil) {
  318. toIterate = shadowingNode;
  319. } else if (completeServerData != nil) {
  320. toIterate = [merge applyToNode:completeServerData];
  321. } else {
  322. return nil;
  323. }
  324. __block NSString *currentNextKey = nil;
  325. __block id<FNode> currentNextNode = nil;
  326. [toIterate enumerateChildrenUsingBlock:^(NSString *key, id<FNode> node, BOOL *stop) {
  327. if ([index compareKey:key andNode:node toOtherKey:post.name andNode:post.node reverse:reverse] > NSOrderedSame &&
  328. (!currentNextKey || [index compareKey:key andNode:node toOtherKey:currentNextKey andNode:currentNextNode reverse:reverse] < NSOrderedSame)) {
  329. currentNextKey = key;
  330. currentNextNode = node;
  331. }
  332. }];
  333. if (currentNextKey != nil) {
  334. return [FNamedNode nodeWithName:currentNextKey node:currentNextNode];
  335. } else {
  336. return nil;
  337. }
  338. }
  339. #pragma mark -
  340. #pragma mark Private Methods
  341. - (BOOL) record:(FWriteRecord *)record containsPath:(FPath *)path {
  342. if ([record isOverwrite]) {
  343. return [record.path contains:path];
  344. } else {
  345. __block BOOL contains = NO;
  346. [record.merge enumerateWrites:^(FPath *childPath, id<FNode> node, BOOL *stop) {
  347. contains = [[record.path child:childPath] contains:path];
  348. *stop = contains;
  349. }];
  350. return contains;
  351. }
  352. }
  353. /**
  354. * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots
  355. */
  356. - (void) resetTree {
  357. self.visibleWrites = [FWriteTree layerTreeFromWrites:self.allWrites filter:[FWriteTree defaultFilter] treeRoot:[FPath empty]];
  358. if ([self.allWrites count] > 0) {
  359. FWriteRecord *lastRecord = self.allWrites[[self.allWrites count] - 1];
  360. self.lastWriteId = lastRecord.writeId;
  361. } else {
  362. self.lastWriteId = -1;
  363. }
  364. }
  365. /**
  366. * The default filter used when constructing the tree. Keep everything that's visible.
  367. */
  368. + (BOOL (^)(FWriteRecord *record)) defaultFilter {
  369. static BOOL (^filter)(FWriteRecord *);
  370. static dispatch_once_t filterToken;
  371. dispatch_once(&filterToken, ^{
  372. filter = ^(FWriteRecord *record) {
  373. return YES;
  374. };
  375. });
  376. return filter;
  377. }
  378. /**
  379. * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct a merge
  380. * at that path
  381. * @return An FImmutableTree of id<FNode>s.
  382. */
  383. + (FCompoundWrite *) layerTreeFromWrites:(NSArray *)writes filter:(BOOL (^)(FWriteRecord *record))filter treeRoot:(FPath *)treeRoot {
  384. __block FCompoundWrite *compoundWrite = [FCompoundWrite emptyWrite];
  385. [writes enumerateObjectsUsingBlock:^(FWriteRecord *record, NSUInteger idx, BOOL *stop) {
  386. // Theory, a later set will either:
  387. // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction
  388. // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction
  389. if (filter(record)) {
  390. FPath *writePath = record.path;
  391. if ([record isOverwrite]) {
  392. if ([treeRoot contains:writePath]) {
  393. FPath *relativePath = [FPath relativePathFrom:treeRoot to:writePath];
  394. compoundWrite = [compoundWrite addWrite:record.overwrite atPath:relativePath];
  395. } else if ([writePath contains:treeRoot]) {
  396. id<FNode> child = [record.overwrite getChild:[FPath relativePathFrom:writePath to:treeRoot]];
  397. compoundWrite = [compoundWrite addWrite:child atPath:[FPath empty]];
  398. } else {
  399. // There is no overlap between root path and write path, ignore write
  400. }
  401. } else {
  402. if ([treeRoot contains:writePath]) {
  403. FPath *relativePath = [FPath relativePathFrom:treeRoot to:writePath];
  404. compoundWrite = [compoundWrite addCompoundWrite:record.merge atPath:relativePath];
  405. } else if ([writePath contains:treeRoot]) {
  406. FPath *relativePath = [FPath relativePathFrom:writePath to:treeRoot];
  407. if (relativePath.isEmpty) {
  408. compoundWrite = [compoundWrite addCompoundWrite:record.merge atPath:[FPath empty]];
  409. } else {
  410. id<FNode> child = [record.merge completeNodeAtPath:relativePath];
  411. if (child != nil) {
  412. // There exists a child in this node that matches the root path
  413. id<FNode> deepNode = [child getChild:[relativePath popFront]];
  414. compoundWrite = [compoundWrite addWrite:deepNode atPath:[FPath empty]];
  415. }
  416. }
  417. } else {
  418. // There is no overlap between root path and write path, ignore write
  419. }
  420. }
  421. }
  422. }];
  423. return compoundWrite;
  424. }
  425. @end