1 /*
<lambda>null2  * Copyright (C) 2023 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 
17 package com.android.intentresolver.measurements
18 
19 import android.os.SystemClock
20 import android.os.Trace
21 import android.os.UserHandle
22 import android.util.SparseArray
23 import androidx.annotation.GuardedBy
24 import java.util.concurrent.atomic.AtomicInteger
25 import java.util.concurrent.atomic.AtomicLong
26 
27 private const val SECTION_LAUNCH_TO_SHORTCUT = "launch-to-shortcut"
28 private const val SECTION_APP_PREDICTOR_PREFIX = "app-predictor-"
29 private const val SECTION_APP_TARGET_PREFIX = "app-target-"
30 
31 object Tracer {
32     private val launchToFirstShortcut = AtomicLong(-1L)
33     private val nextId = AtomicInteger(0)
34     @GuardedBy("self") private val profileRecords = SparseArray<ProfileRecord>()
35 
36     fun markLaunched() {
37         if (launchToFirstShortcut.compareAndSet(-1, elapsedTimeNow())) {
38             Trace.beginAsyncSection(SECTION_LAUNCH_TO_SHORTCUT, 1)
39         }
40     }
41 
42     fun endLaunchToShortcutTrace(): Long {
43         val time = elapsedTimeNow()
44         val startTime = launchToFirstShortcut.get()
45         return if (startTime >= 0 && launchToFirstShortcut.compareAndSet(startTime, -1L)) {
46             Trace.endAsyncSection(SECTION_LAUNCH_TO_SHORTCUT, 1)
47             time - startTime
48         } else {
49             -1L
50         }
51     }
52 
53     /**
54      * Begin shortcuts request tracing. The logic is based on an assumption that each request for
55      * shortcuts update is followed by at least one response. Note, that it is not always measure
56      * the request duration correctly as in the case of a two overlapping requests when the second
57      * requests starts and ends while the first is running, the end of the second request will be
58      * attributed to the first. This is tolerable as this still represents the visible to the user
59      * app's behavior and expected to be quite rare.
60      */
61     fun beginAppPredictorQueryTrace(userHandle: UserHandle) {
62         val queue = getUserShortcutRequestQueue(userHandle, createIfMissing = true) ?: return
63         val startTime = elapsedTimeNow()
64         val id = nextId.getAndIncrement()
65         val sectionName = userHandle.toAppPredictorSectionName()
66         synchronized(queue) {
67             Trace.beginAsyncSection(sectionName, id)
68             queue.addFirst(longArrayOf(startTime, id.toLong()))
69         }
70     }
71 
72     /**
73      * End shortcut request tracing, see [beginAppPredictorQueryTrace].
74      *
75      * @return request duration is milliseconds.
76      */
77     fun endAppPredictorQueryTrace(userHandle: UserHandle): Long {
78         val queue = getUserShortcutRequestQueue(userHandle, createIfMissing = false) ?: return -1L
79         val endTime = elapsedTimeNow()
80         val sectionName = userHandle.toAppPredictorSectionName()
81         return synchronized(queue) { queue.removeLastOrNull() }
82             ?.let { record ->
83                 Trace.endAsyncSection(sectionName, record[1].toInt())
84                 endTime - record[0]
85             }
86             ?: -1L
87     }
88 
89     /**
90      * Trace app target loading section per profile. If there's already an active section, it will
91      * be ended an a new section started.
92      */
93     fun beginAppTargetLoadingSection(userHandle: UserHandle) {
94         val profile = getProfileRecord(userHandle, createIfMissing = true) ?: return
95         val sectionName = userHandle.toAppTargetSectionName()
96         val time = elapsedTimeNow()
97         synchronized(profile) {
98             if (profile.appTargetLoading >= 0) {
99                 Trace.endAsyncSection(sectionName, 0)
100             }
101             profile.appTargetLoading = time
102             Trace.beginAsyncSection(sectionName, 0)
103         }
104     }
105 
106     fun endAppTargetLoadingSection(userHandle: UserHandle): Long {
107         val profile = getProfileRecord(userHandle, createIfMissing = false) ?: return -1L
108         val time = elapsedTimeNow()
109         val sectionName = userHandle.toAppTargetSectionName()
110         return synchronized(profile) {
111             if (profile.appTargetLoading >= 0) {
112                 Trace.endAsyncSection(sectionName, 0)
113                 (time - profile.appTargetLoading).also { profile.appTargetLoading = -1L }
114             } else {
115                 -1L
116             }
117         }
118     }
119 
120     private fun getUserShortcutRequestQueue(
121         userHandle: UserHandle,
122         createIfMissing: Boolean
123     ): ArrayDeque<LongArray>? = getProfileRecord(userHandle, createIfMissing)?.appPredictorRequests
124 
125     private fun getProfileRecord(userHandle: UserHandle, createIfMissing: Boolean): ProfileRecord? =
126         synchronized(profileRecords) {
127             val idx = profileRecords.indexOfKey(userHandle.identifier)
128             when {
129                 idx >= 0 -> profileRecords.valueAt(idx)
130                 createIfMissing ->
131                     ProfileRecord().also { profileRecords.put(userHandle.identifier, it) }
132                 else -> null
133             }
134         }
135 
136     private fun elapsedTimeNow() = SystemClock.elapsedRealtime()
137 }
138 
139 private class ProfileRecord {
140     val appPredictorRequests = ArrayDeque<LongArray>()
141     @GuardedBy("this") var appTargetLoading = -1L
142 }
143 
UserHandlenull144 private fun UserHandle.toAppPredictorSectionName() = SECTION_APP_PREDICTOR_PREFIX + identifier
145 
146 private fun UserHandle.toAppTargetSectionName() = SECTION_APP_TARGET_PREFIX + identifier
147 
148 inline fun <R> runTracing(name: String, block: () -> R): R {
149     Trace.beginSection(name)
150     try {
151         return block()
152     } finally {
153         Trace.endSection()
154     }
155 }
156