Skip to content

Commit dce53aa

Browse files
authored
Install shutdown signal hooks as LifecycleTask (#88)
Motivation: Small code cleanup, reusing LifecycleTask as the shutdown hooks are to be installed just at the beginning of that chain of events anyway. Modifications: Moved signal handler installation to LifecycleTask instead of direct calls. Result: Slightly simpler code.
1 parent e6b78a8 commit dce53aa

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

Sources/Lifecycle/Lifecycle.swift

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,7 @@ public struct LifecycleShutdownHandler<State> {
183183
/// By default, also install shutdown hooks based on `Signal` and backtraces.
184184
public struct ServiceLifecycle {
185185
private static let backtracesInstalled = AtomicBoolean(false)
186+
private static let shutdownHooksInstalled = AtomicBoolean(false)
186187

187188
private let configuration: Configuration
188189

@@ -201,6 +202,7 @@ public struct ServiceLifecycle {
201202
self.underlying = ComponentLifecycle(label: self.configuration.label, logger: self.configuration.logger)
202203
// setup backtraces as soon as possible, so if we crash during setup we get a backtrace
203204
self.installBacktrace()
205+
self.installShutdownHooks()
204206
}
205207

206208
/// Starts the provided `LifecycleTask` array.
@@ -212,7 +214,6 @@ public struct ServiceLifecycle {
212214
guard self.underlying.idle else {
213215
preconditionFailure("already started")
214216
}
215-
self.setupShutdownHook()
216217
self.underlying.start(on: self.configuration.callbackQueue, callback)
217218
}
218219

@@ -222,7 +223,6 @@ public struct ServiceLifecycle {
222223
guard self.underlying.idle else {
223224
preconditionFailure("already started")
224225
}
225-
self.setupShutdownHook()
226226
try self.underlying.startAndWait(on: self.configuration.callbackQueue)
227227
}
228228

@@ -247,9 +247,16 @@ public struct ServiceLifecycle {
247247
}
248248
}
249249

250-
private func setupShutdownHook() {
250+
private func installShutdownHooks() {
251+
if self.configuration.shutdownSignal != nil, ServiceLifecycle.shutdownHooksInstalled.compareAndSwap(expected: false, desired: true) {
252+
self.register(label: "Shutdown hooks",
253+
start: .sync(self.installShutdownSignalHooks),
254+
shutdown: .none)
255+
}
256+
}
257+
258+
private func installShutdownSignalHooks() {
251259
self.configuration.shutdownSignal?.forEach { signal in
252-
self.log("setting up shutdown hook on \(signal)")
253260
let signalSource = ServiceLifecycle.trap(signal: signal, handler: { signal in
254261
self.log("intercepted signal: \(signal)")
255262
self.shutdown()

0 commit comments

Comments
 (0)