### Motivation
`UnixSignalsSequence.Storage` is marked `@unchecked Sendable`, but its
stored properties are `let stateMachine: LockedValueBox<StateMachine>`
and `let sources: [Source]` (where `Source` is already checked
`Sendable`). The compiler can verify this conformance, and keeping
`@unchecked` means it would not catch a future change that breaks
sendability.
### Modifications
- Replace `@unchecked Sendable` with `Sendable` on
`UnixSignalsSequence.Storage`.
### Result
No behavior change; the conformance is now checked by the compiler.
Verified locally on macOS (Swift 6.4.2): `swift build --build-tests
-Xswiftc -strict-concurrency=complete` produces no new diagnostics and
`swift test` passes. Linux is left to CI.
The support window is 3 latest Swift versions. CI i already running for
Swift 6.2, 6.3 and 6.4 only. Updating the Swift tools and the package to
match this.
Fixes#256.
## Motivation
`UnixSignalsSequence` keeps dispatch signal sources alive after the
sequence and its iterator are released. The event handler captures the
whole `Source` value, which holds the `DispatchSource`, creating a
retain cycle.
## Modifications
- Keep the sources on `Storage` and cancel them in `deinit`.
- Resume sources skipped when initialization is cancelled so libdispatch
can run cancellation cleanup and release their handlers.
- Add regression tests for normal teardown and cancelled initialization.
The teardown test waits for cancellation because the registration
callback can briefly retain `Storage` after initialization returns.
## Result
Sources are cleaned up after the last sequence or iterator releases the
storage, including when initialization is cancelled.
In the macOS reproducer, 2,000 create/drop iterations went from 2,005
live dispatch sources before the fix to 5 afterward, matching the
zero-iteration control. These measurements were made on macOS only.
All 10 UnixSignals tests pass locally in release mode on macOS with
Swift 6.3.3 and the CI warning, explicit-import, and Sendable flags.
Strict formatting and `git diff --check` also pass. The weak-reference
test has not been run locally on Linux; its first Linux validation will
be in CI.
Closes#248
## Summary
- remember a graceful-shutdown request made while the service group is
still initial
- start configured services when run() is eventually called, then
deliver the pending request through the existing graceful-shutdown path
- ignore services added after a pre-start shutdown request
- add a regression test covering service startup, graceful shutdown, and
normal completion
## Validation
- swift test
- 70 tests passed
- git diff --check
Fixes#251
## Summary
- Raise the minimum swift-log dependency to 1.14.0, which provides the
task-local Logger.current API.
- Default ServiceGroup's logger parameter to Logger.current so callers
can inherit the current task-local logger.
- Add a regression test that constructs and runs ServiceGroup without an
explicit logger.
## Design
The change is limited to the current ServiceGroup convenience
initializer. Existing explicit logger calls and
ServiceGroupConfiguration initializers remain unchanged.
## Validation
- Focused test passed: swift test --disable-sandbox --filter
ServiceGroupTests/testRun_withDefaultLogger
- Full test suite passed: swift test --disable-sandbox
- Result: 62 ServiceLifecycle/XCTest tests and all Swift Testing suites
passed.
- git diff --check passed.
Tests used the Xcode 27 beta developer toolchain because the active
Command Line Tools installation does not provide XCTest.
Co-authored-by: 赖卓林 <zhuolin@laizhuolindeMac-mini.local>
### Motivation
`ConcurrencyHelpers/Lock` has a pthread fallback branch (taken on every
non-Windows / non-Darwin platform) that types `LockPrimitive` as
`pthread_mutex_t` and initializes `pthread_mutexattr_t` with a default
initializer. Both compile on Linux but fail on FreeBSD / OpenBSD, where
those types are opaque-pointer typedefs Swift imports as
`Optional<OpaquePointer>` — the no-argument initializers don't exist.
This blocks swift-service-lifecycle (and everything that depends on
it — Hummingbird, downstream HTTP servers) from compiling on FreeBSD
with the official Swift FreeBSD preview toolchain.
### Modifications
Mirror the pattern landed in [apple/swift-log#387][log-pr]; same change
is being submitted for the sibling NIOLock copies (e.g.
[apple/swift-http-types#123][sht-pr]):
- On `os(FreeBSD) || os(OpenBSD)` alias `LockPrimitive` to
`pthread_mutex_t?`.
- In `LockOperations.create(_:)`, wrap `pthread_mutexattr_t()` with
`#if os(FreeBSD) || os(OpenBSD)` to use the `bitPattern:` overload.
[log-pr]: https://github.com/apple/swift-log/pull/387
[sht-pr]: https://github.com/apple/swift-http-types/pull/123
Touches one file (`Sources/ConcurrencyHelpers/Lock.swift`), +7 lines,
all behind FreeBSD/OpenBSD conditionals. No behaviour change on
existing platforms.
### Result
`swift build` and `swift test` both clean on FreeBSD 15.0 with the
official Swift FreeBSD preview toolchain:
```
$ uname -a
FreeBSD swiftbuild 15.0-RELEASE FreeBSD 15.0-RELEASE-p9 releng/15.0-n281048-6d536196f1bd GENERIC amd64
$ swift --version
Swift version 6.3-dev (LLVM 972b62858355d07, Swift 3f8c798cfe25bbb)
Target: x86_64-unknown-freebsd14.3
Build config: +assertions
$ swift build
Building for debugging...
... 276 modules ...
Build complete! (42.62s)
$ swift test
... ClosureServiceTests passed ...
✔ Test run passed.
```
Without this change `ServiceLifecycle` fails to compile on the same
toolchain.
### Checks
- [x] Builds on Linux/Darwin (no change there, all changes guarded
behind `#if os(FreeBSD) || os(OpenBSD)`).
- [x] Builds + passes existing tests on FreeBSD 15.0 with Swift
6.3-dev preview toolchain.
- [x] Same pattern as [apple/swift-log#387][log-pr] /
[apple/swift-http-types#123][sht-pr].
Add an extra `serviceName` field to the `ServiceConfiguration` to
customize SSL logs metadata.
Motivation:
This would allow giving meaningful name to services and service groups.
Closes#220.
Modifications:
- Added `.serviceName` to the `ServiceConfiguration`.
- Added a new initializer for `ServiceConfiguration` with `serviceName`
param.
- Logs now use `.serviceName` instead of `.service` for `sl-service`
metadata value.
Result:
Different `ServiceGroup`s can be distinguished in the logs.
## Summary
As I was trying to add Wasm CI to Swift Configuration, I noticed it
failed to build in Service Lifecycle, so adding that here first.
## Test Plan
Haven't run locally, will fail for now.
---------
Co-authored-by: Vladimir Kukushkin <kukushechkin@mac.com>
This PR adds a `ClosureService`.
You can use a `ClosureService` to create a lightweight, inline `Service`
without defining and conforming a dedicated type.
## Motivation
To aid debugging and troubleshooting, it is helpful to understand which
Service led to the error.
## Modifications
Add the service name to the `serviceFinishedUnexpectedly` error.
## Result
Easier to debug failing services.
Motivation:
Adding or raising the deployment platforms in the package manifest is a
SemVer major breaking change as consumers must also add or raise their
deployment platforms. This is a known limitation of SwiftPM.
Unforunately this means that it's very difficult for non-leaf packages
to adopt packages which declare their platforms in the manifest. Doing
so puts the brakes on adoption and ecosystem growth. For 'core' packages
like this one availability constraints should be expressed on
declarations rather than in the manifest.
Modifications:
- Remove platforms from the package manifest
- Add availability annotations to types which require it
Result:
This package can be more widely adopted
I don't expect us to run CI against this until that's more formally
supported, but this would greatly help adoption of server-focused
packages on Android
Currently, if compiler >= 6 then there are 2 implementations. One is
deprecated and one is not.
But if compiler is < 6 then there is only one implementation, which is
deprecated. I think this was by mistake.
I'm using swift-service-lifecycle's UnixSignal in a text UI library, and
needed SIGCONT. It's probably not super relevant in the service use
case, but it looks like UnixSignal is the best way to handle signals,
service or not, and I don't know if there's a downside to the library
supporting it?
Hello! 👋 This PR contains a few changes, notably:
- Updating the ``README.md`` to use the new initializer instead of the
deprecated one.
- Add a ``renamed`` to the deprecated initializer.
- Updating the docs to use the simpler initializer.
- Make the ``logging`` parameter on the initializers optional, the
motivation for this is in cases the user don't or can't do logging, they
don't have to construct a logger and bootstrap the logging system with
``SwiftLogNoOpLogHandler``, so this code:
```swift
LoggingSystem.bootstrap(SwiftLogNoOpLogHandler.init)
let serviceGroup = ServiceGroup(
services: [service],
cancellationSignals: [.sigint],
logger: .init(label: "")
)
```
becomes
```swift
let serviceGroup = ServiceGroup(
services: [service],
cancellationSignals: [.sigint]
)
```
and it also allows the user to do logging outside the ServiceGroup
without necessarily doing logging within it.
If there is anything to improve, let me know! 😃
*thanks dimi and gwynne for helping along the way and answering my
questions :)*
---------
Co-authored-by: Franz Busch <privat@franz-busch.de>
Motivation:
The 'unsafeDowncast' can cause a miscompile leading to unexpected
runtime behaviour.
Modifications:
- Use 'as!' instead
Result:
No miscompiles on 5.10
- sigabrt: usually generated by the abort() function. Useful for cleanup prior to termination.
- sigill: issued if the user attempts to execute an illegal, malformed, or privileged instruction.
- sigsegv: issued if the user makes an invalid memory reference, such as dereferencing a null or invalid pointer.
Motivation:
Deprecation with rename fixit has been seen to cause compiler crashes
in 5.x compiler versions.
Modifications:
Deprecate with message for 5.x compilers.
Result:
Compilation without failure in all scenarios
* Fix global cancelOnGracefulShutdown return type
* Deprecate cancelOnGracefulShutdown and add cancelWhenGracefulShutdown
* Add doc comment even for the deprecated function
* Fix logic issues during graceful shutdown
# Motivation
This should fix the remaining issues raised in https://github.com/swift-server/swift-service-lifecycle/pull/166. The problem here was that if a service finished/threw out of order then we were wrongly treating this as if the service that we are currently shutting down finished.
# Modification
This PR ensures that we use the same `services` array during the graceful shutdown to nil out services that have finished. This way we correctly keep track of any service that finished. Additionally, there was a separate bug where we started to shutdown the next service to early if another service threw and had the termination behaviour of `shutdownGracefully`.
# Result
No more incorrect shutdown orderings.
* Fix one more race condition
* update readme instructions & version
* add full package example
* Update README.md
Co-authored-by: Franz Busch <privat@franz-busch.de>
* Update README.md
Co-authored-by: Franz Busch <privat@franz-busch.de>
* add getting started to docc index
---------
Co-authored-by: Franz Busch <privat@franz-busch.de>
* Mention `TerminationBehavior` in library adoption docs
`ServiceGroupConfiguration.ServiceConfiguration.TerminationBehavior` did not seem to be mentioned in the docs and specifically library adoption docs gave the impression that cancellation on returning from `run` is the only option.
* Update relevant documentation
* Make sure we return after gracefully shutdown
# Motivation
After calling `shutdownGracefully` in our `ServiceGroup` we know that one of two things happened:
1. We got an error so something went wrong
2. We got no error so all services finished
In the 2. case, there might still be a few child tasks in the task group e.g. the graceful shutdown timeout task. We are currently still iterating the remaining child task results which might lead into unexpected fatal errors.
# Modification
This PR makes sure that after we have successfully shutdown we are stopping iterating the child task results.
# Result
No more unexpected fatal errors.
* Fix flaky test
* Add a configurable escalation behaviour
# Motivation
The service group is often running multiple services and orchestrates shutdown for them. We have seen that sometimes some services never shutdown nor do they respond to task cancellation properly. This can become quite problematic when the whole application is waiting for a service to cancel and otherwise appears to be healthy but in reality can't serve any traffic.
# Modification
This PR adds a new configuration to escalate both graceful shutdown and cancellation. The escalation order is graceful shutdown -> task cancellation -> `fatalError`. The `fatalError` acts a last resort to make sure applications are never stuck.
* George review
* Fix some smaller issues
# Motivation
`SIGWINCH` is sent to applications when the window resizes. This is useful to observe for terminal applications to reformat the logging one resize.
# Modification
This PR adds support for `SIGWINCH` in `UnixSignal`s.
# Motivation
We are about to tag a `2.0.0` and cannot depend on any non major package.
# Modification
This vendors in `swift-async-algorithms` so that we can use the `AsyncMergeSequence`. In the future, once `swift-async-algorithms` is `1.0.0` itself we can swap back.
# Result
No more non-major dependency.
# Motivation
Right now creating a `ServiceGroup` always requires creating a `ServiceGroupConfiguration`. This is making the barrier to use the group higher than needed for the 99% use-case.
# Modification
This PR adds a new init on the `ServiceGroup` that takes an array of services, graceful shutdown & cancellation signals and the logger.
# Result
Easier use of the service group for the 99% use-case.
# Motivation
When a service threw during graceful shutdown but had its behaviour set to `gracefulShutdown` itself then we were not rethrowing the error.
# Modification
This PR makes sure that the first service that throws an error which doesn't have its `failureTerminationBehavior` to `.ignore` gets rethrown by the `ServiceGroup`.
# Motivation
To avoid colliding with logging keys of adopters we should prefix our default metadata logging keys.
# Modification
This PR prefixes our default logging keys with `sl-`.