2 // CKDSimulatedAccount+CKDSimulatedAccount.m
6 #import "CKDSimulatedAccount.h"
8 #import <Foundation/Foundation.h>
10 @interface CKDSimulatedAccount ()
11 @property (readwrite) NSMutableDictionary<NSString*, NSObject*>* keyChanges;
12 @property (readwrite) NSMutableSet<NSString*>* peerChanges;
13 @property (readwrite) NSMutableSet<NSString*>* backupPeerChanges;
14 @property (readwrite) BOOL peerRegistrationEnsured;
17 @implementation CKDSimulatedAccount
19 + (instancetype) account {
20 return [[CKDSimulatedAccount alloc] init];
22 - (instancetype) init {
25 self.keysToNotHandle = [NSMutableSet<NSString*> set];
26 self.keyChanges = [NSMutableDictionary<NSString*, NSObject*> dictionary];
28 self.peerChanges = [NSMutableSet<NSString*> set];
29 self.peersToNotSyncWith = [NSMutableSet<NSString*> set];
31 self.backupPeerChanges = [NSMutableSet<NSString*> set];
32 self.backupPeersToNotSyncWith = [NSMutableSet<NSString*> set];
34 self.peerRegistrationEnsured = NO;
39 - (NSSet*) keysChanged: (NSDictionary<NSString*, NSObject*>*) keyValues
40 error: (NSError**) error {
42 NSMutableSet<NSString*>* result = [NSMutableSet<NSString*> set];
44 [keyValues enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, NSObject * _Nonnull obj, BOOL * _Nonnull stop) {
45 if (![self.keysToNotHandle containsObject:key]) {
46 [self.keyChanges setObject:obj forKey:key];
47 [result addObject:key];
54 - (bool) ensurePeerRegistration: (NSError**) error {
55 if (self.peerRegistrationFailureReason == nil) {
56 self.peerRegistrationEnsured = YES;
60 *error = self.peerRegistrationFailureReason;
66 - (NSSet<NSString*>*) syncWithPeers: (NSSet<NSString*>*) peerIDs
67 backups: (NSSet<NSString*>*) backupPeerIDs
68 error: (NSError**) error {
69 NSMutableSet<NSString*>* peerIDsToTake = [peerIDs mutableCopy];
70 [peerIDsToTake minusSet:self.peersToNotSyncWith];
71 [self.peerChanges unionSet: peerIDsToTake];
73 NSMutableSet<NSString*>* backupPeerIDsToTake = [NSMutableSet<NSString*> setWithSet: backupPeerIDs];
74 [backupPeerIDsToTake minusSet:self.backupPeersToNotSyncWith];
75 [self.backupPeerChanges unionSet: backupPeerIDsToTake];
77 // Calculate what we took.
78 [peerIDsToTake unionSet:backupPeerIDsToTake];
82 - (bool) syncWithAllPeers: (NSError**) error {
86 - (NSDictionary<NSString*, NSObject*>*) extractKeyChanges {
87 NSDictionary<NSString*, NSObject*>* result = self.keyChanges;
88 self.keyChanges = [NSMutableDictionary<NSString*, NSObject*> dictionary];
92 - (NSSet<NSString*>*) extractPeerChanges {
93 NSSet<NSString*>* result = self.peerChanges;
94 self.peerChanges = [NSMutableSet<NSString*> set];
97 - (NSSet<NSString*>*) extractBackupPeerChanges {
98 NSSet<NSString*>* result = self.backupPeerChanges;
99 self.backupPeerChanges = [NSMutableSet<NSString*> set];
103 - (BOOL) extractRegistrationEnsured {
104 BOOL result = self.peerRegistrationEnsured;
105 self.peerRegistrationEnsured = NO;