-
Notifications
You must be signed in to change notification settings - Fork 99
/
TracingWorkflowInterceptor.kt
528 lines (482 loc) · 14.9 KB
/
TracingWorkflowInterceptor.kt
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
package com.squareup.workflow1.diagnostic.tracing
import com.squareup.tracing.TraceEncoder
import com.squareup.tracing.TraceEvent.AsyncDurationBegin
import com.squareup.tracing.TraceEvent.AsyncDurationEnd
import com.squareup.tracing.TraceEvent.Counter
import com.squareup.tracing.TraceEvent.DurationBegin
import com.squareup.tracing.TraceEvent.DurationEnd
import com.squareup.tracing.TraceEvent.Instant
import com.squareup.tracing.TraceEvent.Instant.InstantScope.GLOBAL
import com.squareup.tracing.TraceEvent.Instant.InstantScope.PROCESS
import com.squareup.tracing.TraceEvent.ObjectCreated
import com.squareup.tracing.TraceEvent.ObjectDestroyed
import com.squareup.tracing.TraceEvent.ObjectSnapshot
import com.squareup.tracing.TraceLogger
import com.squareup.workflow1.ActionApplied
import com.squareup.workflow1.BaseRenderContext
import com.squareup.workflow1.Snapshot
import com.squareup.workflow1.WorkflowAction
import com.squareup.workflow1.WorkflowIdentifier
import com.squareup.workflow1.WorkflowIdentifierType.Snapshottable
import com.squareup.workflow1.WorkflowIdentifierType.Unsnapshottable
import com.squareup.workflow1.WorkflowInterceptor
import com.squareup.workflow1.WorkflowInterceptor.RenderContextInterceptor
import com.squareup.workflow1.WorkflowInterceptor.WorkflowSession
import com.squareup.workflow1.applyTo
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import okio.buffer
import okio.sink
import java.io.File
import kotlin.LazyThreadSafetyMode.NONE
import kotlin.reflect.KClass
import kotlin.reflect.KType
/**
* A [WorkflowInterceptor] that generates a trace file that can be viewed in Chrome by
* visiting `chrome://tracing`.
*
* @param file The [File] to write the trace to.
* @param name If non-empty, will be used to set the "process name" in the trace file. If empty,
* the workflow type is used for the process name.
*/
public fun TracingWorkflowInterceptor(
file: File,
name: String = ""
): TracingWorkflowInterceptor = TracingWorkflowInterceptor(name) { workflowScope ->
TraceEncoder(workflowScope) {
file.sink()
.buffer()
}
}
/**
* A [WorkflowInterceptor] that generates a trace file that can be viewed in Chrome by
* visiting `chrome://tracing`.
*
* @param name If non-empty, will be used to set the "process name" in the trace file. If empty,
* the workflow type is used for the process name.
* @param encoderProvider A function that returns a [TraceEncoder] that will be used to write trace
* events. The function gets the [CoroutineScope] that the workflow runtime is running in.
*/
public fun TracingWorkflowInterceptor(
name: String = "",
memoryStats: MemoryStats = RuntimeMemoryStats,
encoderProvider: (workflowScope: CoroutineScope) -> TraceEncoder
): TracingWorkflowInterceptor =
TracingWorkflowInterceptor(memoryStats = memoryStats) { workflowScope, type ->
provideLogger(name, workflowScope, type, encoderProvider)
}
internal fun provideLogger(
name: String,
workflowScope: CoroutineScope,
workflowType: String,
encoderProvider: (workflowScope: CoroutineScope) -> TraceEncoder
): TraceLogger {
val encoder = encoderProvider(workflowScope)
val processName = name.ifEmpty { workflowType }
return encoder.createLogger(
processName = processName,
threadName = "Profiling"
)
}
/**
* A [WorkflowInterceptor] that generates a trace file that can be viewed in Chrome by
* visiting `chrome://tracing`.
*
* @constructor The primary constructor is internal so that it can inject [GcDetector] for tests.
*/
public class TracingWorkflowInterceptor internal constructor(
private val memoryStats: MemoryStats,
private val gcDetectorConstructor: GcDetectorConstructor,
private val loggerProvider: (
workflowScope: CoroutineScope,
workflowType: String
) -> TraceLogger
) : WorkflowInterceptor {
/**
* A [WorkflowInterceptor] that generates a trace file that can be viewed in Chrome by
* visiting `chrome://tracing`.
*
* @param loggerProvider A function that returns a [TraceLogger] that will be used to write trace
* events. The function gets the [CoroutineScope] that the workflow runtime is running in, as well
* as a description of the type of the workflow.
*/
public constructor(
memoryStats: MemoryStats = RuntimeMemoryStats,
loggerProvider: (
workflowScope: CoroutineScope,
workflowType: String
) -> TraceLogger
) : this(memoryStats, ::GcDetector, loggerProvider)
/**
* [NONE] is fine here because it will get initialized by [onRuntimeStarted] and there's no
* race conditions.
*/
private var logger: TraceLogger? = null
private var gcDetector: GcDetector? = null
private val workflowNamesById = mutableMapOf<Long, String>()
override fun onSessionStarted(
workflowScope: CoroutineScope,
session: WorkflowSession
) {
val workflowJob = workflowScope.coroutineContext[Job]!!
// Invoke this before runtime logic since cancellation handlers are invoked in the same order
// in which they were registered, and we want to emit workflow stopped before runtime stopped.
workflowJob.invokeOnCompletion {
onWorkflowStopped(session.sessionId)
}
if (session.parent == null) {
onRuntimeStarted(workflowScope, session.identifier.toLoggingName())
workflowJob.invokeOnCompletion {
onRuntimeStopped()
}
}
}
override fun <P, S> onInitialState(
props: P,
snapshot: Snapshot?,
workflowScope: CoroutineScope,
proceed: (P, Snapshot?, CoroutineScope) -> S,
session: WorkflowSession
): S {
val initialState = proceed(props, snapshot, workflowScope)
onWorkflowStarted(
workflowId = session.sessionId,
parentId = session.parent?.sessionId,
workflowType = session.identifier.toLoggingName(),
key = session.renderKey,
initialProps = props,
initialState = initialState,
restoredFromSnapshot = snapshot != null
)
return initialState
}
override fun <P, S> onPropsChanged(
old: P,
new: P,
state: S,
proceed: (P, P, S) -> S,
session: WorkflowSession
): S {
val newState = proceed(old, new, state)
if (session.parent == null) {
// Fake getting the props changed event from the runtime directly.
onPropsChanged(
workflowId = null,
oldProps = old,
newProps = new,
oldState = state,
newState = newState
)
}
onPropsChanged(
workflowId = session.sessionId,
oldProps = old,
newProps = new,
oldState = state,
newState = newState
)
return newState
}
override fun <P, S, O, R> onRender(
renderProps: P,
renderState: S,
context: BaseRenderContext<P, S, O>,
proceed: (P, S, RenderContextInterceptor<P, S, O>?) -> R,
session: WorkflowSession
): R {
if (session.parent == null) {
// Track the overall render pass for the whole tree.
onBeforeRenderPass(renderProps)
}
onBeforeWorkflowRendered(session.sessionId, renderProps, renderState)
val rendering = proceed(renderProps, renderState, TracingContextInterceptor(session))
onAfterWorkflowRendered(session.sessionId, rendering)
if (session.parent == null) {
onAfterRenderPass(rendering)
}
return rendering
}
override fun <S> onSnapshotState(
state: S,
proceed: (S) -> Snapshot?,
session: WorkflowSession
): Snapshot? {
if (session.parent == null) {
onBeforeSnapshotPass()
}
val snapshot = proceed(state)
if (session.parent == null) {
onAfterSnapshotPass()
}
return snapshot
}
private fun onRuntimeStarted(
workflowScope: CoroutineScope,
rootWorkflowType: String
) {
logger = loggerProvider(workflowScope, rootWorkflowType)
// Log garbage collections in case they correlate with unusually long render times.
gcDetector = gcDetectorConstructor {
logger?.log(
listOf(
Instant(
name = "GC detected",
scope = GLOBAL,
category = "system",
args = mapOf(
"freeMemory" to memoryStats.freeMemory(),
"totalMemory" to memoryStats.totalMemory()
)
),
createMemoryEvent()
)
)
}
}
private fun onRuntimeStopped() {
gcDetector?.stop()
}
private fun onBeforeRenderPass(props: Any?) {
logger?.log(
listOf(
DurationBegin(
name = "Render Pass",
category = "rendering",
args = mapOf("props" to props.toString())
),
createMemoryEvent()
)
)
}
private fun onAfterRenderPass(rendering: Any?) {
logger?.log(
listOf(
DurationEnd(
name = "Render Pass",
category = "rendering",
args = mapOf("rendering" to rendering.toString())
),
createMemoryEvent()
)
)
}
private fun onWorkflowStarted(
workflowId: Long,
parentId: Long?,
workflowType: String,
key: String,
initialProps: Any?,
initialState: Any?,
restoredFromSnapshot: Boolean
) {
val keyPart = if (key.isEmpty()) "" else ":$key"
val name = "$workflowType$keyPart (${workflowId.toHex()})"
workflowNamesById[workflowId] = name
logger?.log(
listOf(
AsyncDurationBegin(
id = "workflow",
name = name,
category = "workflow",
args = mapOf(
"workflowId" to workflowId.toHex(),
"initialProps" to initialProps.toString(),
"initialState" to initialState.toString(),
"restoredFromSnapshot" to restoredFromSnapshot,
"parent" to workflowNamesById[parentId]
)
),
ObjectCreated(
id = workflowId,
objectType = name
)
)
)
}
private fun onWorkflowStopped(workflowId: Long) {
val name = workflowNamesById.getValue(workflowId)
logger?.log(
listOf(
AsyncDurationEnd(
id = "workflow",
name = name,
category = "workflow"
),
ObjectDestroyed(
id = workflowId,
objectType = name
)
)
)
workflowNamesById -= workflowId
}
private fun onBeforeWorkflowRendered(
workflowId: Long,
props: Any?,
state: Any?
) {
val name = workflowNamesById.getValue(workflowId)
logger?.log(
DurationBegin(
name,
args = mapOf(
"workflowId" to workflowId.toHex(),
"props" to props.toString(),
"state" to state.toString()
),
category = "rendering"
)
)
}
private fun onAfterWorkflowRendered(
workflowId: Long,
rendering: Any?
) {
val name = workflowNamesById.getValue(workflowId)
logger?.log(
DurationEnd(
name,
args = mapOf("rendering" to rendering.toString()),
category = "rendering"
)
)
}
private fun onBeforeSnapshotPass() {
logger?.log(DurationBegin(name = "Snapshot"))
}
private fun onAfterSnapshotPass() {
logger?.log(DurationEnd(name = "Snapshot"))
}
private fun onSinkReceived(
workflowId: Long,
action: WorkflowAction<*, *, *>
) {
val name = workflowNamesById.getValue(workflowId)
logger?.log(
Instant(
name = "Sink received: $name",
category = "update",
args = mapOf("action" to action.toString())
)
)
}
private fun onPropsChanged(
workflowId: Long?,
oldProps: Any?,
newProps: Any?,
oldState: Any?,
newState: Any?
) {
val name = workflowNamesById[workflowId] ?: "{root}"
logger?.log(
Instant(
name = "Props changed: $name",
args = mapOf(
"oldProps" to oldProps.toString(),
"newProps" to if (oldProps == newProps) "{no change}" else newProps.toString(),
"oldState" to oldState.toString(),
"newState" to if (oldState == newState) "{no change}" else newState.toString()
)
)
)
}
private fun onWorkflowAction(
workflowId: Long,
action: WorkflowAction<*, *, *>,
oldState: Any?,
newState: Any?,
output: ActionApplied<Any?>?
) {
val name = workflowNamesById.getValue(workflowId)
logger?.log(
listOf(
Instant(
name = "WorkflowAction: $name",
category = "update",
scope = PROCESS,
args = mapOf(
"action" to action.toString(),
"oldState" to oldState.toString(),
"newState" to if (oldState == newState) "{no change}" else newState.toString(),
"output" to (output?.let { it.output?.value.toString() } ?: "{no output}")
)
),
ObjectSnapshot(
id = workflowId,
objectType = name,
snapshot = newState.toString()
)
)
)
}
private fun createMemoryEvent(): Counter {
val freeMemory = memoryStats.freeMemory()
val usedMemory = memoryStats.totalMemory() - freeMemory
return Counter(
name = "used/free memory",
series = mapOf(
// This map is ordered. The stacked chart is shown in reverse order so it looks like a
// typical memory usage graph.
"usedMemory" to usedMemory,
"freeMemory" to freeMemory
)
)
}
private inner class TracingContextInterceptor<P, S, O>(
private val session: WorkflowSession
) : RenderContextInterceptor<P, S, O> {
override fun onActionSent(
action: WorkflowAction<P, S, O>,
proceed: (WorkflowAction<P, S, O>) -> Unit
) {
onSinkReceived(session.sessionId, action)
val wrapperAction = TracingAction(action, session)
proceed(wrapperAction)
}
}
private inner class TracingAction<P, S, O>(
private val delegate: WorkflowAction<P, S, O>,
private val session: WorkflowSession
) : WorkflowAction<P, S, O>() {
override fun Updater.apply() {
val oldState = state
val (newState, output) = delegate.applyTo(props, state)
state = newState
output.output?.let { setOutput(it.value) }
onWorkflowAction(
workflowId = session.sessionId,
action = delegate,
oldState = oldState,
newState = newState,
output = output
)
}
}
}
private fun WorkflowIdentifier.toLoggingName(): String {
val type = getRealIdentifierType()
return when {
type is Snapshottable && type.kClass != null -> type.kClass!!.toLoggingName()
type is Unsnapshottable -> type.kType.toLoggingName()
else -> type.typeName
}
}
private fun KType.toLoggingName(): String {
if (classifier == null) return toString()
val classifierName = when (val c = classifier) {
is KClass<*> -> c.toLoggingName()
else -> toString()
}
val params = arguments.map { projection ->
when (val type = projection.type) {
is KType -> type.toLoggingName()
else -> "*"
}
}
return if (params.isEmpty()) classifierName else "$classifierName<${params.joinToString(", ")}>"
}
private fun KClass<*>.toLoggingName(): String {
return simpleName ?: toString()
}
@Suppress("NOTHING_TO_INLINE")
private inline fun Long.toHex() = toString(16)