2 * Copyright (c) 2016 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
26 #import "keychain/ckks/CKKSResultOperation.h"
27 #import "keychain/ckks/NSOperationCategories.h"
28 #import "keychain/ckks/CKKSCondition.h"
29 #import "keychain/categories/NSError+UsefulConstructors.h"
30 #include <utilities/debugging.h>
32 @interface CKKSResultOperation()
33 @property NSMutableArray<CKKSResultOperation*>* successDependencies;
34 @property bool timeoutCanOccur;
35 @property dispatch_queue_t timeoutQueue;
36 @property void (^finishingBlock)(void);
39 @implementation CKKSResultOperation
40 - (instancetype)init {
41 if(self = [super init]) {
43 _successDependencies = [[NSMutableArray alloc] init];
44 _timeoutCanOccur = true;
45 _timeoutQueue = dispatch_queue_create("result-operation-timeout", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL);
46 _completionHandlerDidRunCondition = [[CKKSCondition alloc] init];
48 __weak __typeof(self) weakSelf = self;
49 _finishingBlock = ^(void) {
50 weakSelf.finishDate = [NSDate dateWithTimeIntervalSinceNow:0];
52 self.completionBlock = ^{}; // our _finishing block gets added in the method override
57 - (NSString*)operationStateString {
58 return ([self isFinished] ? [NSString stringWithFormat:@"finished %@", self.finishDate] :
59 [self isCancelled] ? @"cancelled" :
60 [self isExecuting] ? @"executing" :
61 [self isReady] ? @"ready" :
65 - (NSString*)description {
66 NSString* state = [self operationStateString];
69 return [NSString stringWithFormat: @"<%@: %@ error:%@>", [self selfname], state, self.error];
71 return [NSString stringWithFormat: @"<%@: %@%@>", [self selfname], state, [self pendingDependenciesString:@" dep:"]];
75 - (NSString*)debugDescription {
76 return [self description];
79 - (void)setCompletionBlock:(void (^)(void))completionBlock
81 __weak __typeof(self) weakSelf = self;
82 [super setCompletionBlock:^(void) {
83 __strong __typeof(self) strongSelf = weakSelf;
85 secerror("ckksresultoperation: completion handler called on deallocated operation instance");
86 completionBlock(); // go ahead and still behave as things would if this method override were not here
90 strongSelf.finishingBlock();
92 [strongSelf.completionHandlerDidRunCondition fulfill];
94 for (NSOperation *op in strongSelf.dependencies) {
95 [strongSelf removeDependency:op];
101 if(![self allDependentsSuccessful]) {
102 secdebug("ckksresultoperation", "Not running due to some failed dependent: %@", self.error);
105 [self invalidateTimeout];
112 - (void)invalidateTimeout {
113 dispatch_sync(self.timeoutQueue, ^{
114 if(![self isCancelled]) {
115 self.timeoutCanOccur = false;
120 - (NSError* _Nullable)dependenciesDescriptionError {
121 NSError* underlyingReason = nil;
122 NSArray* dependencies = [self.dependencies copy];
123 dependencies = [dependencies objectsAtIndexes: [dependencies indexesOfObjectsPassingTest: ^BOOL (id obj,
126 return [obj isFinished] ? NO : YES;
129 for(NSOperation* dependency in dependencies) {
130 if([dependency isKindOfClass:[CKKSResultOperation class]]) {
131 CKKSResultOperation* ro = (CKKSResultOperation*)dependency;
132 underlyingReason = [ro descriptionError] ?: underlyingReason;
136 return underlyingReason;
139 // Returns, for this CKKSResultOperation, an error describing this operation or its dependents.
140 // Used mainly by other CKKSResultOperations who time out waiting for this operation to start/complete.
141 - (NSError* _Nullable)descriptionError {
142 if(self.descriptionErrorCode != 0) {
143 return [NSError errorWithDomain:CKKSResultDescriptionErrorDomain
144 code:self.descriptionErrorCode
147 return [self dependenciesDescriptionError];
151 - (NSError*)_onqueueTimeoutError {
152 // Find if any of our dependencies are CKKSResultOperations with a custom reason for existing
154 NSError* underlyingReason = [self descriptionError];
156 NSError* error = [NSError errorWithDomain:CKKSResultErrorDomain
157 code:CKKSResultTimedOut
158 description:[NSString stringWithFormat:@"Operation(%@) timed out waiting to start for [%@]",
160 [self pendingDependenciesString:@""]]
161 underlying:underlyingReason];
165 - (instancetype)timeout:(dispatch_time_t)timeout {
166 __weak __typeof(self) weakSelf = self;
167 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timeout), self.timeoutQueue, ^{
168 __strong __typeof(self) strongSelf = weakSelf;
169 if(strongSelf.timeoutCanOccur) {
170 strongSelf.error = [self _onqueueTimeoutError];
171 strongSelf.timeoutCanOccur = false;
179 - (void)addSuccessDependency:(CKKSResultOperation *)operation {
180 [self addNullableSuccessDependency:operation];
183 - (void)addNullableSuccessDependency:(CKKSResultOperation *)operation {
187 @synchronized(self) {
188 [self.successDependencies addObject: operation];
189 [self addDependency: operation];
193 - (bool)allDependentsSuccessful {
194 return [self allSuccessful: self.successDependencies];
197 - (bool)allSuccessful: (NSArray<CKKSResultOperation*>*) operations {
198 @synchronized(self) {
201 bool finished = true; // all dependents must be finished
202 bool cancelled = false; // no dependents can be cancelled
203 bool failed = false; // no dependents can have failed
204 NSMutableArray<NSOperation*>* cancelledSuboperations = [NSMutableArray array];
206 for(CKKSResultOperation* op in operations) {
207 finished &= !!([op isFinished]);
208 cancelled |= !!([op isCancelled]);
209 failed |= (op.error != nil);
211 if([op isCancelled]) {
212 [cancelledSuboperations addObject:op];
215 // TODO: combine suberrors
216 if(op.error != nil) {
217 if([op.error.domain isEqual: CKKSResultErrorDomain] && op.error.code == CKKSResultSubresultError) {
218 // Already a subresult, just copy it on in
219 self.error = op.error;
221 self.error = [NSError errorWithDomain:CKKSResultErrorDomain
222 code:CKKSResultSubresultError
223 description:@"Success-dependent operation failed"
224 underlying:op.error];
229 result = finished && !( cancelled || failed );
231 if(!result && self.error == nil) {
232 self.error = [NSError errorWithDomain:CKKSResultErrorDomain code: CKKSResultSubresultCancelled userInfo:@{NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Operation (%@) cancelled", cancelledSuboperations]}];
238 + (CKKSResultOperation*)operationWithBlock:(void (^)(void))block {
239 CKKSResultOperation* op = [[CKKSResultOperation alloc] init];
240 [op addExecutionBlock: block];
244 +(instancetype)named:(NSString*)name withBlock:(void(^)(void)) block {
245 CKKSResultOperation* blockOp = [CKKSResultOperation operationWithBlock: block];
250 + (instancetype)named:(NSString*)name withBlockTakingSelf:(void(^)(CKKSResultOperation* op))block
252 CKKSResultOperation* op = [[CKKSResultOperation alloc] init];
253 __weak __typeof(op) weakOp = op;
254 [op addExecutionBlock:^{
255 __strong __typeof(op) strongOp = weakOp;