|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the SwiftAWSLambdaRuntime open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2022 Apple Inc. and the SwiftAWSLambdaRuntime project authors |
| 6 | +// Licensed under Apache License v2.0 |
| 7 | +// |
| 8 | +// See LICENSE.txt for license information |
| 9 | +// See CONTRIBUTORS.txt for the list of SwiftAWSLambdaRuntime project authors |
| 10 | +// |
| 11 | +// SPDX-License-Identifier: Apache-2.0 |
| 12 | +// |
| 13 | +//===----------------------------------------------------------------------===// |
| 14 | +import Foundation |
| 15 | +import NIOConcurrencyHelpers |
| 16 | +import NIOCore |
| 17 | +import Logging |
| 18 | + |
| 19 | +/// A container that allows tasks to finish after a synchronous invocation |
| 20 | +/// has produced its response. |
| 21 | +public final class DetachedTasksContainer { |
| 22 | + |
| 23 | + struct Context { |
| 24 | + let eventLoop: EventLoop |
| 25 | + let logger: Logger |
| 26 | + } |
| 27 | + |
| 28 | + private var context: Context |
| 29 | + private var storage: Storage |
| 30 | + |
| 31 | + init(context: Context) { |
| 32 | + self.storage = Storage() |
| 33 | + self.context = context |
| 34 | + } |
| 35 | + |
| 36 | + /// Adds a detached task that runs on the given event loop. |
| 37 | + /// |
| 38 | + /// - Parameters: |
| 39 | + /// - name: The name of the task. |
| 40 | + /// - task: The task to execute. It receives an `EventLoop` and returns an `EventLoopFuture<Void>`. |
| 41 | + /// - Returns: A `RegistrationKey` for the registered task. |
| 42 | + @discardableResult |
| 43 | + public func detached(name: String, task: @escaping (EventLoop) -> EventLoopFuture<Void>) -> RegistrationKey { |
| 44 | + let key = RegistrationKey() |
| 45 | + let task = task(context.eventLoop).always { _ in |
| 46 | + self.storage.remove(key) |
| 47 | + } |
| 48 | + self.storage.add(key: key, name: name, task: task) |
| 49 | + return key |
| 50 | + } |
| 51 | + |
| 52 | + /// Adds a detached async task. |
| 53 | + /// |
| 54 | + /// - Parameters: |
| 55 | + /// - name: The name of the task. |
| 56 | + /// - task: The async task to execute. |
| 57 | + /// - Returns: A `RegistrationKey` for the registered task. |
| 58 | + @discardableResult |
| 59 | + public func detached(name: String, task: @Sendable @escaping () async throws -> Void) -> RegistrationKey { |
| 60 | + let key = RegistrationKey() |
| 61 | + let promise = context.eventLoop.makePromise(of: Void.self) |
| 62 | + promise.completeWithTask(task) |
| 63 | + let task = promise.futureResult.always { result in |
| 64 | + switch result { |
| 65 | + case .success: |
| 66 | + break |
| 67 | + case .failure(let failure): |
| 68 | + self.context.logger.warning( |
| 69 | + "Execution of detached task failed with error.", |
| 70 | + metadata: [ |
| 71 | + "taskName": "\(name)", |
| 72 | + "error": "\(failure)" |
| 73 | + ] |
| 74 | + ) |
| 75 | + } |
| 76 | + self.storage.remove(key) |
| 77 | + } |
| 78 | + self.storage.add(key: key, name: name, task: task) |
| 79 | + return key |
| 80 | + } |
| 81 | + |
| 82 | + /// Informs the runtime that the specified task should not be awaited anymore. |
| 83 | + /// |
| 84 | + /// - Warning: This method does not actually stop the execution of the |
| 85 | + /// detached task, it only prevents the runtime from waiting for it before |
| 86 | + /// `/next` is invoked. |
| 87 | + /// |
| 88 | + /// - Parameter key: The `RegistrationKey` of the task to cancel. |
| 89 | + public func unsafeCancel(_ key: RegistrationKey) { |
| 90 | + // To discuss: |
| 91 | + // Canceling the execution doesn't seem to be an easy |
| 92 | + // task https://github.com/apple/swift-nio/issues/2087 |
| 93 | + // |
| 94 | + // While removing the handler will allow the runtime |
| 95 | + // to invoke `/next` without actually awaiting for the |
| 96 | + // task to complete, it does not actually cancel |
| 97 | + // the execution of the dispatched task. |
| 98 | + // Since this is a bit counter-intuitive, we might not |
| 99 | + // want this method to exist at all. |
| 100 | + self.storage.remove(key) |
| 101 | + } |
| 102 | + |
| 103 | + /// Awaits all registered tasks to complete. |
| 104 | + /// |
| 105 | + /// - Returns: An `EventLoopFuture<Void>` that completes when all tasks have finished. |
| 106 | + internal func awaitAll() -> EventLoopFuture<Void> { |
| 107 | + let tasks = storage.tasks |
| 108 | + if tasks.isEmpty { |
| 109 | + return context.eventLoop.makeSucceededVoidFuture() |
| 110 | + } else { |
| 111 | + return EventLoopFuture.andAllComplete(tasks.map(\.value.task), on: context.eventLoop).flatMap { |
| 112 | + self.awaitAll() |
| 113 | + } |
| 114 | + } |
| 115 | + } |
| 116 | +} |
| 117 | + |
| 118 | +extension DetachedTasksContainer { |
| 119 | + /// Lambda detached task registration key. |
| 120 | + public struct RegistrationKey: Hashable, CustomStringConvertible { |
| 121 | + var value: String |
| 122 | + |
| 123 | + init() { |
| 124 | + // UUID basically |
| 125 | + self.value = UUID().uuidString |
| 126 | + } |
| 127 | + |
| 128 | + public var description: String { |
| 129 | + self.value |
| 130 | + } |
| 131 | + } |
| 132 | +} |
| 133 | + |
| 134 | +extension DetachedTasksContainer { |
| 135 | + fileprivate final class Storage { |
| 136 | + private let lock: NIOLock |
| 137 | + |
| 138 | + private var map: [RegistrationKey: (name: String, task: EventLoopFuture<Void>)] |
| 139 | + |
| 140 | + init() { |
| 141 | + self.lock = .init() |
| 142 | + self.map = [:] |
| 143 | + } |
| 144 | + |
| 145 | + func add(key: RegistrationKey, name: String, task: EventLoopFuture<Void>) { |
| 146 | + self.lock.withLock { |
| 147 | + self.map[key] = (name: name, task: task) |
| 148 | + } |
| 149 | + } |
| 150 | + |
| 151 | + func remove(_ key: RegistrationKey) { |
| 152 | + self.lock.withLock { |
| 153 | + self.map[key] = nil |
| 154 | + } |
| 155 | + } |
| 156 | + |
| 157 | + var tasks: [RegistrationKey: (name: String, task: EventLoopFuture<Void>)] { |
| 158 | + self.lock.withLock { |
| 159 | + self.map |
| 160 | + } |
| 161 | + } |
| 162 | + } |
| 163 | +} |
| 164 | + |
| 165 | +// Ideally this would not be @unchecked Sendable, but Sendable checks do not understand locks |
| 166 | +// We can transition this to an actor once we drop support for older Swift versions |
| 167 | +extension DetachedTasksContainer: @unchecked Sendable {} |
| 168 | +extension DetachedTasksContainer.Storage: @unchecked Sendable {} |
| 169 | +extension DetachedTasksContainer.RegistrationKey: Sendable {} |
0 commit comments