Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 4a47bec6 authored by Peter Kalauskas's avatar Peter Kalauskas
Browse files

Trace dispatcher and coroutine names

Flag: ACONFIG com.android.systemui.coroutine_tracing DISABLED
Bug: 289353932
Test: atest tracinglib-host-test tracinglib-robolectric-test
Change-Id: I4195631613fbec516943ce2bf5edd3aca54bc728
parent e36544ae
Loading
Loading
Loading
Loading
+17 −3
Original line number Diff line number Diff line
@@ -16,12 +16,20 @@

package com.android.app.tracing.coroutines

import com.android.app.tracing.instant
import com.android.app.tracing.beginSlice
import com.android.app.tracing.endSlice
import com.android.systemui.Flags.coroutineTracing
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
import kotlinx.coroutines.CopyableThreadContextElement
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineName

/**
 * If `true`, the CoroutineDispatcher and CoroutineName will be included in the trace each time the
 * coroutine context changes. This makes the trace extremely noisy, so it is off by default.
 */
private const val DEBUG_COROUTINE_CONTEXT_UPDATES = false

/**
 * Returns a new [CoroutineContext] used for tracing. Used to hide internal implementation details.
@@ -30,6 +38,12 @@ fun createCoroutineTracingContext(): CoroutineContext {
    return if (coroutineTracing()) TraceContextElement() else EmptyCoroutineContext
}

private fun CoroutineContext.nameForTrace(): String {
    val dispatcherStr = "${this[CoroutineDispatcher]}"
    val nameStr = "${this[CoroutineName]?.name}"
    return "CoroutineDispatcher: $dispatcherStr; CoroutineName: $nameStr"
}

/**
 * Used for safely persisting [TraceData] state when coroutines are suspended and resumed.
 *
@@ -50,13 +64,13 @@ internal class TraceContextElement(private val traceData: TraceData = TraceData(
        val oldState = threadLocalTrace.get()
        oldState?.endAllOnThread()
        threadLocalTrace.set(traceData)
        instant("resuming ${context[CoroutineDispatcher]}")
        if (DEBUG_COROUTINE_CONTEXT_UPDATES) beginSlice(context.nameForTrace())
        traceData.beginAllOnThread()
        return oldState
    }

    override fun restoreThreadContext(context: CoroutineContext, oldState: TraceData?) {
        instant("suspending ${context[CoroutineDispatcher]}")
        if (DEBUG_COROUTINE_CONTEXT_UPDATES) endSlice()
        traceData.endAllOnThread()
        threadLocalTrace.set(oldState)
        oldState?.beginAllOnThread()