rift-mock-core 0.25.0

Rift core engine: imposter lifecycle, matching, behaviors, scripting and flow-state — usable in-process without the CLI or admin server.
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
//! Declarative post-response state operations (issue #969): `_rift.stateOps` on an `is`
//! response — `set` / `increment` / `delete` / `clearFlow` against the request's resolved flow id,
//! without a script.
//!
//! Reading flow state is declarative (`{{ state.<key> }}` under `_rift.templated`); until this
//! module, writing it was code — an `inject`/`_rift.script` response, with the injection gate, a
//! script engine on the request path and a body of JS/Rhai for one line of intent. These are data,
//! evaluated by the already-ungated `{{ }}` grammar, so they carry none of that.
//!
//! Semantics, all pinned by tests:
//!
//! - **When:** after the `is` response is fully rendered (templates, behaviors), just before it is
//!   written. A body reading `{{ state.hits }}` in the same response therefore sees the value
//!   *before* this request's ops — the WireMock semantics, and the one that makes "show the count,
//!   then bump it" expressible.
//! - **Order:** sequential, in the array's order; a later op sees an earlier op's write.
//! - **`increment`** is `FlowStore::increment_by`: atomic on every backend that has one, so a
//!   counter never loses a bump under concurrency. Never renders anything.
//! - **`set`** renders `value` in the `{{ }}` grammar plus one extra head, `previousValue` — the
//!   key's value before this operation, empty when it had none. A `set` whose value *reads the key
//!   it writes* — through `previousValue`, or through `state.<that key>` — is a bounded
//!   compare-and-set loop (read → render → CAS on the value read; retry on conflict, up to
//!   [`CAS_ATTEMPTS`]), so concurrent read-modify-writes never lose one; a `set` that reads no
//!   prior value is a plain write. The decision is made from the template's heads
//!   ([`template_heads`]), not from a substring search. The `FlowStore` trait's *default* CAS is
//!   get-then-set (not atomic) — both shipped backends override it atomically — which is why the
//!   loop is bounded and the semantics are the contract a backend meets, not something only one
//!   provides.
//! - **What `set` stores.** A rendered value that is exactly a canonical integer (`"42"`, `"-3"`,
//!   `"0"` — not `"007"`, not `"4.5"`) is stored as a JSON number, anything else as a string. That
//!   is what lets `set hits "0"` seed a counter that `increment` then continues from — an
//!   `increment` on a *string* value would otherwise silently restart at 0 — and what keeps
//!   `{{ state.hits }}` reading back as the number it looks like.
//! - **Errors** follow the templating policy: with `debug` on, the first failing op aborts and the
//!   caller serves a 500 naming it — the ops *before* it have already been applied, this is
//!   fail-loud, not transactional; otherwise it is logged at `warn` and the remaining ops still
//!   run. A template token that fails inside a `set` value follows `template_fn`'s own policy
//!   (empty substitution + warn, or an error in debug).
//! - **Where they run, and where they do not.** `is` responses only, which includes a bare `_rift`
//!   response without a script, served as `is: {}` (issue #1685): a `proxy`, `inject` or
//!   `_rift.script` response has its own means, and `_rift.stateOps` on one of those is not run
//!   (`stub_analysis` warns). Not run either when the response was pre-empted before it was built:
//!   a fired `_rift.fault` / `fault` (a probabilistic fault therefore makes the ops probabilistic
//!   too — the ops belong to the response that was actually served), a `strictBehaviors` failure,
//!   a matcher error. A `wait` behaviour delays the ops with the response it delays.
//! - **A store is always provisioned.** An imposter whose stubs carry `stateOps` but no
//!   `_rift.flowState`, scenario or script gets the in-memory store automatically (with the same
//!   warning a script-only imposter gets) rather than the no-op store, which would have discarded
//!   every write silently.
//! - **Absent field ⇒ byte-identical behaviour**, including the prepared-response fast path.

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::extensions::flow_state::{CasOutcome, FlowStore};
use crate::extensions::template::RequestData;
use crate::extensions::template_fn::{TemplateContext, render_templated, template_heads};

