-
Notifications
You must be signed in to change notification settings - Fork 221
/
Nimbus.swift
528 lines (430 loc) · 16.2 KB
/
Nimbus.swift
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
/* 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/. */
import Foundation
import Glean
public class Nimbus: NimbusInterface {
private let _userDefaults: UserDefaults?
private let nimbusClient: NimbusClientProtocol
private let resourceBundles: [Bundle]
private let errorReporter: NimbusErrorReporter
lazy var fetchQueue: OperationQueue = {
var queue = OperationQueue()
queue.name = "Nimbus fetch queue"
queue.maxConcurrentOperationCount = 1
return queue
}()
lazy var dbQueue: OperationQueue = {
var queue = OperationQueue()
queue.name = "Nimbus database queue"
queue.maxConcurrentOperationCount = 1
return queue
}()
init(nimbusClient: NimbusClientProtocol,
resourceBundles: [Bundle],
userDefaults: UserDefaults?,
errorReporter: @escaping NimbusErrorReporter)
{
self.errorReporter = errorReporter
self.nimbusClient = nimbusClient
self.resourceBundles = resourceBundles
_userDefaults = userDefaults
NilVariables.instance.set(bundles: resourceBundles)
}
}
private extension Nimbus {
func catchAll<T>(_ thunk: () throws -> T?) -> T? {
do {
return try thunk()
} catch NimbusError.DatabaseNotReady {
return nil
} catch {
errorReporter(error)
return nil
}
}
func catchAll(_ queue: OperationQueue, thunk: @escaping (Operation) throws -> Void) -> Operation {
let op = BlockOperation()
op.addExecutionBlock {
self.catchAll {
try thunk(op)
}
}
queue.addOperation(op)
return op
}
}
extension Nimbus: NimbusQueues {
public func waitForFetchQueue() {
fetchQueue.waitUntilAllOperationsAreFinished()
}
public func waitForDbQueue() {
dbQueue.waitUntilAllOperationsAreFinished()
}
}
extension Nimbus: NimbusEventStore {
public var events: NimbusEventStore {
self
}
public func recordEvent(_ eventId: String) {
recordEvent(1, eventId)
}
public func recordEvent(_ count: Int, _ eventId: String) {
_ = catchAll(dbQueue) { _ in
try self.nimbusClient.recordEvent(eventId: eventId, count: Int64(count))
}
}
public func recordPastEvent(_ count: Int, _ eventId: String, _ timeAgo: TimeInterval) throws {
try nimbusClient.recordPastEvent(eventId: eventId, secondsAgo: Int64(timeAgo), count: Int64(count))
}
public func advanceEventTime(by duration: TimeInterval) throws {
try nimbusClient.advanceEventTime(bySeconds: Int64(duration))
}
public func clearEvents() {
_ = catchAll(dbQueue) { _ in
try self.nimbusClient.clearEvents()
}
}
}
extension Nimbus: FeaturesInterface {
public var userDefaults: UserDefaults? {
_userDefaults
}
public func recordExposureEvent(featureId: String, experimentSlug: String? = nil) {
catchAll {
nimbusClient.recordFeatureExposure(featureId: featureId, slug: experimentSlug)
}
}
public func recordMalformedConfiguration(featureId: String, with partId: String) {
catchAll {
nimbusClient.recordMalformedFeatureConfig(featureId: featureId, partId: partId)
}
}
func postEnrollmentCalculation(_ events: [EnrollmentChangeEvent]) {
// We need to update the experiment enrollment annotations in Glean
// regardless of whether we recieved any events. Calling the
// `setExperimentActive` function multiple times with the same
// experiment id is safe so nothing bad should happen in case we do.
let experiments = getActiveExperiments()
recordExperimentTelemetry(experiments)
// Record enrollment change events, if any
recordExperimentEvents(events)
// Inform any listeners that we're done here.
notifyOnExperimentsApplied(experiments)
}
func recordExperimentTelemetry(_ experiments: [EnrolledExperiment]) {
for experiment in experiments {
Glean.shared.setExperimentActive(
experiment.slug,
branch: experiment.branchSlug,
extra: nil
)
}
}
func recordExperimentEvents(_ events: [EnrollmentChangeEvent]) {
for event in events {
switch event.change {
case .enrollment:
GleanMetrics.NimbusEvents.enrollment.record(GleanMetrics.NimbusEvents.EnrollmentExtra(
branch: event.branchSlug,
experiment: event.experimentSlug
))
case .disqualification:
GleanMetrics.NimbusEvents.disqualification.record(GleanMetrics.NimbusEvents.DisqualificationExtra(
branch: event.branchSlug,
experiment: event.experimentSlug
))
case .unenrollment:
GleanMetrics.NimbusEvents.unenrollment.record(GleanMetrics.NimbusEvents.UnenrollmentExtra(
branch: event.branchSlug,
experiment: event.experimentSlug
))
case .enrollFailed:
GleanMetrics.NimbusEvents.enrollFailed.record(GleanMetrics.NimbusEvents.EnrollFailedExtra(
branch: event.branchSlug,
experiment: event.experimentSlug,
reason: event.reason
))
case .unenrollFailed:
GleanMetrics.NimbusEvents.unenrollFailed.record(GleanMetrics.NimbusEvents.UnenrollFailedExtra(
experiment: event.experimentSlug,
reason: event.reason
))
}
}
}
func getFeatureConfigVariablesJson(featureId: String) -> [String: Any]? {
do {
guard let string = try nimbusClient.getFeatureConfigVariables(featureId: featureId) else {
return nil
}
return try Dictionary.parse(jsonString: string)
} catch NimbusError.DatabaseNotReady {
GleanMetrics.NimbusHealth.cacheNotReadyForFeature.record(
GleanMetrics.NimbusHealth.CacheNotReadyForFeatureExtra(
featureId: featureId
)
)
return nil
} catch {
errorReporter(error)
return nil
}
}
public func getVariables(featureId: String, sendExposureEvent: Bool) -> Variables {
guard let json = getFeatureConfigVariablesJson(featureId: featureId) else {
return NilVariables.instance
}
if sendExposureEvent {
recordExposureEvent(featureId: featureId)
}
return JSONVariables(with: json, in: resourceBundles)
}
}
private extension Nimbus {
func notifyOnExperimentsFetched() {
NotificationCenter.default.post(name: .nimbusExperimentsFetched, object: nil)
}
func notifyOnExperimentsApplied(_ experiments: [EnrolledExperiment]) {
NotificationCenter.default.post(name: .nimbusExperimentsApplied, object: experiments)
}
}
/*
* Methods split out onto a separate internal extension for testing purposes.
*/
extension Nimbus {
func setGlobalUserParticipationOnThisThread(_ value: Bool) throws {
let changes = try nimbusClient.setGlobalUserParticipation(optIn: value)
postEnrollmentCalculation(changes)
}
func initializeOnThisThread() throws {
try nimbusClient.initialize()
}
func fetchExperimentsOnThisThread() throws {
try GleanMetrics.NimbusHealth.fetchExperimentsTime.measure {
try nimbusClient.fetchExperiments()
}
notifyOnExperimentsFetched()
}
func applyPendingExperimentsOnThisThread() throws {
let changes = try GleanMetrics.NimbusHealth.applyPendingExperimentsTime.measure {
try nimbusClient.applyPendingExperiments()
}
postEnrollmentCalculation(changes)
}
func setExperimentsLocallyOnThisThread(_ experimentsJson: String) throws {
try nimbusClient.setExperimentsLocally(experimentsJson: experimentsJson)
}
func optOutOnThisThread(_ experimentId: String) throws {
let changes = try nimbusClient.optOut(experimentSlug: experimentId)
postEnrollmentCalculation(changes)
}
func optInOnThisThread(_ experimentId: String, branch: String) throws {
let changes = try nimbusClient.optInWithBranch(experimentSlug: experimentId, branch: branch)
postEnrollmentCalculation(changes)
}
func resetTelemetryIdentifiersOnThisThread(_ identifiers: AvailableRandomizationUnits) throws {
let changes = try nimbusClient.resetTelemetryIdentifiers(newRandomizationUnits: identifiers)
postEnrollmentCalculation(changes)
}
}
extension Nimbus: NimbusUserConfiguration {
public var globalUserParticipation: Bool {
get {
catchAll { try nimbusClient.getGlobalUserParticipation() } ?? false
}
set {
_ = catchAll(dbQueue) { _ in
try self.setGlobalUserParticipationOnThisThread(newValue)
}
}
}
public func getActiveExperiments() -> [EnrolledExperiment] {
return catchAll {
try nimbusClient.getActiveExperiments()
} ?? []
}
public func getAvailableExperiments() -> [AvailableExperiment] {
return catchAll {
try nimbusClient.getAvailableExperiments()
} ?? []
}
public func getExperimentBranches(_ experimentId: String) -> [Branch]? {
return catchAll {
try nimbusClient.getExperimentBranches(experimentSlug: experimentId)
}
}
public func optOut(_ experimentId: String) {
_ = catchAll(dbQueue) { _ in
try self.optOutOnThisThread(experimentId)
}
}
public func optIn(_ experimentId: String, branch: String) {
_ = catchAll(dbQueue) { _ in
try self.optInOnThisThread(experimentId, branch: branch)
}
}
public func resetTelemetryIdentifiers() {
_ = catchAll(dbQueue) { _ in
// The "dummy" field here is required for obscure reasons when generating code on desktop,
// so we just automatically set it to a dummy value.
let aru = AvailableRandomizationUnits(clientId: nil, userId: nil, nimbusId: nil, dummy: 0)
try self.resetTelemetryIdentifiersOnThisThread(aru)
}
}
}
extension Nimbus: NimbusStartup {
public func initialize() {
_ = catchAll(dbQueue) { _ in
try self.initializeOnThisThread()
}
}
public func fetchExperiments() {
_ = catchAll(fetchQueue) { _ in
try self.fetchExperimentsOnThisThread()
}
}
public func setFetchEnabled(_ enabled: Bool) {
_ = catchAll(fetchQueue) { _ in
try self.nimbusClient.setFetchEnabled(flag: enabled)
}
}
public func isFetchEnabled() -> Bool {
return catchAll {
try self.nimbusClient.isFetchEnabled()
} ?? true
}
public func applyPendingExperiments() -> Operation {
catchAll(dbQueue) { _ in
try self.applyPendingExperimentsOnThisThread()
}
}
public func applyLocalExperiments(fileURL: URL) -> Operation {
applyLocalExperiments(getString: { try String(contentsOf: fileURL) })
}
func applyLocalExperiments(getString: @escaping () throws -> String) -> Operation {
catchAll(dbQueue) { op in
let json = try getString()
if op.isCancelled {
try self.initializeOnThisThread()
} else {
try self.setExperimentsLocallyOnThisThread(json)
try self.applyPendingExperimentsOnThisThread()
}
}
}
public func setExperimentsLocally(_ fileURL: URL) {
_ = catchAll(dbQueue) { _ in
let json = try String(contentsOf: fileURL)
try self.setExperimentsLocallyOnThisThread(json)
}
}
public func setExperimentsLocally(_ experimentsJson: String) {
_ = catchAll(dbQueue) { _ in
try self.setExperimentsLocallyOnThisThread(experimentsJson)
}
}
public func resetEnrollmentsDatabase() -> Operation {
catchAll(dbQueue) { _ in
try self.nimbusClient.resetEnrollments()
}
}
public func dumpStateToLog() {
catchAll {
try self.nimbusClient.dumpStateToLog()
}
}
}
extension Nimbus: NimbusBranchInterface {
public func getExperimentBranch(experimentId: String) -> String? {
return catchAll {
try nimbusClient.getExperimentBranch(id: experimentId)
}
}
}
extension Nimbus: NimbusMessagingProtocol {
public func createMessageHelper() throws -> NimbusMessagingHelperProtocol {
return try createMessageHelper(string: nil)
}
public func createMessageHelper(additionalContext: [String: Any]) throws -> NimbusMessagingHelperProtocol {
let string = try additionalContext.stringify()
return try createMessageHelper(string: string)
}
public func createMessageHelper<T: Encodable>(additionalContext: T) throws -> NimbusMessagingHelperProtocol {
let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
let data = try encoder.encode(additionalContext)
let string = String(data: data, encoding: .utf8)!
return try createMessageHelper(string: string)
}
private func createMessageHelper(string: String?) throws -> NimbusMessagingHelperProtocol {
let targetingHelper = try nimbusClient.createTargetingHelper(additionalContext: string)
let stringHelper = try nimbusClient.createStringHelper(additionalContext: string)
return NimbusMessagingHelper(targetingHelper: targetingHelper, stringHelper: stringHelper)
}
}
public class NimbusDisabled: NimbusApi {
public static let shared = NimbusDisabled()
public var globalUserParticipation: Bool = false
}
public extension NimbusDisabled {
func getActiveExperiments() -> [EnrolledExperiment] {
return []
}
func getAvailableExperiments() -> [AvailableExperiment] {
return []
}
func getExperimentBranch(experimentId _: String) -> String? {
return nil
}
func getVariables(featureId _: String, sendExposureEvent _: Bool) -> Variables {
return NilVariables.instance
}
func initialize() {}
func fetchExperiments() {}
func setFetchEnabled(_: Bool) {}
func isFetchEnabled() -> Bool {
false
}
func applyPendingExperiments() -> Operation {
BlockOperation()
}
func applyLocalExperiments(fileURL _: URL) -> Operation {
BlockOperation()
}
func setExperimentsLocally(_: URL) {}
func setExperimentsLocally(_: String) {}
func resetEnrollmentsDatabase() -> Operation {
BlockOperation()
}
func optOut(_: String) {}
func optIn(_: String, branch _: String) {}
func resetTelemetryIdentifiers() {}
func recordExposureEvent(featureId _: String, experimentSlug _: String? = nil) {}
func recordMalformedConfiguration(featureId _: String, with _: String) {}
func recordEvent(_: Int, _: String) {}
func recordEvent(_: String) {}
func recordPastEvent(_: Int, _: String, _: TimeInterval) {}
func advanceEventTime(by _: TimeInterval) throws {}
func clearEvents() {}
func dumpStateToLog() {}
func getExperimentBranches(_: String) -> [Branch]? {
return nil
}
func waitForFetchQueue() {}
func waitForDbQueue() {}
}
extension NimbusDisabled: NimbusMessagingProtocol {
public func createMessageHelper() throws -> NimbusMessagingHelperProtocol {
NimbusMessagingHelper(
targetingHelper: AlwaysConstantTargetingHelper(),
stringHelper: EchoStringHelper()
)
}
public func createMessageHelper(additionalContext _: [String: Any]) throws -> NimbusMessagingHelperProtocol {
try createMessageHelper()
}
public func createMessageHelper<T: Encodable>(additionalContext _: T) throws -> NimbusMessagingHelperProtocol {
try createMessageHelper()
}
}