2 * Copyright (c) 2017 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 "CKKSNearFutureScheduler.h"
27 #import "CKKSCondition.h"
28 #import "keychain/ckks/NSOperationCategories.h"
29 #import "keychain/ckks/CKKSResultOperation.h"
30 #import "keychain/ot/ObjCImprovements.h"
31 #include <os/transaction_private.h>
33 @interface CKKSNearFutureScheduler ()
34 @property NSString* name;
35 @property dispatch_time_t initialDelay;
37 @property dispatch_time_t currentDelay;
38 @property dispatch_time_t maximumDelay;
40 @property double backoff;
42 @property NSInteger operationDependencyDescriptionCode;
43 @property CKKSResultOperation* operationDependency;
44 @property (nonnull) NSOperationQueue* operationQueue;
46 @property NSDate* predictedNextFireTime;
47 @property bool liveRequest;
49 @property dispatch_source_t timer;
50 @property dispatch_queue_t queue;
52 @property bool keepProcessAlive;
53 @property os_transaction_t transaction;
56 @implementation CKKSNearFutureScheduler
58 -(instancetype)initWithName:(NSString*)name
59 delay:(dispatch_time_t)ns
60 keepProcessAlive:(bool)keepProcessAlive
61 dependencyDescriptionCode:(NSInteger)code
62 block:(void (^)(void))futureBlock
64 return [self initWithName:name
67 keepProcessAlive:keepProcessAlive
68 dependencyDescriptionCode:code
72 -(instancetype)initWithName:(NSString*)name
73 initialDelay:(dispatch_time_t)initialDelay
74 continuingDelay:(dispatch_time_t)continuingDelay
75 keepProcessAlive:(bool)keepProcessAlive
76 dependencyDescriptionCode:(NSInteger)code
77 block:(void (^)(void))futureBlock
79 // If the continuing delay is below the initial delay, use an exponential backoff of 1
80 // We'll clamp the timer delay to continuing delay at use time.
81 return [self initWithName:name
82 initialDelay:initialDelay
83 expontialBackoff:MAX(initialDelay > 0 ? (continuingDelay / initialDelay) : 1, 1)
84 maximumDelay:continuingDelay
85 keepProcessAlive:keepProcessAlive
86 dependencyDescriptionCode:code
90 - (instancetype)initWithName:(NSString*)name
91 initialDelay:(dispatch_time_t)initialDelay
92 expontialBackoff:(double)backoff
93 maximumDelay:(dispatch_time_t)maximumDelay
94 keepProcessAlive:(bool)keepProcessAlive
95 dependencyDescriptionCode:(NSInteger)code
96 block:(void (^_Nonnull)(void))futureBlock
98 if((self = [super init])) {
101 _queue = dispatch_queue_create([[NSString stringWithFormat:@"near-future-scheduler-%@",name] UTF8String], DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL);
102 _initialDelay = initialDelay;
104 _currentDelay = initialDelay;
105 _maximumDelay = maximumDelay;
108 _futureBlock = futureBlock;
110 _liveRequest = false;
111 _liveRequestReceived = [[CKKSCondition alloc] init];
112 _predictedNextFireTime = nil;
114 _keepProcessAlive = keepProcessAlive;
116 _operationQueue = [[NSOperationQueue alloc] init];
117 _operationDependencyDescriptionCode = code;
118 _operationDependency = [self makeOperationDependency];
123 - (void)changeDelays:(dispatch_time_t)initialDelay continuingDelay:(dispatch_time_t)continuingDelay
125 dispatch_sync(self.queue, ^{
126 self.initialDelay = initialDelay;
127 self.currentDelay = self.initialDelay;
128 self.backoff = initialDelay > 0 ? ((double)continuingDelay) / initialDelay : 1;
129 self.maximumDelay = continuingDelay;
133 - (CKKSResultOperation*)makeOperationDependency {
134 CKKSResultOperation* op = [CKKSResultOperation named:[NSString stringWithFormat:@"nfs-%@", self.name] withBlock:^{}];
135 op.descriptionErrorCode = self.operationDependencyDescriptionCode;
139 -(NSString*)description {
140 NSDate* nextAt = self.nextFireTime;
142 NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
143 [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
144 return [NSString stringWithFormat: @"<CKKSNearFutureScheduler(%@): next at %@", self.name, [dateFormatter stringFromDate: nextAt]];
146 return [NSString stringWithFormat: @"<CKKSNearFutureScheduler(%@): no pending attempts", self.name];
150 - (NSDate*)nextFireTime {
151 // If we have a live request, send the next fire time back. Otherwise, wait a tiny tiny bit to see if we receive a request.
152 if(self.liveRequest) {
153 return self.predictedNextFireTime;
154 } else if([self.liveRequestReceived wait:50*NSEC_PER_USEC] == 0) {
155 return self.predictedNextFireTime;
161 -(void)waitUntil:(uint64_t)delay {
162 dispatch_sync(self.queue, ^{
163 [self _onqueueTrigger:delay maximumDelay:DISPATCH_TIME_FOREVER];
167 - (void)triggerAt:(uint64_t)delay {
169 dispatch_async(self.queue, ^{
171 self.liveRequest = true;
172 [self.liveRequestReceived fulfill];
173 [self _onqueueTrigger:(delay == DISPATCH_TIME_FOREVER ? DISPATCH_TIME_NOW : delay) maximumDelay:delay];
177 -(void)_onqueueTimerTick {
178 dispatch_assert_queue(self.queue);
180 if(self.liveRequest) {
181 // Put a new dependency in place, and save the old one for execution
182 NSOperation* dependency = self.operationDependency;
183 self.operationDependency = [self makeOperationDependency];
186 self.liveRequest = false;
187 self.liveRequestReceived = [[CKKSCondition alloc] init];
188 self.transaction = nil;
190 // No current delay means that exponential backoff means nothing. Head straight for slowtown.
191 if(self.currentDelay == 0) {
192 self.currentDelay = self.maximumDelay;
194 // Modify the delay by the exponential backoff, unless that exceeds the maximum delay
195 self.currentDelay = MIN(self.currentDelay * self.backoff, self.maximumDelay);
197 dispatch_source_set_timer(self.timer,
198 dispatch_walltime(NULL, self.currentDelay),
202 [self.operationQueue addOperation: dependency];
204 self.predictedNextFireTime = [NSDate dateWithTimeIntervalSinceNow: (NSTimeInterval) ((double) self.currentDelay) / (double) NSEC_PER_SEC];
206 // The timer has fired with no requests to call the block. Cancel it.
207 dispatch_source_cancel(self.timer);
208 self.predictedNextFireTime = nil;
209 self.currentDelay = self.initialDelay;
215 dispatch_async(self.queue, ^{
217 // The timer tick should call the block!
218 self.liveRequest = true;
219 [self.liveRequestReceived fulfill];
221 [self _onqueueTrigger:DISPATCH_TIME_NOW maximumDelay:DISPATCH_TIME_FOREVER];
225 -(void)_onqueueTrigger:(dispatch_time_t)requestedDelay maximumDelay:(dispatch_time_t)maximumDelay {
226 dispatch_assert_queue(self.queue);
229 // If we don't have one already, set up an os_transaction
230 if(self.keepProcessAlive && self.transaction == nil) {
231 self.transaction = os_transaction_create([[NSString stringWithFormat:@"com.apple.securityd.%@",self.name] UTF8String]);
234 if(requestedDelay != DISPATCH_TIME_NOW && self.predictedNextFireTime != nil) {
235 NSDate* delayTime = [NSDate dateWithTimeIntervalSinceNow: (NSTimeInterval) ((double) requestedDelay) / (double) NSEC_PER_SEC];
236 if([delayTime compare:self.predictedNextFireTime] != NSOrderedDescending) {
237 // The next fire time is after this delay. Do nothing with the request.
239 // Need to cancel the timer and reset it below.
240 dispatch_source_cancel(self.timer);
241 self.predictedNextFireTime = nil;
245 if(maximumDelay != DISPATCH_TIME_FOREVER && self.predictedNextFireTime != nil) {
246 NSDate* delayTime = [NSDate dateWithTimeIntervalSinceNow: (NSTimeInterval) ((double) requestedDelay) / (double) NSEC_PER_SEC];
247 if([delayTime compare:self.predictedNextFireTime] != NSOrderedDescending) {
248 // Need to cancel the timer and reset it below.
249 dispatch_source_cancel(self.timer);
250 self.predictedNextFireTime = nil;
252 // The next fire time is before the maximum delay. Do nothing with the request.
256 // Check if the timer is alive
257 if(self.timer != nil && 0 == dispatch_source_testcancel(self.timer)) {
258 // timer is alive, do nothing
261 self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,
263 (dispatch_source_timer_flags_t)0,
265 dispatch_source_set_event_handler(self.timer, ^{
267 [self _onqueueTimerTick];
270 dispatch_time_t actualDelay = self.currentDelay;
271 if(requestedDelay != DISPATCH_TIME_NOW) {
272 actualDelay = MAX(actualDelay, requestedDelay);
274 if(maximumDelay != DISPATCH_TIME_FOREVER) {
275 actualDelay = MIN(actualDelay, maximumDelay);
278 // Note: we pass initialDelay in as the timerInterval here. [-_onqueueTimerTick] is responsible for
279 // modifying the delay to be correct for the next time period.
280 dispatch_source_set_timer(self.timer,
281 dispatch_walltime(NULL, actualDelay),
284 dispatch_resume(self.timer);
286 self.predictedNextFireTime = [NSDate dateWithTimeIntervalSinceNow: (NSTimeInterval) ((double) actualDelay) / (double) NSEC_PER_SEC];
291 dispatch_sync(self.queue, ^{
292 if(self.timer != nil && 0 == dispatch_source_testcancel(self.timer)) {
293 dispatch_source_cancel(self.timer);