/// How many times a `previousValue`-bearing `set` retries its compare-and-set before giving up.
///
/// Sized to the worst case rather than the typical one: with `n` writers racing on one key, each
/// round can admit only one, so the unluckiest writer may need `n` rounds — 64 covers a
/// thundering herd of that size on a single key with immediate retries, which is well past what a
/// mock sees. A key hot enough to lose 64 races in a row is a load pattern, not a race, and is
/// reported (in debug, as the op's failure; otherwise a `warn`) rather than looped on forever.
pub const CAS_ATTEMPTS: usize = 64;

fn one() -> i64 {
    1
}

/// One post-response state mutation. Serialized with `op` as the tag, camelCase, so it reads as
/// `{ "op": "set", "key": "...", "value": "..." }` in a stub.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", tag = "op")]
pub enum StateOp {
    /// Set `key` to the rendered `value` template (`{{ }}` grammar plus `previousValue`).
    Set { key: String, value: String },
    /// Add `by` (default 1) to an integer key, creating it at 0. Atomic where the backend is.
    Increment {
        key: String,
        #[serde(default = "one")]
        by: i64,
    },
    /// Delete one key.
    Delete { key: String },
    /// Delete every key in the request's flow.
    ClearFlow,
}

impl StateOp {
    /// A short name for logs and error messages.
    fn describe(&self) -> String {
        match self {
            StateOp::Set { key, .. } => format!("set {key:?}"),
            StateOp::Increment { key, by } => format!("increment {key:?} by {by}"),
            StateOp::Delete { key } => format!("delete {key:?}"),
            StateOp::ClearFlow => "clearFlow".to_owned(),
        }
    }
}

/// Run `ops` in order against `flow_id` on `store`, rendering `set` values against `request`.
///
/// `debug` selects the error policy (see the module doc): `Err` is returned only in debug mode,
/// naming the op that failed; otherwise every failure is logged and `Ok(())` is returned once every
/// op has been attempted.
///
/// # Errors
///
/// In debug mode, the first op that fails — a store error, a value template that fails to render,
/// or a `previousValue` `set` that lost its compare-and-set race [`CAS_ATTEMPTS`] times.
pub fn execute_state_ops(
    ops: &[StateOp],
    store: &dyn FlowStore,
    flow_id: &str,
    request: &RequestData,
    debug: bool,
) -> Result<(), String> {
    for op in ops {
        if let Err(reason) = execute_one(op, store, flow_id, request, debug) {
            let message = format!("stateOps: {} failed: {reason}", op.describe());
            if debug {
                return Err(message);
            }
            tracing::warn!(target: "rift::state_ops", op = %op.describe(), reason = %reason,
                "state operation failed; continuing with the next");
        }
    }
    Ok(())
}

fn execute_one(
    op: &StateOp,
    store: &dyn FlowStore,
    flow_id: &str,
    request: &RequestData,
    debug: bool,
) -> Result<(), String> {
    match op {
        StateOp::Set { key, value } => {
            if reads_own_key(value, key) {
                set_with_previous(store, flow_id, key, value, request, debug)
            } else {
                let rendered = render_value(value, store, flow_id, request, None, debug)?;
                store
                    .set(flow_id, key, stored_value(rendered))
                    .map_err(|e| format!("flow store: {e:#}"))
            }
        }
        StateOp::Increment { key, by } => store
            .increment_by(flow_id, key, *by)
            .map(|_| ())
            .map_err(|e| format!("flow store: {e:#}")),
        StateOp::Delete { key } => store
            .delete(flow_id, key)
            .map_err(|e| format!("flow store: {e:#}")),
        StateOp::ClearFlow => store
            .clear_flow(flow_id)
            .map_err(|e| format!("flow store: {e:#}")),
    }
}

