-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy patheval_assignment.rs
More file actions
325 lines (281 loc) · 10.6 KB
/
eval_assignment.rs
File metadata and controls
325 lines (281 loc) · 10.6 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
// Copyright 2025-Present Datadog, Inc. https://www.datadoghq.com/
// SPDX-License-Identifier: Apache-2.0
use chrono::{DateTime, Utc};
use crate::rules_based::{
error::EvaluationError,
ufc::{Allocation, Assignment, AssignmentReason, CompiledFlagsConfig, Flag, Shard, Split},
Configuration, EvaluationContext, ExpectedFlagType, Timestamp,
};
/// Evaluate the specified feature flag for the given subject and return assigned variation and
/// an optional assignment event for logging.
pub fn get_assignment(
configuration: Option<&Configuration>,
flag_key: &str,
subject: &EvaluationContext,
expected_type: ExpectedFlagType,
now: DateTime<Utc>,
) -> Result<Assignment, EvaluationError> {
let Some(config) = configuration else {
log::trace!(
flag_key,
targeting_key = subject.targeting_key();
"returning default assignment because of: {}", EvaluationError::ConfigurationMissing);
return Err(EvaluationError::ConfigurationMissing);
};
config.eval_flag(flag_key, subject, expected_type, now)
}
impl Configuration {
pub fn eval_flag(
&self,
flag_key: &str,
context: &EvaluationContext,
expected_type: ExpectedFlagType,
now: DateTime<Utc>,
) -> Result<Assignment, EvaluationError> {
let result = self
.flags
.compiled
.eval_flag(flag_key, context, expected_type, now);
match &result {
Ok(assignment) => {
log::trace!(
flag_key,
targeting_key = context.targeting_key(),
assignment:? = assignment.value;
"evaluated a flag");
}
Err(err) => {
log::trace!(
flag_key,
targeting_key = context.targeting_key();
"returning default assignment because of: {err}");
}
}
result
}
}
impl CompiledFlagsConfig {
/// Evaluate the flag for the given subject, expecting `expected_type` type.
fn eval_flag(
&self,
flag_key: &str,
subject: &EvaluationContext,
expected_type: ExpectedFlagType,
now: DateTime<Utc>,
) -> Result<Assignment, EvaluationError> {
self.get_flag(flag_key)?.eval(subject, expected_type, now)
}
fn get_flag(&self, flag_key: &str) -> Result<&Flag, EvaluationError> {
self.flags
.get(flag_key)
.ok_or(EvaluationError::FlagUnrecognizedOrDisabled)?
.as_ref()
.map_err(Clone::clone)
}
}
impl Flag {
fn eval(
&self,
context: &EvaluationContext,
expected_type: ExpectedFlagType,
now: DateTime<Utc>,
) -> Result<Assignment, EvaluationError> {
if !expected_type.is_compatible(self.variation_type.into()) {
return Err(EvaluationError::TypeMismatch {
expected: expected_type,
found: self.variation_type.into(),
});
}
let (allocation, split, reason) = self.find_allocation(context, now)?;
Ok(Assignment {
value: split.value.clone(),
variation_key: split.variation_key.clone(),
allocation_key: allocation.key.clone(),
extra_logging: split.extra_logging.clone(),
reason,
do_log: allocation.do_log,
})
}
fn find_allocation(
&self,
context: &EvaluationContext,
now: DateTime<Utc>,
) -> Result<(&Allocation, &Split, AssignmentReason), EvaluationError> {
for allocation in &self.allocations {
if let Some((split, reason)) = allocation.get_matching_split(context, now)? {
return Ok((allocation, split, reason));
}
}
Err(EvaluationError::DefaultAllocationNull)
}
}
impl Allocation {
fn get_matching_split(
&self,
context: &EvaluationContext,
now: Timestamp,
) -> Result<Option<(&Split, AssignmentReason)>, EvaluationError> {
if self.start_at.is_some_and(|t| now < t) {
return Ok(None);
}
if self.end_at.is_some_and(|t| now > t) {
return Ok(None);
}
let is_allowed_by_rules =
self.rules.is_empty() || self.rules.iter().any(|rule| rule.eval(context));
if !is_allowed_by_rules {
return Ok(None);
}
let Some(split) = self.find_split(context)? else {
return Ok(None);
};
// Determine the reason for assignment
let reason = if !self.rules.is_empty() {
AssignmentReason::TargetingMatch
} else if self.splits.len() == 1 && self.splits[0].shards.is_empty() {
AssignmentReason::Static
} else {
AssignmentReason::Split
};
Ok(Some((split, reason)))
}
fn find_split(&self, subject: &EvaluationContext) -> Result<Option<&Split>, EvaluationError> {
let targeting_key = subject.targeting_key().map(|it| it.as_str());
for split in &self.splits {
if split.matches(targeting_key)? {
return Ok(Some(split));
}
}
Ok(None)
}
}
impl Split {
/// Return `true` if `targeting_key` matches the given split.
///
/// To match a split, subject must match all underlying shards.
fn matches(&self, targeting_key: Option<&str>) -> Result<bool, EvaluationError> {
if self.shards.is_empty() {
return Ok(true);
}
let Some(targeting_key) = targeting_key else {
return Err(EvaluationError::TargetingKeyMissing);
};
Ok(self.shards.iter().all(|shard| shard.matches(targeting_key)))
}
}
impl Shard {
/// Return `true` if `targeting_key` matches the given shard.
fn matches(&self, targeting_key: &str) -> bool {
let h = self.sharder.shard(&[targeting_key]);
self.ranges.iter().any(|range| range.contains(h))
}
}
#[cfg(test)]
mod tests {
use std::{
collections::HashMap,
fs::{self, File},
sync::Arc,
};
use chrono::Utc;
use serde::{Deserialize, Serialize};
use crate::rules_based::{
error::EvaluationError,
eval::get_assignment,
ufc::{AssignmentReason, AssignmentValue, UniversalFlagConfig},
Attribute, Configuration, EvaluationContext, FlagType, Str,
};
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct TestCase {
flag: String,
variation_type: FlagType,
default_value: Arc<serde_json::value::RawValue>,
targeting_key: Option<Str>,
attributes: Arc<HashMap<Str, Attribute>>,
result: TestResult,
}
#[derive(Debug, Serialize, Deserialize)]
struct TestResult {
value: Arc<serde_json::value::RawValue>,
#[serde(default)]
reason: Option<String>,
}
/// Known reason overrides where Rust's shard optimization produces a different
/// (but equally valid) reason than the canonical Go-derived fixtures.
///
/// Rust collapses insignificant shards (single split covering 100% of traffic)
/// to STATIC, whereas Go reports SPLIT. Both are correct interpretations.
/// Key: (flag, targeting_key) -> expected_reason for Rust.
fn known_reason_overrides() -> HashMap<(&'static str, &'static str), &'static str> {
HashMap::from([(("empty_string_flag", "bob"), "STATIC")])
}
#[test]
#[cfg_attr(miri, ignore)] // this test is way too slow on miri
fn evaluation_sdk_test_data() {
let _ = env_logger::builder().is_test(true).try_init();
let config = UniversalFlagConfig::from_json(
std::fs::read("ffe-system-test-data/ufc-config.json").unwrap(),
)
.unwrap();
let config = Configuration::from_server_response(config);
let now = Utc::now();
let reason_overrides = known_reason_overrides();
for entry in fs::read_dir("ffe-system-test-data/evaluation-cases/").unwrap() {
let entry = entry.unwrap();
println!("Processing test file: {:?}", entry.path());
let f = File::open(entry.path()).unwrap();
let test_cases: Vec<TestCase> = serde_json::from_reader(f).unwrap();
for test_case in test_cases {
let default_assignment = AssignmentValue::from_wire(
test_case.variation_type.into(),
test_case.default_value,
)
.unwrap();
print!("test subject {:?} ... ", test_case.targeting_key);
let subject = EvaluationContext::new(test_case.targeting_key, test_case.attributes);
let result = get_assignment(
Some(&config),
&test_case.flag,
&subject,
test_case.variation_type.into(),
now,
);
let result_assingment = result
.as_ref()
.map(|assignment| &assignment.value)
.unwrap_or(&default_assignment);
let expected_assignment = AssignmentValue::from_wire(
test_case.variation_type.into(),
test_case.result.value,
)
.unwrap();
assert_eq!(result_assingment, &expected_assignment);
if let Some(expected_reason) = &test_case.result.reason {
let actual_reason = match &result {
Ok(assignment) => match assignment.reason {
AssignmentReason::TargetingMatch => "TARGETING_MATCH",
AssignmentReason::Split => "SPLIT",
AssignmentReason::Static => "STATIC",
},
Err(EvaluationError::FlagDisabled) => "DISABLED",
Err(_) => "DEFAULT",
};
let tk = subject.targeting_key().map(|s| s.as_ref()).unwrap_or("");
let effective_expected = reason_overrides
.get(&(test_case.flag.as_str(), tk))
.copied()
.unwrap_or(expected_reason.as_str());
assert_eq!(
actual_reason,
effective_expected,
"reason mismatch for flag '{}' targeting_key '{:?}'",
test_case.flag,
subject.targeting_key()
);
}
println!("ok");
}
}
}
}