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 {
23 if ((self = [super init])) {
24 self.keysToNotHandle = [NSMutableSet<NSString*> set];
25 self.keyChanges = [NSMutableDictionary<NSString*, NSObject*> dictionary];
27 self.peerChanges = [NSMutableSet<NSString*> set];
28 self.peersToNotSyncWith = [NSMutableSet<NSString*> set];
30 self.backupPeerChanges = [NSMutableSet<NSString*> set];
31 self.backupPeersToNotSyncWith = [NSMutableSet<NSString*> set];
33 self.peerRegistrationEnsured = NO;
38 - (NSSet*) keysChanged: (NSDictionary<NSString*, NSObject*>*) keyValues
39 error: (NSError**) error {
41 NSMutableSet<NSString*>* result = [NSMutableSet<NSString*> set];
43 [keyValues enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, NSObject * _Nonnull obj, BOOL * _Nonnull stop) {
44 if (![self.keysToNotHandle containsObject:key]) {
45 [self.keyChanges setObject:obj forKey:key];
46 [result addObject:key];
53 - (bool) ensurePeerRegistration: (NSError**) error {
54 if (self.peerRegistrationFailureReason == nil) {
55 self.peerRegistrationEnsured = YES;
59 *error = self.peerRegistrationFailureReason;
65 - (NSSet<NSString*>*) syncWithPeers: (NSSet<NSString*>*) peerIDs
66 backups: (NSSet<NSString*>*) backupPeerIDs
67 error: (NSError**) error {
68 NSMutableSet<NSString*>* peerIDsToTake = [peerIDs mutableCopy];
69 [peerIDsToTake minusSet:self.peersToNotSyncWith];
70 [self.peerChanges unionSet: peerIDsToTake];
72 NSMutableSet<NSString*>* backupPeerIDsToTake = [NSMutableSet<NSString*> setWithSet: backupPeerIDs];
73 [backupPeerIDsToTake minusSet:self.backupPeersToNotSyncWith];
74 [self.backupPeerChanges unionSet: backupPeerIDsToTake];
76 // Calculate what we took.
77 [peerIDsToTake unionSet:backupPeerIDsToTake];
81 - (bool) syncWithAllPeers: (NSError**) error {
85 - (NSDictionary<NSString*, NSObject*>*) extractKeyChanges {
86 NSDictionary<NSString*, NSObject*>* result = self.keyChanges;
87 self.keyChanges = [NSMutableDictionary<NSString*, NSObject*> dictionary];
91 - (NSSet<NSString*>*) extractPeerChanges {
92 NSSet<NSString*>* result = self.peerChanges;
93 self.peerChanges = [NSMutableSet<NSString*> set];
96 - (NSSet<NSString*>*) extractBackupPeerChanges {
97 NSSet<NSString*>* result = self.backupPeerChanges;
98 self.backupPeerChanges = [NSMutableSet<NSString*> set];
102 - (BOOL) extractRegistrationEnsured {
103 BOOL result = self.peerRegistrationEnsured;
104 self.peerRegistrationEnsured = NO;