/// The bounded compare-and-set loop a `previousValue`-bearing `set` runs: the value rendered
/// against what was read is written only if the key still holds what was read.
fn set_with_previous(
    store: &dyn FlowStore,
    flow_id: &str,
    key: &str,
    value: &str,
    request: &RequestData,
    debug: bool,
) -> Result<(), String> {
    for _ in 0..CAS_ATTEMPTS {
        let current = store
            .get(flow_id, key)
            .map_err(|e| format!("flow store: {e:#}"))?;
        let rendered = render_value(value, store, flow_id, request, current.as_ref(), debug)?;
        match store
            .compare_and_set(flow_id, key, current.as_ref(), stored_value(rendered))
            .map_err(|e| format!("flow store: {e:#}"))?
        {
            CasOutcome::Applied => return Ok(()),
            CasOutcome::Conflict(_) => continue,
        }
    }
    Err(format!(
        "lost the compare-and-set race {CAS_ATTEMPTS} times; the key is being written faster than \
         this operation can read-render-write it"
    ))
}

/// Whether a `set`'s value template reads the key it is about to write — through `previousValue`
/// or through `state.<key>` — and therefore needs the compare-and-set loop rather than a plain
/// write. Decided from the template's heads, so a literal `previousValue` in plain text does not
/// trigger it and `{{ state.trail }}` on a `set` of `trail` does.
fn reads_own_key(value: &str, key: &str) -> bool {
    let own = format!("state.{key}");
    template_heads(value)
        .iter()
        .any(|head| head == "previousValue" || *head == own)
}

/// What a rendered `set` value is stored as: a JSON number when it is exactly a canonical
/// integer, otherwise a string (see the module doc for why).
fn stored_value(rendered: String) -> Value {
    match rendered.parse::<i64>() {
        Ok(n) if n.to_string() == rendered => Value::Number(n.into()),
        _ => Value::String(rendered),
    }
}

