Repository navigation
Expand file tree
/
Copy pathStorageMutationGate.swift
More file actions
161 lines (140 loc) · 6.52 KB
/
Copy pathStorageMutationGate.swift
File metadata and controls
161 lines (140 loc) · 6.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
//
// StorageMutationGate.swift
// osaurus
//
// Slim readiness gate for at-rest storage. The only thing the gate
// guards is key rotation: `StorageExportService.rotateStorageKey`
// calls `beginMutating()` before it quiesces + rekeys every database and
// `endMutating()` after. While `isMutating` is true, any
// `*Database.open()` that hits `blockingAwaitNotMutating()` parks so
// it can't open a half-rekeyed file with the wrong key.
//
// Fast path is completely lock-free and main-actor-free: a single
// atomic load that returns immediately when no rotation is running
// (the overwhelmingly common case, including every launch).
//
import Foundation
import os
@MainActor
public final class StorageMutationGate {
public static let shared = StorageMutationGate()
/// True only while a key rotation is actively re-encrypting
/// databases. Mirrored to the lock-free `Self.isMutatingAtomic`
/// so `blockingAwaitNotMutating()` can poll without hopping onto
/// the main actor.
public private(set) var isMutating: Bool = false {
didSet { Self.isMutatingAtomic.store(isMutating) }
}
/// Cross-thread mirror of `isMutating` for the blocking fast
/// path. Reads happen from arbitrary threads (every
/// `*Database.open()` hits the gate defensively); writes happen
/// on the main actor via the `didSet` above.
nonisolated private static let isMutatingAtomic = AtomicBool(false)
/// Lock-free check for main-actor launch paths that prefer to defer
/// (and retry later) rather than park the UI while a rotation runs.
nonisolated public static var isRotationInFlight: Bool { isMutatingAtomic.load() }
/// Monotonic count of mutations that have ever *begun*. Lets an open
/// path close the check-then-open TOCTOU: snapshot the epoch after the
/// gate clears, open, then verify the epoch is unchanged (and no
/// mutation is in flight). If it moved, a quiesce/swap/rekey ran while
/// the file was being opened and the fresh connection may span the
/// swap — close and retry (see `PluginDatabase.open()`).
nonisolated private static let mutationEpochAtomic = OSAllocatedUnfairLock<UInt64>(
initialState: 0)
nonisolated public static var mutationEpoch: UInt64 {
mutationEpochAtomic.withLock { $0 }
}
/// Posted after a key rotation finishes (`endMutating`). Launch paths
/// that skipped a load while a rotation was in flight observe this to
/// retry once storage has settled.
public static let didFinishMutatingNotification = Notification.Name(
"StorageMutationGate.didFinishMutating"
)
/// Continuations parked by `awaitNotMutating` while a rotation is
/// in flight. Drained by `endMutating()`.
private var waiters: [CheckedContinuation<Void, Never>] = []
private init() {}
/// Isolated instance for unit tests. The park/resume semantics tests
/// must not use `shared`: other suites running in parallel (storage
/// migration, key rotation) call `endMutating()` on the singleton and
/// wake the test's parked probes early. Note the `isMutating` didSet
/// still mirrors into the process-wide atomic; harmless under tests,
/// where `blockingAwaitNotMutating()` early-returns anyway.
static func makeForTesting() -> StorageMutationGate {
StorageMutationGate()
}
// MARK: - Rotation hooks
/// Called by `StorageExportService.rotateStorageKey` before it
/// starts re-encrypting. Blocks every subsequent
/// `blockingAwaitNotMutating` / `awaitNotMutating` caller until
/// `endMutating()` runs.
public func beginMutating() {
Self.mutationEpochAtomic.withLock { $0 &+= 1 }
isMutating = true
}
/// Companion to `beginMutating`. Wakes up everything parked in
/// `awaitNotMutating`.
public func endMutating() {
isMutating = false
let parked = waiters
waiters.removeAll()
for cont in parked { cont.resume() }
NotificationCenter.default.post(name: Self.didFinishMutatingNotification, object: nil)
}
// MARK: - Gating
/// Async gate: resolves immediately unless a rotation is in
/// flight, in which case it parks until `endMutating()` runs.
public func awaitNotMutating() async {
while isMutating {
await withCheckedContinuation { (cont: CheckedContinuation<Void, Never>) in
if !isMutating {
cont.resume()
} else {
waiters.append(cont)
}
}
}
}
/// True when `blockingAwaitNotMutating()` is a no-op for this process:
/// keychain-disabled processes and test runs (tests use isolated
/// temporary databases and don't rotate the real storage key under the
/// gate; bypassing prevents Swift Concurrency deadlocks when tests run
/// on the MainActor and hit the semaphore wait). Open paths that retry
/// on the mutation epoch must not spin when the gate never parks them.
nonisolated public static var blockingGateIsBypassed: Bool {
StorageKeyManager.disablesKeychainForProcess || RuntimeEnvironment.isUnderTests
}
/// Synchronous gate for callers that can't go async (the
/// `*Database.open()` paths). Fast path is a lock-free atomic
/// poll. The slow path (only while a rotation is running) spins
/// the main run loop so the UI keeps painting while it waits.
nonisolated public static func blockingAwaitNotMutating() {
if blockingGateIsBypassed {
return
}
// Fast path: no rotation running.
if !isMutatingAtomic.load() {
return
}
// Slow path: park until the rotation finishes.
let semaphore = DispatchSemaphore(value: 0)
Task { @MainActor in
await shared.awaitNotMutating()
semaphore.signal()
}
if Thread.isMainThread {
// Ledger entry: the run-loop spin keeps the UI painting, but a
// rotation that never ends would still be a user-visible stall —
// the watchdog should attribute it to the storage gate.
let token = MainThreadOperationLedger.shared.begin(
subsystem: "storage", operation: "await-key-rotation"
)
defer { MainThreadOperationLedger.shared.end(token) }
while semaphore.wait(timeout: .now() + 0.05) == .timedOut {
RunLoop.current.run(mode: .default, before: Date(timeIntervalSinceNow: 0.05))
}
} else {
semaphore.wait()
}
}
}