FSTDispatchQueue.mm 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. /*
  2. * Copyright 2017 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import <Foundation/Foundation.h>
  17. #import "Firestore/Source/Util/FSTAssert.h"
  18. #import "Firestore/Source/Util/FSTDispatchQueue.h"
  19. NS_ASSUME_NONNULL_BEGIN
  20. /**
  21. * removeDelayedCallback is used by FSTDelayedCallback and so we pre-declare it before the rest of
  22. * the FSTDispatchQueue private interface.
  23. */
  24. @interface FSTDispatchQueue ()
  25. - (void)removeDelayedCallback:(FSTDelayedCallback *)callback;
  26. @end
  27. #pragma mark - FSTDelayedCallback
  28. /**
  29. * Represents a callback scheduled to be run in the future on an FSTDispatchQueue.
  30. *
  31. * It is created via [FSTDelayedCallback createAndScheduleWithQueue].
  32. *
  33. * Supports cancellation (via cancel) and early execution (via skipDelay).
  34. */
  35. @interface FSTDelayedCallback ()
  36. @property(nonatomic, strong, readonly) FSTDispatchQueue *queue;
  37. @property(nonatomic, assign, readonly) FSTTimerID timerID;
  38. @property(nonatomic, assign, readonly) NSTimeInterval targetTime;
  39. @property(nonatomic, copy) void (^callback)();
  40. /** YES if the callback has been run or canceled. */
  41. @property(nonatomic, getter=isDone) BOOL done;
  42. /**
  43. * Creates and returns an FSTDelayedCallback that has been scheduled on the provided queue with the
  44. * provided delay.
  45. *
  46. * @param queue The FSTDispatchQueue to run the callback on.
  47. * @param timerID A FSTTimerID identifying the type of the delayed callback.
  48. * @param delay The delay before the callback should be scheduled.
  49. * @param callback The callback block to run.
  50. * @return The created FSTDelayedCallback instance.
  51. */
  52. + (instancetype)createAndScheduleWithQueue:(FSTDispatchQueue *)queue
  53. timerID:(FSTTimerID)timerID
  54. delay:(NSTimeInterval)delay
  55. callback:(void (^)(void))callback;
  56. /**
  57. * Queues the callback to run immediately (if it hasn't already been run or canceled).
  58. */
  59. - (void)skipDelay;
  60. @end
  61. @implementation FSTDelayedCallback
  62. - (instancetype)initWithQueue:(FSTDispatchQueue *)queue
  63. timerID:(FSTTimerID)timerID
  64. targetTime:(NSTimeInterval)targetTime
  65. callback:(void (^)(void))callback {
  66. if (self = [super init]) {
  67. _queue = queue;
  68. _timerID = timerID;
  69. _targetTime = targetTime;
  70. _callback = callback;
  71. _done = NO;
  72. }
  73. return self;
  74. }
  75. + (instancetype)createAndScheduleWithQueue:(FSTDispatchQueue *)queue
  76. timerID:(FSTTimerID)timerID
  77. delay:(NSTimeInterval)delay
  78. callback:(void (^)(void))callback {
  79. NSTimeInterval targetTime = [[NSDate date] timeIntervalSince1970] + delay;
  80. FSTDelayedCallback *delayedCallback = [[FSTDelayedCallback alloc] initWithQueue:queue
  81. timerID:timerID
  82. targetTime:targetTime
  83. callback:callback];
  84. [delayedCallback startWithDelay:delay];
  85. return delayedCallback;
  86. }
  87. /**
  88. * Starts the timer. This is called immediately after construction by createAndScheduleWithQueue.
  89. */
  90. - (void)startWithDelay:(NSTimeInterval)delay {
  91. dispatch_time_t delayNs = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC));
  92. dispatch_after(delayNs, self.queue.queue, ^{
  93. [self delayDidElapse];
  94. });
  95. }
  96. - (void)skipDelay {
  97. [self.queue dispatchAsyncAllowingSameQueue:^{
  98. [self delayDidElapse];
  99. }];
  100. }
  101. - (void)cancel {
  102. [self.queue verifyIsCurrentQueue];
  103. if (!self.isDone) {
  104. // PORTING NOTE: There's no way to actually cancel the dispatched callback, but it'll be a no-op
  105. // since we set done to YES.
  106. [self markDone];
  107. }
  108. }
  109. - (void)delayDidElapse {
  110. [self.queue verifyIsCurrentQueue];
  111. if (!self.isDone) {
  112. [self markDone];
  113. self.callback();
  114. }
  115. }
  116. /**
  117. * Marks this delayed callback as done, and notifies the FSTDispatchQueue that it should be removed.
  118. */
  119. - (void)markDone {
  120. self.done = YES;
  121. [self.queue removeDelayedCallback:self];
  122. }
  123. @end
  124. #pragma mark - FSTDispatchQueue
  125. @interface FSTDispatchQueue ()
  126. /**
  127. * Callbacks scheduled to be queued in the future. Callbacks are automatically removed after they
  128. * are run or canceled.
  129. */
  130. @property(nonatomic, strong, readonly) NSMutableArray<FSTDelayedCallback *> *delayedCallbacks;
  131. - (instancetype)initWithQueue:(dispatch_queue_t)queue NS_DESIGNATED_INITIALIZER;
  132. @end
  133. @implementation FSTDispatchQueue
  134. + (instancetype)queueWith:(dispatch_queue_t)dispatchQueue {
  135. return [[FSTDispatchQueue alloc] initWithQueue:dispatchQueue];
  136. }
  137. - (instancetype)initWithQueue:(dispatch_queue_t)queue {
  138. if (self = [super init]) {
  139. _queue = queue;
  140. _delayedCallbacks = [NSMutableArray array];
  141. }
  142. return self;
  143. }
  144. - (void)verifyIsCurrentQueue {
  145. FSTAssert([self onTargetQueue],
  146. @"We are running on the wrong dispatch queue. Expected '%@' Actual: '%@'",
  147. [self targetQueueLabel], [self currentQueueLabel]);
  148. }
  149. - (void)dispatchAsync:(void (^)(void))block {
  150. FSTAssert(![self onTargetQueue],
  151. @"dispatchAsync called when we are already running on target dispatch queue '%@'",
  152. [self targetQueueLabel]);
  153. dispatch_async(self.queue, block);
  154. }
  155. - (void)dispatchAsyncAllowingSameQueue:(void (^)(void))block {
  156. dispatch_async(self.queue, block);
  157. }
  158. - (FSTDelayedCallback *)dispatchAfterDelay:(NSTimeInterval)delay
  159. timerID:(FSTTimerID)timerID
  160. block:(void (^)(void))block {
  161. // While not necessarily harmful, we currently don't expect to have multiple callbacks with the
  162. // same timerID in the queue, so defensively reject them.
  163. FSTAssert(![self containsDelayedCallbackWithTimerID:timerID],
  164. @"Attempted to schedule multiple callbacks with id %ld", (unsigned long)timerID);
  165. FSTDelayedCallback *delayedCallback = [FSTDelayedCallback createAndScheduleWithQueue:self
  166. timerID:timerID
  167. delay:delay
  168. callback:block];
  169. [self.delayedCallbacks addObject:delayedCallback];
  170. return delayedCallback;
  171. }
  172. - (BOOL)containsDelayedCallbackWithTimerID:(FSTTimerID)timerID {
  173. NSUInteger matchIndex = [self.delayedCallbacks
  174. indexOfObjectPassingTest:^BOOL(FSTDelayedCallback *obj, NSUInteger idx, BOOL *stop) {
  175. return obj.timerID == timerID;
  176. }];
  177. return matchIndex != NSNotFound;
  178. }
  179. - (void)runDelayedCallbacksUntil:(FSTTimerID)lastTimerID {
  180. dispatch_semaphore_t doneSemaphore = dispatch_semaphore_create(0);
  181. [self dispatchAsync:^{
  182. FSTAssert(lastTimerID == FSTTimerIDAll || [self containsDelayedCallbackWithTimerID:lastTimerID],
  183. @"Attempted to run callbacks until missing timer ID: %ld",
  184. (unsigned long)lastTimerID);
  185. [self sortDelayedCallbacks];
  186. for (FSTDelayedCallback *callback in self.delayedCallbacks) {
  187. [callback skipDelay];
  188. if (lastTimerID != FSTTimerIDAll && callback.timerID == lastTimerID) {
  189. break;
  190. }
  191. }
  192. // Now that the callbacks are queued, we want to enqueue an additional item to release the
  193. // 'done' semaphore.
  194. [self dispatchAsyncAllowingSameQueue:^{
  195. dispatch_semaphore_signal(doneSemaphore);
  196. }];
  197. }];
  198. dispatch_semaphore_wait(doneSemaphore, DISPATCH_TIME_FOREVER);
  199. }
  200. // NOTE: For performance we could store the callbacks sorted (e.g. using std::priority_queue),
  201. // but this sort only happens in tests (if runDelayedCallbacksUntil: is called), and the size
  202. // is guaranteed to be small since we don't allow duplicate TimerIds (of which there are only 4).
  203. - (void)sortDelayedCallbacks {
  204. // We want to run callbacks in the same order they'd run if they ran naturally.
  205. [self.delayedCallbacks
  206. sortUsingComparator:^NSComparisonResult(FSTDelayedCallback *a, FSTDelayedCallback *b) {
  207. return a.targetTime < b.targetTime
  208. ? NSOrderedAscending
  209. : a.targetTime > b.targetTime ? NSOrderedDescending : NSOrderedSame;
  210. }];
  211. }
  212. /** Called by FSTDelayedCallback when a callback is run or canceled. */
  213. - (void)removeDelayedCallback:(FSTDelayedCallback *)callback {
  214. NSUInteger index = [self.delayedCallbacks indexOfObject:callback];
  215. FSTAssert(index != NSNotFound, @"Delayed callback not found.");
  216. [self.delayedCallbacks removeObjectAtIndex:index];
  217. }
  218. #pragma mark - Private Methods
  219. - (NSString *)currentQueueLabel {
  220. return [NSString stringWithUTF8String:dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL)];
  221. }
  222. - (NSString *)targetQueueLabel {
  223. return [NSString stringWithUTF8String:dispatch_queue_get_label(self.queue)];
  224. }
  225. - (BOOL)onTargetQueue {
  226. return [[self currentQueueLabel] isEqualToString:[self targetQueueLabel]];
  227. }
  228. @end
  229. NS_ASSUME_NONNULL_END