fn render_value(
    value: &str,
    store: &dyn FlowStore,
    flow_id: &str,
    request: &RequestData,
    previous_value: Option<&Value>,
    debug: bool,
) -> Result<String, String> {
    let ctx = TemplateContext {
        request,
        flow_id,
        flow_store: store,
        previous_value,
    };
    render_templated(value, &ctx, debug)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::backends::InMemoryFlowStore;
    use serde_json::json;

    fn request() -> RequestData {
        RequestData::new(
            "GET",
            "/orders",
            Some("id=7&item=apple"),
            &crate::imposter::Headers::new(),
            None,
        )
    }

    #[test]
    fn ops_parse_and_serialize_with_op_as_the_tag() {
        let ops: Vec<StateOp> = serde_json::from_value(json!([
            { "op": "set", "key": "lastId", "value": "{{ request.query.id }}" },
            { "op": "increment", "key": "hits" },
            { "op": "increment", "key": "score", "by": -3 },
            { "op": "delete", "key": "tmp" },
            { "op": "clearFlow" }
        ]))
        .expect("parses");
        assert_eq!(
            ops,
            vec![
                StateOp::Set {
                    key: "lastId".into(),
                    value: "{{ request.query.id }}".into()
                },
                StateOp::Increment {
                    key: "hits".into(),
                    by: 1
                },
                StateOp::Increment {
                    key: "score".into(),
                    by: -3
                },
                StateOp::Delete { key: "tmp".into() },
                StateOp::ClearFlow,
            ]
        );
        // Round-trips through the same shape, `by` included, so `GET /imposters` reads back what
        // was written.
        let back = serde_json::to_value(&ops).expect("serializes");
        assert_eq!(
            back[1],
            json!({ "op": "increment", "key": "hits", "by": 1 })
        );
        assert_eq!(back[4], json!({ "op": "clearFlow" }));
    }

    #[test]
    fn an_unknown_op_is_a_parse_error_naming_it() {
        let err = serde_json::from_value::<StateOp>(json!({ "op": "frobnicate", "key": "k" }))
            .expect_err("unknown op");
        assert!(err.to_string().contains("frobnicate"), "{err}");
    }

    #[test]
    fn set_renders_from_the_request_and_previous_value_is_empty_when_absent() {
        let store = InMemoryFlowStore::new(300);
        let ops = vec![
            StateOp::Set {
                key: "lastId".into(),
                value: "{{ request.query.id }}".into(),
            },
            StateOp::Set {
                key: "trail".into(),
                value: "{{ previousValue }}|{{ request.query.item }}".into(),
            },
        ];
        execute_state_ops(&ops, &store, "f", &request(), true).expect("ops run");
        // `7` renders as a canonical integer, so it is stored as a number (see module doc).
        assert_eq!(store.get("f", "lastId").unwrap(), Some(json!(7)));
        assert_eq!(store.get("f", "trail").unwrap(), Some(json!("|apple")));
        // The second time, `previousValue` is what the first write left.
        execute_state_ops(&ops, &store, "f", &request(), true).expect("ops run");
        assert_eq!(
            store.get("f", "trail").unwrap(),
            Some(json!("|apple|apple"))
        );
    }

    #[test]
    fn a_set_that_reads_its_own_key_uses_the_cas_loop_and_seeds_a_counter_as_a_number() {
        let store = InMemoryFlowStore::new(300);
        // `state.trail` on a set of `trail` is the accumulator idiom spelled the other way; it must
        // take the same compare-and-set path `previousValue` does — and a literal mention of the
        // word in plain text must not.
        assert!(reads_own_key("{{ previousValue }}|x", "trail"));
        assert!(reads_own_key("{{ state.trail | json }}|x", "trail"));
        assert!(!reads_own_key("{{ state.other }}|x", "trail"));
        assert!(!reads_own_key("previousValue unknown", "trail"));

        // Seeding a counter with `set` stores a number, so `increment` continues from it instead
        // of silently restarting at 0 (which is what an increment on a string would do).
        let ops = vec![
            StateOp::Set {
                key: "hits".into(),
                value: "40".into(),
            },
            StateOp::Increment {
                key: "hits".into(),
                by: 2,
            },
        ];
        execute_state_ops(&ops, &store, "f", &request(), true).expect("ops run");
        assert_eq!(store.get("f", "hits").unwrap(), Some(json!(42)));
        // Non-canonical or non-integer renderings stay strings.
        assert_eq!(stored_value("007".into()), json!("007"));
        assert_eq!(stored_value("4.5".into()), json!("4.5"));
        assert_eq!(stored_value("-3".into()), json!(-3));
        assert_eq!(stored_value(String::new()), json!(""));
    }

    #[test]
    fn increment_delete_and_clear_flow_run_in_order() {
        let store = InMemoryFlowStore::new(300);
        let ops = vec![
            StateOp::Increment {
                key: "hits".into(),
                by: 1,
            },
            StateOp::Increment {
                key: "hits".into(),
                by: 10,
            },
            StateOp::Set {
                key: "tmp".into(),
                value: "x".into(),
            },
            StateOp::Delete { key: "tmp".into() },
        ];
        execute_state_ops(&ops, &store, "f", &request(), true).expect("ops run");
        assert_eq!(store.get("f", "hits").unwrap(), Some(json!(11)));
        assert_eq!(store.get("f", "tmp").unwrap(), None);
        execute_state_ops(&[StateOp::ClearFlow], &store, "f", &request(), true).expect("clear");
        assert_eq!(store.get("f", "hits").unwrap(), None);
    }

    #[test]
    fn debug_aborts_on_the_first_failure_and_non_debug_continues() {
        let store = InMemoryFlowStore::new(300);
        // A `set` whose template fails to render: in debug that is the op's failure.
        let ops = vec![
            StateOp::Set {
                key: "a".into(),
                value: "{{ request.query.missing }}".into(),
            },
            StateOp::Increment {
                key: "hits".into(),
                by: 1,
            },
        ];
        let err = execute_state_ops(&ops, &store, "f", &request(), true).expect_err("debug fails");
        assert!(err.contains("set \"a\""), "{err}");
        assert_eq!(
            store.get("f", "hits").unwrap(),
            None,
            "the later op did not run"
        );

        // Non-debug: the failing token substitutes empty, the op is not a failure at all, and the
        // increment runs.
        execute_state_ops(&ops, &store, "f", &request(), false).expect("non-debug never errors");
        assert_eq!(store.get("f", "a").unwrap(), Some(json!("")));
        assert_eq!(store.get("f", "hits").unwrap(), Some(json!(1)));
    }
}