|
| 1 | +import Foundation |
| 2 | + |
| 3 | +/// Unified serial async task queue with operation-type-aware coalescing. |
| 4 | +/// - Non-coalescable operations always execute in order |
| 5 | +/// - Consecutive coalescable operations are coalesced (only the last one executes) |
| 6 | +/// - Order is always preserved |
| 7 | +internal actor AsyncUnifiedQueue { |
| 8 | + private var currentTask: Task<Void, Never>? |
| 9 | + |
| 10 | + private struct QueuedOperation { |
| 11 | + let operation: () async -> Void |
| 12 | + let continuation: CheckedContinuation<Void, Never> |
| 13 | + let canCoalesce: Bool |
| 14 | + } |
| 15 | + |
| 16 | + private var queue: [QueuedOperation] = [] |
| 17 | + |
| 18 | + /// Runs the given operation serially. |
| 19 | + /// - If canCoalesce is false: operation always executes |
| 20 | + /// - If canCoalesce is true: may be skipped if superseded by a later coalescable operation |
| 21 | + func run(canCoalesce: Bool, operation: @Sendable @escaping () async -> Void) async { |
| 22 | + await withCheckedContinuation { continuation in |
| 23 | + queue.append(QueuedOperation(operation: operation, continuation: continuation, canCoalesce: canCoalesce)) |
| 24 | + |
| 25 | + if currentTask == nil { |
| 26 | + processNext() |
| 27 | + } |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + private func processNext() { |
| 32 | + guard !queue.isEmpty else { |
| 33 | + currentTask = nil |
| 34 | + return |
| 35 | + } |
| 36 | + |
| 37 | + // Find the next batch to execute |
| 38 | + // A batch is either: |
| 39 | + // 1. A single non-coalescable operation, OR |
| 40 | + // 2. Consecutive coalescable operations (we execute only the last one) |
| 41 | + |
| 42 | + let firstOp = queue[0] |
| 43 | + |
| 44 | + if !firstOp.canCoalesce { |
| 45 | + // Non-coalescable operation: execute it immediately |
| 46 | + let op = queue.removeFirst() |
| 47 | + currentTask = Task { [weak self] in |
| 48 | + await op.operation() |
| 49 | + op.continuation.resume() |
| 50 | + await self?.processNext() |
| 51 | + } |
| 52 | + } else { |
| 53 | + // Coalescable operation: find all consecutive coalescable ops |
| 54 | + var coalescableCount = 0 |
| 55 | + for op in queue { |
| 56 | + if op.canCoalesce { |
| 57 | + coalescableCount += 1 |
| 58 | + } else { |
| 59 | + break |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + // Execute only the last one in the coalescable batch |
| 64 | + let toSkip = Array(queue.prefix(coalescableCount - 1)) |
| 65 | + let toExecute = queue[coalescableCount - 1] |
| 66 | + queue.removeFirst(coalescableCount) |
| 67 | + |
| 68 | + currentTask = Task { [weak self] in |
| 69 | + await toExecute.operation() |
| 70 | + |
| 71 | + // Resume all continuations (both skipped and executed) |
| 72 | + for op in toSkip { |
| 73 | + op.continuation.resume() |
| 74 | + } |
| 75 | + toExecute.continuation.resume() |
| 76 | + |
| 77 | + await self?.processNext() |
| 78 | + } |
| 79 | + } |
| 80 | + } |
| 81 | +} |
0 commit comments