-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathDefaultDecisionService.swift
More file actions
734 lines (623 loc) · 33.8 KB
/
DefaultDecisionService.swift
File metadata and controls
734 lines (623 loc) · 33.8 KB
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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
//
// Copyright 2019-2022, Optimizely, Inc. and contributors
//
// 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.
//
import Foundation
struct FeatureDecision {
var experiment: ExperimentCore?
let variation: Variation
let source: String
}
typealias UserProfile = OPTUserProfileService.UPProfile
class DefaultDecisionService: OPTDecisionService {
let bucketer: OPTBucketer
let userProfileService: OPTUserProfileService
// thread-safe lazy logger load (after HandlerRegisterService ready)
private let threadSafeLogger = ThreadSafeLogger()
// user-profile-service read-modify-write lock for supporting multiple clients
static let upsRMWLock = DispatchQueue(label: "ups-rmw")
var logger: OPTLogger {
return threadSafeLogger.logger
}
init(userProfileService: OPTUserProfileService) {
self.bucketer = DefaultBucketer()
self.userProfileService = userProfileService
}
init(userProfileService: OPTUserProfileService, bucketer: OPTBucketer) {
self.bucketer = bucketer
self.userProfileService = userProfileService
}
// MARK: - Experiment Decision
/// Determines the variation for a user in a given experiment.
/// - Parameters:
/// - config: The project configuration containing experiment and feature details.
/// - experiment: The experiment to evaluate.
/// - user: The user context containing user ID and attributes.
/// - options: Optional decision options (e.g., ignore user profile service).
/// - Returns: A `DecisionResponse` containing the assigned variation (if any) and decision reasons.
func getVariation(config: ProjectConfig,
experiment: Experiment,
user: OptimizelyUserContext,
options: [OptimizelyDecideOption]? = nil) -> DecisionResponse<Variation> {
let userId = user.userId
let ignoreUPS = (options ?? []).contains(.ignoreUserProfileService)
var profileTracker: UserProfileTracker?
if !ignoreUPS {
profileTracker = UserProfileTracker(userId: userId, userProfileService: self.userProfileService, logger: self.logger)
profileTracker?.loadUserProfile()
}
let response = getVariation(config: config, experiment: experiment, user: user, userProfileTracker: profileTracker)
if (!ignoreUPS) {
profileTracker?.save()
}
return response
}
/// Determines the variation for a user in an experiment, considering user profile and decision rules.
/// - Parameters:
/// - config: The project configuration.
/// - experiment: The experiment to evaluate.
/// - user: The user context.
/// - options: Optional decision options.
/// - userProfileTracker: Optional tracker for user profile data.
/// - Returns: A `DecisionResponse` with the variation (if any) and decision reasons.
func getVariation(config: ProjectConfig,
experiment: Experiment,
user: OptimizelyUserContext,
options: [OptimizelyDecideOption]? = nil,
userProfileTracker: UserProfileTracker?) -> DecisionResponse<Variation> {
let reasons = DecisionReasons(options: options)
let userId = user.userId
let attributes = user.attributes
let experimentId = experiment.id
// Acquire bucketingId .
let bucketingId = getBucketingId(userId: userId, attributes: attributes)
// ---- check if the experiment is running ----
if !experiment.isActivated {
let info = LogMessage.experimentNotRunning(experiment.key)
logger.i(info)
reasons.addInfo(info)
return DecisionResponse(result: nil, reasons: reasons)
}
// ---- check if the user is forced into a variation ----
let decisionResponse = config.getForcedVariation(experimentKey: experiment.key, userId: userId)
reasons.merge(decisionResponse.reasons)
if let variationId = decisionResponse.result?.id,
let variation = experiment.getVariation(id: variationId) {
return DecisionResponse(result: variation, reasons: reasons)
}
// ---- check to see if user is white-listed for a certain variation ----
if let variationKey = experiment.forcedVariations[userId] {
if let variation = experiment.getVariation(key: variationKey) {
let info = LogMessage.forcedVariationFound(variationKey, userId)
logger.i(info)
reasons.addInfo(info)
return DecisionResponse(result: variation, reasons: reasons)
}
// mapped to invalid variation - ignore and continue for other deciesions
let info = LogMessage.forcedVariationFoundButInvalid(variationKey, userId)
logger.e(info)
reasons.addInfo(info)
}
/// Load variation from tracker
if let profile = userProfileTracker?.userProfile,
let variationId = getVariationIdFromProfile(profile: profile, experimentId: experimentId),
let variation = experiment.getVariation(id: variationId) {
let info = LogMessage.gotVariationFromUserProfile(variation.key, experiment.key, userId)
logger.i(info)
reasons.addInfo(info)
return DecisionResponse(result: variation, reasons: reasons)
}
var bucketedVariation: Variation?
// ---- check if the user passes audience targeting before bucketing ----
let audienceResponse = doesMeetAudienceConditions(config: config,
experiment: experiment,
user: user)
reasons.merge(audienceResponse.reasons)
if audienceResponse.result ?? false {
// bucket user into a variation
let decisionResponse = bucketer.bucketExperiment(config: config,
experiment: experiment,
bucketingId: bucketingId)
reasons.merge(decisionResponse.reasons)
bucketedVariation = decisionResponse.result
if let variation = bucketedVariation {
let info = LogMessage.userBucketedIntoVariationInExperiment(userId, experiment.key, variation.key)
logger.i(info)
reasons.addInfo(info)
userProfileTracker?.updateProfile(experiment: experiment, variation: variation)
} else {
let info = LogMessage.userNotBucketedIntoVariation(userId)
logger.i(info)
reasons.addInfo(info)
}
} else {
let info = LogMessage.userNotInExperiment(userId, experiment.key)
logger.i(info)
reasons.addInfo(info)
}
return DecisionResponse(result: bucketedVariation, reasons: reasons)
}
// MARK: - Feature Flag Decision
/// Determines the feature decision for a user for a specific feature flag.
/// - Parameters:
/// - config: The project configuration.
/// - featureFlag: The feature flag to evaluate.
/// - user: The user context.
/// - options: Optional decision options.
/// - Returns: A `DecisionResponse` with the feature decision (if any) and reasons.
func getVariationForFeature(config: ProjectConfig,
featureFlag: FeatureFlag,
user: OptimizelyUserContext,
options: [OptimizelyDecideOption]? = nil) -> DecisionResponse<FeatureDecision> {
let response = getVariationForFeatureList(config: config, featureFlags: [featureFlag], user: user, options: options).first
guard response?.result != nil else {
let reasons = response?.reasons ?? DecisionReasons(options: options)
return DecisionResponse(result: nil, reasons: reasons)
}
return response!
}
/// Determines feature decisions for a list of feature flags.
/// - Parameters:
/// - config: The project configuration.
/// - featureFlags: The list of feature flags to evaluate.
/// - user: The user context.
/// - options: Optional decision options.
/// - Returns: An array of `DecisionResponse` objects, each containing a feature decision and reasons.
func getVariationForFeatureList(config: ProjectConfig,
featureFlags: [FeatureFlag],
user: OptimizelyUserContext,
options: [OptimizelyDecideOption]? = nil) -> [DecisionResponse<FeatureDecision>] {
let userId = user.userId
let ignoreUPS = (options ?? []).contains(.ignoreUserProfileService)
var profileTracker: UserProfileTracker?
if !ignoreUPS {
profileTracker = UserProfileTracker(userId: userId, userProfileService: self.userProfileService, logger: self.logger)
profileTracker?.loadUserProfile()
}
var decisions = [DecisionResponse<FeatureDecision>]()
for featureFlag in featureFlags {
let flagDecisionResponse = getDecisionForFlag(config: config, featureFlag: featureFlag, user: user, userProfileTracker: profileTracker)
decisions.append(flagDecisionResponse)
}
// save profile
if !ignoreUPS {
profileTracker?.save()
}
return decisions
}
/// Determines the feature decision for a feature flag, considering holdout, experiment and rollout
/// - Parameters:
/// - config: The project configuration.
/// - featureFlag: The feature flag to evaluate.
/// - user: The user context.
/// - userProfileTracker: Optional tracker for user profile data.
/// - options: Optional decision options.
/// - Returns: A `DecisionResponse` with the feature decision (if any) and reasons.
func getDecisionForFlag(config: ProjectConfig,
featureFlag: FeatureFlag,
user: OptimizelyUserContext,
userProfileTracker: UserProfileTracker? = nil,
options: [OptimizelyDecideOption]? = nil) -> DecisionResponse<FeatureDecision> {
let reasons = DecisionReasons(options: options)
let holdouts = config.getHoldoutForFlag(id: featureFlag.id)
for holdout in holdouts {
let holdoutDecision = getVariationForHoldout(config: config,
flagKey: featureFlag.key,
holdout: holdout,
user: user)
reasons.merge(holdoutDecision.reasons)
if let variation = holdoutDecision.result {
let featureDicision = FeatureDecision(experiment: holdout, variation: variation, source: Constants.DecisionSource.holdout.rawValue)
return DecisionResponse(result: featureDicision, reasons: reasons)
}
}
let flagExpDecision = getVariationForFeatureExperiments(config: config, featureFlag: featureFlag, user: user, userProfileTracker: userProfileTracker)
reasons.merge(flagExpDecision.reasons)
if let decision = flagExpDecision.result {
return DecisionResponse(result: decision, reasons: reasons)
}
let rolloutDecision = getVariationForFeatureRollout(config: config, featureFlag: featureFlag, user: user)
reasons.merge(rolloutDecision.reasons)
if let decision = rolloutDecision.result {
return DecisionResponse(result: decision, reasons: reasons)
} else {
return DecisionResponse(result: nil, reasons: reasons)
}
}
/// Determines the feature decision for a feature flag, considering experiments
/// - Parameters:
/// - config: The project configuration.
/// - featureFlag: The feature flag to evaluate.
/// - user: The user context.
/// - userProfileTracker: Optional tracker for user profile data.
/// - options: Optional decision options.
/// - Returns: A `DecisionResponse` with the feature decision (if any) and reasons.
func getVariationForFeatureExperiments(config: ProjectConfig,
featureFlag: FeatureFlag,
user: OptimizelyUserContext,
userProfileTracker: UserProfileTracker? = nil,
options: [OptimizelyDecideOption]? = nil) -> DecisionResponse<FeatureDecision> {
let reasons = DecisionReasons(options: options)
let experimentIds = featureFlag.experimentIds
if experimentIds.isEmpty {
let info = LogMessage.featureHasNoExperiments(featureFlag.key)
logger.d(info)
reasons.addInfo(info)
}
// Check if there are any experiment IDs inside feature flag
// Evaluate each experiment ID and return the first bucketed experiment variation
for experimentId in experimentIds {
if let experiment = config.getExperiment(id: experimentId) {
let decisionResponse = getVariationFromExperimentRule(config: config,
flagKey: featureFlag.key,
rule: experiment,
user: user,
userProfileTracker: userProfileTracker,
options: options)
reasons.merge(decisionResponse.reasons)
if let variation = decisionResponse.result {
let featureDecision = FeatureDecision(experiment: experiment, variation: variation, source: Constants.DecisionSource.featureTest.rawValue)
return DecisionResponse(result: featureDecision, reasons: reasons)
}
}
}
return DecisionResponse(result: nil, reasons: reasons)
}
/// Determines the feature decision for a feature flag's rollout rules.
/// - Parameters:
/// - config: The project configuration.
/// - featureFlag: The feature flag to evaluate.
/// - user: The user context.
/// - options: Optional decision options.
/// - Returns: A `DecisionResponse` with the feature decision (if any) and reasons.
func getVariationForFeatureRollout(config: ProjectConfig,
featureFlag: FeatureFlag,
user: OptimizelyUserContext,
options: [OptimizelyDecideOption]? = nil) -> DecisionResponse<FeatureDecision> {
let reasons = DecisionReasons(options: options)
let rolloutId = featureFlag.rolloutId.trimmingCharacters(in: CharacterSet.whitespaces)
guard !rolloutId.isEmpty else {
let info = LogMessage.noRolloutExists(featureFlag.key)
logger.d(info)
reasons.addInfo(info)
return DecisionResponse(result: nil, reasons: reasons)
}
guard let rollout = config.getRollout(id: rolloutId) else {
let info = OptimizelyError.rolloutIdInvalid(rolloutId, featureFlag.key)
logger.d(info)
reasons.addInfo(info)
return DecisionResponse(result: nil, reasons: reasons)
}
let rolloutRules = rollout.experiments
if rolloutRules.isEmpty {
let info = LogMessage.rolloutHasNoExperiments(rolloutId)
logger.e(info)
reasons.addInfo(info)
return DecisionResponse(result: nil, reasons: reasons)
}
var index = 0
while index < rolloutRules.count {
let decisionResponse = getVariationFromDeliveryRule(config: config,
flagKey: featureFlag.key,
rules: rolloutRules,
ruleIndex: index,
user: user,
options: options)
reasons.merge(decisionResponse.reasons)
let (variation, skipToEveryoneElse) = decisionResponse.result!
if let variation = variation {
let rule = rolloutRules[index]
let featureDecision = FeatureDecision(experiment: rule, variation: variation, source: Constants.DecisionSource.rollout.rawValue)
return DecisionResponse(result: featureDecision, reasons: reasons)
}
// the last rule is special for "Everyone Else"
index = skipToEveryoneElse ? (rolloutRules.count - 1) : (index + 1)
}
return DecisionResponse(result: nil, reasons: reasons)
}
// MARK: - Holdout and Rule Decisions
/// Determines the variation for a holdout group.
/// - Parameters:
/// - config: The project configuration.
/// - flagKey: The feature flag key.
/// - holdout: The holdout group to evaluate.
/// - user: The user context.
/// - options: Optional decision options.
/// - Returns: A `DecisionResponse` with the variation (if any) and reasons.
func getVariationForHoldout(config: ProjectConfig,
flagKey: String,
holdout: Holdout,
user: OptimizelyUserContext,
options: [OptimizelyDecideOption]? = nil) -> DecisionResponse<Variation> {
let reasons = DecisionReasons(options: options)
guard holdout.isActivated else {
let info = LogMessage.holdoutNotRunning(holdout.key)
reasons.addInfo(info)
logger.i(info)
return DecisionResponse(result: nil, reasons: reasons)
}
// ---- check if the user passes audience targeting before bucketing ----
let audienceResponse = doesMeetAudienceConditions(config: config,
experiment: holdout,
user: user)
reasons.merge(audienceResponse.reasons)
let userId = user.userId
let attributes = user.attributes
// Acquire bucketingId .
let bucketingId = getBucketingId(userId: userId, attributes: attributes)
var bucketedVariation: Variation?
if audienceResponse.result ?? false {
let info = LogMessage.userMeetsConditionsForHoldout(userId, holdout.key)
reasons.addInfo(info)
logger.i(info)
// bucket user into holdout variation
let decisionResponse = (bucketer as? DefaultBucketer)?.bucketToVariation(experiment: holdout, bucketingId: bucketingId)
if let reason = decisionResponse?.reasons {
reasons.merge(reason)
}
bucketedVariation = decisionResponse?.result
if let variation = bucketedVariation {
let info = LogMessage.userBucketedIntoVariationInHoldout(userId, holdout.key, variation.key)
reasons.addInfo(info)
logger.i(info)
} else {
let info = LogMessage.userNotBucketedIntoHoldoutVariation(userId)
reasons.addInfo(info)
logger.i(info)
}
} else {
let info = LogMessage.userDoesntMeetConditionsForHoldout(userId, holdout.key)
reasons.addInfo(info)
logger.i(info)
}
return DecisionResponse(result: bucketedVariation, reasons: reasons)
}
/// Determines the variation for an experiment rule within a feature flag.
/// - Parameters:
/// - config: The project configuration.
/// - flagKey: The feature flag key.
/// - rule: The experiment rule to evaluate.
/// - user: The user context.
/// - userProfileTracker: Optional tracker for user profile data.
/// - options: Optional decision options.
/// - Returns: A `DecisionResponse` with the variation (if any) and reasons.
func getVariationFromExperimentRule(config: ProjectConfig,
flagKey: String,
rule: Experiment,
user: OptimizelyUserContext,
userProfileTracker: UserProfileTracker?,
options: [OptimizelyDecideOption]? = nil) -> DecisionResponse<Variation> {
let reasons = DecisionReasons(options: options)
// check forced-decision first
let forcedDecisionResponse = findValidatedForcedDecision(config: config,
user: user,
context: OptimizelyDecisionContext(flagKey: flagKey, ruleKey: rule.key))
reasons.merge(forcedDecisionResponse.reasons)
if let variation = forcedDecisionResponse.result {
return DecisionResponse(result: variation, reasons: reasons)
}
let decisionResponse = getVariation(config: config,
experiment: rule,
user: user,
userProfileTracker: userProfileTracker)
let variation = decisionResponse.result
reasons.merge(decisionResponse.reasons)
return DecisionResponse(result: variation, reasons: reasons)
}
/// Determines the variation for a delivery rule in a rollout.
/// - Parameters:
/// - config: The project configuration.
/// - flagKey: The feature flag key.
/// - rules: The list of rollout rules.
/// - ruleIndex: The index of the rule to evaluate.
/// - user: The user context.
/// - options: Optional decision options.
/// - Returns: A `DecisionResponse` with the variation (if any), a flag indicating whether to skip to the "Everyone Else" rule, and reasons.
func getVariationFromDeliveryRule(config: ProjectConfig,
flagKey: String,
rules: [Experiment],
ruleIndex: Int,
user: OptimizelyUserContext,
options: [OptimizelyDecideOption]? = nil) -> DecisionResponse<(Variation?, Bool)> {
let reasons = DecisionReasons(options: options)
var skipToEveryoneElse = false
// check forced-decision first
let rule = rules[ruleIndex]
let forcedDecisionResponse = findValidatedForcedDecision(config: config,
user: user,
context: OptimizelyDecisionContext(flagKey: flagKey, ruleKey: rule.key))
reasons.merge(forcedDecisionResponse.reasons)
if let variation = forcedDecisionResponse.result {
return DecisionResponse(result: (variation, skipToEveryoneElse), reasons: reasons)
}
// regular decision
let userId = user.userId
let attributes = user.attributes
let bucketingId = getBucketingId(userId: userId, attributes: attributes)
let everyoneElse = (ruleIndex == rules.count - 1)
let loggingKey = everyoneElse ? "Everyone Else" : String(ruleIndex + 1)
var bucketedVariation: Variation?
let audienceDecisionResponse = doesMeetAudienceConditions(config: config,
experiment: rule,
user: user,
logType: .rolloutRule,
loggingKey: loggingKey)
reasons.merge(audienceDecisionResponse.reasons)
if audienceDecisionResponse.result ?? false {
var info = LogMessage.userMeetsConditionsForTargetingRule(userId, loggingKey)
logger.d(info)
reasons.addInfo(info)
let decisionResponse = bucketer.bucketExperiment(config: config,
experiment: rule,
bucketingId: bucketingId)
reasons.merge(decisionResponse.reasons)
bucketedVariation = decisionResponse.result
if bucketedVariation != nil {
info = LogMessage.userBucketedIntoTargetingRule(userId, loggingKey)
logger.d(info)
reasons.addInfo(info)
} else if !everyoneElse {
// skip this logging for EveryoneElse since this has a message not for EveryoneElse
info = LogMessage.userNotBucketedIntoTargetingRule(userId, loggingKey)
logger.d(info)
reasons.addInfo(info)
// skip the rest of rollout rules to the everyone-else rule if audience matches but not bucketed.
skipToEveryoneElse = true
}
} else {
let info = LogMessage.userDoesntMeetConditionsForTargetingRule(userId, loggingKey)
logger.d(info)
reasons.addInfo(info)
}
return DecisionResponse(result: (bucketedVariation, skipToEveryoneElse), reasons: reasons)
}
// MARK: - Audience Evaluation
/// Evaluates whether a user meets the audience conditions for an experiment or rule.
/// - Parameters:
/// - config: The project configuration.
/// - experiment: The experiment or rule to evaluate.
/// - user: The user context.
/// - logType: The type of evaluation for logging (e.g., experiment or rollout rule).
/// - loggingKey: Optional key for logging.
/// - Returns: A `DecisionResponse` with a boolean indicating whether conditions are met and reasons.
func doesMeetAudienceConditions(config: ProjectConfig,
experiment: ExperimentCore,
user: OptimizelyUserContext,
logType: Constants.EvaluationLogType = .experiment,
loggingKey: String? = nil) -> DecisionResponse<Bool> {
let reasons = DecisionReasons()
var result = true // success as default (no condition, etc)
let evType = logType.rawValue
let finalLoggingKey = loggingKey ?? experiment.key
do {
if let conditions = experiment.audienceConditions {
logger.d { () -> String in
return LogMessage.evaluatingAudiencesCombined(evType, finalLoggingKey, Utils.getConditionString(conditions: conditions)).description
}
switch conditions {
case .array(let arrConditions):
if arrConditions.count > 0 {
result = try conditions.evaluate(project: config.project, user: user)
} else {
// empty conditions (backward compatibility with "audienceIds" is ignored if exists even though empty
result = true
}
case .leaf:
result = try conditions.evaluate(project: config.project, user: user)
default:
result = true
}
}
// backward compatibility with audienceIds list
else if experiment.audienceIds.count > 0 {
var holder = [ConditionHolder]()
holder.append(.logicalOp(.or))
for id in experiment.audienceIds {
holder.append(.leaf(.audienceId(id)))
}
logger.d { () -> String in
return LogMessage.evaluatingAudiencesCombined(evType, finalLoggingKey, Utils.getConditionString(conditions: holder)).description
}
result = try holder.evaluate(project: config.project, user: user)
}
} catch {
if let error = error as? OptimizelyError {
logger.i(error)
reasons.addInfo(error)
}
result = false
}
logger.i(.audienceEvaluationResultCombined(evType, finalLoggingKey, result.description))
return DecisionResponse(result: result, reasons: reasons)
}
// MARK: - Utilities
/// Retrieves the bucketing ID for a user, defaulting to user ID unless overridden in attributes.
/// - Parameters:
/// - userId: The user's ID.
/// - attributes: The user's attributes.
/// - Returns: The bucketing ID to use for variation assignment.
func getBucketingId(userId: String, attributes: OptimizelyAttributes) -> String {
// By default, the bucketing ID should be the user ID .
var bucketingId = userId
// If the bucketing ID key is defined in attributes, then use that
// in place of the userID for the murmur hash key
if let newBucketingId = attributes[Constants.Attributes.reservedBucketIdAttribute] as? String {
bucketingId = newBucketingId
}
return bucketingId
}
/// Finds and validates a forced decision for a given context.
/// - Parameters:
/// - config: The project configuration.
/// - user: The user context.
/// - context: The decision context (flag and rule keys).
/// - Returns: A `DecisionResponse` with the forced variation (if valid) and reasons.
func findValidatedForcedDecision(config: ProjectConfig,
user: OptimizelyUserContext,
context: OptimizelyDecisionContext) -> DecisionResponse<Variation> {
let reasons = DecisionReasons()
if let variationKey = user.getForcedDecision(context: context)?.variationKey {
let userId = user.userId
if let variation = config.getFlagVariationByKey(flagKey: context.flagKey, variationKey: variationKey) {
let info = LogMessage.userHasForcedDecision(userId, context.flagKey, context.ruleKey, variationKey)
logger.i(info)
reasons.addInfo(info)
return DecisionResponse(result: variation, reasons: reasons)
} else {
let info = LogMessage.userHasForcedDecisionButInvalid(userId, context.flagKey, context.ruleKey)
logger.i(info)
reasons.addInfo(info)
}
}
return DecisionResponse(result: nil, reasons: reasons)
}
}
// MARK: - UserProfileService Helpers
extension DefaultDecisionService {
func getVariationIdFromProfile(userId: String,
experimentId: String) -> String? {
if let profile = userProfileService.lookup(userId: userId),
let bucketMap = profile[UserProfileKeys.kBucketMap] as? OPTUserProfileService.UPBucketMap,
let experimentMap = bucketMap[experimentId],
let variationId = experimentMap[UserProfileKeys.kVariationId] {
return variationId
} else {
return nil
}
}
func getVariationIdFromProfile(profile: UserProfile?,
experimentId: String) -> String? {
if let _profile = profile,
let bucketMap = _profile[UserProfileKeys.kBucketMap] as? OPTUserProfileService.UPBucketMap,
let experimentMap = bucketMap[experimentId],
let variationId = experimentMap[UserProfileKeys.kVariationId] {
return variationId
} else {
return nil
}
}
func saveProfile(userId: String,
experimentId: String,
variationId: String) {
DefaultDecisionService.upsRMWLock.sync {
var profile = self.userProfileService.lookup(userId: userId) ?? OPTUserProfileService.UPProfile()
var bucketMap = profile[UserProfileKeys.kBucketMap] as? OPTUserProfileService.UPBucketMap ?? OPTUserProfileService.UPBucketMap()
bucketMap[experimentId] = [UserProfileKeys.kVariationId: variationId]
profile[UserProfileKeys.kBucketMap] = bucketMap
profile[UserProfileKeys.kUserId] = userId
self.userProfileService.save(userProfile: profile)
self.logger.i(.savedVariationInUserProfile(variationId, experimentId, userId))
}
}
}