1 /*
<lambda>null2 * Copyright (C) 2024 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package com.example.tracing.demo.experiments
17
18 import android.os.Trace
19 import com.android.app.tracing.coroutines.traceCoroutine
20 import com.android.app.tracing.traceSection
21 import com.example.tracing.demo.delayHandler
22 import kotlin.coroutines.Continuation
23 import kotlin.coroutines.resume
24 import kotlin.random.Random
25 import kotlinx.coroutines.delay
26 import kotlinx.coroutines.suspendCancellableCoroutine
27
28 private class DelayedContinuationRunner(
29 private val continuation: Continuation<Unit>,
30 private val traceName: String,
31 private val cookie: Int,
32 ) : Runnable {
33 override fun run() {
34 Trace.asyncTraceForTrackEnd(Trace.TRACE_TAG_APP, TRACK_NAME, cookie)
35 Trace.traceBegin(Trace.TRACE_TAG_APP, "resume after $traceName")
36 try {
37 continuation.resume(Unit)
38 } finally {
39 Trace.traceEnd(Trace.TRACE_TAG_APP)
40 }
41 }
42 }
43
44 /** Like [delay], but naively implemented so that it always suspends. */
forceSuspendnull45 suspend fun forceSuspend(traceName: String? = null, timeMillis: Long) {
46 val traceMessage = "delay($timeMillis)${traceName?.let { " [$it]" } ?: ""}"
47 val cookie = Random.nextInt()
48 Trace.asyncTraceForTrackBegin(Trace.TRACE_TAG_APP, TRACK_NAME, traceMessage, cookie)
49 traceCoroutine(traceMessage) {
50 suspendCancellableCoroutine { continuation ->
51 traceSection("scheduling DelayedContinuationRunner for $traceName") {
52 val delayedRunnable = DelayedContinuationRunner(continuation, traceMessage, cookie)
53 if (delayHandler.postDelayed(delayedRunnable, timeMillis)) {
54 continuation.invokeOnCancellation { cause ->
55 Trace.instant(
56 Trace.TRACE_TAG_APP,
57 "$traceMessage, cancelled due to ${cause?.javaClass}",
58 )
59 delayHandler.removeCallbacks(delayedRunnable)
60 Trace.asyncTraceForTrackEnd(Trace.TRACE_TAG_APP, TRACK_NAME, cookie)
61 }
62 }
63 }
64 }
65 }
66 }
67
68 const val TRACK_NAME = "async-trace-events"
69