summaryrefslogtreecommitdiff
path: root/directaccess/src/com/google/gct/directaccess/provisioner/DirectAccessDeviceTemplate.kt
blob: 7aeb00d186a30e1567c9dafaea616fa74d7ba63c (plain)
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
/*
 * Copyright (C) 2023 The Android Open Source Project
 *
 * 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.
 */
package com.google.gct.directaccess.provisioner

import com.android.sdklib.AndroidVersion
import com.android.sdklib.deviceprovisioner.DeviceAction
import com.android.sdklib.deviceprovisioner.DeviceActionDisabledException
import com.android.sdklib.deviceprovisioner.DeviceActionException
import com.android.sdklib.deviceprovisioner.DeviceError
import com.android.sdklib.deviceprovisioner.DeviceHandle
import com.android.sdklib.deviceprovisioner.DeviceId
import com.android.sdklib.deviceprovisioner.DeviceState
import com.android.sdklib.deviceprovisioner.DeviceTemplate
import com.android.sdklib.deviceprovisioner.Resolution
import com.android.sdklib.deviceprovisioner.TemplateActivationAction
import com.android.sdklib.deviceprovisioner.TemplateState
import com.android.tools.adbbridge.Reservation
import com.android.tools.idea.concurrency.AndroidDispatchers
import com.android.tools.idea.concurrency.createChildScope
import com.android.tools.idea.devicemanager.DeviceType
import com.google.gct.directaccess.analytics.DirectAccessUsageTracker
import com.google.gct.directaccess.directAccessCloudProjectManager
import com.google.services.firebase.directaccess.client.findOrCreateReservation
import com.google.services.firebase.directaccess.client.waitUntilActive
import com.google.wireless.android.sdk.stats.DirectAccessUsageEvent.FailureReason
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import icons.StudioIcons
import java.time.Duration
import javax.swing.Icon
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

val SHORT_AWAITING_RESERVATION_READY_TIME_LIMIT: Duration = Duration.ofMinutes(1)
val LONG_AWAITING_RESERVATION_READY_TIME_LIMIT: Duration = Duration.ofMinutes(15)

