0
0
// ingress (staging, exclusive): a bidder's market endpoint over iroh comes back after its IngressProxy `ingress-iroh` is
// replaced while its core stays up (docs/plans/0040-findings.md, "A BIDDER GOES DEAF OVER IROH WHEN ITS STORED DUMBPIPE
// PATH CHANGES"). The trigger is the bidder root's own component override: the MarketBidder `app` (the one kube write the
// test host may make on a bidder, restored after) gets spec.components["IngressProxy/ingress-iroh"].settings.ingressProxy
// .keepaliveMilliseconds (an xrpc-subscription setting the iroh provider never reads); the compose pass rewrites the
// IngressProxy spec, the generation changes and the core's runtime stops the instance and builds a new one: the path a
// compose rewrite of spec.iroh.dumbpipePath takes after a binary switch, without changing the pin. For each bidder of the
// target, ROUNDS times (6000 ms, 6001 ms, then the override as it was: three replacements, the root restored): read every
// 3 s for at most HEAL_S, the round has healed when the core logged an ingressproxy_iroh_started after the patch, an
// ingressproxy_iroh_dumbpipe_listening of the market Exposure after the LAST started, and the IngressProxy is Ready at its
// generation. After the last round: the core has a live dumbpipe child listening on the address of that last listening
// line, and a run limited to that bidder (`--exec -- id`, the requester's bidder endpoints iroh only) exits 0, so its
// submitRfp over iroh reached the bidder and was answered; its records are gone after. Any failure while an override is
// applied (a round that does not heal, the deadline, a failed call) puts it back first; a run killed from outside is put
// back by the test host's end (the kube ledger restores every spec the run patched).
use abi::{Event, Handle, Run};
use serde_json::{Value, json};
use steps::{MIN, S, host, kube, sw};
const ROUNDS: u64 = 3;
const HEAL_S: f64 = 180.0;
const INGRESS: &str = "ingress-iroh";
const OVERRIDE: &str = "IngressProxy/ingress-iroh";
const EXPOSURE: &str = "svc-bidder-bidder-iroh";
fn at(t: &str) -> f64 {
let t = t.trim();
if t.ends_with('Z') || t.len() < 6 {
return steps::secs(t);
}
let (base, zone) = t.split_at(t.len() - 6);
let sign = match zone.as_bytes()[0] {
b'+' => 1.0,
b'-' => -1.0,
_ => return steps::secs(t),
};
let h = zone[1..3].parse::<f64>().unwrap_or(0.0);
let m = zone[4..6].parse::<f64>().unwrap_or(0.0);
steps::secs(&format!("{base}Z")) - sign * (h * 3600.0 + m * 60.0)
}
fn times(o: &Value) -> Vec<(f64, Value)> {
o["lines"].as_array().into_iter().flatten().map(|l| (at(l["time"].as_str().unwrap_or_default()), l.clone())).collect()
}
fn watch(h: Handle, name: &Value, cluster: &str) -> Handle {
h.call(host("st", "bidder.logLines", json!({ "name": name, "texts": [["\"msg\":\"ingressproxy_iroh_started\""]], "keys": ["dumbpipe"] })))
.call(host("ls", "bidder.logLines", json!({ "name": name, "texts": [["\"msg\":\"ingressproxy_iroh_dumbpipe_listening\"", EXPOSURE]], "keys": ["address", "exposure"] })))
.call(kube("ip", "get", cluster, sw("IngressProxy", INGRESS)))
}
/// The MarketBidder patch of round `round`: a keepalive override, or (the last round) the override as it was before.
fn root_patch(st: &Value, round: u64) -> Value {
if round + 1 < ROUNDS {
return json!({ "spec": { "components": { OVERRIDE: { "settings": { "ingressProxy": { "keepaliveMilliseconds": 6000 + round } } } } } });
}
restore(st)
}
fn restore(st: &Value) -> Value {
if st["hadComponents"] == true {
json!({ "spec": { "components": { OVERRIDE: st["original"].clone() } } })
} else {
json!({ "spec": { "components": null } })
}
}
/// Fail; first, when a kick of this bidder went out and the root is not restored yet, put its override back ("unkick"
/// fails the run with `why` once answered). The test host's end puts every patched spec back too (the kube ledger), so a
/// run killed from outside leaves no override either.
fn bail(s: &mut S, h: Handle, cluster: &str, why: String) -> Handle {
if s.st["kicked"] != true || s.st["restored"] == true || s.is("unkick") {
return s.fail(why);
}
s.st["failing"] = json!(why);
s.set("unkick");
let p = restore(&s.st);
s.keep(h.call(root("unkick", cluster, p)))
}
fn root(id: &str, cluster: &str, patch: Value) -> abi::Call {
let mut q = sw("MarketBidder", "app");
q["patch"] = patch;
kube(id, "patch", cluster, q)
}
pub fn run_ingress(run: Run<Value>) -> Result<Handle, String> {
let args = &run.args;
let mut s = S::new(run.state, args["now"].as_str().unwrap_or_default());
if let Some(h) = steps::market_event(&mut s, &run.event) {
return Ok(h);
}
let base = args["name"].as_str().ok_or("name")?.to_string();
let bidders: Vec<Value> = args["bidders"].as_array().cloned().unwrap_or_default();
let i = s.st["i"].as_u64().unwrap_or(0) as usize;
let round = s.st["round"].as_u64().unwrap_or(0);
let bname = |i: usize| bidders.get(i).map(|b| b["name"].clone()).unwrap_or_default();
let bcluster = |i: usize| bidders.get(i).and_then(|b| b["cluster"].as_str()).unwrap_or_default().to_string();
let name = format!("{base}-{i}");
let req = format!("req{i}");
let mut h = Handle::new();
let kick = |s: &mut S, h: Handle, round: u64| {
s.set("kick");
s.mark("kick");
s.st["kickAt"] = json!(s.now);
s.st["round"] = json!(round);
s.st["kicked"] = json!(true);
let p = root_patch(&s.st, round);
h.call(root("kick", &bcluster(i), p))
};
match run.event {
Event::Start => {
if args["target"] == "prod" {
return Ok(s.unmet("staging only: it replaces the bidders' IngressProxy"));
}
if bidders.is_empty() || bidders.iter().any(|b| !b["name"].is_string() || !b["cluster"].is_string() || !b["did"].is_string()) {
return Ok(s.unmet("the target names no bidder with a name, a did and a kcp"));
}
s.set("root");
h = h.call(kube("mb", "get", &bcluster(0), sw("MarketBidder", "app"))).timer("deadline", (15 * bidders.len() as u64) * MIN);
}
Event::Timer { id } if id == "deadline" => {
let why = format!("not done (phase {}, bidder {}, round {round})", s.phase(), bname(i));
return Ok(bail(&mut s, h, &bcluster(i), why));
}
Event::Timer { id } if id == "watch" && s.is("heal") => {
s.st["got"] = json!({});
h = watch(h, &bname(i), &bcluster(i));
}
Event::Message { id, data, .. } if id == req => match data["msg"].as_str().unwrap_or_default() {
"contract" if data["phase"] == "Failed" => return Ok(s.fail(format!("{}: the contract failed: {}", bname(i), data["message"]))),
"exited" if data["code"].as_i64().unwrap_or(1) != 0 => {
return Ok(s.fail(format!("{}: the run over iroh exited {}: {}", bname(i), data["code"], data["tail"])));
}
"exited" => {
s.st["readings"]["rent"][bname(i).as_str().unwrap_or_default()] = json!({ "seconds": s.since("rent") });
s.set("records");
h = h.cancel(&req).call(host("records", "request.records", json!({ "name": name })));
}
_ => {}
},
Event::Closed { id, error } if id == req && s.is("rent") => return Ok(s.fail(format!("req closed: {}", error.unwrap_or_default()))),
Event::Result { id, result, .. } => {
let o = match result.output() {
Ok(o) => o.clone(),
Err(e) if id == "unkick" => {
return Ok(s.fail(format!("{}; the override could not be put back now ({e}): the test host's end restores it", s.st["failing"].as_str().unwrap_or("failed"))));
}
Err(e) => return Ok(bail(&mut s, h, &bcluster(i), format!("{id}: {e}"))),
};
match id.as_str() {
"mb" => {
s.st["kicked"] = json!(false);
s.st["restored"] = json!(false);
let components = &o["spec"]["components"];
s.st["hadComponents"] = json!(components.is_object());
s.st["original"] = components[OVERRIDE].clone();
h = kick(&mut s, h, 0);
}
"kick" => {
if round + 1 >= ROUNDS {
s.st["restored"] = json!(true);
}
s.set("heal");
h = h.timer("watch", 3_000);
}
"unkick" => return Ok(s.fail(s.st["failing"].as_str().unwrap_or("failed").to_string())),
"st" | "ls" | "ip" => {
s.st["got"][id.as_str()] = o;
let g = s.st["got"].clone();
if !["st", "ls", "ip"].iter().all(|k| !g[*k].is_null()) {
return Ok(s.keep(h));
}
let kicked = s.st["kickAt"].as_f64().unwrap_or(0.0);
let started = times(&g["st"]);
let listening = times(&g["ls"]);
let last = started.iter().map(|(t, _)| *t).fold(f64::MIN, f64::max);
let after: Vec<&(f64, Value)> = listening.iter().filter(|(t, _)| *t > last).collect();
let ip = &g["ip"];
let ready = ip["status"]["phase"] == "Ready" && ip["status"]["observedGeneration"] == ip["metadata"]["generation"];
let replaced = started.iter().filter(|(t, _)| *t >= kicked - 1.0).count();
if replaced > 0 && !after.is_empty() && ready {
let address = after.last().map(|(_, l)| l["address"].clone()).unwrap_or_default();
let key = bname(i).as_str().unwrap_or_default().to_string();
let mut rounds = s.st["readings"]["rounds"][&key].as_array().cloned().unwrap_or_default();
rounds.push(json!({ "round": round, "healS": s.since("kick"), "startedSinceKick": replaced, "started": started.len(),
"listening": listening.len(), "generation": ip["metadata"]["generation"], "address": address }));
s.st["readings"]["rounds"][&key] = json!(rounds);
s.st["address"] = address;
if round + 1 < ROUNDS {
let h = kick(&mut s, h, round + 1);
return Ok(s.keep(h));
}
s.set("probe");
h = h.call(host("dp", "bidder.dumbpipe", json!({ "name": bname(i) })));
return Ok(s.keep(h));
}
if s.since("kick") > HEAL_S {
let why = format!(
"{} round {round}: {HEAL_S} s after the IngressProxy {INGRESS} was replaced: {replaced} ingressproxy_iroh_started since, {} dumbpipe_listening of {EXPOSURE} after the last started, IngressProxy phase {} generation {} observed {}",
bname(i), after.len(), ip["status"]["phase"], ip["metadata"]["generation"], ip["status"]["observedGeneration"]
);
return Ok(bail(&mut s, h, &bcluster(i), why));
}
h = h.timer("watch", 3_000);
}
"dp" => {
let want = s.st["address"].as_str().unwrap_or_default().to_string();
let live: Vec<Value> = o["listeners"].as_array().cloned().unwrap_or_default();
s.st["readings"]["dumbpipe"][bname(i).as_str().unwrap_or_default()] = o.clone();
if !live.iter().any(|l| l["host"] == want.as_str()) {
return Ok(s.fail(format!("{}: no live dumbpipe child of the core listens on {want} (the last dumbpipe_listening): {o}", bname(i))));
}
s.set("rent");
s.mark("rent");
let q = json!({ "name": name, "args": ["--exec", "--", "id"], "bidderDids": [bidders[i]["did"]], "bidderEndpoints": ["iroh"] });
h = h.call(steps::host_sub(&req, "request.start", q));
}
"records" => h = h.call(host("gone", "assert.recordsGone", json!({ "uris": o["uris"] }))),
"gone" => {
if o["left"].as_array().is_none_or(|l| !l.is_empty()) {
return Ok(s.fail(format!("{}: records left: {} {}", bname(i), o["left"], o["errors"])));
}
if i + 1 < bidders.len() {
s.st["i"] = json!(i + 1);
s.st["round"] = json!(0);
s.set("root");
h = h.call(kube("mb", "get", &bcluster(i + 1), sw("MarketBidder", "app")));
return Ok(s.keep(h));
}
return Ok(s.pass());
}
_ => {}
}
}
_ => {}
}
Ok(s.keep(h))
}