-
Notifications
You must be signed in to change notification settings - Fork 221
/
Nimbus.kt
587 lines (523 loc) · 22 KB
/
Nimbus.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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
@file:Suppress("TooManyFunctions")
package org.mozilla.experiments.nimbus
import android.content.Context
import android.content.SharedPreferences
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import androidx.annotation.AnyThread
import androidx.annotation.RawRes
import androidx.annotation.VisibleForTesting
import androidx.annotation.WorkerThread
import androidx.core.content.pm.PackageInfoCompat
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import mozilla.appservices.remotesettings.RemoteSettingsConfig
import mozilla.telemetry.glean.Glean
import org.json.JSONObject
import org.mozilla.experiments.nimbus.GleanMetrics.NimbusEvents
import org.mozilla.experiments.nimbus.GleanMetrics.NimbusHealth
import org.mozilla.experiments.nimbus.internal.AppContext
import org.mozilla.experiments.nimbus.internal.AvailableExperiment
import org.mozilla.experiments.nimbus.internal.AvailableRandomizationUnits
import org.mozilla.experiments.nimbus.internal.EnrolledExperiment
import org.mozilla.experiments.nimbus.internal.EnrollmentChangeEvent
import org.mozilla.experiments.nimbus.internal.EnrollmentChangeEventType
import org.mozilla.experiments.nimbus.internal.EnrollmentStatusExtraDef
import org.mozilla.experiments.nimbus.internal.FeatureExposureExtraDef
import org.mozilla.experiments.nimbus.internal.MalformedFeatureConfigExtraDef
import org.mozilla.experiments.nimbus.internal.MetricsHandler
import org.mozilla.experiments.nimbus.internal.NimbusClient
import org.mozilla.experiments.nimbus.internal.NimbusClientInterface
import org.mozilla.experiments.nimbus.internal.NimbusException
import java.io.File
import java.io.IOException
private const val EXPERIMENT_COLLECTION_NAME = "nimbus-mobile-experiments"
private const val NIMBUS_DATA_DIR: String = "nimbus_data"
/**
* This class allows client apps to configure Nimbus to point to your own server.
* Client app developers should set up their own Nimbus infrastructure, to avoid different
* organizations running conflicting experiments or hitting servers with extra network traffic.
*/
data class NimbusServerSettings(
val url: Uri,
val collection: String = EXPERIMENT_COLLECTION_NAME,
)
/**
* A implementation of the [NimbusInterface] interface backed by the Nimbus SDK.
*/
@Suppress("LargeClass", "LongParameterList")
open class Nimbus(
override val context: Context,
override val prefs: SharedPreferences? = null,
appInfo: NimbusAppInfo,
coenrollingFeatureIds: List<String>,
server: NimbusServerSettings?,
deviceInfo: NimbusDeviceInfo,
private val observer: NimbusInterface.Observer? = null,
delegate: NimbusDelegate,
) : NimbusInterface {
// An I/O scope is used for reading or writing from the Nimbus's RKV database.
private val dbScope: CoroutineScope = delegate.dbScope
// An I/O scope is used for getting experiments from the network.
private val fetchScope: CoroutineScope = delegate.fetchScope
private val updateScope: CoroutineScope? = delegate.updateScope
private val errorReporter = delegate.errorReporter
private val logger = delegate.logger
private val metricsHandler = object : MetricsHandler {
override fun recordEnrollmentStatuses(enrollmentStatusExtras: List<EnrollmentStatusExtraDef>) {
for (extra in enrollmentStatusExtras) {
NimbusEvents.enrollmentStatus.record(
NimbusEvents.EnrollmentStatusExtra(
branch = extra.branch,
slug = extra.slug,
status = extra.status,
reason = extra.reason,
errorString = extra.errorString,
conflictSlug = extra.conflictSlug,
),
)
}
}
override fun recordFeatureActivation(event: FeatureExposureExtraDef) {
NimbusEvents.activation.record(
NimbusEvents.ActivationExtra(
experiment = event.slug,
branch = event.branch,
featureId = event.featureId,
),
)
}
override fun recordFeatureExposure(event: FeatureExposureExtraDef) {
NimbusEvents.exposure.record(
NimbusEvents.ExposureExtra(
experiment = event.slug,
branch = event.branch,
featureId = event.featureId,
),
)
}
override fun recordMalformedFeatureConfig(event: MalformedFeatureConfigExtraDef) {
NimbusEvents.malformedFeature.record(
NimbusEvents.MalformedFeatureExtra(
experiment = event.slug,
branch = event.branch,
featureId = event.featureId,
partId = event.part,
),
)
}
}
private val nimbusClient: NimbusClientInterface
override var globalUserParticipation: Boolean
get() = nimbusClient.getGlobalUserParticipation()
set(active) {
dbScope.launch {
setGlobalUserParticipationOnThisThread(active)
}
}
init {
NullVariables.instance.setContext(context)
// Set the name of the native library so that we use
// the appservices megazord for compiled code.
System.setProperty(
"uniffi.component.nimbus.libraryOverride",
System.getProperty("mozilla.appservices.megazord.library", "megazord"),
)
// Build a File object to represent the data directory for Nimbus data
val dataDir = File(context.applicationInfo.dataDir, NIMBUS_DATA_DIR)
// Build Nimbus AppContext object to pass into initialize
val experimentContext = buildExperimentContext(context, appInfo, deviceInfo)
// Initialize Nimbus
val remoteSettingsConfig = server?.let {
RemoteSettingsConfig(
serverUrl = it.url.toString(),
collectionName = it.collection,
)
}
nimbusClient = NimbusClient(
experimentContext,
coenrollingFeatureIds,
dataDir.path,
remoteSettingsConfig,
// The "dummy" field here is required for obscure reasons when generating code on desktop,
// so we just automatically set it to a dummy value.
AvailableRandomizationUnits(clientId = null, userId = null, nimbusId = null, dummy = 0),
metricsHandler,
)
}
// This is currently not available from the main thread.
// see https://jira.mozilla.com/browse/SDK-191
@WorkerThread
override fun getActiveExperiments(): List<EnrolledExperiment> = withCatchAll("getActiveExperiments") {
nimbusClient.getActiveExperiments()
} ?: emptyList()
@WorkerThread
override fun getAvailableExperiments(): List<AvailableExperiment> = withCatchAll("getAvailableExperiments") {
nimbusClient.getAvailableExperiments()
} ?: emptyList()
@AnyThread
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal fun getFeatureConfigVariablesJson(featureId: String): JSONObject? =
@Suppress("TooGenericExceptionCaught")
try {
nimbusClient.getFeatureConfigVariables(featureId)?.let { JSONObject(it) }
} catch (e: NimbusException.DatabaseNotReady) {
NimbusHealth.cacheNotReadyForFeature.record(
NimbusHealth.CacheNotReadyForFeatureExtra(
featureId = featureId,
),
)
null
} catch (e: Throwable) {
reportError("getFeatureConfigVariablesJson", e)
null
}
private fun reportError(msg: String, e: Throwable) =
@Suppress("TooGenericExceptionCaught")
try {
errorReporter("Nimbus Rust: $msg", e)
} catch (e1: Throwable) {
logger("Exception calling rust: $e")
logger("Exception reporting the exception: $e1")
}
override fun getExperimentBranch(experimentId: String): String? = withCatchAll("getExperimentBranch") {
nimbusClient.getExperimentBranch(experimentId)
}
override fun getVariables(featureId: String, recordExposureEvent: Boolean): Variables =
getFeatureConfigVariablesJson(featureId)?.let { json ->
if (recordExposureEvent) {
recordExposureEvent(featureId)
}
JSONVariables(context, json)
}
?: NullVariables.instance
@WorkerThread
override fun getExperimentBranches(experimentId: String): List<Branch>? = withCatchAll("getExperimentBranches") {
nimbusClient.getExperimentBranches(experimentId)
}
// Method and apparatus to catch any uncaught exceptions
@SuppressWarnings("TooGenericExceptionCaught")
private fun <R> withCatchAll(method: String, thunk: () -> R) =
try {
thunk()
} catch (e: NimbusException.DatabaseNotReady) {
// NOOP
null
} catch (e: Throwable) {
reportError(method, e)
null
}
@WorkerThread
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal fun initializeOnThisThread() = withCatchAll("initialize") {
nimbusClient.initialize()
postEnrolmentCalculation()
}
override fun fetchExperiments() {
fetchScope.launch {
fetchExperimentsOnThisThread()
}
}
override fun setFetchEnabled(enabled: Boolean) {
fetchScope.launch {
withCatchAll("setFetchEnabled") {
nimbusClient.setFetchEnabled(enabled)
}
}
}
override fun isFetchEnabled() = withCatchAll("isFetchEnabled") {
nimbusClient.isFetchEnabled()
} ?: true
@WorkerThread
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal fun fetchExperimentsOnThisThread() = withCatchAll("fetchExperiments") {
try {
NimbusHealth.fetchExperimentsTime.measure {
nimbusClient.fetchExperiments()
}
updateObserver {
it.onExperimentsFetched()
}
} catch (e: NimbusException.ClientException) {
errorReporter("Error fetching experiments from endpoint", e)
}
}
private fun updateObserver(updater: (NimbusInterface.Observer) -> Unit) {
val observer = observer ?: return
if (updateScope != null) {
updateScope.launch {
updater(observer)
}
} else {
updater(observer)
}
}
override fun applyPendingExperiments(): Job =
dbScope.launch {
withContext(NonCancellable) {
applyPendingExperimentsOnThisThread()
}
}
@WorkerThread
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal fun applyPendingExperimentsOnThisThread() = withCatchAll("applyPendingExperiments") {
try {
val events = NimbusHealth.applyPendingExperimentsTime.measure {
nimbusClient.applyPendingExperiments()
}
recordExperimentTelemetryEvents(events)
// Get the experiments to record in telemetry
postEnrolmentCalculation()
} catch (e: NimbusException.InvalidExperimentFormat) {
reportError("Invalid experiment format", e)
}
}
override fun applyLocalExperiments(@RawRes file: Int): Job =
applyLocalExperiments { loadRawResource(file) }
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
fun applyLocalExperiments(getString: suspend () -> String): Job =
dbScope.launch {
val payload = try {
getString()
} catch (e: CancellationException) {
// TODO consider reporting a glean event here.
logger(e.stackTraceToString())
null
} catch (e: IOException) {
logger(e.stackTraceToString())
null
}
withContext(NonCancellable) {
if (payload != null) {
setExperimentsLocallyOnThisThread(payload)
applyPendingExperimentsOnThisThread()
} else {
initializeOnThisThread()
}
}
}
@WorkerThread
private fun postEnrolmentCalculation() {
nimbusClient.getActiveExperiments().let {
recordExperimentTelemetry(it)
updateObserver { observer ->
observer.onUpdatesApplied(it)
}
}
}
override fun setExperimentsLocally(@RawRes file: Int) {
dbScope.launch {
withCatchAll("setExperimentsLocally") {
loadRawResource(file)
}?.let { payload ->
setExperimentsLocallyOnThisThread(payload)
}
}
}
private fun loadRawResource(file: Int): String =
context.resources.openRawResource(file).use {
it.bufferedReader().readText()
}
override fun setExperimentsLocally(payload: String) {
dbScope.launch {
setExperimentsLocallyOnThisThread(payload)
}
}
@WorkerThread
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal fun setExperimentsLocallyOnThisThread(payload: String) = withCatchAll("setExperimentsLocally") {
nimbusClient.setExperimentsLocally(payload)
}
override fun resetEnrollmentsDatabase() =
dbScope.launch {
withCatchAll("resetEnrollments") {
nimbusClient.resetEnrollments()
}
}
@WorkerThread
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal fun setGlobalUserParticipationOnThisThread(active: Boolean) = withCatchAll("setGlobalUserParticipation") {
val enrolmentChanges = nimbusClient.setGlobalUserParticipation(active)
if (enrolmentChanges.isNotEmpty()) {
recordExperimentTelemetryEvents(enrolmentChanges)
postEnrolmentCalculation()
}
}
override fun optOut(experimentId: String) {
dbScope.launch {
optOutOnThisThread(experimentId)
}
}
@WorkerThread
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal fun optOutOnThisThread(experimentId: String) = withCatchAll("optOut") {
nimbusClient.optOut(experimentId).also(::recordExperimentTelemetryEvents)
}
override fun resetTelemetryIdentifiers() {
// The "dummy" field here is required for obscure reasons when generating code on desktop,
// so we just automatically set it to a dummy value.
val aru = AvailableRandomizationUnits(clientId = null, userId = null, nimbusId = null, dummy = 0)
dbScope.launch {
withCatchAll("resetTelemetryIdentifiers") {
nimbusClient.resetTelemetryIdentifiers(aru).also { enrollmentChangeEvents ->
recordExperimentTelemetryEvents(enrollmentChangeEvents)
}
}
}
}
override fun optInWithBranch(experimentId: String, branch: String) {
dbScope.launch {
withCatchAll("optIn") {
nimbusClient.optInWithBranch(experimentId, branch).also(::recordExperimentTelemetryEvents)
}
}
}
override fun recordExposureEvent(featureId: String, experimentSlug: String?) {
recordExposureOnThisThread(featureId, experimentSlug)
}
override fun recordMalformedConfiguration(featureId: String, partId: String) {
recordMalformedConfigurationOnThisThread(featureId, partId)
}
@AnyThread
override fun recordEvent(count: Long, eventId: String) {
dbScope.launch {
withCatchAll("recordEvent") {
nimbusClient.recordEvent(eventId, count)
}
}
}
override fun recordPastEvent(count: Long, eventId: String, secondsAgo: Long) =
nimbusClient.recordPastEvent(eventId, secondsAgo, count)
override fun advanceEventTime(bySeconds: Long) =
nimbusClient.advanceEventTime(bySeconds)
@WorkerThread
override fun clearEvents() {
dbScope.launch {
nimbusClient.clearEvents()
}
}
@AnyThread
override fun dumpStateToLog() {
nimbusClient.dumpStateToLog()
}
override fun createMessageHelper(additionalContext: JSONObject?): GleanPlumbMessageHelper =
GleanPlumbMessageHelper(
nimbusClient.createTargetingHelper(additionalContext),
nimbusClient.createStringHelper(additionalContext),
)
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal fun recordExperimentTelemetry(experiments: List<EnrolledExperiment>) {
// Call Glean.setExperimentActive() for each active experiment.
experiments.forEach { experiment ->
// For now, we will just record the experiment id and the branch id. Once we can call
// Glean from Rust, this will move to the nimbus-sdk Rust core.
Glean.setExperimentActive(
experiment.slug,
experiment.branchSlug,
)
}
}
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal fun recordExperimentTelemetryEvents(enrollmentChangeEvents: List<EnrollmentChangeEvent>) {
enrollmentChangeEvents.forEach { event ->
when (event.change) {
EnrollmentChangeEventType.ENROLLMENT -> {
NimbusEvents.enrollment.record(
NimbusEvents.EnrollmentExtra(
experiment = event.experimentSlug,
branch = event.branchSlug,
),
)
}
EnrollmentChangeEventType.DISQUALIFICATION -> {
NimbusEvents.disqualification.record(
NimbusEvents.DisqualificationExtra(
experiment = event.experimentSlug,
branch = event.branchSlug,
),
)
}
EnrollmentChangeEventType.UNENROLLMENT -> {
NimbusEvents.unenrollment.record(
NimbusEvents.UnenrollmentExtra(
experiment = event.experimentSlug,
branch = event.branchSlug,
),
)
}
EnrollmentChangeEventType.ENROLL_FAILED -> {
NimbusEvents.enrollFailed.record(
NimbusEvents.EnrollFailedExtra(
experiment = event.experimentSlug,
branch = event.branchSlug,
reason = event.reason,
),
)
}
EnrollmentChangeEventType.UNENROLL_FAILED -> {
NimbusEvents.unenrollFailed.record(
NimbusEvents.UnenrollFailedExtra(
experiment = event.experimentSlug,
reason = event.reason,
),
)
}
}
}
}
// The exposure event should be recorded when the expected treatment (or no-treatment, such as
// for a "control" branch) is applied or shown to the user.
// If the experiment slug is known, then use that to look up the enrollment.
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
@AnyThread
internal fun recordExposureOnThisThread(featureId: String, experimentSlug: String? = null) = withCatchAll("recordFeatureExposure") {
nimbusClient.recordFeatureExposure(featureId, experimentSlug)
}
// The malformed feature event is recorded by app developers, if the configuration is
// _semantically_ invalid or malformed.
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
@AnyThread
internal fun recordMalformedConfigurationOnThisThread(featureId: String, partId: String) = withCatchAll("recordMalformedConfiguration") {
nimbusClient.recordMalformedFeatureConfig(featureId, partId)
}
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal fun buildExperimentContext(context: Context, appInfo: NimbusAppInfo, deviceInfo: NimbusDeviceInfo): AppContext {
val packageInfo: PackageInfo? = try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
context.packageManager.getPackageInfo(context.packageName, PackageManager.PackageInfoFlags.of(0))
} else {
@Suppress("DEPRECATION")
context.packageManager.getPackageInfo(context.packageName, 0)
}
} catch (e: PackageManager.NameNotFoundException) {
null
}
return AppContext(
appId = context.packageName,
appName = appInfo.appName,
channel = appInfo.channel,
androidSdkVersion = Build.VERSION.SDK_INT.toString(),
appBuild = packageInfo?.let { PackageInfoCompat.getLongVersionCode(it).toString() },
appVersion = packageInfo?.versionName,
architecture = Build.SUPPORTED_ABIS[0],
debugTag = null,
deviceManufacturer = Build.MANUFACTURER,
deviceModel = Build.MODEL,
locale = deviceInfo.localeTag,
os = "Android",
osVersion = Build.VERSION.RELEASE,
installationDate = packageInfo?.firstInstallTime,
homeDirectory = context.applicationInfo?.dataDir,
customTargetingAttributes = appInfo.customTargetingAttributes,
)
}
}