Modern Apps git

xtool.git

Public
git clone https://git.maproj.org/xtool.git
main ▾

xtool.git / Sources / XCLIUtils / ShutdownRegistry.swift

ShutdownRegistry.swift44 lines · 1.4 KiBRaw
1import ConcurrencyExtras
2import Dependencies
3
4/// Anything registered here will be cleaned up when the process exits
5public final class ShutdownRegistry: DependencyKey, Sendable {
6 public static var liveValue: ShutdownRegistry { ShutdownRegistry() }
7 public static var testValue: ShutdownRegistry { ShutdownRegistry() }
8
9 private struct State {
10 var operations: [@Sendable () async -> Void] = []
11 var shutdownTask: Task<Void, Never>?
12 }
13
14 private let state = LockIsolated(State())
15
16 public init() {}
17
18 /// Register cleanup before shutdown begins.
19 public func register(_ operation: @escaping @Sendable () async -> Void) {
20 state.withValue { $0.operations.append(operation) }
21 }
22
23 /// Runs cleanup in reverse registration order, once, even for concurrent callers.
24 public func shutdown() async {
25 let task = state.withValue { state in
26 if let task = state.shutdownTask { return task }
27 let pending = state.operations.reversed()
28 state.operations.removeAll()
29 let task = Task {
30 for operation in pending { await operation() }
31 }
32 state.shutdownTask = task
33 return task
34 }
35 await task.value
36 }
37}
38
39extension DependencyValues {
40 public var shutdownRegistry: ShutdownRegistry {
41 get { self[ShutdownRegistry.self] }
42 set { self[ShutdownRegistry.self] = newValue }
43 }
44}