rototo 0.1.0-alpha.8

Control plane for runtime configuration of your application.
Documentation
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
use std::collections::BTreeSet;

use serde::Serialize;
use serde_json::Value as JsonValue;

use crate::error::{Result, RototoError};
use crate::lint::{RuntimePackage, compile_runtime_package, parse_arm_buckets};
use crate::model::{
    AllocationInspectReport, PackageInspectReport, PackageInspectRequest, RulePathwayInspectReport,
    VariableInspectReport, VariableResolutionTrace,
};
use crate::resolve::{allocation_bucket, trace_variable_unchecked};
use crate::source::{SourceOptions, stage_package_source};

mod context_factory;
mod render;

use context_factory::ContextFactory;

pub use render::{ContextForm, render_command, render_comment};

#[derive(Clone, Debug, Default)]
pub struct FixtureGenerateSelection {
    pub variables: FixtureTargetSelection,
}

impl FixtureGenerateSelection {
    pub fn all() -> Self {
        Self {
            variables: FixtureTargetSelection::All,
        }
    }

    fn normalized(self) -> Self {
        if self.variables.is_none() {
            Self::all()
        } else {
            self
        }
    }
}

#[derive(Clone, Debug, Default)]
pub enum FixtureTargetSelection {
    #[default]
    None,
    Some(BTreeSet<String>),
    All,
}

impl FixtureTargetSelection {
    pub fn some(values: impl IntoIterator<Item = String>) -> Self {
        Self::Some(values.into_iter().collect())
    }

    fn is_none(&self) -> bool {
        matches!(self, Self::None)
    }
}

/// A single `rototo resolve` invocation that exercises one behavior case of a
/// variable. The CLI renders these into runnable command lines;
/// nothing is persisted to disk.
#[derive(Clone, Debug)]
pub struct ResolveInvocation {
    pub target: ResolveTarget,
    pub case_id: String,
    pub title: String,
    pub because: Option<String>,
    pub context: JsonValue,
    pub expect: ResolveExpectation,
}

#[derive(Clone, Debug)]
pub enum ResolveTarget {
    Variable(String),
}

impl ResolveTarget {
    /// The `kind:id` label used in headers and JSON output.
    pub fn label(&self) -> String {
        match self {
            Self::Variable(id) => format!("variable:{id}"),
        }
    }

    /// The resolve selector flag that targets this entity.
    pub fn selector_flag(&self) -> &'static str {
        match self {
            Self::Variable(_) => "--variable",
        }
    }

    pub fn id(&self) -> &str {
        match self {
            Self::Variable(id) => id,
        }
    }
}

/// The expected result of a printed invocation, used to annotate each command
/// with its resolution outcome.
#[derive(Clone, Debug, Serialize)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum ResolveExpectation {
    Variable {
        value: JsonValue,
        matched: MatchedBy,
    },
}

#[derive(Clone, Debug, Serialize)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum MatchedBy {
    Default,
    Rule { index: usize, condition: String },
    Arm { allocation: String, arm: String },
}

pub async fn generate_resolve_invocations(
    package_source: impl AsRef<str>,
    source_options: &SourceOptions,
    selection: FixtureGenerateSelection,
) -> Result<Vec<ResolveInvocation>> {
    let package_source = package_source.as_ref();
    let selection = selection.normalized();
    let staged = stage_package_source(package_source.to_owned(), source_options).await?;
    let report =
        crate::inspect_package_report(staged.path(), PackageInspectRequest::default()).await?;

    let variable_ids = selected_variable_ids(&report, &selection.variables)?;
    let factory = ContextFactory::new(&report);
    // The fixture hunt traces many candidate contexts per variable; one
    // compiled runtime serves them all instead of recompiling per trace.
    let runtime = compile_runtime_package(staged.path()).await?;

    let mut invocations = Vec::new();

    for id in variable_ids {
        let variable = report
            .variables
            .iter()
            .find(|variable| variable.id == id)
            .expect("selected variable id was validated");
        generate_variable_invocations(&runtime, variable, &factory, &mut invocations)?;
    }

    Ok(invocations)
}

/// One traced resolution against the shared compiled runtime, with the same
/// per-variable context validation `trace_variable_resolution` performs.
fn trace_candidate(
    runtime: &RuntimePackage,
    id: &str,
    context: &JsonValue,
) -> Result<VariableResolutionTrace> {
    runtime.validate_context_for_variable(id, context)?;
    trace_variable_unchecked(runtime, id, context)
}

fn selected_variable_ids(
    report: &PackageInspectReport,
    selection: &FixtureTargetSelection,
) -> Result<Vec<String>> {
    selected_ids(
        selection,
        report.variables.iter().map(|variable| variable.id.as_str()),
        "variable",
    )
}

