-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathSubtreeManager.swift
453 lines (362 loc) · 16.2 KB
/
SubtreeManager.swift
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
/*
* Copyright 2020 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Dispatch
extension WorkflowNode {
/// Manages the subtree of a workflow. Specifically, this type encapsulates the logic required to update and manage
/// the lifecycle of nested workflows across multiple render passes.
internal final class SubtreeManager {
internal var onUpdate: ((Output) -> Void)?
/// Sinks from the outside world (i.e. UI)
internal private(set) var eventPipes: [EventPipe] = []
/// Reusable sinks from the previous render pass
private var previousSinks: [ObjectIdentifier: AnyReusableSink] = [:]
/// The current array of children
internal private(set) var childWorkflows: [ChildKey: AnyChildWorkflow] = [:]
/// The current array of side-effects
internal private(set) var sideEffectLifetimes: [AnyHashable: SideEffectLifetime] = [:]
init() {}
/// Performs an update pass using the given closure.
func render<Rendering>(_ actions: (RenderContext<WorkflowType>) -> Rendering) -> Rendering {
/// Invalidate the previous action handlers.
for eventPipe in eventPipes {
eventPipe.invalidate()
}
/// Create a workflow context containing the existing children
let context = Context(
previousSinks: previousSinks,
originalChildWorkflows: childWorkflows,
originalSideEffectLifetimes: sideEffectLifetimes
)
let wrapped = RenderContext.make(implementation: context)
/// Pass the context into the closure to allow a render to take place
let rendering = actions(wrapped)
wrapped.invalidate()
/// After the render is complete, assign children using *only the children that were used during the render
/// pass.* This means that any pre-existing children that were *not* used during the render pass are removed
/// as a result of this call to `render`.
childWorkflows = context.usedChildWorkflows
sideEffectLifetimes = context.usedSideEffectLifetimes
/// Captured the reusable sinks from this render pass.
previousSinks = context.sinkStore.usedSinks
/// Capture all the pipes to be enabled after render completes.
eventPipes = context.eventPipes
eventPipes.append(contentsOf: context.sinkStore.eventPipes)
/// Set all event pipes to `pending`.
eventPipes.forEach { $0.setPending() }
/// Return the rendered result
return rendering
}
/// Enable the eventPipes for the previous rendering. The eventPipes are not valid until this has
/// be called. If is an error to call this twice without generating a new rendering.
func enableEvents() {
/// Enable all action pipes.
for eventPipe in eventPipes {
eventPipe.enable { [weak self] output in
self?.handle(output: output)
}
}
/// Enable all child workflows.
for child in childWorkflows {
child.value.enableEvents()
}
}
func makeDebugSnapshot() -> [WorkflowHierarchyDebugSnapshot.Child] {
return childWorkflows
.sorted(by: { (lhs, rhs) -> Bool in
lhs.key.key < rhs.key.key
})
.map {
WorkflowHierarchyDebugSnapshot.Child(
key: $0.key.key,
snapshot: $0.value.makeDebugSnapshot()
)
}
}
private func handle(output: Output) {
onUpdate?(output)
}
}
}
extension WorkflowNode.SubtreeManager {
enum Output {
case update(AnyWorkflowAction<WorkflowType>, source: WorkflowUpdateDebugInfo.Source)
case childDidUpdate(WorkflowUpdateDebugInfo)
}
}
// MARK: - Render Context
extension WorkflowNode.SubtreeManager {
/// The workflow context implementation used by the subtree manager.
fileprivate final class Context: RenderContextType {
internal private(set) var eventPipes: [EventPipe]
internal private(set) var sinkStore: SinkStore
private let originalChildWorkflows: [ChildKey: AnyChildWorkflow]
internal private(set) var usedChildWorkflows: [ChildKey: AnyChildWorkflow]
private let originalSideEffectLifetimes: [AnyHashable: SideEffectLifetime]
internal private(set) var usedSideEffectLifetimes: [AnyHashable: SideEffectLifetime]
internal init(
previousSinks: [ObjectIdentifier: AnyReusableSink],
originalChildWorkflows: [ChildKey: AnyChildWorkflow],
originalSideEffectLifetimes: [AnyHashable: SideEffectLifetime]
) {
self.eventPipes = []
self.sinkStore = SinkStore(previousSinks: previousSinks)
self.originalChildWorkflows = originalChildWorkflows
self.usedChildWorkflows = [:]
self.originalSideEffectLifetimes = originalSideEffectLifetimes
self.usedSideEffectLifetimes = [:]
}
func render<Child, Action>(workflow: Child, key: String, outputMap: @escaping (Child.Output) -> Action) -> Child.Rendering where Child: Workflow, Action: WorkflowAction, WorkflowType == Action.WorkflowType {
/// A unique key used to identify this child workflow
let childKey = ChildKey(childType: Child.self, key: key)
/// If the key already exists in `used`, than a workflow of the same type has been rendered multiple times
/// during this render pass with the same key. This is not allowed.
guard usedChildWorkflows[childKey] == nil else {
fatalError("Child workflows of the same type must be given unique keys. Duplicate workflows of type \(Child.self) were encountered with the key \"\(key)\" in \(WorkflowType.self)")
}
let child: ChildWorkflow<Child>
let eventPipe = EventPipe()
eventPipes.append(eventPipe)
/// See if we can
if let existing = originalChildWorkflows[childKey] {
/// Cast the untyped child into a specific typed child. Because our children are keyed by their workflow
/// type, this should never fail.
guard let existing = existing as? ChildWorkflow<Child> else {
fatalError("ChildKey class type does not match the underlying workflow type.")
}
/// Update the existing child
existing.update(
workflow: workflow,
outputMap: { AnyWorkflowAction(outputMap($0)) },
eventPipe: eventPipe
)
child = existing
} else {
/// We could not find an existing child matching the given child key, so we will generate a new child.
/// This spins up a new workflow node, etc to host the newly created child.
child = ChildWorkflow<Child>(
workflow: workflow,
outputMap: { AnyWorkflowAction(outputMap($0)) },
eventPipe: eventPipe
)
}
/// Store the resolved child in `used`. This allows us to a) hold on to any used children after this render
/// pass, and b) ensure that we never allow the use of a given workflow type with identical keys.
usedChildWorkflows[childKey] = child
return child.render()
}
func makeSink<Action>(of actionType: Action.Type) -> Sink<Action> where Action: WorkflowAction, WorkflowType == Action.WorkflowType {
let reusableSink = sinkStore.findOrCreate(actionType: Action.self)
let sink = Sink<Action> { [weak reusableSink] action in
WorkflowLogger.logSinkEvent(ref: SignpostRef(), action: action)
// use a weak reference as we'd like control over the lifetime
reusableSink?.handle(action: action)
}
return sink
}
func runSideEffect(key: AnyHashable, action: (Lifetime) -> Void) {
if let existingSideEffect = originalSideEffectLifetimes[key] {
usedSideEffectLifetimes[key] = existingSideEffect
} else {
let sideEffectLifetime = SideEffectLifetime()
action(sideEffectLifetime.lifetime)
usedSideEffectLifetimes[key] = sideEffectLifetime
}
}
}
}
// MARK: - Reusable Sink
extension WorkflowNode.SubtreeManager {
fileprivate struct SinkStore {
var eventPipes: [EventPipe] {
return usedSinks.values.map { reusableSink -> EventPipe in
reusableSink.eventPipe
}
}
private var previousSinks: [ObjectIdentifier: AnyReusableSink]
private(set) var usedSinks: [ObjectIdentifier: AnyReusableSink]
init(previousSinks: [ObjectIdentifier: AnyReusableSink]) {
self.previousSinks = previousSinks
self.usedSinks = [:]
}
mutating func findOrCreate<Action: WorkflowAction>(actionType: Action.Type) -> ReusableSink<Action> {
let key = ObjectIdentifier(actionType)
let reusableSink: ReusableSink<Action>
if let previousSink = previousSinks.removeValue(forKey: key) as? ReusableSink<Action> {
// Reuse a previous sink, creating a new event pipe to send the action through.
previousSink.eventPipe = EventPipe()
reusableSink = previousSink
} else if let usedSink = usedSinks[key] as? ReusableSink<Action> {
// Multiple sinks using the same backing sink.
reusableSink = usedSink
} else {
// Create a new reusable sink.
reusableSink = ReusableSink<Action>()
}
usedSinks[key] = reusableSink
return reusableSink
}
}
/// Type-erased base class for reusable sinks.
fileprivate class AnyReusableSink {
var eventPipe: EventPipe
init() {
self.eventPipe = EventPipe()
}
}
fileprivate final class ReusableSink<Action: WorkflowAction>: AnyReusableSink where Action.WorkflowType == WorkflowType {
func handle(action: Action) {
let output = Output.update(AnyWorkflowAction(action), source: .external)
if case .pending = eventPipe.validationState {
// Workflow is currently processing an `event`.
// Scheduling it to be processed after.
DispatchQueue.workflowExecution.async { [weak self] in
self?.eventPipe.handle(event: output)
}
return
}
eventPipe.handle(event: output)
}
}
}
// MARK: - EventPipe
extension WorkflowNode.SubtreeManager {
internal final class EventPipe {
var validationState: ValidationState
enum ValidationState {
case preparing
case pending
case valid(handler: (Output) -> Void)
case invalid
}
init() {
self.validationState = .preparing
}
func handle(event: Output) {
dispatchPrecondition(condition: .onQueue(DispatchQueue.workflowExecution))
switch validationState {
case .preparing:
fatalError("[\(WorkflowType.self)] Sink sent an action inside `render`. Sinks are not valid until `render` has completed.")
case .pending:
fatalError("[\(WorkflowType.self)] Action sent to pipe while in the `pending` state.")
case .valid(let handler):
handler(event)
case .invalid:
fatalError("[\(WorkflowType.self)] Sink sent an action after it was invalidated. Sinks can only be used for a single valid `Rendering`.")
}
}
func setPending() {
guard case .preparing = validationState else {
fatalError("Attempted to `setPending` an EventPipe that was not in the preparing state.")
}
validationState = .pending
}
func enable(with handler: @escaping (Output) -> Void) {
guard case .pending = validationState else {
fatalError("EventPipe can only be enabled from the `pending` state")
}
validationState = .valid(handler: handler)
}
func invalidate() {
validationState = .invalid
}
}
}
// MARK: - ChildKey
extension WorkflowNode.SubtreeManager {
struct ChildKey: Hashable {
var childType: Any.Type
var key: String
init<T>(childType: T.Type, key: String) {
self.childType = childType
self.key = key
}
func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(childType))
hasher.combine(key)
}
static func == (lhs: ChildKey, rhs: ChildKey) -> Bool {
return lhs.childType == rhs.childType
&& lhs.key == rhs.key
}
}
}
// MARK: - Child Workflows
extension WorkflowNode.SubtreeManager {
/// Abstract base class for running children in the subtree.
internal class AnyChildWorkflow {
fileprivate var eventPipe: EventPipe
fileprivate init(eventPipe: EventPipe) {
self.eventPipe = eventPipe
}
func enableEvents() {
fatalError()
}
func makeDebugSnapshot() -> WorkflowHierarchyDebugSnapshot {
fatalError()
}
}
fileprivate final class ChildWorkflow<W: Workflow>: AnyChildWorkflow {
private let node: WorkflowNode<W>
private var outputMap: (W.Output) -> AnyWorkflowAction<WorkflowType>
init(workflow: W, outputMap: @escaping (W.Output) -> AnyWorkflowAction<WorkflowType>, eventPipe: EventPipe) {
self.outputMap = outputMap
self.node = WorkflowNode<W>(workflow: workflow)
super.init(eventPipe: eventPipe)
node.onOutput = { [weak self] output in
self?.handle(workflowOutput: output)
}
}
override func enableEvents() {
node.enableEvents()
}
func render() -> W.Rendering {
return node.render(isRootNode: false)
}
func update(workflow: W, outputMap: @escaping (W.Output) -> AnyWorkflowAction<WorkflowType>, eventPipe: EventPipe) {
self.outputMap = outputMap
self.eventPipe = eventPipe
node.update(workflow: workflow)
}
private func handle(workflowOutput: WorkflowNode<W>.Output) {
let output: Output
if let outputEvent = workflowOutput.outputEvent {
output = Output.update(
outputMap(outputEvent),
source: .subtree(workflowOutput.debugInfo)
)
} else {
output = Output.childDidUpdate(workflowOutput.debugInfo)
}
eventPipe.handle(event: output)
}
override func makeDebugSnapshot() -> WorkflowHierarchyDebugSnapshot {
return node.makeDebugSnapshot()
}
}
}
// MARK: - Side Effects
extension WorkflowNode.SubtreeManager {
internal class SideEffectLifetime {
fileprivate let lifetime: Lifetime
fileprivate init() {
self.lifetime = Lifetime()
}
deinit {
// Explicitly end the lifetime in case someone retained it from outside
lifetime.end()
}
}
}