1use chrono::Utc;
2use lazy_static::lazy_static;
3
4use crate::evaluation::cmab_evaluator::evaluate_cmab;
5use crate::evaluation::comparisons::{
6 compare_arrays, compare_numbers, compare_str_with_regex, compare_strings_in_array,
7 compare_time, compare_versions,
8};
9use crate::evaluation::dynamic_value::DynamicValue;
10use crate::evaluation::evaluation_details::EvaluationDetails;
11use crate::evaluation::evaluation_types::SecondaryExposure;
12use crate::evaluation::evaluator_context::EvaluatorContext;
13use crate::evaluation::evaluator_value::{EvaluatorValue, EvaluatorValueType};
14use crate::evaluation::get_unit_id::get_unit_id;
15use crate::evaluation::ua_parser::UserAgentParser;
16use crate::event_logging::exposable_string;
17use crate::specs_response::spec_types::{Condition, Rule, Spec};
18use crate::{dyn_value, log_e, unwrap_or_return, StatsigErr};
19
20use super::country_lookup::CountryLookup;
21
22const TAG: &str = stringify!(Evaluator);
23
24pub struct Evaluator;
25
26lazy_static! {
27 static ref EMPTY_STR: String = String::new();
28 static ref EMPTY_EVALUATOR_VALUE: EvaluatorValue =
29 EvaluatorValue::new(EvaluatorValueType::Null);
30 static ref EMPTY_DYNAMIC_VALUE: DynamicValue = DynamicValue::new();
31}
32
33#[derive(Clone)]
34pub enum SpecType {
35 Gate,
36 DynamicConfig,
37 Experiment,
38 Layer,
39}
40
41#[derive(PartialEq, Eq)]
42pub enum Recognition {
43 Unrecognized,
44 Recognized,
45}
46
47impl Evaluator {
48 pub fn evaluate_with_details(
49 ctx: &mut EvaluatorContext,
50 spec_name: &str,
51 spec_type: &SpecType,
52 ) -> Result<EvaluationDetails, StatsigErr> {
53 let recognition = Self::evaluate(ctx, spec_name, spec_type)?;
54
55 if recognition == Recognition::Unrecognized {
56 return Ok(EvaluationDetails::unrecognized(ctx.spec_store_data));
57 }
58
59 if let Some(reason) = ctx.result.override_reason {
60 return Ok(EvaluationDetails::recognized_but_overridden(
61 ctx.spec_store_data,
62 reason,
63 ));
64 }
65
66 Ok(EvaluationDetails::recognized(
67 ctx.spec_store_data,
68 &ctx.result,
69 ))
70 }
71
72 pub fn evaluate(
73 ctx: &mut EvaluatorContext,
74 spec_name: &str,
75 spec_type: &SpecType,
76 ) -> Result<Recognition, StatsigErr> {
77 let opt_spec = match spec_type {
78 SpecType::Gate => ctx.spec_store_data.values.feature_gates.get(spec_name),
79 SpecType::DynamicConfig => ctx.spec_store_data.values.dynamic_configs.get(spec_name),
80 SpecType::Experiment => ctx.spec_store_data.values.dynamic_configs.get(spec_name),
81 SpecType::Layer => ctx.spec_store_data.values.layer_configs.get(spec_name),
82 }
83 .map(|a| a.spec.as_ref());
84
85 if try_apply_override(ctx, spec_name, spec_type, opt_spec) {
86 return Ok(Recognition::Recognized);
87 }
88
89 if try_apply_config_mapping(ctx, spec_name, spec_type, opt_spec) {
90 return Ok(Recognition::Recognized);
91 }
92
93 if evaluate_cmab(ctx, spec_name, spec_type) {
94 return Ok(Recognition::Recognized);
95 }
96
97 let spec = unwrap_or_return!(opt_spec, Ok(Recognition::Unrecognized));
98
99 if ctx.result.id_type.is_none() {
100 ctx.result.id_type = Some(&spec.id_type);
101 }
102
103 if ctx.result.version.is_none() {
104 if let Some(version) = spec.version {
105 ctx.result.version = Some(version);
106 }
107 }
108
109 if let Some(is_active) = spec.is_active {
110 ctx.result.is_experiment_active = is_active;
111 }
112
113 if let Some(has_shared_params) = spec.has_shared_params {
114 ctx.result.is_in_layer = has_shared_params;
115 }
116
117 if let Some(explicit_params) = &spec.explicit_parameters {
118 ctx.result.explicit_parameters = Some(explicit_params);
119 }
120
121 for rule in &spec.rules {
122 evaluate_rule(ctx, rule)?;
123
124 if ctx.result.unsupported {
125 return Ok(Recognition::Recognized);
126 }
127
128 if !ctx.result.bool_value {
129 continue;
130 }
131
132 if evaluate_config_delegate(ctx, rule)? {
133 ctx.finalize_evaluation(spec, Some(rule));
134 return Ok(Recognition::Recognized);
135 }
136
137 let did_pass = evaluate_pass_percentage(ctx, rule, &spec.salt);
138
139 if did_pass {
140 ctx.result.bool_value = rule.return_value.get_bool() != Some(false);
141 ctx.result.json_value = rule.return_value.get_json();
142 } else {
143 ctx.result.bool_value = spec.default_value.get_bool() == Some(true);
144 ctx.result.json_value = spec.default_value.get_json();
145 }
146
147 ctx.result.rule_id = Some(&rule.id);
148 ctx.result.group_name = rule.group_name.as_ref();
149 ctx.result.is_experiment_group = rule.is_experiment_group.unwrap_or(false);
150 ctx.result.is_experiment_active = spec.is_active.unwrap_or(false);
151 ctx.finalize_evaluation(spec, Some(rule));
152 return Ok(Recognition::Recognized);
153 }
154
155 ctx.result.bool_value = spec.default_value.get_bool() == Some(true);
156 ctx.result.json_value = spec.default_value.get_json();
157 ctx.result.rule_id = match spec.enabled {
158 true => Some(&exposable_string::DEFAULT_RULE),
159 false => Some(&exposable_string::DISABLED_RULE),
160 };
161 ctx.finalize_evaluation(spec, None);
162
163 Ok(Recognition::Recognized)
164 }
165}
166
167fn try_apply_config_mapping(
168 ctx: &mut EvaluatorContext,
169 spec_name: &str,
170 spec_type: &SpecType,
171 opt_spec: Option<&Spec>,
172) -> bool {
173 let overrides = match &ctx.spec_store_data.values.overrides {
174 Some(overrides) => overrides,
175 None => return false,
176 };
177
178 let override_rules = match &ctx.spec_store_data.values.override_rules {
179 Some(override_rules) => override_rules,
180 None => return false,
181 };
182
183 let mapping_list = match overrides.get(spec_name) {
184 Some(mapping_list) => mapping_list,
185 None => return false,
186 };
187
188 let spec_salt = match opt_spec {
189 Some(spec) => &spec.salt,
190 None => &EMPTY_STR,
191 };
192
193 for mapping in mapping_list {
194 for override_rule in &mapping.rules {
195 let start_time = override_rule.start_time.unwrap_or_default();
196
197 if start_time > Utc::now().timestamp_millis() {
198 continue;
199 }
200
201 let rule = match override_rules.get(&override_rule.rule_name) {
202 Some(rule) => rule,
203 None => continue,
204 };
205 match evaluate_rule(ctx, rule) {
206 Ok(_) => {}
207 Err(_) => {
208 ctx.reset_result();
209 continue;
210 }
211 }
212
213 if !ctx.result.bool_value || ctx.result.unsupported {
214 ctx.reset_result();
215 continue;
216 }
217 ctx.reset_result();
218 let pass = evaluate_pass_percentage(ctx, rule, spec_salt);
219 if pass {
220 ctx.result.override_config_name = Some(&mapping.new_config_name);
221 match Evaluator::evaluate(ctx, mapping.new_config_name.as_str(), spec_type) {
222 Ok(Recognition::Recognized) => {
223 return true;
224 }
225 _ => {
226 ctx.reset_result();
227 break;
228 }
229 }
230 }
231 }
232 }
233
234 false
235}
236
237fn try_apply_override(
238 ctx: &mut EvaluatorContext,
239 spec_name: &str,
240 spec_type: &SpecType,
241 opt_spec: Option<&Spec>,
242) -> bool {
243 let adapter = match &ctx.override_adapter {
244 Some(adapter) => adapter,
245 None => return false,
246 };
247
248 match spec_type {
249 SpecType::Gate => adapter.get_gate_override(ctx.user.user_ref, spec_name, &mut ctx.result),
250
251 SpecType::DynamicConfig => {
252 adapter.get_dynamic_config_override(ctx.user.user_ref, spec_name, &mut ctx.result)
253 }
254
255 SpecType::Experiment => {
256 adapter.get_experiment_override(ctx.user.user_ref, spec_name, &mut ctx.result, opt_spec)
257 }
258
259 SpecType::Layer => {
260 adapter.get_layer_override(ctx.user.user_ref, spec_name, &mut ctx.result)
261 }
262 }
263}
264
265fn evaluate_rule<'a>(ctx: &mut EvaluatorContext<'a>, rule: &'a Rule) -> Result<(), StatsigErr> {
266 let mut all_conditions_pass = true;
267 for condition_hash in &rule.conditions {
269 let opt_condition = ctx.spec_store_data.values.condition_map.get(condition_hash);
271 let condition = if let Some(c) = opt_condition {
272 c
273 } else {
274 ctx.result.unsupported = true;
276 return Ok(());
277 };
278
279 evaluate_condition(ctx, condition)?;
280
281 if !ctx.result.bool_value {
282 all_conditions_pass = false;
283 }
284 }
285
286 ctx.result.bool_value = all_conditions_pass;
287
288 Ok(())
289}
290
291fn evaluate_condition<'a>(
292 ctx: &mut EvaluatorContext<'a>,
293 condition: &'a Condition,
294) -> Result<(), StatsigErr> {
295 let temp_value: Option<DynamicValue>;
296 let target_value = condition
297 .target_value
298 .as_ref()
299 .unwrap_or(&EMPTY_EVALUATOR_VALUE);
300 let condition_type = &condition.condition_type;
301
302 let value: &DynamicValue = match condition_type as &str {
303 "public" => {
304 ctx.result.bool_value = true;
305 return Ok(());
306 }
307 "fail_gate" | "pass_gate" => {
308 evaluate_nested_gate(ctx, target_value, condition_type)?;
309 return Ok(());
310 }
311 "ua_based" => match ctx.user.get_user_value(&condition.field) {
312 Some(value) => Some(value),
313 None => {
314 temp_value =
315 UserAgentParser::get_value_from_user_agent(ctx.user, &condition.field, ctx);
316 temp_value.as_ref()
317 }
318 },
319 "ip_based" => match ctx.user.get_user_value(&condition.field) {
320 Some(value) => Some(value),
321 None => {
322 temp_value = CountryLookup::get_value_from_ip(ctx.user, &condition.field, ctx);
323 temp_value.as_ref()
324 }
325 },
326 "user_field" => ctx.user.get_user_value(&condition.field),
327 "environment_field" => {
328 temp_value = ctx.user.get_value_from_environment(&condition.field);
329 temp_value.as_ref()
330 }
331 "current_time" => {
332 temp_value = Some(DynamicValue::for_timestamp_evaluation(
333 Utc::now().timestamp_millis(),
334 ));
335 temp_value.as_ref()
336 }
337 "user_bucket" => {
338 temp_value = Some(get_hash_for_user_bucket(ctx, condition));
339 temp_value.as_ref()
340 }
341 "target_app" => ctx.app_id,
342 "unit_id" => ctx.user.get_unit_id(&condition.id_type),
343 _ => {
344 ctx.result.unsupported = true;
345 return Ok(());
346 }
347 }
348 .unwrap_or(&EMPTY_DYNAMIC_VALUE);
349
350 let operator = match &condition.operator {
353 Some(operator) => operator,
354 None => {
355 ctx.result.unsupported = true;
356 return Ok(());
357 }
358 };
359
360 ctx.result.bool_value = match operator as &str {
361 "gt" | "gte" | "lt" | "lte" => compare_numbers(value, target_value, operator),
363
364 "version_gt" | "version_gte" | "version_lt" | "version_lte" | "version_eq"
366 | "version_neq" => compare_versions(value, target_value, operator),
367
368 "any"
370 | "none"
371 | "str_starts_with_any"
372 | "str_ends_with_any"
373 | "str_contains_any"
374 | "str_contains_none" => compare_strings_in_array(value, target_value, operator, true),
375 "any_case_sensitive" | "none_case_sensitive" => {
376 compare_strings_in_array(value, target_value, operator, false)
377 }
378 "str_matches" => compare_str_with_regex(value, target_value),
379
380 "before" | "after" | "on" => compare_time(value, target_value, operator),
382
383 "eq" => target_value.is_equal_to_dynamic_value(value),
385 "neq" => !target_value.is_equal_to_dynamic_value(value),
386
387 "in_segment_list" | "not_in_segment_list" => {
389 evaluate_id_list(ctx, operator, target_value, value)
390 }
391
392 "array_contains_any"
393 | "array_contains_none"
394 | "array_contains_all"
395 | "not_array_contains_all" => compare_arrays(value, target_value, operator),
396
397 _ => {
398 ctx.result.unsupported = true;
399 return Ok(());
400 }
401 };
402
403 Ok(())
404}
405
406fn evaluate_id_list(
407 ctx: &mut EvaluatorContext<'_>,
408 op: &str,
409 target_value: &EvaluatorValue,
410 value: &DynamicValue,
411) -> bool {
412 let list_name = unwrap_or_return!(&target_value.string_value, false);
413 let id_lists = &ctx.spec_store_data.id_lists;
414
415 let list = unwrap_or_return!(id_lists.get(&list_name.value), false);
416
417 let dyn_str = unwrap_or_return!(&value.string_value, false);
418 let hashed = ctx.hashing.sha256(&dyn_str.value);
419 let lookup_id: String = hashed.chars().take(8).collect();
420
421 let is_in_list = list.ids.contains(&lookup_id);
422
423 if op == "not_in_segment_list" {
424 return !is_in_list;
425 }
426
427 is_in_list
428}
429
430fn evaluate_nested_gate<'a>(
431 ctx: &mut EvaluatorContext<'a>,
432 target_value: &'a EvaluatorValue,
433 condition_type: &'a String,
434) -> Result<(), StatsigErr> {
435 let gate_name = if let Some(name) = target_value.string_value.as_ref() {
436 &name.value
437 } else {
438 log_e!(
439 TAG,
440 "Invalid target_value for condition {}, {:?}",
441 condition_type,
442 target_value
443 );
444 ctx.result.unsupported = true;
445 return Ok(());
446 };
447
448 match ctx.nested_gate_memo.get(gate_name.as_str()) {
449 Some((previous_bool, previous_rule_id)) => {
450 ctx.result.bool_value = *previous_bool;
451 ctx.result.rule_id = *previous_rule_id;
452 }
453 None => {
454 ctx.prep_for_nested_evaluation()?;
455 let _ = Evaluator::evaluate(ctx, gate_name, &SpecType::Gate)?;
456
457 if ctx.result.unsupported {
458 return Ok(());
459 }
460
461 ctx.nested_gate_memo
462 .insert(gate_name, (ctx.result.bool_value, ctx.result.rule_id));
463 }
464 }
465
466 if !&gate_name.starts_with("segment:") {
467 let res = &ctx.result;
468 let expo = SecondaryExposure {
469 gate: gate_name.clone(),
470 gate_value: res.bool_value.to_string(),
471 rule_id: res
472 .rule_id
473 .unwrap_or(&exposable_string::EMPTY_STRING)
474 .clone(),
475 };
476
477 if res.sampling_rate.is_none() {
478 ctx.result.has_seen_analytical_gates = Option::from(true);
479 }
480
481 ctx.result.secondary_exposures.push(expo);
482 }
483
484 if condition_type == "fail_gate" {
485 ctx.result.bool_value = !ctx.result.bool_value;
486 }
487 Ok(())
488}
489
490fn evaluate_config_delegate<'a>(
491 ctx: &mut EvaluatorContext<'a>,
492 rule: &'a Rule,
493) -> Result<bool, StatsigErr> {
494 let delegate = unwrap_or_return!(&rule.config_delegate, Ok(false));
495 let delegate_spec = unwrap_or_return!(
496 ctx.spec_store_data.values.dynamic_configs.get(delegate),
497 Ok(false)
498 );
499
500 ctx.result.undelegated_secondary_exposures = Some(ctx.result.secondary_exposures.clone());
501
502 ctx.prep_for_nested_evaluation()?;
503 let recognition = Evaluator::evaluate(ctx, delegate, &SpecType::Experiment)?;
504 if recognition == Recognition::Unrecognized {
505 ctx.result.undelegated_secondary_exposures = None;
506 return Ok(false);
507 }
508
509 ctx.result.explicit_parameters = delegate_spec.spec.explicit_parameters.as_ref();
510 ctx.result.config_delegate = rule.config_delegate.as_ref();
511
512 Ok(true)
513}
514
515fn evaluate_pass_percentage(ctx: &mut EvaluatorContext, rule: &Rule, spec_salt: &String) -> bool {
516 if rule.pass_percentage == 100f64 {
517 return true;
518 }
519
520 if rule.pass_percentage == 0f64 {
521 return false;
522 }
523
524 let rule_salt = rule.salt.as_deref().unwrap_or(rule.id.as_str());
525 let unit_id = get_unit_id(ctx, &rule.id_type);
526 let input = format!("{spec_salt}.{rule_salt}.{unit_id}");
527 match ctx.hashing.evaluation_hash(&input) {
528 Some(hash) => ((hash % 10000) as f64) < rule.pass_percentage * 100.0,
529 None => false,
530 }
531}
532
533fn get_hash_for_user_bucket(ctx: &mut EvaluatorContext, condition: &Condition) -> DynamicValue {
534 let unit_id = get_unit_id(ctx, &condition.id_type);
535
536 let mut salt: &String = &EMPTY_STR;
537
538 if let Some(add_values) = &condition.additional_values {
539 if let Some(v) = add_values.get("salt") {
540 salt = v;
541 }
542 }
543
544 let input = format!("{salt}.{unit_id}");
545 let hash = ctx.hashing.evaluation_hash(&input).unwrap_or(1);
546 dyn_value!(hash % 1000)
547}