fn selected_ids<'a>(
    selection: &FixtureTargetSelection,
    available: impl Iterator<Item = &'a str>,
    kind: &str,
) -> Result<Vec<String>> {
    let available = available.map(str::to_owned).collect::<Vec<_>>();
    match selection {
        FixtureTargetSelection::None => Ok(Vec::new()),
        FixtureTargetSelection::All => Ok(available),
        FixtureTargetSelection::Some(ids) => {
            for id in ids {
                if !available.iter().any(|available| available == id) {
                    return Err(RototoError::new(format!("{kind} not found: {kind}://{id}")));
                }
            }
            Ok(available
                .into_iter()
                .filter(|id| ids.contains(id))
                .collect())
        }
    }
}

fn generate_variable_invocations(
    runtime: &RuntimePackage,
    variable: &VariableInspectReport,
    factory: &ContextFactory,
    out: &mut Vec<ResolveInvocation>,
) -> Result<()> {
    let target = ResolveTarget::Variable(variable.id.clone());

    if variable.resolve.method == "allocation" {
        if let Some(allocation) = &variable.resolve.allocation {
            generate_allocation_invocations(runtime, variable, allocation, factory, out)?;
        }
        return Ok(());
    }

    if let Some(context) = variable_default_context(runtime, variable, factory)? {
        let trace = trace_candidate(runtime, &variable.id, &context)?;
        if trace.rules.iter().any(|rule| rule.matched) {
            return Err(RototoError::new(format!(
                "generated default fixture matched a rule for variable: {}",
                variable.id
            )));
        }
        out.push(ResolveInvocation {
            target: target.clone(),
            case_id: "default".to_owned(),
            title: "Uses the default value when no rule matches".to_owned(),
            because: Some("Every rule condition is false.".to_owned()),
            context,
            expect: variable_expectation(&trace),
        });
    }

    for rule in &variable.resolve.rules {
        let Some(context) = variable_rule_context(runtime, variable, rule, factory)? else {
            continue;
        };
        let trace = trace_candidate(runtime, &variable.id, &context)?;
        if !trace
            .rules
            .iter()
            .any(|trace_rule| trace_rule.index == rule.index && trace_rule.matched)
        {
            continue;
        }
        let condition = rule_condition_label(rule);
        let case_id = format!("rule-{}-{}", rule.index, sanitize_id(&condition));
        let title = format!(
            "Rule {} selects {} when {} matches",
            rule.index,
            rule.value
                .as_ref()
                .map(serde_json::Value::to_string)
                .unwrap_or_else(|| "<missing>".to_owned()),
            condition
        );
        out.push(ResolveInvocation {
            target: target.clone(),
            case_id,
            title,
            because: Some("Earlier rule conditions are kept false when possible.".to_owned()),
            context,
            expect: variable_expectation(&trace),
        });
    }

    Ok(())
}

/// How many candidate unit ids to hash while hunting for one that lands in an
/// arm's bucket range. Arms claiming at least ~1/1000 of the line are found
/// comfortably; narrower arms are skipped rather than searched forever.
const MAX_UNIT_CANDIDATES: u32 = 8192;

/// Fixture cases for a `method = "allocation"` variable: one unit id per arm
/// (found by hashing candidates against the layer's diversion, exactly the way
/// resolution will) plus a no-arm case that lands on the default.
fn generate_allocation_invocations(
    runtime: &RuntimePackage,
    variable: &VariableInspectReport,
    allocation: &AllocationInspectReport,
    factory: &ContextFactory,
    out: &mut Vec<ResolveInvocation>,
) -> Result<()> {
    let target = ResolveTarget::Variable(variable.id.clone());

    // The no-arm case: the unit is not enrolled or lands in unclaimed buckets.
    for context in factory.candidates_for(&variable.id) {
        if let Ok(trace) = trace_candidate(runtime, &variable.id, context)
            && trace
                .allocation
                .as_ref()
                .is_none_or(|allocation| allocation.arm.is_none())
        {
            out.push(ResolveInvocation {
                target: target.clone(),
                case_id: "default".to_owned(),
                title: "Uses the default value when the unit is in no arm".to_owned(),
                because: Some("The unit is not enrolled or lands in unclaimed buckets.".to_owned()),
                context: context.clone(),
                expect: variable_expectation(&trace),
            });
            break;
        }
    }

    let (Some(layer), Some(unit), Some(buckets)) =
        (&allocation.layer, &allocation.unit, allocation.buckets)
    else {
        return Ok(());
    };
    if buckets < 1 {
        return Ok(());
    }
    let buckets = buckets as u32;
    // Synthesis places the unit value at the diversion's context path, so it
    // only works when `unit` is a plain path like `context.user.id`.
    let Some(unit_path) = plain_context_path(unit) else {
        return Ok(());
    };

    for arm in &allocation.arms {
        let (Some(name), Some(range)) = (&arm.name, &arm.buckets) else {
            continue;
        };
        let Some((start, end)) = parse_arm_buckets(range) else {
            continue;
        };
        let Some(unit_value) = (0..MAX_UNIT_CANDIDATES).find_map(|index| {
            let candidate = format!("{name}-unit-{index:04}");
            let bucket = allocation_bucket(layer, &JsonValue::String(candidate.clone()), buckets);
            (bucket >= start && bucket <= end).then_some(candidate)
        }) else {
            continue;
        };

        // Verify by real resolution against each candidate base context; the
        // first base that enrolls the unit (eligibility can depend on other
        // context facts) wins.
        for base in factory.candidates_for(&variable.id) {
            let mut context = base.clone();
            set_context_path(
                &mut context,
                &unit_path,
                JsonValue::String(unit_value.clone()),
            );
            let Ok(trace) = trace_candidate(runtime, &variable.id, &context) else {
                continue;
            };
            let assigned = trace
                .allocation
                .as_ref()
                .and_then(|allocation| allocation.arm.as_deref());
            if assigned != Some(name.as_str()) {
                continue;
            }
            let value = trace.resolution.value.clone();
            out.push(ResolveInvocation {
                target: target.clone(),
                case_id: format!("arm-{}", sanitize_id(name)),
                title: format!("Arm {name} assigns {value} when the unit lands in its buckets"),
                because: Some(format!(
                    "The unit id hashes into buckets {range} of layer {layer}."
                )),
                context,
                expect: variable_expectation(&trace),
            });
            break;
        }
    }

    Ok(())
}

