Files
swift-service-lifecycle/Sources/ServiceLifecycle/ServiceRunnerError.swift
T
Franz Busch fafab8f7ad Overhaul service lifecycle for Structured Concurrency (#130)
* Overhaul service lifecycle for Structured Concurrency

# Motivation
Since the release of Swift Concurrency the server ecosystem has adopted `async`/`await` in a lot of APIs making the user experience amazing. Another thing that Swift Concurrency introduced is Structured Concurrency which allows to create a task tree that with parent to child relations. Structured Concurrency has many benefits such as automatic cancellation and task local propagation.
The current state of this library predates the introduction of Swift Concurrency and is not inline anymore with how applications are structured that want to leverage Concurrency.

# Modification
This PR overhauls the implementation of service lifecycle completely. The reason for this is that the current implementation is very focused on how NIO based applications work before the introduction of Concurrency. Furthermore, Structured Concurrency is actually replacing part of the current functionality by providing new scoping mechanisms.
The overhauled implementation provides two primitive types. Anew `Service` protocol and a `ServiceRunner`. The former is providing a clear API which services have to conform to so that they can be run by the `ServiceRunner`.

An example usage of the types looks like this

```swift
actor FooService: Service {
    func run() async throws {}

    func shutdownGracefully() async throws {}
}
actor BarService: Service {
    func run() async throws {}

    func shutdownGracefully() async throws {}
}

let fooService = FooService()
let barService = BarService()

let runner = ServiceRunner(
    services: [fooService, barService],
   configuration: .init(),
   logger: logger
)

try await runner.run()
```

# Result
We now have a service lifecycle library that integrates nicely with Structured Concurrency. Its value add is that it solves to complex setup of the task group with the signal handling. Furthermore, it provides a currency type `Service` that can be passed to inject services.

* Remove `shutdownGracefully` method and switch to a handler based approach.

* Code review from George

* Add extensions to `TaskGroup` and `ThrowingTaskGroup`

* Remove long running property

* Documentation

* Fix tests

* Ensure ordering of shutdown

* Test

# Motivation

# Modification

# Result

* Introduce ServiceLifecycleTestKit

* Add AsyncCancelOngracefulShutdownSequence

* Tests and docs for graceful shutdown

# Motivation

# Modification

# Result

* Remove unsafe flags

* Add article for application authors

* Add correct licence and notice information for the things we copied from swift-nio

* Code review

* Remove @_unsafeInheritExectuor

* Code review

* Change log levels, rename to withGracefulShutdownHandler and support nested service runner graceful shutdown

* Add public `shutdownGracefully` method to the service runner

* Code review and expose new cancelOnGracefulShutdown method

* Extend graceful shutdown APIs and tolerate running outside of a `ServiceRunner`

* Rename to `ServiceGroup`

* Enable Swift 5.6 support

* Update soundess dockerfile

* Update Readme

* Make 5.6 build work
2023-04-27 11:56:08 +01:00

124 lines
4.0 KiB
Swift

//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftServiceLifecycle open source project
//
// Copyright (c) 2023 Apple Inc. and the SwiftServiceLifecycle project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftServiceLifecycle project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
/// Errors thrown by the ``ServiceGroup``.
public struct ServiceGroupError: Error, Hashable, Sendable {
/// A struct representing the possible error codes.
public struct Code: Hashable, Sendable, CustomStringConvertible {
private enum _Code: Hashable, Sendable {
case alreadyRunning
case alreadyFinished
case serviceFinishedUnexpectedly
}
private var code: _Code
private init(code: _Code) {
self.code = code
}
public var description: String {
switch self.code {
case .alreadyRunning:
return "The service group is already running the services."
case .alreadyFinished:
return "The service group has already finished running the services."
case .serviceFinishedUnexpectedly:
return "A service has finished unexpectedly."
}
}
/// Indicates that the service group is already running.
public static let alreadyRunning = Code(code: .alreadyRunning)
/// Indicates that the service group has already finished running.
public static let alreadyFinished = Code(code: .alreadyFinished)
/// Indicates that a service finished unexpectedly.
public static let serviceFinishedUnexpectedly = Code(code: .serviceFinishedUnexpectedly)
}
/// Internal class that contains the actual error code.
private final class Backing: Hashable, Sendable {
let errorCode: Code
let file: String
let line: Int
init(errorCode: Code, file: String, line: Int) {
self.errorCode = errorCode
self.file = file
self.line = line
}
static func == (lhs: Backing, rhs: Backing) -> Bool {
lhs.errorCode == rhs.errorCode
}
func hash(into hasher: inout Hasher) {
hasher.combine(self.errorCode)
}
}
/// The backing storage of the error.
private let backing: Backing
/// The error code.
///
/// - Note: This is the only thing used for the `Equatable` and `Hashable` comparison.
public var errorCode: Code {
self.backing.errorCode
}
private init(_ backing: Backing) {
self.backing = backing
}
/// Indicates that the service group is already running.
public static func alreadyRunning(file: String = #fileID, line: Int = #line) -> Self {
Self(
.init(
errorCode: .alreadyRunning,
file: file,
line: line
)
)
}
/// Indicates that the service group has already finished running.
public static func alreadyFinished(file: String = #fileID, line: Int = #line) -> Self {
Self(
.init(
errorCode: .alreadyFinished,
file: file,
line: line
)
)
}
/// Indicates that a service finished unexpectedly even though it indicated it is a long running service.
public static func serviceFinishedUnexpectedly(file: String = #fileID, line: Int = #line) -> Self {
Self(
.init(
errorCode: .serviceFinishedUnexpectedly,
file: file,
line: line
)
)
}
}
extension ServiceGroupError: CustomStringConvertible {
public var description: String {
"ServiceGroupError: errorCode: \(self.backing.errorCode), file: \(self.backing.file), line: \(self.backing.line)"
}
}