-
Notifications
You must be signed in to change notification settings - Fork 108
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Draft] Detached tasks #334
Merged
Merged
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
e02b9b6
First prototype
Buratti 31c7845
Fix build
Buratti c6d766d
Merge branch 'main' into detached-tasks
sebsto 22483e0
Removes task cancellation
Buratti 224039a
Force user to handle errors
Buratti 7934a0f
Remove EventLoop API
Buratti 2491f6f
Make DetachedTaskContainer internal
Buratti a059ec5
Removes @unchecked Sendable
Buratti 9804c04
Invoke awaitAll() from async context
Buratti fb6e19e
Fix ambiguous expression type for swift 5.7
Buratti b87bfed
Fix visibility of detachedBackgroundTask
Buratti 888af29
Add swift-doc
Buratti c4aff5c
Add example usage to readme
Buratti 7e647e8
Add tests
Buratti File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,95 @@ | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// This source file is part of the SwiftAWSLambdaRuntime open source project | ||
// | ||
// Copyright (c) 2022 Apple Inc. and the SwiftAWSLambdaRuntime project authors | ||
// Licensed under Apache License v2.0 | ||
// | ||
// See LICENSE.txt for license information | ||
// See CONTRIBUTORS.txt for the list of SwiftAWSLambdaRuntime project authors | ||
// | ||
// SPDX-License-Identifier: Apache-2.0 | ||
// | ||
//===----------------------------------------------------------------------===// | ||
import Foundation | ||
import NIOConcurrencyHelpers | ||
import NIOCore | ||
import Logging | ||
|
||
/// A container that allows tasks to finish after a synchronous invocation | ||
/// has produced its response. | ||
actor DetachedTasksContainer: Sendable { | ||
|
||
struct Context: Sendable { | ||
let eventLoop: EventLoop | ||
let logger: Logger | ||
} | ||
|
||
private var context: Context | ||
private var storage: [RegistrationKey: EventLoopFuture<Void>] = [:] | ||
|
||
init(context: Context) { | ||
self.context = context | ||
} | ||
|
||
/// Adds a detached async task. | ||
/// | ||
/// - Parameters: | ||
/// - name: The name of the task. | ||
/// - task: The async task to execute. | ||
/// - Returns: A `RegistrationKey` for the registered task. | ||
func detached(task: @Sendable @escaping () async -> Void) { | ||
let key = RegistrationKey() | ||
let promise = context.eventLoop.makePromise(of: Void.self) | ||
promise.completeWithTask(task) | ||
let task = promise.futureResult.always { [weak self] result in | ||
guard let self else { return } | ||
Task { | ||
await self.removeTask(forKey: key) | ||
} | ||
} | ||
self.storage[key] = task | ||
} | ||
|
||
func removeTask(forKey key: RegistrationKey) { | ||
self.storage.removeValue(forKey: key) | ||
} | ||
|
||
/// Awaits all registered tasks to complete. | ||
/// | ||
/// - Returns: An `EventLoopFuture<Void>` that completes when all tasks have finished. | ||
func awaitAll() -> EventLoopFuture<Void> { | ||
let tasks = storage.values | ||
if tasks.isEmpty { | ||
return context.eventLoop.makeSucceededVoidFuture() | ||
} else { | ||
let context = context | ||
return EventLoopFuture.andAllComplete(Array(tasks), on: context.eventLoop).flatMap { [weak self] in | ||
guard let self else { | ||
return context.eventLoop.makeSucceededFuture(()) | ||
} | ||
let promise = context.eventLoop.makePromise(of: Void.self) | ||
promise.completeWithTask { | ||
try await self.awaitAll().get() | ||
} | ||
return promise.futureResult | ||
} | ||
} | ||
} | ||
} | ||
|
||
extension DetachedTasksContainer { | ||
/// Lambda detached task registration key. | ||
struct RegistrationKey: Hashable, CustomStringConvertible, Sendable { | ||
var value: String | ||
|
||
init() { | ||
// UUID basically | ||
self.value = UUID().uuidString | ||
} | ||
|
||
var description: String { | ||
self.value | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,80 @@ | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// This source file is part of the SwiftAWSLambdaRuntime open source project | ||
// | ||
// Copyright (c) 2017-2018 Apple Inc. and the SwiftAWSLambdaRuntime project authors | ||
// Licensed under Apache License v2.0 | ||
// | ||
// See LICENSE.txt for license information | ||
// See CONTRIBUTORS.txt for the list of SwiftAWSLambdaRuntime project authors | ||
// | ||
// SPDX-License-Identifier: Apache-2.0 | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
@testable import AWSLambdaRuntimeCore | ||
import NIO | ||
import XCTest | ||
import Logging | ||
|
||
class DetachedTasksTest: XCTestCase { | ||
|
||
actor Expectation { | ||
var isFulfilled = false | ||
func fulfill() { | ||
isFulfilled = true | ||
} | ||
} | ||
|
||
func testAwaitTasks() async throws { | ||
let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1) | ||
defer { XCTAssertNoThrow(try eventLoopGroup.syncShutdownGracefully()) } | ||
|
||
let context = DetachedTasksContainer.Context( | ||
eventLoop: eventLoopGroup.next(), | ||
logger: Logger(label: "test") | ||
) | ||
let expectation = Expectation() | ||
|
||
let container = DetachedTasksContainer(context: context) | ||
await container.detached { | ||
try! await Task.sleep(for: .milliseconds(200)) | ||
await expectation.fulfill() | ||
} | ||
|
||
try await container.awaitAll().get() | ||
let isFulfilled = await expectation.isFulfilled | ||
XCTAssert(isFulfilled) | ||
} | ||
|
||
func testAwaitChildrenTasks() async throws { | ||
let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1) | ||
defer { XCTAssertNoThrow(try eventLoopGroup.syncShutdownGracefully()) } | ||
|
||
let context = DetachedTasksContainer.Context( | ||
eventLoop: eventLoopGroup.next(), | ||
logger: Logger(label: "test") | ||
) | ||
let expectation1 = Expectation() | ||
let expectation2 = Expectation() | ||
|
||
let container = DetachedTasksContainer(context: context) | ||
await container.detached { | ||
await container.detached { | ||
try! await Task.sleep(for: .milliseconds(300)) | ||
await expectation1.fulfill() | ||
} | ||
try! await Task.sleep(for: .milliseconds(200)) | ||
await container.detached { | ||
try! await Task.sleep(for: .milliseconds(100)) | ||
await expectation2.fulfill() | ||
} | ||
} | ||
|
||
try await container.awaitAll().get() | ||
let isFulfilled1 = await expectation1.isFulfilled | ||
let isFulfilled2 = await expectation2.isFulfilled | ||
XCTAssert(isFulfilled1) | ||
XCTAssert(isFulfilled2) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is the only point that remains open @fabianfett. When the runtime fails to report a result to AWS Lambda, do we want to wait for the background tasks to complete before stopping the execution of the whole process?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
In the error case we should await all subtasks.