Files
firebase-ios-sdk/FirebaseDatabase/Sources/Core/FSyncTree.m
T

1093 lines
45 KiB
Objective-C
Raw Normal View History

2017-05-15 12:27:07 -07:00
/*
* Copyright 2017 Google
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
2020-06-22 07:58:52 -07:00
#import "FirebaseDatabase/Sources/Core/FSyncTree.h"
2022-02-07 08:42:49 -09:00
#import "FirebaseCore/Internal/FirebaseCoreInternal.h"
2020-06-22 07:58:52 -07:00
#import "FirebaseDatabase/Sources/Core/FCompoundHash.h"
#import "FirebaseDatabase/Sources/Core/FListenProvider.h"
#import "FirebaseDatabase/Sources/Core/FQueryParams.h"
#import "FirebaseDatabase/Sources/Core/FQuerySpec.h"
#import "FirebaseDatabase/Sources/Core/FRangeMerge.h"
#import "FirebaseDatabase/Sources/Core/FServerValues.h"
#import "FirebaseDatabase/Sources/Core/FSnapshotHolder.h"
#import "FirebaseDatabase/Sources/Core/FSyncPoint.h"
#import "FirebaseDatabase/Sources/Core/FWriteRecord.h"
#import "FirebaseDatabase/Sources/Core/FWriteTree.h"
#import "FirebaseDatabase/Sources/Core/FWriteTreeRef.h"
#import "FirebaseDatabase/Sources/Core/Operation/FAckUserWrite.h"
#import "FirebaseDatabase/Sources/Core/Operation/FMerge.h"
#import "FirebaseDatabase/Sources/Core/Operation/FOperation.h"
#import "FirebaseDatabase/Sources/Core/Operation/FOperationSource.h"
#import "FirebaseDatabase/Sources/Core/Operation/FOverwrite.h"
#import "FirebaseDatabase/Sources/Core/Utilities/FImmutableTree.h"
#import "FirebaseDatabase/Sources/Core/Utilities/FPath.h"
#import "FirebaseDatabase/Sources/Core/View/FCacheNode.h"
#import "FirebaseDatabase/Sources/Core/View/FEventRaiser.h"
#import "FirebaseDatabase/Sources/Core/View/FEventRegistration.h"
#import "FirebaseDatabase/Sources/Core/View/FKeepSyncedEventRegistration.h"
#import "FirebaseDatabase/Sources/Core/View/FView.h"
#import "FirebaseDatabase/Sources/FListenComplete.h"
#import "FirebaseDatabase/Sources/Persistence/FPersistenceManager.h"
#import "FirebaseDatabase/Sources/Snapshot/FChildrenNode.h"
#import "FirebaseDatabase/Sources/Snapshot/FCompoundWrite.h"
#import "FirebaseDatabase/Sources/Snapshot/FEmptyNode.h"
#import "FirebaseDatabase/Sources/Snapshot/FNode.h"
#import "FirebaseDatabase/Sources/Snapshot/FSnapshotUtilities.h"
#import "FirebaseDatabase/Sources/Utilities/FAtomicNumber.h"
#import "FirebaseDatabase/Sources/Utilities/FUtilities.h"
#import "FirebaseDatabase/Sources/Utilities/Tuples/FTupleRemovedQueriesEvents.h"
2017-05-15 12:27:07 -07:00
// Size after which we start including the compound hash
static const NSUInteger kFSizeThresholdForCompoundHash = 1024;
2019-08-05 13:27:47 -07:00
@interface FListenContainer : NSObject <FSyncTreeHash>
2017-05-15 12:27:07 -07:00
2019-08-05 13:27:47 -07:00
@property(nonatomic, strong) FView *view;
@property(nonatomic, copy) fbt_nsarray_nsstring onComplete;
2017-05-15 12:27:07 -07:00
@end
@implementation FListenContainer
2019-08-05 13:27:47 -07:00
- (instancetype)initWithView:(FView *)view
onComplete:(fbt_nsarray_nsstring)onComplete {
2017-05-15 12:27:07 -07:00
self = [super init];
if (self != nil) {
self->_view = view;
self->_onComplete = onComplete;
}
return self;
}
- (id<FNode>)serverCache {
return self.view.serverCache;
}
- (FCompoundHash *)compoundHash {
return [FCompoundHash fromNode:[self serverCache]];
}
- (NSString *)simpleHash {
return [[self serverCache] dataHash];
}
- (BOOL)includeCompoundHash {
2019-08-05 13:27:47 -07:00
return [FSnapshotUtilities estimateSerializedNodeSize:[self serverCache]] >
kFSizeThresholdForCompoundHash;
2017-05-15 12:27:07 -07:00
}
@end
@interface FSyncTree ()
/**
2019-08-05 13:27:47 -07:00
* Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more
* views.
*/
@property(nonatomic, strong) FImmutableTree *syncPointTree;
2017-05-15 12:27:07 -07:00
/**
2019-08-05 13:27:47 -07:00
* A tree of all pending user writes (user-initiated set, transactions, updates,
* etc)
*/
@property(nonatomic, strong) FWriteTree *pendingWriteTree;
2017-05-15 12:27:07 -07:00
/**
2019-08-05 13:27:47 -07:00
* Maps tagId -> FTuplePathQueryParams
*/
@property(nonatomic, strong) NSMutableDictionary *tagToQueryMap;
@property(nonatomic, strong) NSMutableDictionary *queryToTagMap;
@property(nonatomic, strong) FListenProvider *listenProvider;
@property(nonatomic, strong) FPersistenceManager *persistenceManager;
@property(nonatomic, strong) FAtomicNumber *queryTagCounter;
@property(nonatomic, strong) NSMutableSet *keepSyncedQueries;
2017-05-15 12:27:07 -07:00
@end
/**
2019-08-05 13:27:47 -07:00
* SyncTree is the central class for managing event callback registration, data
* caching, views (query processing), and event generation. There are typically
* two SyncTree instances for each Repo, one for the normal Firebase data, and
* one for the .info data.
*
* It has a number of responsibilities, including:
* - Tracking all user event callbacks (registered via addEventRegistration:
* and removeEventRegistration:).
* - Applying and caching data changes for user setValue:,
* runTransactionBlock:, and updateChildValues: calls
* (applyUserOverwriteAtPath:, applyUserMergeAtPath:).
* - Applying and caching data changes for server data changes
* (applyServerOverwriteAtPath:, applyServerMergeAtPath:).
* - Generating user-facing events for server and user changes (all of the
* apply* methods return the set of events that need to be raised as a result).
* - Maintaining the appropriate set of server listens to ensure we are always
* subscribed to the correct set of paths and queries to satisfy the current set
* of user event callbacks (listens are started/stopped using the provided
* listenProvider).
*
* NOTE: Although SyncTree tracks event callbacks and calculates events to
* raise, the actual events are returned to the caller rather than raised
* synchronously.
*/
2017-05-15 12:27:07 -07:00
@implementation FSyncTree
2019-08-05 13:27:47 -07:00
- (id)initWithListenProvider:(FListenProvider *)provider {
2017-05-15 12:27:07 -07:00
return [self initWithPersistenceManager:nil listenProvider:provider];
}
2019-08-05 13:27:47 -07:00
- (id)initWithPersistenceManager:(FPersistenceManager *)persistenceManager
listenProvider:(FListenProvider *)provider {
2017-05-15 12:27:07 -07:00
self = [super init];
if (self) {
self.syncPointTree = [FImmutableTree empty];
self.pendingWriteTree = [[FWriteTree alloc] init];
self.tagToQueryMap = [[NSMutableDictionary alloc] init];
self.queryToTagMap = [[NSMutableDictionary alloc] init];
self.listenProvider = provider;
self.persistenceManager = persistenceManager;
self.queryTagCounter = [[FAtomicNumber alloc] init];
self.keepSyncedQueries = [NSMutableSet set];
}
return self;
}
#pragma mark -
#pragma mark Apply Operations
/**
2019-08-05 13:27:47 -07:00
* Apply data changes for a user-generated setValue: runTransactionBlock:
* updateChildValues:, etc.
* @return NSArray of FEvent to raise.
*/
- (NSArray *)applyUserOverwriteAtPath:(FPath *)path
newData:(id<FNode>)newData
writeId:(NSInteger)writeId
isVisible:(BOOL)visible {
2017-05-15 12:27:07 -07:00
// Record pending write
2019-08-05 13:27:47 -07:00
[self.pendingWriteTree addOverwriteAtPath:path
newData:newData
writeId:writeId
isVisible:visible];
2017-05-15 12:27:07 -07:00
if (!visible) {
return @[];
} else {
2019-08-05 13:27:47 -07:00
FOverwrite *operation =
[[FOverwrite alloc] initWithSource:[FOperationSource userInstance]
path:path
snap:newData];
2017-05-15 12:27:07 -07:00
return [self applyOperationToSyncPoints:operation];
}
}
/**
2019-08-05 13:27:47 -07:00
* Apply the data from a user-generated updateChildValues: call
* @return NSArray of FEvent to raise.
*/
- (NSArray *)applyUserMergeAtPath:(FPath *)path
changedChildren:(FCompoundWrite *)changedChildren
writeId:(NSInteger)writeId {
2017-05-15 12:27:07 -07:00
// Record pending merge
2019-08-05 13:27:47 -07:00
[self.pendingWriteTree addMergeAtPath:path
changedChildren:changedChildren
writeId:writeId];
2017-05-15 12:27:07 -07:00
2019-08-05 13:27:47 -07:00
FMerge *operation =
[[FMerge alloc] initWithSource:[FOperationSource userInstance]
path:path
children:changedChildren];
2017-05-15 12:27:07 -07:00
return [self applyOperationToSyncPoints:operation];
}
/**
2019-08-05 13:27:47 -07:00
* Acknowledge a pending user write that was previously registered with
* applyUserOverwriteAtPath: or applyUserMergeAtPath:
* TODO[offline]: Taking a serverClock here is awkward, but server values are
* awkward. :-(
2017-05-15 12:27:07 -07:00
* @return NSArray of FEvent to raise.
*/
2019-08-05 13:27:47 -07:00
- (NSArray *)ackUserWriteWithWriteId:(NSInteger)writeId
revert:(BOOL)revert
persist:(BOOL)persist
clock:(id<FClock>)clock {
2017-05-15 12:27:07 -07:00
FWriteRecord *write = [self.pendingWriteTree writeForId:writeId];
BOOL needToReevaluate = [self.pendingWriteTree removeWriteId:writeId];
if (write.visible) {
if (persist) {
[self.persistenceManager removeUserWrite:writeId];
}
if (!revert) {
2019-08-05 13:27:47 -07:00
NSDictionary *serverValues =
[FServerValues generateServerValues:clock];
2017-05-15 12:27:07 -07:00
if ([write isOverwrite]) {
2019-08-05 13:27:47 -07:00
id<FNode> resolvedNode =
[FServerValues resolveDeferredValueSnapshot:write.overwrite
withSyncTree:self
atPath:write.path
serverValues:serverValues];
2019-08-05 13:27:47 -07:00
[self.persistenceManager applyUserWrite:resolvedNode
toServerCacheAtPath:write.path];
2017-05-15 12:27:07 -07:00
} else {
2019-08-05 13:27:47 -07:00
FCompoundWrite *resolvedMerge = [FServerValues
resolveDeferredValueCompoundWrite:write.merge
withSyncTree:self
atPath:write.path
serverValues:serverValues];
2019-08-05 13:27:47 -07:00
[self.persistenceManager applyUserMerge:resolvedMerge
toServerCacheAtPath:write.path];
2017-05-15 12:27:07 -07:00
}
}
}
if (!needToReevaluate) {
return @[];
} else {
__block FImmutableTree *affectedTree = [FImmutableTree empty];
if (write.isOverwrite) {
affectedTree = [affectedTree setValue:@YES atPath:[FPath empty]];
} else {
2019-08-05 13:27:47 -07:00
[write.merge
enumerateWrites:^(FPath *path, id<FNode> node, BOOL *stop) {
affectedTree = [affectedTree setValue:@YES atPath:path];
}];
2017-05-15 12:27:07 -07:00
}
2019-08-05 13:27:47 -07:00
FAckUserWrite *operation =
[[FAckUserWrite alloc] initWithPath:write.path
affectedTree:affectedTree
revert:revert];
2017-05-15 12:27:07 -07:00
return [self applyOperationToSyncPoints:operation];
}
}
/**
2019-08-05 13:27:47 -07:00
* Apply new server data for the specified path
* @return NSArray of FEvent to raise.
*/
- (NSArray *)applyServerOverwriteAtPath:(FPath *)path
newData:(id<FNode>)newData {
[self.persistenceManager
updateServerCacheWithNode:newData
forQuery:[FQuerySpec defaultQueryAtPath:path]];
FOverwrite *operation =
[[FOverwrite alloc] initWithSource:[FOperationSource serverInstance]
path:path
snap:newData];
2017-05-15 12:27:07 -07:00
return [self applyOperationToSyncPoints:operation];
}
/**
2019-08-05 13:27:47 -07:00
* Applied new server data to be merged in at the specified path
* @return NSArray of FEvent to raise.
*/
- (NSArray *)applyServerMergeAtPath:(FPath *)path
changedChildren:(FCompoundWrite *)changedChildren {
[self.persistenceManager updateServerCacheWithMerge:changedChildren
atPath:path];
FMerge *operation =
[[FMerge alloc] initWithSource:[FOperationSource serverInstance]
path:path
children:changedChildren];
2017-05-15 12:27:07 -07:00
return [self applyOperationToSyncPoints:operation];
}
2019-08-05 13:27:47 -07:00
- (NSArray *)applyServerRangeMergeAtPath:(FPath *)path
updates:(NSArray *)ranges {
2017-05-15 12:27:07 -07:00
FSyncPoint *syncPoint = [self.syncPointTree valueAtPath:path];
if (syncPoint == nil) {
// Removed view, so it's safe to just ignore this update
return @[];
} else {
2019-08-05 13:27:47 -07:00
// This could be for any "complete" (unfiltered) view, and if there is
// more than one complete view, they should each have the same cache so
// it doesn't matter which one we use.
2017-05-15 12:27:07 -07:00
FView *view = [syncPoint completeView];
if (view != nil) {
id<FNode> serverNode = [view serverCache];
for (FRangeMerge *merge in ranges) {
serverNode = [merge applyToNode:serverNode];
}
return [self applyServerOverwriteAtPath:path newData:serverNode];
} else {
2019-08-05 13:27:47 -07:00
// There doesn't exist a view for this update, so it was removed and
// it's safe to just ignore this range merge
2017-05-15 12:27:07 -07:00
return @[];
}
}
}
/**
2019-08-05 13:27:47 -07:00
* Apply a listen complete to a path
* @return NSArray of FEvent to raise.
*/
- (NSArray *)applyListenCompleteAtPath:(FPath *)path {
[self.persistenceManager
setQueryComplete:[FQuerySpec defaultQueryAtPath:path]];
id<FOperation> operation = [[FListenComplete alloc]
initWithSource:[FOperationSource serverInstance]
path:path];
2017-05-15 12:27:07 -07:00
return [self applyOperationToSyncPoints:operation];
}
/**
2019-08-05 13:27:47 -07:00
* Apply a listen complete to a path
* @return NSArray of FEvent to raise.
*/
- (NSArray *)applyTaggedListenCompleteAtPath:(FPath *)path
tagId:(NSNumber *)tagId {
2017-05-15 12:27:07 -07:00
FQuerySpec *query = [self queryForTag:tagId];
if (query != nil) {
[self.persistenceManager setQueryComplete:query];
FPath *relativePath = [FPath relativePathFrom:query.path to:path];
2019-08-05 13:27:47 -07:00
id<FOperation> op = [[FListenComplete alloc]
initWithSource:[FOperationSource forServerTaggedQuery:query.params]
path:relativePath];
2017-05-15 12:27:07 -07:00
return [self applyTaggedOperation:op atPath:query.path];
} else {
// We've already removed the query. No big deal, ignore the update.
return @[];
}
}
/**
2019-08-05 13:27:47 -07:00
* Internal helper method to apply tagged operation
*/
- (NSArray *)applyTaggedOperation:(id<FOperation>)operation
atPath:(FPath *)path {
2017-05-15 12:27:07 -07:00
FSyncPoint *syncPoint = [self.syncPointTree valueAtPath:path];
2019-08-05 13:27:47 -07:00
NSAssert(syncPoint != nil,
@"Missing sync point for query tag that we're tracking.");
FWriteTreeRef *writesCache =
[self.pendingWriteTree childWritesForPath:path];
return [syncPoint applyOperation:operation
writesCache:writesCache
serverCache:nil];
2017-05-15 12:27:07 -07:00
}
/**
2019-08-05 13:27:47 -07:00
* Apply new server data for the specified tagged query
* @return NSArray of FEvent to raise.
*/
- (NSArray *)applyTaggedQueryOverwriteAtPath:(FPath *)path
newData:(id<FNode>)newData
tagId:(NSNumber *)tagId {
2017-05-15 12:27:07 -07:00
FQuerySpec *query = [self queryForTag:tagId];
if (query != nil) {
FPath *relativePath = [FPath relativePathFrom:query.path to:path];
2019-08-05 13:27:47 -07:00
FQuerySpec *queryToOverwrite =
relativePath.isEmpty ? query : [FQuerySpec defaultQueryAtPath:path];
[self.persistenceManager updateServerCacheWithNode:newData
forQuery:queryToOverwrite];
FOverwrite *operation = [[FOverwrite alloc]
initWithSource:[FOperationSource forServerTaggedQuery:query.params]
path:relativePath
snap:newData];
2017-05-15 12:27:07 -07:00
return [self applyTaggedOperation:operation atPath:query.path];
} else {
// Query must have been removed already
return @[];
}
}
/**
2019-08-05 13:27:47 -07:00
* Apply server data to be merged in for the specified tagged query
* @return NSArray of FEvent to raise.
*/
- (NSArray *)applyTaggedQueryMergeAtPath:(FPath *)path
changedChildren:(FCompoundWrite *)changedChildren
tagId:(NSNumber *)tagId {
2017-05-15 12:27:07 -07:00
FQuerySpec *query = [self queryForTag:tagId];
if (query != nil) {
FPath *relativePath = [FPath relativePathFrom:query.path to:path];
2019-08-05 13:27:47 -07:00
[self.persistenceManager updateServerCacheWithMerge:changedChildren
atPath:path];
FMerge *operation = [[FMerge alloc]
initWithSource:[FOperationSource forServerTaggedQuery:query.params]
path:relativePath
children:changedChildren];
2017-05-15 12:27:07 -07:00
return [self applyTaggedOperation:operation atPath:query.path];
} else {
// We've already removed the query. No big deal, ignore the update.
return @[];
}
}
2019-08-05 13:27:47 -07:00
- (NSArray *)applyTaggedServerRangeMergeAtPath:(FPath *)path
updates:(NSArray *)ranges
tagId:(NSNumber *)tagId {
2017-05-15 12:27:07 -07:00
FQuerySpec *query = [self queryForTag:tagId];
if (query != nil) {
2019-08-05 13:27:47 -07:00
NSAssert([path isEqual:query.path],
@"Tagged update path and query path must match");
2017-05-15 12:27:07 -07:00
FSyncPoint *syncPoint = [self.syncPointTree valueAtPath:path];
2019-08-05 13:27:47 -07:00
NSAssert(syncPoint != nil,
@"Missing sync point for query tag that we're tracking.");
2017-05-15 12:27:07 -07:00
FView *view = [syncPoint viewForQuery:query];
2019-08-05 13:27:47 -07:00
NSAssert(view != nil,
@"Missing view for query tag that we're tracking");
2017-05-15 12:27:07 -07:00
id<FNode> serverNode = [view serverCache];
for (FRangeMerge *merge in ranges) {
serverNode = [merge applyToNode:serverNode];
}
2019-08-05 13:27:47 -07:00
return [self applyTaggedQueryOverwriteAtPath:path
newData:serverNode
tagId:tagId];
2017-05-15 12:27:07 -07:00
} else {
// We've already removed the query. No big deal, ignore the update.
return @[];
}
}
/**
2019-08-05 13:27:47 -07:00
* Add an event callback for the specified query
* @return NSArray of FEvent to raise.
*/
- (NSArray *)addEventRegistration:(id<FEventRegistration>)eventRegistration
forQuery:(FQuerySpec *)query {
2017-05-15 12:27:07 -07:00
FPath *path = query.path;
__block BOOL foundAncestorDefaultView = NO;
2019-08-05 13:27:47 -07:00
[self.syncPointTree
forEachOnPath:query.path
whileBlock:^BOOL(FPath *pathToSyncPoint, FSyncPoint *syncPoint) {
foundAncestorDefaultView =
foundAncestorDefaultView || [syncPoint hasCompleteView];
return !foundAncestorDefaultView;
}];
2017-05-15 12:27:07 -07:00
[self.persistenceManager setQueryActive:query];
FSyncPoint *syncPoint = [self.syncPointTree valueAtPath:path];
if (syncPoint == nil) {
2019-08-05 13:27:47 -07:00
syncPoint = [[FSyncPoint alloc]
initWithPersistenceManager:self.persistenceManager];
self.syncPointTree = [self.syncPointTree setValue:syncPoint
atPath:path];
2017-05-15 12:27:07 -07:00
}
BOOL viewAlreadyExists = [syncPoint viewExistsForQuery:query];
NSArray *events;
if (viewAlreadyExists) {
2019-08-05 13:27:47 -07:00
events = [syncPoint addEventRegistration:eventRegistration
forExistingViewForQuery:query];
2017-05-15 12:27:07 -07:00
} else {
if (![query loadsAllData]) {
// We need to track a tag for this query
2019-08-05 13:27:47 -07:00
NSAssert(self.queryToTagMap[query] == nil,
@"View does not exist, but we have a tag");
2017-05-15 12:27:07 -07:00
NSNumber *tagId = [self.queryTagCounter getAndIncrement];
self.queryToTagMap[query] = tagId;
self.tagToQueryMap[tagId] = query;
}
2019-08-05 13:27:47 -07:00
FWriteTreeRef *writesCache =
[self.pendingWriteTree childWritesForPath:path];
2017-05-15 12:27:07 -07:00
FCacheNode *serverCache = [self serverCacheForQuery:query];
events = [syncPoint addEventRegistration:eventRegistration
forNonExistingViewForQuery:query
writesCache:writesCache
serverCache:serverCache];
// There was no view and no default listen
if (!foundAncestorDefaultView) {
FView *view = [syncPoint viewForQuery:query];
NSMutableArray *mutableEvents = [events mutableCopy];
2019-08-05 13:27:47 -07:00
[mutableEvents
addObjectsFromArray:[self setupListenerOnQuery:query
view:view]];
2017-05-15 12:27:07 -07:00
events = mutableEvents;
}
}
return events;
}
- (FCacheNode *)serverCacheForQuery:(FQuerySpec *)query {
__block id<FNode> serverCacheNode = nil;
2019-08-05 13:27:47 -07:00
[self.syncPointTree
forEachOnPath:query.path
whileBlock:^BOOL(FPath *pathToSyncPoint, FSyncPoint *syncPoint) {
FPath *relativePath = [FPath relativePathFrom:pathToSyncPoint
to:query.path];
serverCacheNode =
[syncPoint completeServerCacheAtPath:relativePath];
return serverCacheNode == nil;
}];
2017-05-15 12:27:07 -07:00
FCacheNode *serverCache;
if (serverCacheNode != nil) {
2019-08-05 13:27:47 -07:00
FIndexedNode *indexed =
[FIndexedNode indexedNodeWithNode:serverCacheNode
index:query.index];
serverCache = [[FCacheNode alloc] initWithIndexedNode:indexed
isFullyInitialized:YES
isFiltered:NO];
2017-05-15 12:27:07 -07:00
} else {
2019-08-05 13:27:47 -07:00
FCacheNode *persistenceServerCache =
[self.persistenceManager serverCacheForQuery:query];
2017-05-15 12:27:07 -07:00
if (persistenceServerCache.isFullyInitialized) {
serverCache = persistenceServerCache;
} else {
serverCacheNode = [FEmptyNode emptyNode];
2019-08-05 13:27:47 -07:00
FImmutableTree *subtree =
[self.syncPointTree subtreeAtPath:query.path];
[subtree
forEachChild:^(NSString *childKey, FSyncPoint *childSyncPoint) {
id<FNode> completeCache =
[childSyncPoint completeServerCacheAtPath:[FPath empty]];
if (completeCache) {
serverCacheNode =
[serverCacheNode updateImmediateChild:childKey
withNewChild:completeCache];
}
}];
2017-05-15 12:27:07 -07:00
// Fill the node with any available children we have
2019-08-05 13:27:47 -07:00
[persistenceServerCache.node
enumerateChildrenUsingBlock:^(NSString *key, id<FNode> node,
BOOL *stop) {
if (![serverCacheNode hasChild:key]) {
serverCacheNode =
[serverCacheNode updateImmediateChild:key
withNewChild:node];
}
}];
FIndexedNode *indexed =
[FIndexedNode indexedNodeWithNode:serverCacheNode
index:query.index];
serverCache = [[FCacheNode alloc] initWithIndexedNode:indexed
isFullyInitialized:NO
isFiltered:NO];
2017-05-15 12:27:07 -07:00
}
}
return serverCache;
}
/**
2019-08-05 13:27:47 -07:00
* Remove event callback(s).
*
* If query is the default query, we'll check all queries for the specified
* eventRegistration. If eventRegistration is null, we'll remove all callbacks
* for the specified query/queries.
*
* @param eventRegistration if nil, all callbacks are removed
* @param cancelError If provided, appropriate cancel events will be returned
* @return NSArray of FEvent to raise.
*/
- (NSArray *)removeEventRegistration:(id<FEventRegistration>)eventRegistration
forQuery:(FQuerySpec *)query
cancelError:(NSError *)cancelError {
// Find the syncPoint first. Then deal with whether or not it has matching
// listeners
2017-05-15 12:27:07 -07:00
FPath *path = query.path;
FSyncPoint *maybeSyncPoint = [self.syncPointTree valueAtPath:path];
NSArray *cancelEvents = @[];
2019-08-05 13:27:47 -07:00
// A removal on a default query affects all queries at that location. A
// removal on an indexed query, even one without other query constraints,
// does *not* affect all queries at that location. So this check must be for
// 'default', and not loadsAllData:
if (maybeSyncPoint &&
([query isDefault] || [maybeSyncPoint viewExistsForQuery:query])) {
FTupleRemovedQueriesEvents *removedAndEvents =
[maybeSyncPoint removeEventRegistration:eventRegistration
forQuery:query
cancelError:cancelError];
2017-05-15 12:27:07 -07:00
if ([maybeSyncPoint isEmpty]) {
self.syncPointTree = [self.syncPointTree removeValueAtPath:path];
}
NSArray *removed = removedAndEvents.removedQueries;
cancelEvents = removedAndEvents.cancelEvents;
2019-08-05 13:27:47 -07:00
// We may have just removed one of many listeners and can short-circuit
// this whole process We may also not have removed a default listener,
// in which case all of the descendant listeners should already be
// properly set up.
2017-05-15 12:27:07 -07:00
//
2019-08-05 13:27:47 -07:00
// Since indexed queries can shadow if they don't have other query
// constraints, check for loadsAllData: instead of isDefault:
NSUInteger defaultQueryIndex = [removed
indexOfObjectPassingTest:^BOOL(FQuerySpec *q, NSUInteger idx,
BOOL *stop) {
return [q loadsAllData];
}];
2017-05-15 12:27:07 -07:00
BOOL removingDefault = defaultQueryIndex != NSNotFound;
2019-08-05 13:27:47 -07:00
[removed enumerateObjectsUsingBlock:^(FQuerySpec *query, NSUInteger idx,
BOOL *stop) {
[self.persistenceManager setQueryInactive:query];
2017-05-15 12:27:07 -07:00
}];
2019-08-05 13:27:47 -07:00
NSNumber *covered = [self.syncPointTree
findOnPath:path
andApplyBlock:^id(FPath *relativePath,
FSyncPoint *parentSyncPoint) {
return
[NSNumber numberWithBool:[parentSyncPoint hasCompleteView]];
}];
2017-05-15 12:27:07 -07:00
if (removingDefault && ![covered boolValue]) {
FImmutableTree *subtree = [self.syncPointTree subtreeAtPath:path];
2019-08-05 13:27:47 -07:00
// There are potentially child listeners. Determine what if any
// listens we need to send before executing the removal
2017-05-15 12:27:07 -07:00
if (![subtree isEmpty]) {
2019-08-05 13:27:47 -07:00
// We need to fold over our subtree and collect the listeners to
// send
NSArray *newViews =
[self collectDistinctViewsForSubTree:subtree];
2017-05-15 12:27:07 -07:00
// Ok, we've collected all the listens we need. Set them up.
2019-08-05 13:27:47 -07:00
[newViews enumerateObjectsUsingBlock:^(
FView *view, NSUInteger idx, BOOL *stop) {
FQuerySpec *newQuery = view.query;
FListenContainer *listenContainer =
[self createListenerForView:view];
self.listenProvider.startListening(
[self queryForListening:newQuery],
[self tagForQuery:newQuery], listenContainer,
listenContainer.onComplete);
2017-05-15 12:27:07 -07:00
}];
} else {
2019-08-05 13:27:47 -07:00
// There's nothing below us, so nothing we need to start
// listening on
2017-05-15 12:27:07 -07:00
}
}
2019-08-05 13:27:47 -07:00
// If we removed anything and we're not covered by a higher up listen,
// we need to stop listening on this query. The above block has us
// covered in terms of making sure we're set up on listens lower in the
// tree. Also, note that if we have a cancelError, it's already been
// removed at the provider level.
2017-05-15 12:27:07 -07:00
if (![covered boolValue] && [removed count] > 0 && cancelError == nil) {
2019-08-05 13:27:47 -07:00
// If we removed a default, then we weren't listening on any of the
// other queries here. Just cancel the one default. Otherwise, we
// need to iterate through and cancel each individual query
2017-05-15 12:27:07 -07:00
if (removingDefault) {
// We don't tag default listeners
2019-08-05 13:27:47 -07:00
self.listenProvider.stopListening(
[self queryForListening:query], nil);
2017-05-15 12:27:07 -07:00
} else {
2019-08-05 13:27:47 -07:00
[removed
enumerateObjectsUsingBlock:^(FQuerySpec *queryToRemove,
NSUInteger idx, BOOL *stop) {
NSNumber *tagToRemove =
[self.queryToTagMap objectForKey:queryToRemove];
self.listenProvider.stopListening(
[self queryForListening:queryToRemove], tagToRemove);
}];
2017-05-15 12:27:07 -07:00
}
}
// Now, clear all the tags we're tracking for the removed listens.
[self removeTags:removed];
} else {
// No-op, this listener must've been already removed
}
return cancelEvents;
}
- (void)keepQuery:(FQuerySpec *)query synced:(BOOL)keepSynced {
// Only do something if we actually need to add/remove an event registration
if (keepSynced && ![self.keepSyncedQueries containsObject:query]) {
2019-08-05 13:27:47 -07:00
[self addEventRegistration:[FKeepSyncedEventRegistration instance]
forQuery:query];
2017-05-15 12:27:07 -07:00
[self.keepSyncedQueries addObject:query];
} else if (!keepSynced && [self.keepSyncedQueries containsObject:query]) {
2019-08-05 13:27:47 -07:00
[self removeEventRegistration:[FKeepSyncedEventRegistration instance]
forQuery:query
cancelError:nil];
2017-05-15 12:27:07 -07:00
[self.keepSyncedQueries removeObject:query];
}
}
2019-08-05 13:27:47 -07:00
- (NSArray *)removeAllWrites {
2017-05-15 12:27:07 -07:00
[self.persistenceManager removeAllUserWrites];
NSArray *removedWrites = [self.pendingWriteTree removeAllWrites];
if (removedWrites.count > 0) {
2019-08-05 13:27:47 -07:00
FImmutableTree *affectedTree =
[[FImmutableTree empty] setValue:@YES atPath:[FPath empty]];
return [self applyOperationToSyncPoints:[[FAckUserWrite alloc]
initWithPath:[FPath empty]
affectedTree:affectedTree
revert:YES]];
2017-05-15 12:27:07 -07:00
} else {
return @[];
}
}
/** Returns a non-empty cache node if one exists. Otherwise returns null. */
- (FIndexedNode *)persistenceServerCache:(FQuerySpec *)querySpec {
FCacheNode *cacheNode =
[self.persistenceManager serverCacheForQuery:querySpec];
if (cacheNode == nil || cacheNode.node.isEmpty) {
return nil;
}
2021-08-10 05:53:09 +02:00
return cacheNode.indexedNode;
}
- (id<FNode>)getServerValue:(FQuerySpec *)query {
__block id<FNode> serverCacheNode = nil;
__block FSyncPoint *targetSyncPoint = nil;
[self.syncPointTree
forEachOnPath:query.path
whileBlock:^BOOL(FPath *pathToSyncPoint, FSyncPoint *syncPoint) {
FPath *relativePath = [FPath relativePathFrom:pathToSyncPoint
to:query.path];
serverCacheNode =
[syncPoint completeEventCacheAtPath:relativePath];
targetSyncPoint = syncPoint;
return serverCacheNode == nil;
}];
if (targetSyncPoint == nil) {
targetSyncPoint = [[FSyncPoint alloc]
initWithPersistenceManager:self.persistenceManager];
self.syncPointTree = [self.syncPointTree setValue:targetSyncPoint
atPath:[query path]];
} else {
serverCacheNode =
serverCacheNode != nil
? serverCacheNode
: [targetSyncPoint completeServerCacheAtPath:[FPath empty]];
}
FIndexedNode *indexed = [FIndexedNode
indexedNodeWithNode:serverCacheNode != nil ? serverCacheNode
: [FEmptyNode emptyNode]
index:query.index];
FCacheNode *serverCache =
[[FCacheNode alloc] initWithIndexedNode:indexed
isFullyInitialized:serverCacheNode != nil
isFiltered:NO];
FView *view = [targetSyncPoint
getView:query
writesCache:[_pendingWriteTree childWritesForPath:[query path]]
serverCache:serverCache];
return [view completeEventCache];
}
2017-05-15 12:27:07 -07:00
/**
2019-08-05 13:27:47 -07:00
* Returns a complete cache, if we have one, of the data at a particular path.
* The location must have a listener above it, but as this is only used by
* transaction code, that should always be the case anyways.
*
* Note: this method will *include* hidden writes from transaction with
* applyLocally set to false.
* @param path The path to the data we want
* @param writeIdsToExclude A specific set to be excluded
*/
- (id<FNode>)calcCompleteEventCacheAtPath:(FPath *)path
excludeWriteIds:(NSArray *)writeIdsToExclude {
2017-05-15 12:27:07 -07:00
BOOL includeHiddenSets = YES;
FWriteTree *writeTree = self.pendingWriteTree;
2019-08-05 13:27:47 -07:00
id<FNode> serverCache = [self.syncPointTree
findOnPath:path
andApplyBlock:^id<FNode>(FPath *pathSoFar, FSyncPoint *syncPoint) {
FPath *relativePath = [FPath relativePathFrom:pathSoFar to:path];
id<FNode> serverCache =
[syncPoint completeServerCacheAtPath:relativePath];
if (serverCache) {
return serverCache;
} else {
return nil;
}
}];
return [writeTree calculateCompleteEventCacheAtPath:path
completeServerCache:serverCache
excludeWriteIds:writeIdsToExclude
includeHiddenWrites:includeHiddenSets];
2017-05-15 12:27:07 -07:00
}
#pragma mark -
#pragma mark Private Methods
/**
2019-08-05 13:27:47 -07:00
* This collapses multiple unfiltered views into a single view, since we only
* need a single listener for them.
* @return NSArray of FView
*/
- (NSArray *)collectDistinctViewsForSubTree:(FImmutableTree *)subtree {
return [subtree foldWithBlock:^NSArray *(FPath *relativePath,
FSyncPoint *maybeChildSyncPoint,
NSDictionary *childMap) {
if (maybeChildSyncPoint && [maybeChildSyncPoint hasCompleteView]) {
FView *completeView = [maybeChildSyncPoint completeView];
return @[ completeView ];
} else {
// No complete view here, flatten any deeper listens into an array
NSMutableArray *views = [[NSMutableArray alloc] init];
if (maybeChildSyncPoint) {
views = [[maybeChildSyncPoint queryViews] mutableCopy];
}
[childMap enumerateKeysAndObjectsUsingBlock:^(
NSString *childKey, NSArray *childViews, BOOL *stop) {
[views addObjectsFromArray:childViews];
}];
return views;
}
2017-05-15 12:27:07 -07:00
}];
}
/**
2019-08-05 13:27:47 -07:00
* @param queries NSArray of FQuerySpec
*/
- (void)removeTags:(NSArray *)queries {
[queries enumerateObjectsUsingBlock:^(FQuerySpec *removedQuery,
NSUInteger idx, BOOL *stop) {
if (![removedQuery loadsAllData]) {
// We should have a tag for this
NSNumber *removedQueryTag = self.queryToTagMap[removedQuery];
[self.queryToTagMap removeObjectForKey:removedQuery];
[self.tagToQueryMap removeObjectForKey:removedQueryTag];
}
2017-05-15 12:27:07 -07:00
}];
}
2019-08-05 13:27:47 -07:00
- (FQuerySpec *)queryForListening:(FQuerySpec *)query {
2017-05-15 12:27:07 -07:00
if (query.loadsAllData && !query.isDefault) {
// We treat queries that load all data as default queries
return [FQuerySpec defaultQueryAtPath:query.path];
} else {
return query;
}
}
/**
2019-08-05 13:27:47 -07:00
* For a given new listen, manage the de-duplication of outstanding
* subscriptions.
* @return NSArray of FEvent events to support synchronous data sources
*/
- (NSArray *)setupListenerOnQuery:(FQuerySpec *)query view:(FView *)view {
2017-05-15 12:27:07 -07:00
FPath *path = query.path;
NSNumber *tagId = [self tagForQuery:query];
FListenContainer *listenContainer = [self createListenerForView:view];
2019-08-05 13:27:47 -07:00
NSArray *events = self.listenProvider.startListening(
[self queryForListening:query], tagId, listenContainer,
listenContainer.onComplete);
2017-05-15 12:27:07 -07:00
FImmutableTree *subtree = [self.syncPointTree subtreeAtPath:path];
2019-08-05 13:27:47 -07:00
// The root of this subtree has our query. We're here because we definitely
// need to send a listen for that, but we may need to shadow other listens
// as well.
2017-05-15 12:27:07 -07:00
if (tagId != nil) {
2019-08-05 13:27:47 -07:00
NSAssert(![subtree.value hasCompleteView],
@"If we're adding a query, it shouldn't be shadowed");
2017-05-15 12:27:07 -07:00
} else {
2019-08-05 13:27:47 -07:00
// Shadow everything at or below this location, this is a default
// listener.
NSArray *queriesToStop =
[subtree foldWithBlock:^id(FPath *relativePath,
FSyncPoint *maybeChildSyncPoint,
NSDictionary *childMap) {
if (![relativePath isEmpty] && maybeChildSyncPoint != nil &&
[maybeChildSyncPoint hasCompleteView]) {
return @[ [maybeChildSyncPoint completeView].query ];
} else {
// No default listener here, flatten any deeper queries into
// an array
NSMutableArray *queries = [[NSMutableArray alloc] init];
if (maybeChildSyncPoint != nil) {
for (FView *view in [maybeChildSyncPoint queryViews]) {
[queries addObject:view.query];
}
}
[childMap
enumerateKeysAndObjectsUsingBlock:^(
NSString *key, NSArray *childQueries, BOOL *stop) {
[queries addObjectsFromArray:childQueries];
}];
return queries;
}
}];
2017-05-15 12:27:07 -07:00
for (FQuerySpec *queryToStop in queriesToStop) {
2019-08-05 13:27:47 -07:00
self.listenProvider.stopListening(
[self queryForListening:queryToStop],
[self tagForQuery:queryToStop]);
2017-05-15 12:27:07 -07:00
}
}
return events;
}
2019-08-05 13:27:47 -07:00
- (FListenContainer *)createListenerForView:(FView *)view {
2017-05-15 12:27:07 -07:00
FQuerySpec *query = view.query;
NSNumber *tagId = [self tagForQuery:query];
2019-08-05 13:27:47 -07:00
FListenContainer *listenContainer = [[FListenContainer alloc]
initWithView:view
onComplete:^(NSString *status) {
if ([status isEqualToString:@"ok"]) {
if (tagId != nil) {
return [self applyTaggedListenCompleteAtPath:query.path
tagId:tagId];
} else {
return [self applyListenCompleteAtPath:query.path];
}
2017-05-15 12:27:07 -07:00
} else {
2019-08-05 13:27:47 -07:00
// If a listen failed, kill all of the listeners here, not just
// the one that triggered the error. Note that this may need to
// be scoped to just this listener if we change permissions on
// filtered children
NSError *error = [FUtilities errorForStatus:status
andReason:nil];
FFWarn(@"I-RDB038012", @"Listener at %@ failed: %@", query.path,
status);
return [self removeEventRegistration:nil
forQuery:query
cancelError:error];
2017-05-15 12:27:07 -07:00
}
2019-08-05 13:27:47 -07:00
}];
2017-05-15 12:27:07 -07:00
return listenContainer;
}
/**
2019-08-05 13:27:47 -07:00
* @return The query associated with the given tag, if we have one
*/
- (FQuerySpec *)queryForTag:(NSNumber *)tagId {
2017-05-15 12:27:07 -07:00
return self.tagToQueryMap[tagId];
}
/**
2019-08-05 13:27:47 -07:00
* @return The tag associated with the given query
*/
- (NSNumber *)tagForQuery:(FQuerySpec *)query {
2017-05-15 12:27:07 -07:00
return self.queryToTagMap[query];
}
#pragma mark -
#pragma mark applyOperation Helpers
/**
2019-08-05 13:27:47 -07:00
* A helper method that visits all descendant and ancestor SyncPoints, applying
the operation.
2017-05-15 12:27:07 -07:00
*
* NOTES:
2019-08-05 13:27:47 -07:00
* - Descendant SyncPoints will be visited first (since we raise events
depth-first).
2017-05-15 12:27:07 -07:00
* - We call applyOperation: on each SyncPoint passing three things:
2019-08-05 13:27:47 -07:00
* 1. A version of the Operation that has been made relative to the SyncPoint
location.
2017-05-15 12:27:07 -07:00
* 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.
* 3. A snapshot Node with cached server data, if we have it.
2019-08-05 13:27:47 -07:00
* - We concatenate all of the events returned by each SyncPoint and return the
result.
2017-05-15 12:27:07 -07:00
*
* @return Array of FEvent
*/
2019-08-05 13:27:47 -07:00
- (NSArray *)applyOperationToSyncPoints:(id<FOperation>)operation {
return [self applyOperationHelper:operation
syncPointTree:self.syncPointTree
serverCache:nil
writesCache:[self.pendingWriteTree
childWritesForPath:[FPath empty]]];
2017-05-15 12:27:07 -07:00
}
/**
2019-08-05 13:27:47 -07:00
* Recursive helper for applyOperationToSyncPoints_
*/
- (NSArray *)applyOperationHelper:(id<FOperation>)operation
syncPointTree:(FImmutableTree *)syncPointTree
serverCache:(id<FNode>)serverCache
writesCache:(FWriteTreeRef *)writesCache {
2017-05-15 12:27:07 -07:00
if ([operation.path isEmpty]) {
2019-08-05 13:27:47 -07:00
return [self applyOperationDescendantsHelper:operation
syncPointTree:syncPointTree
serverCache:serverCache
writesCache:writesCache];
2017-05-15 12:27:07 -07:00
} else {
FSyncPoint *syncPoint = syncPointTree.value;
2019-08-05 13:27:47 -07:00
// If we don't have cached server data, see if we can get it from this
// SyncPoint
2017-05-15 12:27:07 -07:00
if (serverCache == nil && syncPoint != nil) {
serverCache = [syncPoint completeServerCacheAtPath:[FPath empty]];
}
NSMutableArray *events = [[NSMutableArray alloc] init];
NSString *childKey = [operation.path getFront];
id<FOperation> childOperation = [operation operationForChild:childKey];
FImmutableTree *childTree = [syncPointTree.children get:childKey];
if (childTree != nil && childOperation != nil) {
2019-08-05 13:27:47 -07:00
id<FNode> childServerCache =
serverCache ? [serverCache getImmediateChild:childKey] : nil;
FWriteTreeRef *childWritesCache =
[writesCache childWriteTreeRef:childKey];
[events
addObjectsFromArray:[self
applyOperationHelper:childOperation
syncPointTree:childTree
serverCache:childServerCache
writesCache:childWritesCache]];
2017-05-15 12:27:07 -07:00
}
if (syncPoint) {
2019-08-05 13:27:47 -07:00
[events addObjectsFromArray:[syncPoint applyOperation:operation
writesCache:writesCache
serverCache:serverCache]];
2017-05-15 12:27:07 -07:00
}
return events;
}
}
/**
2019-08-05 13:27:47 -07:00
* Recursive helper for applyOperationToSyncPoints:
*/
- (NSArray *)applyOperationDescendantsHelper:(id<FOperation>)operation
syncPointTree:(FImmutableTree *)syncPointTree
serverCache:(id<FNode>)serverCache
writesCache:(FWriteTreeRef *)writesCache {
2017-05-15 12:27:07 -07:00
FSyncPoint *syncPoint = syncPointTree.value;
2019-08-05 13:27:47 -07:00
// If we don't have cached server data, see if we can get it from this
// SyncPoint
2017-05-15 12:27:07 -07:00
id<FNode> resolvedServerCache;
if (serverCache == nil & syncPoint != nil) {
2019-08-05 13:27:47 -07:00
resolvedServerCache =
[syncPoint completeServerCacheAtPath:[FPath empty]];
2017-05-15 12:27:07 -07:00
} else {
resolvedServerCache = serverCache;
}
NSMutableArray *events = [[NSMutableArray alloc] init];
2019-08-05 13:27:47 -07:00
[syncPointTree.children enumerateKeysAndObjectsUsingBlock:^(
NSString *childKey, FImmutableTree *childTree,
BOOL *stop) {
id<FNode> childServerCache = nil;
if (resolvedServerCache != nil) {
childServerCache = [resolvedServerCache getImmediateChild:childKey];
}
FWriteTreeRef *childWritesCache =
[writesCache childWriteTreeRef:childKey];
id<FOperation> childOperation = [operation operationForChild:childKey];
if (childOperation != nil) {
[events addObjectsFromArray:
[self applyOperationDescendantsHelper:childOperation
syncPointTree:childTree
serverCache:childServerCache
writesCache:childWritesCache]];
}
2017-05-15 12:27:07 -07:00
}];
if (syncPoint) {
2019-08-05 13:27:47 -07:00
[events
addObjectsFromArray:[syncPoint applyOperation:operation
writesCache:writesCache
serverCache:resolvedServerCache]];
2017-05-15 12:27:07 -07:00
}
return events;
}
@end