use super::core::{LoadClock, StubState, first_divergence, restamp};
use super::types::{ImposterError, Stub};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use tracing::error;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Persistence {
Datadir,
Ephemeral,
}
#[derive(Debug, Clone)]
pub struct DesiredImposter {
pub config: super::types::ImposterConfig,
pub persistence: Persistence,
pub script_files: super::script_resolve::ScriptFileAccess,
}
#[derive(Debug, Default)]
pub struct ApplyReport {
pub created: Vec<u16>,
pub replaced: Vec<u16>,
pub stub_patched: Vec<u16>,
pub toggled: Vec<u16>,
pub deleted: Vec<u16>,
pub failed: Vec<(u16, ImposterError)>,
}
impl ApplyReport {
#[must_use]
pub fn port_lists(&self) -> serde_json::Map<String, serde_json::Value> {
let mut lists = serde_json::Map::new();
for (key, ports) in [
("created", &self.created),
("replaced", &self.replaced),
("stubPatched", &self.stub_patched),
("toggled", &self.toggled),
("deleted", &self.deleted),
] {
lists.insert(key.to_owned(), serde_json::json!(ports));
}
lists
}
}
#[derive(Debug, Default)]
pub struct DeleteAllReport {
pub deleted: Vec<super::types::ImposterConfig>,
pub failed: Vec<(u16, ImposterError)>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ImposterEvent {
Created(u16),
Replaced(u16),
StubsChanged(u16),
EnabledChanged {
port: u16,
enabled: bool,
},
Deleted(u16),
AllDeleted,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct EventContext {
pub principal: Option<String>,
}
pub trait ImposterEventListener: Send + Sync {
fn on_event(&self, event: &ImposterEvent, ctx: &EventContext);
}
pub fn stub_key(stub: &Stub, occurrence: usize) -> String {
match &stub.id {
Some(id) => id.clone(),
None => key_for(None, content_hash(stub), occurrence),
}
}
pub(crate) fn key_for(id: Option<&str>, hash: u64, occurrence: usize) -> String {
match id {
Some(id) => id.to_string(),
None => format!("~{hash:016x}#{occurrence}"),
}
}
pub(crate) fn content_hash(stub: &Stub) -> u64 {
if stub.recorded_at.is_some() {
let mut keyed = stub.clone();
keyed.recorded_at = None;
return content_hash(&keyed);
}
let mut hasher = Fnv1a::default();
let hashed = serde_json::to_value(stub)
.and_then(|canonical| serde_json::to_writer(&mut hasher, &canonical));
if let Err(e) = hashed {
error!("stub serialization failed while keying; falling back to Debug format: {e}");
hasher = Fnv1a::default();
hasher.update(format!("{stub:?}").as_bytes());
}
hasher.0
}
pub(crate) struct Fnv1a(u64);
impl Default for Fnv1a {
fn default() -> Self {
Self(0xcbf2_9ce4_8422_2325)
}
}
impl Fnv1a {
pub(crate) fn finish(&self) -> u64 {
self.0
}
pub(crate) fn update(&mut self, bytes: &[u8]) {
const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
self.0 = bytes.iter().fold(self.0, |hash, byte| {
(hash ^ u64::from(*byte)).wrapping_mul(FNV_PRIME)
});
}
}
impl std::io::Write for Fnv1a {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.update(buf);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
#[cfg(test)]
pub(crate) fn stub_keys(stubs: &[Stub]) -> Vec<String> {
keys_from(
stubs
.iter()
.map(|stub| (stub.id.as_deref(), content_hash(stub))),
)
}
pub(crate) fn keys_from<'a>(stubs: impl Iterator<Item = (Option<&'a str>, u64)>) -> Vec<String> {
let mut seen: HashMap<u64, usize> = HashMap::new();
stubs
.map(|(id, hash)| match id {
Some(id) => id.to_string(),
None => {
let occurrence = seen.entry(hash).or_insert(0);
let key = key_for(None, hash, *occurrence);
*occurrence += 1;
key
}
})
.collect()
}
#[derive(Debug)]
pub(crate) enum StubReconcile {
Unchanged,
Patched {
removed_keys: Vec<String>,
},
Degenerate,
Widens,
}
pub(crate) enum StubPlan {
Unchanged,
Degenerate,
Patched {
next: Vec<Arc<StubState>>,
removed_keys: Vec<String>,
},
}
pub(crate) fn plan_stub_reconcile(
states: &[Arc<StubState>],
desired: &[Stub],
clock: &LoadClock,
) -> StubPlan {
let desired_hashes: Vec<u64> = desired.iter().map(content_hash).collect();
let unchanged = states.len() == desired.len()
&& states
.iter()
.zip(desired.iter().zip(&desired_hashes))
.all(|(state, (stub, hash))| state.stub.id == stub.id && state.content_hash() == *hash);
if unchanged {
return StubPlan::Unchanged;
}
let old_keys = keys_from(
states
.iter()
.map(|state| (state.stub.id.as_deref(), state.content_hash())),
);
let new_keys = keys_from(
desired
.iter()
.zip(&desired_hashes)
.map(|(stub, hash)| (stub.id.as_deref(), *hash)),
);
let old_index: HashMap<&String, usize> =
old_keys.iter().enumerate().map(|(i, k)| (k, i)).collect();
let new_set: HashSet<&String> = new_keys.iter().collect();
let deletes = old_keys.iter().filter(|k| !new_set.contains(*k)).count();
let mut inserts = 0usize;
let mut content_replaced = 0usize;
for (i, key) in new_keys.iter().enumerate() {
match old_index.get(key) {
None => inserts += 1,
Some(&j) if states[j].content_hash() != desired_hashes[i] => {
content_replaced += 1;
}
Some(_) => {}
}
}
let changed_slots = deletes + inserts + 2 * content_replaced;
if changed_slots * 2 > states.len() + desired.len() {
return StubPlan::Degenerate;
}
let mut by_key: HashMap<String, Arc<StubState>> =
old_keys.into_iter().zip(states.iter().cloned()).collect();
let mut fresh: Option<chrono::DateTime<chrono::Utc>> = None;
let mut stamp = || *fresh.get_or_insert_with(|| clock.next());
let next = new_keys
.into_iter()
.zip(desired.iter().zip(desired_hashes))
.map(|(key, (stub, hash))| match by_key.remove(&key) {
Some(state) if state.content_hash() == hash => state,
Some(state) => Arc::new(
state
.with_stub_hashed(stub.clone(), hash)
.with_loaded_at(stamp()),
),
None => Arc::new(StubState::with_hash(stub.clone(), hash).with_loaded_at(stamp())),
})
.collect::<Vec<_>>();
let mut next = next;
let k = first_divergence(states.iter().map(|s| &s.stub), desired.iter());
for p in 0..next.len() {
let at = match states.get(p) {
Some(prev) if p < k && prev.content_hash() == next[p].content_hash() => {
prev.loaded_at()
}
_ => stamp(),
};
if next[p].loaded_at() != at {
restamp(&mut next, p..=p, at);
}
}
let removed_keys = by_key
.into_values()
.map(|state| state.sequence_key())
.collect();
StubPlan::Patched { next, removed_keys }
}
#[cfg(test)]
pub(crate) fn reconcile_stub_states(
states: &mut Vec<Arc<StubState>>,
desired: Vec<Stub>,
) -> StubReconcile {
match plan_stub_reconcile(states, &desired, &LoadClock::new()) {
StubPlan::Unchanged => StubReconcile::Unchanged,
StubPlan::Degenerate => StubReconcile::Degenerate,
StubPlan::Patched { next, removed_keys } => {
*states = next;
StubReconcile::Patched { removed_keys }
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::imposter::core::StubState;
#[test]
fn port_lists_has_every_list_even_when_empty() {
let lists = ApplyReport::default().port_lists();
let mut keys: Vec<&str> = lists.keys().map(String::as_str).collect();
keys.sort_unstable();
assert_eq!(
keys,
["created", "deleted", "replaced", "stubPatched", "toggled"]
);
assert!(lists.values().all(|v| v == &json!([])));
let report = ApplyReport {
toggled: vec![7],
stub_patched: vec![8],
..ApplyReport::default()
};
let lists = report.port_lists();
assert_eq!(lists["toggled"], json!([7]));
assert_eq!(lists["stubPatched"], json!([8]));
}
use crate::imposter::types::Stub;
use serde_json::json;
fn stub(v: serde_json::Value) -> Stub {
serde_json::from_value(v).expect("test stub json")
}
fn one_resp(body: &str) -> Stub {
stub(json!({
"predicates": [{"equals": {"path": format!("/{body}")}}],
"responses": [{"is": {"statusCode": 200, "body": body}}]
}))
}
fn two_resp(first: &str, second: &str) -> Stub {
stub(json!({
"predicates": [{"equals": {"path": "/cycled"}}],
"responses": [
{"is": {"statusCode": 200, "body": first}},
{"is": {"statusCode": 200, "body": second}}
]
}))
}
fn st(stub: Stub) -> Arc<StubState> {
Arc::new(StubState::new(stub))
}
fn next_body(state: &StubState) -> String {
let resp = state.get_next_response().expect("stub has responses");
serde_json::to_value(resp).expect("serialize response")["is"]["body"]
.as_str()
.expect("string body")
.to_string()
}
const MULTI_KEY_STUB: &str = r#"{
"predicates": [
{"equals": {"method": "GET", "path": "/a", "query": {"q": "1", "r": "2"}, "body": "x"}},
{"or": [{"contains": {"path": "/a", "body": "y", "method": "G"}}, {"not": {"startsWith": {"path": "/b", "body": "z"}}}]}
],
"responses": [{"is": {"statusCode": 200, "headers": {"Content-Type": "application/json", "X-A": "1", "X-B": "2", "X-C": "3", "X-D": "4"}, "body": "b"}}]
}"#;
fn parse_multi() -> Stub {
serde_json::from_str(MULTI_KEY_STUB).expect("multi-key stub json")
}
#[test]
fn stub_key_is_stable_across_fresh_parses() {
let first = stub_key(&parse_multi(), 0);
for _ in 0..20 {
assert_eq!(stub_key(&parse_multi(), 0), first);
}
}
#[test]
fn identical_multi_key_stubs_are_unchanged() {
let mut live = vec![st(parse_multi()), st(one_resp("a"))];
let before: Vec<_> = live.iter().map(Arc::clone).collect();
let outcome = reconcile_stub_states(&mut live, vec![parse_multi(), one_resp("a")]);
assert!(
matches!(outcome, StubReconcile::Unchanged),
"a re-parsed identical set must be Unchanged, got {outcome:?}"
);
assert!(live.iter().zip(&before).all(|(a, b)| Arc::ptr_eq(a, b)));
}
#[test]
fn identical_multi_key_siblings_get_distinct_occurrences() {
let keys = stub_keys(&[parse_multi(), parse_multi()]);
assert!(keys[0].ends_with("#0"), "{keys:?}");
assert!(keys[1].ends_with("#1"), "{keys:?}");
assert_eq!(
keys[0].trim_end_matches("#0"),
keys[1].trim_end_matches("#1")
);
}
#[test]
fn stub_key_value_is_pinned() {
assert_eq!(stub_key(&one_resp("a"), 0), "~e2d14a5a1776f053#0");
}
#[test]
fn a_numeric_string_status_keys_as_before() {
let parse = |status: serde_json::Value| -> Stub {
serde_json::from_value(serde_json::json!({
"responses": [{"is": {"statusCode": status, "body": "a"}}]
}))
.expect("stub")
};
let key = stub_key(&parse(serde_json::json!("404")), 0);
assert_eq!(key, stub_key(&parse(serde_json::json!(404)), 0));
assert_eq!(key, "~03fc7688c0fb7a8d#0");
}
#[test]
fn stub_key_ignores_absent_name() {
let unnamed = one_resp("a");
assert_eq!(stub_key(&unnamed, 0), "~e2d14a5a1776f053#0");
let mut named = serde_json::to_value(&unnamed).expect("print");
named["name"] = json!("s1");
let named = stub(named);
assert_ne!(stub_key(&named, 0), stub_key(&unnamed, 0));
}
#[test]
fn corpus_stubs_keep_their_key_through_a_print_round_trip() {
use crate::imposter::types::ImposterConfig;
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../sdk-conformance/corpus/imposters");
let mut seen = 0;
for entry in std::fs::read_dir(&dir).expect("read the corpus") {
let path = entry.expect("corpus entry").path();
if path.extension().is_none_or(|e| e != "json") {
continue;
}
let text = std::fs::read_to_string(&path).expect("read corpus file");
let loaded: ImposterConfig = serde_json::from_str(&text)
.unwrap_or_else(|e| panic!("{}: decode: {e}", path.display()));
let printed = serde_json::to_value(&loaded).expect("print");
let reloaded: ImposterConfig = serde_json::from_value(printed)
.unwrap_or_else(|e| panic!("{}: re-load: {e}", path.display()));
assert_eq!(
stub_keys(&loaded.stubs),
stub_keys(&reloaded.stubs),
"{}",
path.display()
);
seen += 1;
}
assert!(seen > 0, "no corpus fixtures under {}", dir.display());
}
#[test]
fn stub_key_ignores_json_key_order() {
let a = stub(json!({
"predicates": [{"equals": {"method": "GET", "path": "/p"}}],
"responses": [{"is": {"headers": {"A": "1", "B": "2"}, "statusCode": 200}}]
}));
let b = stub(json!({
"responses": [{"is": {"statusCode": 200, "headers": {"B": "2", "A": "1"}}}],
"predicates": [{"equals": {"path": "/p", "method": "GET"}}]
}));
assert_eq!(stub_key(&a, 0), stub_key(&b, 0));
}
#[test]
fn recorded_at_is_not_part_of_the_key() {
let plain = one_resp("a");
let mut recorded = one_resp("a");
recorded.recorded_at = Some(1_700_000_000);
assert_eq!(stub_key(&plain, 0), stub_key(&recorded, 0));
}
#[test]
fn stub_key_is_deterministic_and_prefixed() {
let a = one_resp("a");
let b = one_resp("a");
let key = stub_key(&a, 0);
assert_eq!(
key,
stub_key(&b, 0),
"same content must hash to the same key"
);
assert!(key.starts_with('~'), "generated keys carry the ~ prefix");
assert!(key.ends_with("#0"));
assert_eq!(
key.len(),
"~".len() + 16 + "#0".len(),
"16-hex content hash"
);
}
#[test]
fn stub_key_uses_explicit_id_verbatim() {
let mut s = one_resp("a");
s.id = Some("checkout-flow".into());
assert_eq!(stub_key(&s, 0), "checkout-flow");
assert_eq!(
stub_key(&s, 3),
"checkout-flow",
"occurrence is irrelevant for explicit ids"
);
}
#[test]
fn stub_key_occurrence_suffix_disambiguates_identical_siblings() {
let s = one_resp("dup");
let keys = stub_keys(&[s.clone(), s.clone(), one_resp("other")]);
assert_eq!(keys.len(), 3);
assert_ne!(
keys[0], keys[1],
"byte-identical siblings get distinct keys"
);
assert!(keys[0].ends_with("#0"));
assert!(keys[1].ends_with("#1"));
assert!(keys[2].ends_with("#0"));
assert_ne!(keys[0], keys[2]);
}
#[test]
fn stub_key_content_change_changes_key() {
assert_ne!(stub_key(&one_resp("a"), 0), stub_key(&one_resp("b"), 0));
}
#[test]
fn patch_preserves_untouched_stub_cursors() {
let mut states = vec![
st(two_resp("a1", "a2")),
st(one_resp("b")),
st(one_resp("c")),
];
assert_eq!(next_body(&states[0]), "a1");
let desired = vec![two_resp("a1", "a2"), one_resp("b"), one_resp("c2")];
let outcome = reconcile_stub_states(&mut states, desired);
assert!(matches!(outcome, StubReconcile::Patched { .. }));
assert_eq!(states.len(), 3);
assert_eq!(
next_body(&states[0]),
"a2",
"untouched stub keeps its cursor"
);
assert_eq!(next_body(&states[2]), "c2", "changed stub swapped in");
}
#[test]
fn pure_reorder_preserves_all_cursors() {
let mut states = vec![st(two_resp("a1", "a2")), st(two_resp("b1", "b2"))];
assert_eq!(next_body(&states[0]), "a1");
assert_eq!(next_body(&states[1]), "b1");
let desired = vec![two_resp("b1", "b2"), two_resp("a1", "a2")];
let outcome = reconcile_stub_states(&mut states, desired);
assert!(matches!(outcome, StubReconcile::Patched { .. }));
assert_eq!(next_body(&states[0]), "b2", "moved stub keeps its cursor");
assert_eq!(next_body(&states[1]), "a2", "moved stub keeps its cursor");
}
#[test]
fn degenerate_ratio_falls_back_without_mutating() {
let mut states = vec![st(one_resp("a")), st(one_resp("b"))];
let outcome = reconcile_stub_states(&mut states, vec![one_resp("x"), one_resp("y")]);
assert!(matches!(outcome, StubReconcile::Degenerate));
assert_eq!(
next_body(&states[0]),
"a",
"a degenerate outcome must not mutate the live stubs"
);
assert_eq!(next_body(&states[1]), "b");
}
#[test]
fn identical_stubs_are_unchanged() {
let mut states = vec![st(one_resp("a")), st(one_resp("b"))];
let outcome = reconcile_stub_states(&mut states, vec![one_resp("a"), one_resp("b")]);
assert!(matches!(outcome, StubReconcile::Unchanged));
}
#[test]
fn same_id_content_change_patches_in_place_keeping_cursor() {
let mut with_id = two_resp("v1a", "v1b");
with_id.id = Some("s1".into());
let mut states = vec![st(with_id), st(one_resp("b")), st(one_resp("c"))];
assert_eq!(next_body(&states[0]), "v1a");
let mut updated = two_resp("v2a", "v2b");
updated.id = Some("s1".into());
let outcome =
reconcile_stub_states(&mut states, vec![updated, one_resp("b"), one_resp("c")]);
assert!(matches!(outcome, StubReconcile::Patched { .. }));
assert_eq!(
next_body(&states[0]),
"v2b",
"in-place id replace keeps the slot's cursor"
);
}
#[test]
fn insertion_below_threshold_patches() {
let mut states = vec![
st(two_resp("a1", "a2")),
st(one_resp("b")),
st(one_resp("c")),
];
assert_eq!(next_body(&states[0]), "a1");
let desired = vec![
two_resp("a1", "a2"),
one_resp("new"),
one_resp("b"),
one_resp("c"),
];
let outcome = reconcile_stub_states(&mut states, desired);
assert!(matches!(outcome, StubReconcile::Patched { .. }));
assert_eq!(states.len(), 4);
assert_eq!(next_body(&states[0]), "a2");
assert_eq!(next_body(&states[1]), "new");
}
}