-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathConcurrencySupport.swift
More file actions
422 lines (398 loc) · 14.4 KB
/
ConcurrencySupport.swift
File metadata and controls
422 lines (398 loc) · 14.4 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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
extension AsyncStream {
/// Initializes an `AsyncStream` from any `AsyncSequence`.
///
/// Useful as a type eraser for live `AsyncSequence`-based dependencies.
///
/// For example, your feature may want to subscribe to screenshot notifications. You can model
/// this as a dependency client that returns an `AsyncStream`:
///
/// ```swift
/// struct ScreenshotsClient {
/// var screenshots: () -> AsyncStream<Void>
/// func callAsFunction() -> AsyncStream<Void> { self.screenshots() }
/// }
/// ```
///
/// The "live" implementation of the dependency can supply a stream by erasing the appropriate
/// `NotificationCenter.Notifications` async sequence:
///
/// ```swift
/// extension ScreenshotsClient {
/// static let live = Self(
/// screenshots: {
/// AsyncStream(
/// NotificationCenter.default
/// .notifications(named: UIApplication.userDidTakeScreenshotNotification)
/// .map { _ in }
/// )
/// }
/// )
/// }
/// ```
///
/// While your tests can use `AsyncStream.streamWithContinuation` to spin up a controllable stream
/// for tests:
///
/// ```swift
/// let screenshots = AsyncStream<Void>.streamWithContinuation()
///
/// let store = TestStore(
/// initialState: Feature.State(),
/// reducer: Feature()
/// )
///
/// store.dependencies.screenshots.screenshots = { screenshots.stream }
///
/// screenshots.continuation.yield() // Simulate a screenshot being taken.
///
/// await store.receive(.screenshotTaken) { ... }
/// ```
///
/// - Parameters:
/// - sequence: An `AsyncSequence`.
/// - limit: The maximum number of elements to hold in the buffer. By default, this value is
/// unlimited. Use a `Continuation.BufferingPolicy` to buffer a specified number of oldest or
/// newest elements.
public init<S: AsyncSequence & Sendable>(
_ sequence: S,
bufferingPolicy limit: Continuation.BufferingPolicy = .unbounded
) where S.Element == Element {
self.init(bufferingPolicy: limit) { (continuation: Continuation) in
let task = Task {
do {
for try await element in sequence {
continuation.yield(element)
}
} catch {}
continuation.finish()
}
continuation.onTermination =
{ _ in
task.cancel()
}
// NB: This explicit cast is needed to work around a compiler bug in Swift 5.5.2
as @Sendable (Continuation.Termination) -> Void
}
}
/// Constructs and returns a stream along with its backing continuation.
///
/// This is handy for immediately escaping the continuation from an async stream, which typically
/// requires multiple steps:
///
/// ```swift
/// var _continuation: AsyncStream<Int>.Continuation!
/// let stream = AsyncStream<Int> { continuation = $0 }
/// let continuation = _continuation!
///
/// // vs.
///
/// let (stream, continuation) = AsyncStream<Int>.streamWithContinuation()
/// ```
///
/// This tool is usually used for tests where we need to supply an async sequence to a dependency
/// endpoint and get access to its continuation so that we can emulate the dependency
/// emitting data. For example, suppose you have a dependency exposing an async sequence for
/// listening to notifications. To test this you can use `streamWithContinuation`:
///
/// ```swift
/// let notifications = AsyncStream<Void>.streamWithContinuation()
///
/// let store = TestStore(
/// initialState: Feature.State(),
/// reducer: Feature()
/// )
///
/// store.dependencies.notifications = { notifications.stream }
///
/// await store.send(.task)
/// notifications.continuation.yield("Hello") // Simulate notification being posted
/// await store.receive(.notification("Hello")) {
/// $0.message = "Hello"
/// }
/// ```
///
/// > Warning: ⚠️ `AsyncStream` does not support multiple subscribers, therefore you can only use
/// > this helper to test features that do not subscribe multiple times to the dependency
/// > endpoint.
///
/// - Parameters:
/// - elementType: The type of element the `AsyncStream` produces.
/// - limit: A Continuation.BufferingPolicy value to set the stream’s buffering behavior. By
/// default, the stream buffers an unlimited number of elements. You can also set the policy to
/// buffer a specified number of oldest or newest elements.
/// - Returns: An `AsyncStream`.
public static func streamWithContinuation(
_ elementType: Element.Type = Element.self,
bufferingPolicy limit: Continuation.BufferingPolicy = .unbounded
) -> (stream: Self, continuation: Continuation) {
var continuation: Continuation!
return (Self(elementType, bufferingPolicy: limit) { continuation = $0 }, continuation)
}
/// An `AsyncStream` that never emits and never completes unless cancelled.
public static var never: Self {
Self { _ in }
}
public static var finished: Self {
Self { $0.finish() }
}
}
extension AsyncThrowingStream where Failure == Error {
/// Initializes an `AsyncThrowingStream` from any `AsyncSequence`.
///
/// - Parameters:
/// - sequence: An `AsyncSequence`.
/// - limit: The maximum number of elements to hold in the buffer. By default, this value is
/// unlimited. Use a `Continuation.BufferingPolicy` to buffer a specified number of oldest or
/// newest elements.
public init<S: AsyncSequence & Sendable>(
_ sequence: S,
bufferingPolicy limit: Continuation.BufferingPolicy = .unbounded
) where S.Element == Element {
self.init(bufferingPolicy: limit) { (continuation: Continuation) in
let task = Task {
do {
for try await element in sequence {
continuation.yield(element)
}
continuation.finish()
} catch {
continuation.finish(throwing: error)
}
}
continuation.onTermination =
{ _ in
task.cancel()
}
// NB: This explicit cast is needed to work around a compiler bug in Swift 5.5.2
as @Sendable (Continuation.Termination) -> Void
}
}
/// Constructs and returns a stream along with its backing continuation.
///
/// This is handy for immediately escaping the continuation from an async stream, which typically
/// requires multiple steps:
///
/// ```swift
/// var _continuation: AsyncThrowingStream<Int, Error>.Continuation!
/// let stream = AsyncThrowingStream<Int, Error> { continuation = $0 }
/// let continuation = _continuation!
///
/// // vs.
///
/// let (stream, continuation) = AsyncThrowingStream<Int, Error>.streamWithContinuation()
/// ```
///
/// This tool is usually used for tests where we need to supply an async sequence to a dependency
/// endpoint and get access to its continuation so that we can emulate the dependency
/// emitting data. For example, suppose you have a dependency exposing an async sequence for
/// listening to notifications. To test this you can use `streamWithContinuation`:
///
/// ```swift
/// let notifications = AsyncThrowingStream<Void>.streamWithContinuation()
///
/// let store = TestStore(
/// initialState: Feature.State(),
/// reducer: Feature()
/// )
///
/// store.dependencies.notifications = { notifications.stream }
///
/// await store.send(.task)
/// notifications.continuation.yield("Hello") // Simulate a notification being posted
/// await store.receive(.notification("Hello")) {
/// $0.message = "Hello"
/// }
/// ```
///
/// > Warning: ⚠️ `AsyncStream` does not support multiple subscribers, therefore you can only use
/// > this helper to test features that do not subscribe multiple times to the dependency
/// > endpoint.
///
/// - Parameters:
/// - elementType: The type of element the `AsyncThrowingStream` produces.
/// - limit: A Continuation.BufferingPolicy value to set the stream’s buffering behavior. By
/// default, the stream buffers an unlimited number of elements. You can also set the policy to
/// buffer a specified number of oldest or newest elements.
/// - Returns: An `AsyncThrowingStream`.
public static func streamWithContinuation(
_ elementType: Element.Type = Element.self,
bufferingPolicy limit: Continuation.BufferingPolicy = .unbounded
) -> (stream: Self, continuation: Continuation) {
var continuation: Continuation!
return (Self(elementType, bufferingPolicy: limit) { continuation = $0 }, continuation)
}
/// An `AsyncThrowingStream` that never emits and never completes unless cancelled.
public static var never: Self {
Self { _ in }
}
public static var finished: Self {
Self { $0.finish() }
}
}
extension Task where Failure == Never {
/// An async function that never returns.
public static func never() async throws -> Success {
for await element in AsyncStream<Success>.never {
return element
}
throw _Concurrency.CancellationError()
}
}
extension Task where Success == Never, Failure == Never {
/// An async function that never returns.
public static func never() async throws {
for await _ in AsyncStream<Never>.never {}
throw _Concurrency.CancellationError()
}
}
/// A generic wrapper for isolating a mutable value to an actor.
///
/// This type is most useful when writing tests for when you want to inspect what happens inside
/// an effect. For example, suppose you have a feature such that when a button is tapped you
/// track some analytics:
///
/// ```swift
/// @Dependency(\.analytics) var analytics
///
/// func reduce(into state: inout State, action: Action) -> EffectTask<Action> {
/// switch action {
/// case .buttonTapped:
/// return .fireAndForget { try await self.analytics.track("Button Tapped") }
/// }
/// }
/// ```
///
/// Then, in tests we can construct an analytics client that appends events to a mutable array
/// rather than actually sending events to an analytics server. However, in order to do this in
/// a safe way we should use an actor, and ``ActorIsolated`` makes this easy:
///
/// ```swift
/// @MainActor
/// func testAnalytics() async {
/// let store = TestStore(…)
///
/// let events = ActorIsolated<[String]>([])
/// store.dependencies.analytics = AnalyticsClient(
/// track: { event in
/// await events.withValue { $0.append(event) }
/// }
/// )
///
/// await store.send(.buttonTapped)
///
/// await events.withValue { XCTAssertEqual($0, ["Button Tapped"]) }
/// }
/// ```
@dynamicMemberLookup
public final actor ActorIsolated<Value: Sendable> {
/// The actor-isolated value.
public var value: Value
/// Initializes actor-isolated state around a value.
///
/// - Parameter value: A value to isolate in an actor.
public init(_ value: Value) {
self.value = value
}
public subscript<Subject>(dynamicMember keyPath: KeyPath<Value, Subject>) -> Subject {
self.value[keyPath: keyPath]
}
/// Perform an operation with isolated access to the underlying value.
///
/// Useful for inspecting an actor-isolated value for a test assertion:
///
/// ```swift
/// let didOpenSettings = ActorIsolated(false)
/// store.dependencies.openSettings = { await didOpenSettings.setValue(true) }
///
/// await store.send(.settingsButtonTapped)
///
/// await didOpenSettings.withValue { XCTAssertTrue($0) }
/// ```
///
/// - Parameters: operation: An operation to be performed on the actor with the underlying value.
/// - Returns: The result of the operation.
public func withValue<T: Sendable>(
_ operation: @Sendable (inout Value) async throws -> T
) async rethrows -> T {
var value = self.value
defer { self.value = value }
return try await operation(&value)
}
/// Overwrite the isolated value with a new value.
///
/// Useful for setting an actor-isolated value when a tested dependency runs.
///
/// ```swift
/// let didOpenSettings = ActorIsolated(false)
/// store.dependencies.openSettings = { await didOpenSettings.setValue(true) }
///
/// await store.send(.settingsButtonTapped)
///
/// await didOpenSettings.withValue { XCTAssertTrue($0) }
/// ```
///
/// - Parameter newValue: The value to replace the current isolated value with.
public func setValue(_ newValue: Value) {
self.value = newValue
}
}
/// A generic wrapper for turning any non-`Sendable` type into a `Sendable` one, in an unchecked
/// manner.
///
/// Sometimes we need to use types that should be sendable but have not yet been audited for
/// sendability. If we feel confident that the type is truly sendable, and we don't want to blanket
/// disable concurrency warnings for a module via `@preconcurrency import`, then we can selectively
/// make that single type sendable by wrapping it in ``UncheckedSendable``.
///
/// > Note: By wrapping something in ``UncheckedSendable`` you are asking the compiler to trust
/// you that the type is safe to use from multiple threads, and the compiler cannot help you find
/// potential race conditions in your code.
@dynamicMemberLookup
@propertyWrapper
public struct UncheckedSendable<Value>: @unchecked Sendable {
/// The unchecked value.
public var value: Value
public init(_ value: Value) {
self.value = value
}
public init(wrappedValue: Value) {
self.value = wrappedValue
}
public var wrappedValue: Value {
_read { yield self.value }
_modify { yield &self.value }
}
public var projectedValue: Self {
get { self }
set { self = newValue }
}
public subscript<Subject>(dynamicMember keyPath: KeyPath<Value, Subject>) -> Subject {
self.value[keyPath: keyPath]
}
public subscript<Subject>(dynamicMember keyPath: WritableKeyPath<Value, Subject>) -> Subject {
_read { yield self.value[keyPath: keyPath] }
_modify { yield &self.value[keyPath: keyPath] }
}
}
extension UncheckedSendable: Equatable where Value: Equatable {}
extension UncheckedSendable: Hashable where Value: Hashable {}
extension UncheckedSendable: Decodable where Value: Decodable {
public init(from decoder: Decoder) throws {
do {
let container = try decoder.singleValueContainer()
self.init(wrappedValue: try container.decode(Value.self))
} catch {
self.init(wrappedValue: try Value(from: decoder))
}
}
}
extension UncheckedSendable: Encodable where Value: Encodable {
public func encode(to encoder: Encoder) throws {
do {
var container = encoder.singleValueContainer()
try container.encode(self.wrappedValue)
} catch {
try self.wrappedValue.encode(to: encoder)
}
}
}