1use num::bigint::{BigInt, Sign};
7use std::cell::Cell;
8use std::collections::HashMap;
9use std::sync::OnceLock;
10
11use serde_json::Value;
12use sha1::{Digest, Sha1};
13
14fn value_to_id_string(value: &Value) -> String {
16 match value {
17 Value::String(s) => s.clone(),
18 Value::Number(n) => {
19 if let Some(i) = n.as_i64() {
20 i.to_string()
21 } else if let Some(f) = n.as_f64() {
22 if f.fract() == 0.0 {
24 format!("{f:.1}")
25 } else {
26 f.to_string()
27 }
28 } else {
29 n.to_string()
30 }
31 }
32 Value::Bool(b) => if *b { "True" } else { "False" }.to_string(),
33 Value::Array(arr) => {
34 let items: Vec<String> = arr.iter().map(value_to_id_string).collect();
35 format!("[{}]", items.join(", "))
36 }
37 Value::Null => "None".to_string(),
38 Value::Object(_) => value.to_string(),
39 }
40}
41
42pub struct FeatureContext {
47 data: HashMap<String, Value>,
48 identity_fields: Vec<String>,
49 cached_id: Cell<Option<u64>>,
50}
51
52impl FeatureContext {
53 pub fn new() -> Self {
54 Self {
55 data: HashMap::new(),
56 identity_fields: Vec::new(),
57 cached_id: Cell::new(None),
58 }
59 }
60
61 pub fn identity_fields(&mut self, fields: Vec<&str>) {
66 self.identity_fields = fields.into_iter().map(|s| s.to_string()).collect();
67 self.cached_id.set(None);
68 }
69
70 pub fn insert(&mut self, key: &str, value: impl Into<Value>) {
72 self.data.insert(key.to_string(), value.into());
73 self.cached_id.set(None);
74 }
75
76 pub fn get(&self, key: &str) -> Option<&Value> {
78 self.data.get(key)
79 }
80
81 pub fn has(&self, key: &str) -> bool {
83 self.data.contains_key(key)
84 }
85
86 pub fn id(&self) -> u64 {
93 if let Some(id) = self.cached_id.get() {
94 return id;
95 }
96 let id = self.compute_id();
97 self.cached_id.set(Some(id));
98 id
99 }
100
101 fn compute_id(&self) -> u64 {
110 let mut identity_fields: Vec<&String> = self
111 .identity_fields
112 .iter()
113 .filter(|f| self.data.contains_key(f.as_str()))
114 .collect();
115 if identity_fields.is_empty() {
116 identity_fields = self.data.keys().collect();
117 }
118 identity_fields.sort();
119
120 let mut parts: Vec<String> = Vec::with_capacity(identity_fields.len() * 2);
121 for key in identity_fields {
122 parts.push(key.clone());
123 parts.push(value_to_id_string(&self.data[key.as_str()]));
124 }
125 let mut hasher = Sha1::new();
126 hasher.update(parts.join(":").as_bytes());
127 let digest = hasher.finalize();
128
129 let bigint = BigInt::from_bytes_be(Sign::Plus, digest.as_slice());
131
132 let small: BigInt = bigint % 1000000000;
136 let id_parts = small.to_u64_digits().1;
137 if id_parts.is_empty() { 0 } else { id_parts[0] }
138 }
139}
140
141impl Default for FeatureContext {
142 fn default() -> Self {
143 Self::new()
144 }
145}
146
147#[derive(Debug)]
148enum OperatorKind {
149 In,
150 NotIn,
151 Contains,
152 NotContains,
153 Equals,
154 NotEquals,
155}
156
157#[derive(Debug)]
158struct Condition {
159 property: String,
160 operator: OperatorKind,
161 value: Value,
162}
163
164#[derive(Debug)]
165struct Segment {
166 rollout: u64,
167 conditions: Vec<Condition>,
168}
169
170#[derive(Debug)]
171struct Feature {
172 enabled: bool,
173 segments: Vec<Segment>,
174}
175
176impl Feature {
177 fn from_json(value: &Value) -> Option<Self> {
178 let enabled = value
180 .get("enabled")
181 .and_then(|v| v.as_bool())
182 .unwrap_or(true);
183 let segments = value
184 .get("segments")?
185 .as_array()?
186 .iter()
187 .filter_map(Segment::from_json)
188 .collect();
189 Some(Feature { enabled, segments })
190 }
191
192 fn matches(&self, context: &FeatureContext) -> bool {
193 if !self.enabled {
194 return false;
195 }
196 for segment in &self.segments {
197 if segment.conditions_match(context) {
198 return segment.in_rollout(context);
199 }
200 }
201 false
202 }
203}
204
205impl Segment {
206 fn from_json(value: &Value) -> Option<Self> {
207 let rollout = value.get("rollout").and_then(|v| v.as_u64()).unwrap_or(100);
208 let conditions = value
209 .get("conditions")
210 .and_then(|v| v.as_array())
211 .map(|arr| arr.iter().filter_map(Condition::from_json).collect())
212 .unwrap_or_default();
213 Some(Segment {
214 rollout,
215 conditions,
216 })
217 }
218
219 fn conditions_match(&self, context: &FeatureContext) -> bool {
220 self.conditions.iter().all(|c| c.matches(context))
221 }
222
223 fn in_rollout(&self, context: &FeatureContext) -> bool {
224 if self.rollout == 0 {
225 return false;
226 }
227 if self.rollout >= 100 {
228 return true;
229 }
230 context.id() % 100 < self.rollout
231 }
232}
233
234impl Condition {
235 fn from_json(value: &Value) -> Option<Self> {
236 let property = value.get("property")?.as_str()?.to_string();
237 let operator = match value.get("operator")?.as_str()? {
238 "in" => OperatorKind::In,
239 "not_in" => OperatorKind::NotIn,
240 "contains" => OperatorKind::Contains,
241 "not_contains" => OperatorKind::NotContains,
242 "equals" => OperatorKind::Equals,
243 "not_equals" => OperatorKind::NotEquals,
244 _ => return None,
245 };
246 let value = value.get("value")?.clone();
247 Some(Condition {
248 property,
249 operator,
250 value,
251 })
252 }
253
254 fn matches(&self, context: &FeatureContext) -> bool {
255 let Some(ctx_val) = context.get(&self.property) else {
256 return false;
257 };
258 match &self.operator {
259 OperatorKind::In => eval_in(ctx_val, &self.value),
260 OperatorKind::NotIn => !eval_in(ctx_val, &self.value),
261 OperatorKind::Contains => eval_contains(ctx_val, &self.value),
262 OperatorKind::NotContains => !eval_contains(ctx_val, &self.value),
263 OperatorKind::Equals => eval_equals(ctx_val, &self.value),
264 OperatorKind::NotEquals => !eval_equals(ctx_val, &self.value),
265 }
266 }
267}
268
269fn eval_in(ctx_val: &Value, condition_val: &Value) -> bool {
272 let Some(arr) = condition_val.as_array() else {
273 return false;
274 };
275 match ctx_val {
276 Value::String(s) => {
277 let s_lower = s.to_lowercase();
278 arr.iter()
279 .any(|v| v.as_str().is_some_and(|cv| cv.to_lowercase() == s_lower))
280 }
281 Value::Number(n) => {
282 if let Some(i) = n.as_i64() {
283 arr.iter().any(|v| v.as_i64().is_some_and(|cv| cv == i))
284 } else if let Some(f) = n.as_f64() {
285 arr.iter().any(|v| v.as_f64().is_some_and(|cv| cv == f))
286 } else {
287 false
288 }
289 }
290 Value::Bool(b) => arr.iter().any(|v| v.as_bool().is_some_and(|cv| cv == *b)),
291 _ => false,
292 }
293}
294
295fn eval_contains(ctx_val: &Value, condition_val: &Value) -> bool {
298 let Some(ctx_arr) = ctx_val.as_array() else {
299 return false;
300 };
301 match condition_val {
302 Value::String(s) => {
303 let s_lower = s.to_lowercase();
304 ctx_arr
305 .iter()
306 .any(|v| v.as_str().is_some_and(|cv| cv.to_lowercase() == s_lower))
307 }
308 Value::Number(n) => {
309 if let Some(i) = n.as_i64() {
310 ctx_arr.iter().any(|v| v.as_i64().is_some_and(|cv| cv == i))
311 } else if let Some(f) = n.as_f64() {
312 ctx_arr.iter().any(|v| v.as_f64().is_some_and(|cv| cv == f))
313 } else {
314 false
315 }
316 }
317 Value::Bool(b) => ctx_arr
318 .iter()
319 .any(|v| v.as_bool().is_some_and(|cv| cv == *b)),
320 _ => false,
321 }
322}
323
324fn eval_equals(ctx_val: &Value, condition_val: &Value) -> bool {
328 match (ctx_val, condition_val) {
329 (Value::String(a), Value::String(b)) => a.to_lowercase() == b.to_lowercase(),
330 (Value::Number(a), Value::Number(b)) => {
331 if let (Some(ai), Some(bi)) = (a.as_i64(), b.as_i64()) {
333 ai == bi
334 } else if let (Some(af), Some(bf)) = (a.as_f64(), b.as_f64()) {
335 af == bf
336 } else {
337 false
338 }
339 }
340 (Value::Bool(a), Value::Bool(b)) => a == b,
341 (Value::Array(a), Value::Array(b)) => {
342 a.len() == b.len() && a.iter().zip(b.iter()).all(|(av, bv)| eval_equals(av, bv))
343 }
344 _ => false,
345 }
346}
347
348#[derive(Debug, PartialEq)]
349enum DebugLogLevel {
350 None,
351 Parse,
352 Match,
353 All,
354}
355
356static DEBUG_LOG_LEVEL: OnceLock<DebugLogLevel> = OnceLock::new();
357static DEBUG_MATCH_SAMPLE_RATE: OnceLock<u64> = OnceLock::new();
358
359fn debug_log_level() -> &'static DebugLogLevel {
360 DEBUG_LOG_LEVEL.get_or_init(|| {
361 match std::env::var("SENTRY_OPTIONS_FEATURE_DEBUG_LOG")
362 .as_deref()
363 .unwrap_or("")
364 {
365 "all" => DebugLogLevel::All,
366 "parse" => DebugLogLevel::Parse,
367 "match" => DebugLogLevel::Match,
368 _ => DebugLogLevel::None,
369 }
370 })
371}
372
373fn debug_match_sample_rate() -> u64 {
374 *DEBUG_MATCH_SAMPLE_RATE.get_or_init(|| {
375 std::env::var("SENTRY_OPTIONS_FEATURE_DEBUG_LOG_SAMPLE_RATE")
376 .ok()
377 .and_then(|v| v.parse::<f64>().ok())
378 .map(|r| (r.clamp(0.0, 1.0) * 1000.0) as u64)
379 .unwrap_or(1000)
380 })
381}
382
383fn debug_log_parse(msg: &str) {
384 match debug_log_level() {
385 DebugLogLevel::Parse | DebugLogLevel::All => eprintln!("[sentry-options/parse] {msg}"),
386 _ => {}
387 }
388}
389
390fn debug_log_match(feature: &str, result: bool, context_id: u64) {
391 match debug_log_level() {
392 DebugLogLevel::Match | DebugLogLevel::All => {
393 if context_id % 1000 < debug_match_sample_rate() {
394 eprintln!(
395 "[sentry-options/match] feature='{feature}' result={result} context_id={context_id}"
396 );
397 }
398 }
399 _ => {}
400 }
401}
402
403pub struct FeatureChecker {
405 namespace: String,
406 options: &'static crate::Options,
407}
408
409impl FeatureChecker {
410 pub fn new(namespace: String, options: &'static crate::Options) -> Self {
411 Self { namespace, options }
412 }
413
414 pub fn has(&self, feature_name: &str, context: &FeatureContext) -> bool {
418 let key = format!("feature.{feature_name}");
419
420 let feature_val = match self.options.get(&self.namespace, &key) {
421 Ok(v) => v,
422 Err(e) => {
423 debug_log_parse(&format!("Failed to get feature '{key}': {e}"));
424 return false;
425 }
426 };
427
428 let feature = match Feature::from_json(&feature_val) {
429 Some(f) => {
430 debug_log_parse(&format!("Parsed feature '{key}'"));
431 f
432 }
433 None => {
434 debug_log_parse(&format!("Failed to parse feature '{key}'"));
435 return false;
436 }
437 };
438
439 let result = feature.matches(context);
440 debug_log_match(feature_name, result, context.id());
441 result
442 }
443}
444
445pub fn features(namespace: &str) -> FeatureChecker {
449 let opts = crate::GLOBAL_OPTIONS
450 .get()
451 .expect("options not initialized - call init() first");
452 FeatureChecker {
453 namespace: namespace.to_string(),
454 options: opts,
455 }
456}
457
458#[cfg(test)]
459mod tests {
460 use super::*;
461 use crate::Options;
462 use serde_json::json;
463 use std::fs;
464 use std::path::Path;
465 use tempfile::TempDir;
466
467 fn create_schema(dir: &Path, namespace: &str, schema: &str) {
468 let schema_dir = dir.join(namespace);
469 fs::create_dir_all(&schema_dir).unwrap();
470 fs::write(schema_dir.join("schema.json"), schema).unwrap();
471 }
472
473 fn create_values(dir: &Path, namespace: &str, values: &str) {
474 let ns_dir = dir.join(namespace);
475 fs::create_dir_all(&ns_dir).unwrap();
476 fs::write(ns_dir.join("values.json"), values).unwrap();
477 }
478
479 const FEATURE_SCHEMA: &str = r##"{
480 "version": "1.0",
481 "type": "object",
482 "properties": {
483 "feature.organizations:test-feature": {
484 "$ref": "#/definitions/Feature"
485 }
486 }
487 }"##;
488
489 fn setup_feature_options(feature_json: &str) -> (Options, TempDir) {
490 let temp = TempDir::new().unwrap();
491 let schemas = temp.path().join("schemas");
492 fs::create_dir_all(&schemas).unwrap();
493 create_schema(&schemas, "test", FEATURE_SCHEMA);
494
495 let values = temp.path().join("values");
496 let values_json = format!(
497 r#"{{"options": {{"feature.organizations:test-feature": {}}}}}"#,
498 feature_json
499 );
500 create_values(&values, "test", &values_json);
501
502 let opts = Options::from_directory(temp.path()).unwrap();
503 (opts, temp)
504 }
505
506 fn feature_json(enabled: bool, rollout: u64, conditions: &str) -> String {
507 format!(
508 r#"{{
509 "name": "test-feature",
510 "enabled": {enabled},
511 "owner": {{"team": "test-team"}},
512 "created_at": "2024-01-01",
513 "segments": [{{
514 "name": "test-segment",
515 "rollout": {rollout},
516 "conditions": [{conditions}]
517 }}]
518 }}"#
519 )
520 }
521
522 fn in_condition(property: &str, values: &str) -> String {
523 format!(r#"{{"property": "{property}", "operator": "in", "value": [{values}]}}"#)
524 }
525
526 fn check(opts: &Options, feature: &str, ctx: &FeatureContext) -> bool {
527 let key = format!("feature.{feature}");
528 let Ok(val) = opts.get("test", &key) else {
529 return false;
530 };
531 Feature::from_json(&val).is_some_and(|f| f.matches(ctx))
532 }
533
534 #[test]
535 fn test_feature_context_insert_and_get() {
536 let mut ctx = FeatureContext::new();
537 ctx.insert("org_id", json!(123));
538 ctx.insert("name", json!("sentry"));
539 ctx.insert("active", json!(true));
540
541 assert!(ctx.has("org_id"));
542 assert!(!ctx.has("missing"));
543 assert_eq!(ctx.get("org_id"), Some(&json!(123)));
544 assert_eq!(ctx.get("name"), Some(&json!("sentry")));
545 }
546
547 #[test]
548 fn test_feature_context_id_is_cached() {
549 let mut ctx = FeatureContext::new();
550 ctx.identity_fields(vec!["user_id"]);
551 ctx.insert("user_id", json!(42));
552
553 let id1 = ctx.id();
554 let id2 = ctx.id();
555 assert_eq!(id1, id2, "ID should be cached and consistent");
556 }
557
558 #[test]
559 fn test_feature_context_id_resets_on_identity_change() {
560 let mut ctx = FeatureContext::new();
561 ctx.insert("user_id", json!(1));
562 ctx.insert("org_id", json!(2));
563
564 ctx.identity_fields(vec!["user_id"]);
565 let id_user = ctx.id();
566
567 ctx.identity_fields(vec!["org_id"]);
568 let id_org = ctx.id();
569
570 assert_ne!(
571 id_user, id_org,
572 "Different identity fields should produce different IDs"
573 );
574 }
575
576 #[test]
577 fn test_feature_context_id_deterministic() {
578 let make_ctx = || {
579 let mut ctx = FeatureContext::new();
580 ctx.identity_fields(vec!["user_id", "org_id"]);
581 ctx.insert("user_id", json!(456));
582 ctx.insert("org_id", json!(123));
583 ctx
584 };
585
586 assert_eq!(make_ctx().id(), make_ctx().id());
587
588 let mut other_ctx = FeatureContext::new();
589 other_ctx.identity_fields(vec!["user_id", "org_id"]);
590 other_ctx.insert("user_id", json!(789));
591 other_ctx.insert("org_id", json!(123));
592
593 assert_ne!(make_ctx().id(), other_ctx.id());
594 }
595
596 #[test]
597 fn test_feature_context_id_value_align_with_python() {
598 let ctx = FeatureContext::new();
602 assert_eq!(ctx.id() % 100, 5, "should match with python implementation");
603
604 let mut ctx = FeatureContext::new();
605 ctx.insert("foo", json!("bar"));
606 ctx.insert("baz", json!("barfoo"));
607 ctx.identity_fields(vec!["foo"]);
608 assert_eq!(ctx.id() % 100, 62);
609
610 let mut ctx = FeatureContext::new();
612 ctx.insert("foo", json!("bar"));
613 ctx.insert("baz", json!("barfoo"));
614 ctx.identity_fields(vec!["foo", "whoops"]);
615 assert_eq!(ctx.id() % 100, 62);
616
617 let mut ctx = FeatureContext::new();
618 ctx.insert("foo", json!("bar"));
619 ctx.insert("baz", json!("barfoo"));
620 ctx.identity_fields(vec!["foo", "baz"]);
621 assert_eq!(ctx.id() % 100, 1);
622
623 let mut ctx = FeatureContext::new();
624 ctx.insert("foo", json!("bar"));
625 ctx.insert("baz", json!("barfoo"));
626 ctx.identity_fields(vec!["whoops", "nope"]);
629 assert_eq!(ctx.id() % 100, 1);
630 }
631
632 #[test]
633 fn test_feature_prefix_is_added() {
634 let cond = in_condition("organization_id", "123");
635 let (opts, _t) = setup_feature_options(&feature_json(true, 100, &cond));
636
637 let mut ctx = FeatureContext::new();
638 ctx.insert("organization_id", json!(123));
639
640 assert!(check(&opts, "organizations:test-feature", &ctx));
641 }
642
643 #[test]
644 fn test_undefined_feature_returns_false() {
645 let cond = in_condition("organization_id", "123");
646 let (opts, _t) = setup_feature_options(&feature_json(true, 100, &cond));
647
648 let ctx = FeatureContext::new();
649 assert!(!check(&opts, "nonexistent", &ctx));
650 }
651
652 #[test]
653 fn test_missing_context_field_returns_false() {
654 let cond = in_condition("organization_id", "123");
655 let (opts, _t) = setup_feature_options(&feature_json(true, 100, &cond));
656
657 let ctx = FeatureContext::new();
658 assert!(!check(&opts, "organizations:test-feature", &ctx));
659 }
660
661 #[test]
662 fn test_matching_context_returns_true() {
663 let cond = in_condition("organization_id", "123, 456");
664 let (opts, _t) = setup_feature_options(&feature_json(true, 100, &cond));
665
666 let mut ctx = FeatureContext::new();
667 ctx.insert("organization_id", json!(123));
668
669 assert!(check(&opts, "organizations:test-feature", &ctx));
670 }
671
672 #[test]
673 fn test_non_matching_context_returns_false() {
674 let cond = in_condition("organization_id", "123, 456");
675 let (opts, _t) = setup_feature_options(&feature_json(true, 100, &cond));
676
677 let mut ctx = FeatureContext::new();
678 ctx.insert("organization_id", json!(999));
679
680 assert!(!check(&opts, "organizations:test-feature", &ctx));
681 }
682
683 #[test]
684 fn test_disabled_feature_returns_false() {
685 let cond = in_condition("organization_id", "123");
686 let (opts, _t) = setup_feature_options(&feature_json(false, 100, &cond));
687
688 let mut ctx = FeatureContext::new();
689 ctx.insert("organization_id", json!(123));
690
691 assert!(!check(&opts, "organizations:test-feature", &ctx));
692 }
693
694 #[test]
695 fn test_rollout_zero_returns_false() {
696 let cond = in_condition("organization_id", "123");
697 let (opts, _t) = setup_feature_options(&feature_json(true, 0, &cond));
698
699 let mut ctx = FeatureContext::new();
700 ctx.insert("organization_id", json!(123));
701
702 assert!(!check(&opts, "organizations:test-feature", &ctx));
703 }
704
705 #[test]
706 fn test_rollout_100_returns_true() {
707 let cond = in_condition("organization_id", "123");
708 let (opts, _t) = setup_feature_options(&feature_json(true, 100, &cond));
709
710 let mut ctx = FeatureContext::new();
711 ctx.insert("organization_id", json!(123));
712
713 assert!(check(&opts, "organizations:test-feature", &ctx));
714 }
715
716 #[test]
717 fn test_rollout_is_deterministic() {
718 let mut ctx = FeatureContext::new();
719 ctx.identity_fields(vec!["user_id"]);
720 ctx.insert("user_id", json!(42));
721 ctx.insert("organization_id", json!(123));
722
723 let id_mod = (ctx.id() % 100) + 1;
725 let cond = in_condition("organization_id", "123");
726
727 let (opts_at, _t1) = setup_feature_options(&feature_json(true, id_mod, &cond));
728 assert!(check(&opts_at, "organizations:test-feature", &ctx));
729 }
730
731 #[test]
732 fn test_condition_in_string_case_insensitive() {
733 let cond = r#"{"property": "slug", "operator": "in", "value": ["Sentry", "ACME"]}"#;
734 let (opts, _t) = setup_feature_options(&feature_json(true, 100, cond));
735
736 let mut ctx = FeatureContext::new();
737 ctx.insert("slug", json!("sentry"));
738 assert!(check(&opts, "organizations:test-feature", &ctx));
739 }
740
741 #[test]
742 fn test_condition_not_in() {
743 let cond = r#"{"property": "organization_id", "operator": "not_in", "value": [999]}"#;
744 let (opts, _t) = setup_feature_options(&feature_json(true, 100, cond));
745
746 let mut ctx = FeatureContext::new();
747 ctx.insert("organization_id", json!(123));
748 assert!(check(&opts, "organizations:test-feature", &ctx));
749
750 let mut ctx2 = FeatureContext::new();
751 ctx2.insert("organization_id", json!(999));
752 assert!(!check(&opts, "organizations:test-feature", &ctx2));
753 }
754
755 #[test]
756 fn test_condition_contains() {
757 let cond = r#"{"property": "tags", "operator": "contains", "value": "beta"}"#;
758 let (opts, _t) = setup_feature_options(&feature_json(true, 100, cond));
759
760 let mut ctx = FeatureContext::new();
761 ctx.insert("tags", json!(["alpha", "beta"]));
762 assert!(check(&opts, "organizations:test-feature", &ctx));
763
764 let mut ctx2 = FeatureContext::new();
765 ctx2.insert("tags", json!(["alpha"]));
766 assert!(!check(&opts, "organizations:test-feature", &ctx2));
767 }
768
769 #[test]
770 fn test_condition_equals() {
771 let cond = r#"{"property": "plan", "operator": "equals", "value": "enterprise"}"#;
772 let (opts, _t) = setup_feature_options(&feature_json(true, 100, cond));
773
774 let mut ctx = FeatureContext::new();
775 ctx.insert("plan", json!("Enterprise"));
776 assert!(check(&opts, "organizations:test-feature", &ctx));
777
778 let mut ctx2 = FeatureContext::new();
779 ctx2.insert("plan", json!("free"));
780 assert!(!check(&opts, "organizations:test-feature", &ctx2));
781 }
782
783 #[test]
784 fn test_condition_equals_bool() {
785 let cond = r#"{"property": "is_free", "operator": "equals", "value": true}"#;
786 let (opts, _t) = setup_feature_options(&feature_json(true, 100, cond));
787
788 let mut ctx = FeatureContext::new();
789 ctx.insert("is_free", json!(true));
790 assert!(check(&opts, "organizations:test-feature", &ctx));
791
792 let mut ctx2 = FeatureContext::new();
793 ctx2.insert("is_free", json!(false));
794 assert!(!check(&opts, "organizations:test-feature", &ctx2));
795 }
796
797 #[test]
798 fn test_segment_with_no_conditions_always_matches() {
799 let feature = r#"{
800 "name": "test-feature",
801 "enabled": true,
802 "owner": {"team": "test-team"},
803 "created_at": "2024-01-01",
804 "segments": [{"name": "open", "rollout": 100, "conditions": []}]
805 }"#;
806 let (opts, _t) = setup_feature_options(feature);
807
808 let ctx = FeatureContext::new();
809 assert!(check(&opts, "organizations:test-feature", &ctx));
810 }
811
812 #[test]
813 fn test_feature_enabled_and_rollout_default_values() {
814 let feature = r#"{
816 "name": "test-feature",
817 "owner": {"team": "test-team"},
818 "created_at": "2024-01-01",
819 "segments": [
820 {
821 "name": "first",
822 "conditions": [{"property": "org_id", "operator": "in", "value":[1]}]
823 }
824 ]
825 }"#;
826 let (opts, _t) = setup_feature_options(feature);
827
828 let mut ctx = FeatureContext::new();
829 ctx.insert("org_id", 1);
830 ctx.identity_fields(vec!["org_id"]);
831 assert!(check(&opts, "organizations:test-feature", &ctx));
832 }
833
834 #[test]
835 fn test_feature_with_no_segments_returns_false() {
836 let feature = r#"{
837 "name": "test-feature",
838 "enabled": true,
839 "owner": {"team": "test-team"},
840 "created_at": "2024-01-01",
841 "segments": []
842 }"#;
843 let (opts, _t) = setup_feature_options(feature);
844
845 let ctx = FeatureContext::new();
846 assert!(!check(&opts, "organizations:test-feature", &ctx));
847 }
848
849 #[test]
850 fn test_multiple_segments_or_logic() {
851 let feature = r#"{
852 "name": "test-feature",
853 "enabled": true,
854 "owner": {"team": "test-team"},
855 "created_at": "2024-01-01",
856 "segments": [
857 {
858 "name": "segment-a",
859 "rollout": 100,
860 "conditions": [{"property": "org_id", "operator": "in", "value": [1]}]
861 },
862 {
863 "name": "segment-b",
864 "rollout": 100,
865 "conditions": [{"property": "org_id", "operator": "in", "value": [2]}]
866 }
867 ]
868 }"#;
869 let (opts, _t) = setup_feature_options(feature);
870
871 let mut ctx1 = FeatureContext::new();
872 ctx1.insert("org_id", json!(1));
873 assert!(check(&opts, "organizations:test-feature", &ctx1));
874
875 let mut ctx2 = FeatureContext::new();
876 ctx2.insert("org_id", json!(2));
877 assert!(check(&opts, "organizations:test-feature", &ctx2));
878
879 let mut ctx3 = FeatureContext::new();
880 ctx3.insert("org_id", json!(3));
881 assert!(!check(&opts, "organizations:test-feature", &ctx3));
882 }
883
884 #[test]
885 fn test_multiple_conditions_and_logic() {
886 let conds = r#"
887 {"property": "org_id", "operator": "in", "value": [123]},
888 {"property": "user_email", "operator": "in", "value": ["admin@example.com"]}
889 "#;
890 let (opts, _t) = setup_feature_options(&feature_json(true, 100, conds));
891
892 let mut ctx = FeatureContext::new();
893 ctx.insert("org_id", json!(123));
894 ctx.insert("user_email", json!("admin@example.com"));
895 assert!(check(&opts, "organizations:test-feature", &ctx));
896
897 let mut ctx2 = FeatureContext::new();
898 ctx2.insert("org_id", json!(123));
899 ctx2.insert("user_email", json!("other@example.com"));
900 assert!(!check(&opts, "organizations:test-feature", &ctx2));
901 }
902
903 #[test]
904 fn test_in_int_context_against_string_list_returns_false() {
905 let cond = r#"{"property": "org_id", "operator": "in", "value": ["123", "456"]}"#;
906 let (opts, _t) = setup_feature_options(&feature_json(true, 100, cond));
907
908 let mut ctx = FeatureContext::new();
909 ctx.insert("org_id", json!(123));
910 assert!(!check(&opts, "organizations:test-feature", &ctx));
911 }
912
913 #[test]
914 fn test_in_string_context_against_int_list_returns_false() {
915 let cond = r#"{"property": "slug", "operator": "in", "value": [123, 456]}"#;
916 let (opts, _t) = setup_feature_options(&feature_json(true, 100, cond));
917
918 let mut ctx = FeatureContext::new();
919 ctx.insert("slug", json!("123"));
920 assert!(!check(&opts, "organizations:test-feature", &ctx));
921 }
922
923 #[test]
924 fn test_in_bool_context_against_string_list_returns_false() {
925 let cond = r#"{"property": "active", "operator": "in", "value": ["true", "false"]}"#;
926 let (opts, _t) = setup_feature_options(&feature_json(true, 100, cond));
927
928 let mut ctx = FeatureContext::new();
929 ctx.insert("active", json!(true));
930 assert!(!check(&opts, "organizations:test-feature", &ctx));
931 }
932
933 #[test]
934 fn test_in_float_context_against_string_list_returns_false() {
935 let cond = r#"{"property": "score", "operator": "in", "value": ["0.5", "1.0"]}"#;
936 let (opts, _t) = setup_feature_options(&feature_json(true, 100, cond));
937
938 let mut ctx = FeatureContext::new();
939 ctx.insert("score", json!(0.5));
940 assert!(!check(&opts, "organizations:test-feature", &ctx));
941 }
942
943 #[test]
944 fn test_not_in_int_context_against_string_list_returns_true() {
945 let cond = r#"{"property": "org_id", "operator": "not_in", "value": ["123", "456"]}"#;
947 let (opts, _t) = setup_feature_options(&feature_json(true, 100, cond));
948
949 let mut ctx = FeatureContext::new();
950 ctx.insert("org_id", json!(123));
951 assert!(check(&opts, "organizations:test-feature", &ctx));
952 }
953
954 #[test]
955 fn test_not_in_string_context_against_int_list_returns_true() {
956 let cond = r#"{"property": "slug", "operator": "not_in", "value": [123, 456]}"#;
958 let (opts, _t) = setup_feature_options(&feature_json(true, 100, cond));
959
960 let mut ctx = FeatureContext::new();
961 ctx.insert("slug", json!("123"));
962 assert!(check(&opts, "organizations:test-feature", &ctx));
963 }
964}