/// `context.a.b` as its path segments, or `None` when the expression is not a
/// plain dotted context path.
fn plain_context_path(source: &str) -> Option<Vec<String>> {
    let path = source.trim().strip_prefix("context.")?;
    let segments: Vec<String> = path.split('.').map(str::to_owned).collect();
    segments
        .iter()
        .all(|segment| {
            !segment.is_empty()
                && segment
                    .chars()
                    .all(|ch| ch.is_ascii_alphanumeric() || ch == '_')
        })
        .then_some(segments)
}

/// Force-set a dotted path in a context object, replacing whatever value the
/// base context carried there.
fn set_context_path(context: &mut JsonValue, path: &[String], value: JsonValue) {
    if !context.is_object() {
        *context = JsonValue::Object(serde_json::Map::new());
    }
    let mut current = context;
    for segment in &path[..path.len() - 1] {
        let object = current.as_object_mut().expect("object ensured above");
        let entry = object
            .entry(segment.clone())
            .or_insert_with(|| JsonValue::Object(serde_json::Map::new()));
        if !entry.is_object() {
            *entry = JsonValue::Object(serde_json::Map::new());
        }
        current = entry;
    }
    current
        .as_object_mut()
        .expect("object ensured above")
        .insert(path[path.len() - 1].clone(), value);
}

fn variable_expectation(trace: &VariableResolutionTrace) -> ResolveExpectation {
    if let Some(allocation) = &trace.allocation
        && let Some(arm) = &allocation.arm
    {
        return ResolveExpectation::Variable {
            value: trace.resolution.value.clone(),
            matched: MatchedBy::Arm {
                allocation: allocation.allocation.clone(),
                arm: arm.clone(),
            },
        };
    }
    let matched = trace.rules.iter().find(|rule| rule.matched);
    ResolveExpectation::Variable {
        value: trace.resolution.value.clone(),
        matched: match matched {
            Some(rule) => MatchedBy::Rule {
                index: rule.index,
                condition: rule.condition.clone(),
            },
            None => MatchedBy::Default,
        },
    }
}

fn rule_condition_label(rule: &RulePathwayInspectReport) -> String {
    rule.when.as_deref().unwrap_or("<missing>").to_owned()
}

/// The first candidate context that drives `rule` to win for `variable`.
/// Selection is by real resolution, so the rule under test must be the one that
/// actually matches (earlier rules kept false), not merely have a true `when`.
fn variable_rule_context(
    runtime: &RuntimePackage,
    variable: &VariableInspectReport,
    rule: &RulePathwayInspectReport,
    factory: &ContextFactory,
) -> Result<Option<JsonValue>> {
    for context in factory.candidates_for(&variable.id) {
        if let Ok(trace) = trace_candidate(runtime, &variable.id, context)
            && trace
                .rules
                .iter()
                .any(|trace_rule| trace_rule.index == rule.index && trace_rule.matched)
        {
            return Ok(Some(context.clone()));
        }
    }

    Ok(None)
}

/// The first candidate context under which no rule matches, so `variable`
/// resolves to its default.
fn variable_default_context(
    runtime: &RuntimePackage,
    variable: &VariableInspectReport,
    factory: &ContextFactory,
) -> Result<Option<JsonValue>> {
    for context in factory.candidates_for(&variable.id) {
        if let Ok(trace) = trace_candidate(runtime, &variable.id, context)
            && trace.rules.iter().all(|rule| !rule.matched)
        {
            return Ok(Some(context.clone()));
        }
    }

    Ok(None)
}

fn sanitize_id(value: &str) -> String {
    let mut sanitized = String::new();
    for ch in value.chars() {
        if ch.is_ascii_alphanumeric() {
            sanitized.push(ch.to_ascii_lowercase());
        } else if matches!(ch, '-' | '_' | '.') {
            sanitized.push('-');
        }
    }
    let sanitized = sanitized.trim_matches('-').to_owned();
    if sanitized.is_empty() {
        "fixture".to_owned()
    } else {
        sanitized
    }
}