class DirectAccessDeviceTemplate(
  private val project: Project,
  private val deviceInfoFlow: StateFlow<DeviceInfo>,
  private val devices: MutableStateFlow<List<DeviceHandle>>,
  private val scope: CoroutineScope,
  private val isAuthenticatorReady: Flow<Boolean>,
) : DeviceTemplate {
  val deviceInfo: DeviceInfo
    get() = deviceInfoFlow.value

  override val id = DeviceId(PLUGIN_ID, true, "model_id=${deviceInfo.key}")

  override val properties = deviceInfo.toDeviceProperties()

  override val stateFlow =
    isAuthenticatorReady
      .combine(deviceInfoFlow) { isReady, deviceInfo ->
        val waitTimeText =
          deviceInfo.deviceAvailabilityEstimateSeconds?.let { waitTimeText(it, "min") }

        TemplateState(
          if (isReady && waitTimeText != null)
            DirectAccessDeviceError(DeviceError.Severity.WARNING, "$waitTimeText")
          else null
        )
      }
      .stateIn(scope, SharingStarted.Eagerly, TemplateState(null))

  private val isActivationStarted = MutableStateFlow(false)

  /** Icon to show for the template and handle */
  val icon: Icon
    get() = properties.icon

  /**
   * Last device handle activated by the template.
   *
   * TODO (b/246171065): resolve potential race condition to support activating multiple devices
   */
  var activeDevice: DirectAccessDeviceHandle? = null
    private set(device) {
      field?.let {
        devices.update { list -> list - it }
        it.scope.cancel()
        isActivationStarted.value = false
      }
      field = device
      if (device != null) {
        devices.update { list -> list + device }
        device.scope.launch {
          device.stateFlow.collect {
            if (it.reservation?.state?.isClosed() == true) {
              field = null
              isActivationStarted.value = false
              devices.update { list -> list - device }
              device.scope.cancel()
            }
          }
        }
      }
    }

  override val activationAction: TemplateActivationAction =
    object : TemplateActivationAction {
      // TODO: Pass duration through to the DirectAccessConnectionManager.
      override val durationUsed = false

      /**
       * Creates a [DirectAccessDeviceHandle] and starts a connection to it.
       *
       * The returned device handle prioritizes connecting to an existing reservation over
       * requesting a new one. This method is disabled when a device handle is active or being
       * created. At most one device is available for each template.
       *
       * TODO (b/246171065): activating multiple devices.
       */
      override suspend fun activate(duration: Duration?): DeviceHandle {
        // Disable further activate actions to avoid multiple devices.
        if (!isActivationStarted.compareAndSet(expect = false, update = true)) {
          throw DeviceActionDisabledException(this)
        }
        confirmWaitingTime()

        val reservationName =
          try {
            findOrCreateReservation()
          } catch (e: CancellationException) {
            throw e
          } catch (e: Exception) {
            isActivationStarted.value = false
            if (e.localizedMessage.contains("RESOURCE_EXHAUSTED")) {
              throw DeviceActionException(
                "All Spark plan minutes for the current period have been used. " +
                  "Upgrade to a Blaze plan to immediately continue using this service.",
                e,
              )
            }
            throw DeviceActionException("Failed to reserve a device. Please try again.", e)
          }

        try {
          return createDeviceHandle(reservationName).also { it.activationAction?.activate() }
        } catch (e: CancellationException) {
          isActivationStarted.value = false
          throw e
        } catch (e: DeviceActionException) {
          isActivationStarted.value = false
          // Re-throw exception to propagate the message present in the exception
          throw e
        } catch (e: Exception) {
          isActivationStarted.value = false
          throw DeviceActionException("Failed to connect to device. Please try again.", e)
        }
      }

      private suspend fun confirmWaitingTime() {
        deviceInfo.deviceAvailabilityEstimateSeconds
          ?.let { seconds -> waitTimeText(seconds, "minutes") }
          ?.let { waitingTimeText ->
            val title = "Reserve ${properties.title}"
            val message =
              "The ${properties.title} will be available in $waitingTimeText.\n" +
                "You will not be billed for this duration."
            val result =
              withContext(AndroidDispatchers.uiThread) {
                Messages.showOkCancelDialog(
                  message,
                  title,
                  "Reserve",
                  "Cancel",
                  Messages.getQuestionIcon(),
                )
              }
            if (result != Messages.OK) {
              isActivationStarted.value = false
              throw CancellationException("Device reservation cancelled.")
            }
          }
      }

      private fun findOrCreateReservation(): String {
        val reservationManager =
          project.directAccessCloudProjectManager?.reservationManager
            ?: throw RuntimeException("Unable to access ReservationManager.")

        val (reservationName, startTime) =
          try {
            reservationManager.findOrCreateReservation(
              deviceInfo.codename,
              deviceInfo.api.toString(),
            )
          } catch (e: Exception) {
            // TODO(b/277240160): Add correct failure reason
            trackReserveDevice(false, failureReason = FailureReason.UNKNOWN_FAILURE)
            throw e
          }
        if (startTime != 0L) {
          scope.logReserveMetricWhenReservationActive(
            reservationManager.fetchReservationFlow(reservationName),
            startTime,
          )
        }
        scope.launch {
          project.directAccessCloudProjectManager?.reservationListFlowWithException?.refresh()
        }
        return reservationName
      }

      private val defaultPresentation =
        DeviceAction.Presentation("Acquire", StudioIcons.Avd.RUN, false)

      override val presentation: StateFlow<DeviceAction.Presentation> =
        isActivationStarted
          .combine(isAuthenticatorReady) { started, authenticatorReady ->
            !started && authenticatorReady
          }
          .combine(deviceInfoFlow) { enabled, deviceInfo ->
            // TODO(b/314857500): Improve user experience with null
            // deviceAvailabilityEstimateSeconds.
            val icon =
              if (
                deviceInfo.deviceAvailabilityEstimateSeconds?.let {
                  it >= SHORT_AWAITING_RESERVATION_READY_TIME_LIMIT.seconds
                } == true
              )
                StudioIcons.Avd.START_RESERVATION
              else StudioIcons.Avd.RUN
            defaultPresentation.copy(
              icon = icon,
              enabled = enabled,
              detail =
                if (enabled) null
                else "Device unavailable: click the Firebase action to address issues",
            )
          }
          .stateIn(scope, SharingStarted.Eagerly, defaultPresentation)
    }

  override val editAction = null

  /**
   * Creates a [DirectAccessDeviceHandle] with Disconnected state for [reservationName] if one is
   * not present already.
   *
   * The returned device handle prioritizes connecting to an existing reservation over requesting a
   * new one. This method is disabled when a device handle is active or being created. At most one
   * device is available for each template.
   *
   * TODO (b/246171065): activating multiple devices.
   */
  fun createDeviceHandleIfAbsent(reservationName: String): DeviceHandle? {
    if (isActivationStarted.compareAndSet(expect = false, update = true)) {
      try {
        return createDeviceHandle(reservationName)
      } catch (e: Exception) {
        isActivationStarted.value = false
        throw e
      }
    }
    return null
  }

  /**
   * Creates a [DirectAccessDeviceHandle] for the given [reservationName].
   *
   * Reservation corresponding to [reservationName] can be a new reservation requested by the user
   * that is inactive, or it can be an active reservation created elsewhere.
   */
  private fun createDeviceHandle(reservationName: String): DeviceHandle {
    val deviceScope = scope.createChildScope(isSupervisor = true)
    // Notify provisioner plugin of the new device.
    return DirectAccessDeviceHandle(
        project,
        deviceScope,
        this@DirectAccessDeviceTemplate,
        DeviceState.Disconnected(properties),
        reservationName,
      )
      .also { activeDevice = it }
  }

  init {
    scope.launch {
      isAuthenticatorReady.distinctUntilChanged().collect { isReady ->
        if (!isReady) {
          activeDevice = null
        }
      }
    }
  }

  private fun CoroutineScope.logReserveMetricWhenReservationActive(
    reservationFlow: StateFlow<Reservation>,
    reserveStartTime: Long,
  ) = launch {
    reservationFlow.waitUntilActive()
    trackReserveDevice(
      true,
      System.currentTimeMillis() - reserveStartTime,
      reservationFlow.value.name,
    )
  }

  private fun trackReserveDevice(
    wasSuccessful: Boolean,
    timeToReserve: Long? = null,
    reservationName: String? = null,
    failureReason: FailureReason? = null,
  ) {
    DirectAccessUsageTracker.getInstance()
      .trackReserveDevice(
        wasSuccessful,
        timeToReserve,
        reservationName,
        properties.deviceInfoProto,
        failureReason,
      )
  }

  private fun waitTimeText(seconds: Long, minuteSuffix: String): String? =
    "${LONG_AWAITING_RESERVATION_READY_TIME_LIMIT.toMinutes()} $minuteSuffix"
      .let { suffix ->
        when {
          seconds < SHORT_AWAITING_RESERVATION_READY_TIME_LIMIT.seconds -> null
          seconds < LONG_AWAITING_RESERVATION_READY_TIME_LIMIT.seconds -> "less than $suffix"
          else -> "more than $suffix"
        }
      }

  private data class DirectAccessDeviceError(
    override val severity: DeviceError.Severity = DeviceError.Severity.WARNING,
    override val message: String,
  ) : DeviceError
}

internal fun DeviceInfo.toDeviceProperties(connectionCount: Int = 0): DirectAccessDeviceProperties {
  val info = this
  return DirectAccessDeviceProperties.build {
    manufacturer = info.manufacturer
    model = info.name
    androidVersion = AndroidVersion(info.api)
    deviceType =
      when (info.type) {
        DeviceType.PHONE -> com.android.sdklib.deviceprovisioner.DeviceType.HANDHELD
        DeviceType.TV -> com.android.sdklib.deviceprovisioner.DeviceType.TV
        DeviceType.WEAR_OS -> com.android.sdklib.deviceprovisioner.DeviceType.WEAR
        DeviceType.AUTOMOTIVE -> com.android.sdklib.deviceprovisioner.DeviceType.AUTOMOTIVE
      }
    resolution = Resolution(info.screenX, info.screenY)
    density = info.screenDensity
    icon = info.icon
    populateDeviceInfoProto(PLUGIN_ID, null, emptyMap(), connectionCount.toString())
  }
}