Skip to content

add handlers that support async functions #99

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

Merged
merged 1 commit into from
May 13, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 71 additions & 1 deletion Sources/Lifecycle/Lifecycle.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@
//
//===----------------------------------------------------------------------===//

#if compiler(>=5.5)
import _Concurrency
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this import required?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It'll be gone eventually (it should be already but seems something went wrong)

#endif

#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#else
Expand Down Expand Up @@ -95,6 +99,28 @@ public struct LifecycleHandler {
}
}

#if compiler(>=5.5)
@available(macOS 12.0, *)
extension LifecycleHandler {
public init(_ handler: @escaping () async throws -> Void) {
self = LifecycleHandler { callback in
detach {
do {
try await handler()
callback(nil)
} catch {
callback(error)
}
}
}
}

public static func async(_ handler: @escaping () async throws -> Void) -> LifecycleHandler {
return LifecycleHandler(handler)
}
}
#endif

// MARK: - Stateful Lifecycle Handlers

/// LifecycleHandler for starting stateful tasks. The state can then be fed into a LifecycleShutdownHandler
Expand Down Expand Up @@ -137,6 +163,28 @@ public struct LifecycleStartHandler<State> {
}
}

#if compiler(>=5.5)
@available(macOS 12.0, *)
extension LifecycleStartHandler {
public init(_ handler: @escaping () async throws -> State) {
self = LifecycleStartHandler { callback in
detach {
do {
let state = try await handler()
callback(.success(state))
} catch {
callback(.failure(error))
}
}
}
}

public static func async(_ handler: @escaping () async throws -> State) -> LifecycleStartHandler {
return LifecycleStartHandler(handler)
}
}
#endif

/// LifecycleHandler for shutting down stateful tasks. The state comes from a LifecycleStartHandler
public struct LifecycleShutdownHandler<State> {
private let underlying: (State, @escaping (Error?) -> Void) -> Void
Expand Down Expand Up @@ -177,6 +225,28 @@ public struct LifecycleShutdownHandler<State> {
}
}

#if compiler(>=5.5)
@available(macOS 12.0, *)
extension LifecycleShutdownHandler {
public init(_ handler: @escaping (State) async throws -> Void) {
self = LifecycleShutdownHandler { state, callback in
detach {
do {
try await handler(state)
callback(nil)
} catch {
callback(error)
}
}
}
}

public static func async(_ handler: @escaping (State) async throws -> Void) -> LifecycleShutdownHandler {
return LifecycleShutdownHandler(handler)
}
}
#endif

// MARK: - ServiceLifecycle

/// `ServiceLifecycle` provides a basic mechanism to cleanly startup and shutdown the application, freeing resources in order before exiting.
Expand Down Expand Up @@ -671,7 +741,7 @@ internal struct _LifecycleTask: LifecycleTask {
}
}

// internal for testing
// internal (instead of private) for testing
internal class StatefulLifecycleTask<State>: LifecycleTask {
let label: String
let shutdownIfNotStarted: Bool = false
Expand Down
4 changes: 4 additions & 0 deletions Tests/LifecycleTests/ComponentLifecycleTests+XCTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,10 @@ extension ComponentLifecycleTests {
("testStatefulNIO", testStatefulNIO),
("testStatefulNIOStartFailure", testStatefulNIOStartFailure),
("testStatefulNIOShutdownFailure", testStatefulNIOShutdownFailure),
("testAsyncAwait", testAsyncAwait),
("testAsyncAwaitStateful", testAsyncAwaitStateful),
("testAsyncAwaitErrorOnStart", testAsyncAwaitErrorOnStart),
("testAsyncAwaitErrorOnShutdown", testAsyncAwaitErrorOnShutdown),
("testMetrics", testMetrics),
]
}
Expand Down
142 changes: 142 additions & 0 deletions Tests/LifecycleTests/ComponentLifecycleTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1249,6 +1249,148 @@ final class ComponentLifecycleTests: XCTestCase {
XCTAssertFalse(item.shutdown, "expected item to be shutdown")
}

func testAsyncAwait() throws {
#if compiler(<5.2)
return
#elseif compiler(<5.5)
throw XCTSkip()
#else
guard #available(macOS 12.0, *) else {
throw XCTSkip()
}

class Item {
var isShutdown: Bool = false

func start() async throws {}

func shutdown() async throws {
self.isShutdown = true // not thread safe but okay for this purpose
}
}

let lifecycle = ComponentLifecycle(label: "test")

let item = Item()
lifecycle.register(label: "test", start: .async(item.start), shutdown: .async(item.shutdown))

lifecycle.start { error in
XCTAssertNil(error, "not expecting error")
lifecycle.shutdown()
}
lifecycle.wait()
XCTAssertTrue(item.isShutdown, "expected item to be shutdown")
#endif
}

func testAsyncAwaitStateful() throws {
#if compiler(<5.2)
return
#elseif compiler(<5.5)
throw XCTSkip()
#else
guard #available(macOS 12.0, *) else {
throw XCTSkip()
}

class Item {
var isShutdown: Bool = false
let id: String = UUID().uuidString

func start() async throws -> String {
return self.id
}

func shutdown(state: String) async throws {
XCTAssertEqual(self.id, state)
self.isShutdown = true // not thread safe but okay for this purpose
}
}

let lifecycle = ComponentLifecycle(label: "test")

let item = Item()
lifecycle.registerStateful(label: "test", start: .async(item.start), shutdown: .async(item.shutdown))

lifecycle.start { error in
XCTAssertNil(error, "not expecting error")
lifecycle.shutdown()
}
lifecycle.wait()
XCTAssertTrue(item.isShutdown, "expected item to be shutdown")
#endif
}

func testAsyncAwaitErrorOnStart() throws {
#if compiler(<5.2)
return
#elseif compiler(<5.5)
throw XCTSkip()
#else
guard #available(macOS 12.0, *) else {
throw XCTSkip()
}

class Item {
var isShutdown: Bool = false

func start() async throws {
throw TestError()
}

func shutdown() async throws {
self.isShutdown = true // not thread safe but okay for this purpose
}
}

let lifecycle = ComponentLifecycle(label: "test")

let item = Item()
lifecycle.register(label: "test", start: .async(item.start), shutdown: .async(item.shutdown))

lifecycle.start { error in
XCTAssert(error is TestError, "expected error to match")
lifecycle.shutdown()
}
lifecycle.wait()
XCTAssertTrue(item.isShutdown, "expected item to be shutdown")
#endif
}

func testAsyncAwaitErrorOnShutdown() throws {
#if compiler(<5.2)
return
#elseif compiler(<5.5)
throw XCTSkip()
#else
guard #available(macOS 12.0, *) else {
throw XCTSkip()
}
class Item {
var isShutdown: Bool = false

func start() async throws {}

func shutdown() async throws {
self.isShutdown = true // not thread safe but okay for this purpose
throw TestError()
}
}

let lifecycle = ComponentLifecycle(label: "test")

let item = Item()
lifecycle.register(label: "test", start: .async(item.start), shutdown: .async(item.shutdown))

lifecycle.start { error in
XCTAssertNil(error, "not expecting error")
lifecycle.shutdown()
}
lifecycle.wait()
XCTAssertTrue(item.isShutdown, "expected item to be shutdown")
#endif
}

func testMetrics() {
let metrics = TestMetrics()
MetricsSystem.bootstrap(metrics)
Expand Down