swift-server / swift-service-lifecycle

Cleanly startup and shutdown server application, freeing resources in order before exiting.
https://swiftpackageindex.com/swift-server/swift-service-lifecycle/documentation/servicelifecycle
Apache License 2.0
396 stars 38 forks source link

Add support for `return/ThrowBehavior` of services #148

Closed FranzBusch closed 1 year ago

FranzBusch commented 1 year ago

Motivation

Currently the ServiceGroup cancels the whole group when a service returns or throws. This is fine for most server applications but it doesn't work for CLI tools since they mostly want to use the group to orchestrate the services as long as the user command is handled and then return cleanly from the group. Furthermore, even on server setups one might want to customize the behavior of what happens when a service returns/throws e.g. one might want to shutdown the group after their HTTP server throws so that a telemetry service flushes out all the remaining data.

Modification

This PR does a few things:

  1. It creates a new ServiceConfiguration and TerminationBehavior in the ServiceGroupConfiguration. Those can be used to declare the services that are run and what happens when the service returns or throws
  2. Adds a new cancellationSignals to to the ServiceGroupConfiguration which allows cancellation to trigger based on a signal
  3. Makes sure that any given service is only retained as long as necessary i.e. when a service returns the group is not retaining it anymore. This allows freeing of resources as early as possible
  4. Breaking: Removes the Hashable conformance on the configuration structs. This was wrong in the first place and something we should just avoid doing in general.

Result

We now give the user even more control about the group's behaviors.