1use std::collections::HashMap;
18use std::sync::{LazyLock, Mutex};
19use std::time::{Duration, Instant};
20
21pub(crate) const RENEW_EVERY: Duration = Duration::from_secs(20);
23
24const UNSUPPORTED_BACKOFF: Duration = Duration::from_secs(600);
27
28const HELD_ELSEWHERE_FRESH: Duration = Duration::from_secs(90);
31
32pub fn instance_id() -> String {
35 format!(
36 "{}/{}",
37 crate::backend::reactive::registry::local_host_label(),
38 crate::backend::reactive::registry::local_channel_id()
39 )
40}
41
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub enum Outcome {
44 Held,
46 HeldElsewhere(String),
48 Unknown,
50}
51
52#[derive(Default)]
53struct Entry {
54 held: bool,
55 last_ok: Option<Instant>,
56 elsewhere: Option<(String, Instant)>,
57 forgotten_at: Option<Instant>,
60}
61
62static STATE: LazyLock<Mutex<HashMap<String, Entry>>> = LazyLock::new(Default::default);
63static OPS: LazyLock<Mutex<HashMap<String, std::sync::Arc<tokio::sync::Mutex<()>>>>> = LazyLock::new(Default::default);
68
69fn op_lock(agent_id: &str) -> std::sync::Arc<tokio::sync::Mutex<()>> {
70 OPS.lock().unwrap_or_else(|e| e.into_inner()).entry(key(agent_id)).or_default().clone()
71}
72
73static UNSUPPORTED_UNTIL: LazyLock<Mutex<Option<Instant>>> = LazyLock::new(Default::default);
74
75fn key(agent_id: &str) -> String {
76 agent_id.trim().to_lowercase()
77}
78
79pub fn held_elsewhere(agent: &str) -> Option<String> {
82 let state = STATE.lock().unwrap_or_else(|e| e.into_inner());
83 let (desc, at) = state.get(&key(agent))?.elsewhere.clone()?;
84 (at.elapsed() < HELD_ELSEWHERE_FRESH).then_some(desc)
85}
86
87pub async fn forget_elsewhere(agent: &str) {
91 let op = op_lock(agent);
95 let _op = op.lock().await;
96 let mut state = STATE.lock().unwrap_or_else(|e| e.into_inner());
97 let e = state.entry(key(agent)).or_default();
98 e.elsewhere = None;
99 e.forgotten_at = Some(Instant::now());
100}
101
102pub fn holder_on_this_computer(desc: &str) -> bool {
105 desc == THIS_COMPUTER || desc.starts_with("this computer, ")
106}
107
108const THIS_COMPUTER: &str = "this computer";
109
110pub fn held_on_this_computer_by(agent: &str) -> Option<String> {
113 let desc = held_elsewhere(agent)?;
114 if !holder_on_this_computer(&desc) {
115 return None;
116 }
117 desc.split(", ").find_map(|part| part.strip_prefix("channel ")).map(str::to_string)
118}
119
120pub fn held_on_another_computer(agent: &str) -> Option<String> {
123 held_elsewhere(agent).filter(|desc| !desc.is_empty() && !holder_on_this_computer(desc))
124}
125
126pub(crate) fn describe_holder(held_by: &serde_json::Value) -> String {
128 let field = |k: &str| held_by.get(k).and_then(|v| v.as_str()).unwrap_or("").to_string();
129 let mut parts = Vec::new();
130 let host = field("host");
131 if !host.is_empty() {
132 if host.eq_ignore_ascii_case(&crate::backend::reactive::registry::local_host_label()) {
135 parts.push(THIS_COMPUTER.to_string());
136 } else {
137 parts.push(format!("computer {host}"));
138 }
139 }
140 let channel = field("channel");
141 if !channel.is_empty() {
142 parts.push(format!("channel {channel}"));
143 }
144 let version = field("version");
145 if !version.is_empty() {
146 parts.push(format!("v{version}"));
147 }
148 parts.join(", ")
149}
150
151fn record(agent_id: &str, outcome: &Outcome) {
152 let mut state = STATE.lock().unwrap_or_else(|e| e.into_inner());
153 let e = state.entry(key(agent_id)).or_default();
154 match outcome {
155 Outcome::Held => {
156 e.held = true;
157 e.last_ok = Some(Instant::now());
158 e.elsewhere = None;
159 }
160 Outcome::HeldElsewhere(desc) => {
161 e.held = false;
162 e.last_ok = None;
163 e.elsewhere = Some((desc.clone(), Instant::now()));
164 }
165 Outcome::Unknown => {}
166 }
167}
168
169pub(crate) fn note_not_holder_since(agent_id: &str, body: &serde_json::Value, started: Instant) -> Option<String> {
175 let desc = body.get("held_by").map(describe_holder).unwrap_or_default();
176 let mut state = STATE.lock().unwrap_or_else(|e| e.into_inner());
179 let e = state.entry(key(agent_id)).or_default();
180 if e.forgotten_at.is_some_and(|at| at > started) {
181 return None;
182 }
183 e.held = false;
184 e.last_ok = None;
185 e.elsewhere = Some((desc.clone(), Instant::now()));
186 Some(desc)
187}
188
189pub(crate) fn is_held(agent_id: &str) -> bool {
191 STATE.lock().unwrap_or_else(|e| e.into_inner()).get(&key(agent_id)).is_some_and(|e| e.held)
192}
193
194#[cfg(test)]
195pub(crate) fn mark_held_for_test(agent_id: &str) {
196 record(agent_id, &Outcome::Held);
197}
198
199#[cfg(any(test, feature = "test-support"))]
201pub fn note_not_holder(agent_id: &str, body: &serde_json::Value) -> String {
202 let desc = body.get("held_by").map(describe_holder).unwrap_or_default();
203 record(agent_id, &Outcome::HeldElsewhere(desc.clone()));
204 desc
205}
206
207pub(crate) async fn ensure(
210 base: &str,
211 agent_id: &str,
212 token: &str,
213 http: &reqwest::Client,
214 still_subscribed: impl Fn() -> bool,
215) -> Outcome {
216 if UNSUPPORTED_UNTIL.lock().unwrap_or_else(|e| e.into_inner()).is_some_and(|t| t > Instant::now()) {
217 return Outcome::Unknown;
218 }
219 let op = op_lock(agent_id);
220 let _op = op.lock().await;
221 if !still_subscribed() {
225 return Outcome::Unknown;
226 }
227 let renew_due = {
228 let state = STATE.lock().unwrap_or_else(|e| e.into_inner());
229 match state.get(&key(agent_id)) {
230 Some(e) if e.held => match e.last_ok {
231 Some(at) if at.elapsed() < RENEW_EVERY => return Outcome::Held,
232 _ => true,
233 },
234 _ => false,
235 }
236 };
237 let outcome = if renew_due {
238 match call(base, agent_id, token, http, "/agents/lease/renew").await {
239 Some((409, body)) if body.get("held_by").is_some_and(|h| h.is_null()) => {
241 claim_outcome(call(base, agent_id, token, http, "/agents/lease").await)
242 }
243 other => claim_outcome(other),
244 }
245 } else {
246 claim_outcome(call(base, agent_id, token, http, "/agents/lease").await)
247 };
248 record(agent_id, &outcome);
249 outcome
250}
251
252fn claim_outcome(resp: Option<(u16, serde_json::Value)>) -> Outcome {
253 match resp {
254 Some((200..=299, _)) => Outcome::Held,
255 Some((409, body)) => Outcome::HeldElsewhere(body.get("held_by").map(describe_holder).unwrap_or_default()),
256 Some((404, _)) | Some((405, _)) => {
257 *UNSUPPORTED_UNTIL.lock().unwrap_or_else(|e| e.into_inner()) = Some(Instant::now() + UNSUPPORTED_BACKOFF);
258 tracing::info!("wan_lease: relay has no agent-lease routes yet — WAN tier inactive for now");
259 Outcome::Unknown
260 }
261 _ => Outcome::Unknown,
262 }
263}
264
265fn seal_offer(agent_id: &str) -> Option<crate::backend::jekt_seal::SealOffer> {
269 let wan = crate::backend::storage::wan_identity::global()?;
270 let key = wan.agent_key_load(agent_id).ok().flatten()?;
271 let instance = wan.instance_ensure(&crate::backend::reactive::registry::local_host_label()).ok()?;
272 let seed: [u8; 32] = agentmux_common::jekt_sign::decode_key(&key.private_key)?.try_into().ok()?;
273 crate::backend::jekt_seal::offer(&instance.instance_id, agent_id, &key.public_key_bytes()?, &seed)
274}
275
276async fn call(base: &str, agent_id: &str, token: &str, http: &reqwest::Client, path: &str) -> Option<(u16, serde_json::Value)> {
278 let body = serde_json::json!({
279 "agent_id": agent_id,
280 "instance": instance_id(),
281 "host": crate::backend::reactive::registry::local_host_label(),
282 "channel": crate::backend::reactive::registry::local_channel_id(),
283 "version": env!("CARGO_PKG_VERSION"),
284 "features": [agentmux_common::jekt_files::CLOUD_FEATURE],
287 "seal": seal_offer(agent_id),
288 });
289 post(base, path, token, http, Some(agent_id), &body).await
290}
291
292async fn post(
295 base: &str,
296 path: &str,
297 token: &str,
298 http: &reqwest::Client,
299 agent_id: Option<&str>,
300 body: &serde_json::Value,
301) -> Option<(u16, serde_json::Value)> {
302 let mut req = http
303 .post(format!("{base}{path}"))
304 .header("Authorization", format!("Bearer {token}"))
305 .json(body)
306 .timeout(Duration::from_secs(10));
307 if let Some(agent_id) = agent_id {
308 req = req.header("X-Agent-ID", agent_id);
309 }
310 match req.send().await {
311 Ok(r) => {
312 let status = r.status().as_u16();
313 let json = r.json::<serde_json::Value>().await.unwrap_or(serde_json::Value::Null);
314 Some((status, json))
315 }
316 Err(e) => {
317 tracing::debug!(agent_id, path, error = %e, "wan_lease: relay unreachable");
318 None
319 }
320 }
321}
322
323pub(crate) async fn renew_held_batch(
331 base: &str,
332 agents: &[String],
333 token: &str,
334 http: &reqwest::Client,
335 still_subscribed: impl Fn(&str) -> bool,
336) -> HashMap<String, Outcome> {
337 let mut outcomes = HashMap::new();
338 let lease_tier_off = UNSUPPORTED_UNTIL.lock().unwrap_or_else(|e| e.into_inner()).is_some_and(|t| t > Instant::now());
339 if lease_tier_off || super::relay::batch_routes_missing(base) {
340 return outcomes;
341 }
342 let mut due: Vec<String> = {
343 let state = STATE.lock().unwrap_or_else(|e| e.into_inner());
344 agents
345 .iter()
346 .map(|a| key(a))
347 .filter(|k| {
348 state
349 .get(k)
350 .is_some_and(|e| e.held && e.last_ok.is_none_or(|at| at.elapsed() >= RENEW_EVERY))
351 })
352 .collect()
353 };
354 due.sort();
355 due.dedup();
356 if due.len() < 2 {
357 return outcomes;
358 }
359 let locks: Vec<_> = due.iter().map(|a| op_lock(a)).collect();
363 let mut _guards = Vec::with_capacity(locks.len());
364 for lock in &locks {
365 _guards.push(lock.lock().await);
366 }
367 due.retain(|a| still_subscribed(a));
368 for chunk in due.chunks(super::relay::MAX_BATCH_AGENTS) {
369 let body = serde_json::json!({ "instance": instance_id(), "agent_ids": chunk });
370 let results = match post(base, "/agents/lease/renew-batch", token, http, None, &body).await {
371 Some((404, _)) | Some((405, _)) => {
372 super::relay::note_batch_routes_missing(base);
373 return outcomes;
374 }
375 Some((200..=299, body)) => body.get("results").cloned().unwrap_or_default(),
376 _ => continue,
377 };
378 for agent in chunk {
379 let Some(entry) = results.get(agent.as_str()) else { continue };
380 let outcome = if entry.get("ok").and_then(serde_json::Value::as_bool) == Some(true) {
381 Outcome::Held
382 } else if entry.get("error").and_then(serde_json::Value::as_str) != Some("not_holder") {
383 continue; } else if entry.get("held_by").is_some_and(serde_json::Value::is_null) {
385 claim_outcome(call(base, agent, token, http, "/agents/lease").await)
387 } else {
388 Outcome::HeldElsewhere(entry.get("held_by").map(describe_holder).unwrap_or_default())
389 };
390 record(agent, &outcome);
391 outcomes.insert(agent.clone(), outcome);
392 }
393 }
394 outcomes
395}
396
397pub(crate) async fn release(
401 base: &str,
402 agent_id: &str,
403 token: &str,
404 http: &reqwest::Client,
405 still_gone: impl Fn() -> bool,
406) -> bool {
407 let op = op_lock(agent_id);
408 let _op = op.lock().await;
409 if !still_gone() {
412 return false;
413 }
414 let was_held = STATE
415 .lock()
416 .unwrap_or_else(|e| e.into_inner())
417 .remove(&key(agent_id))
418 .is_some_and(|e| e.held);
419 if was_held {
420 let _ = call(base, agent_id, token, http, "/agents/lease/release").await;
421 }
422 true
423}
424
425pub(crate) async fn take_over(base: &str, agent_id: &str, token: &str, http: &reqwest::Client) -> Outcome {
434 let op = op_lock(agent_id);
435 let _op = op.lock().await;
436 let claimed = claim_outcome(call(base, agent_id, token, http, "/agents/lease").await);
437 let outcome = match claimed {
438 Outcome::HeldElsewhere(desc) if holder_on_this_computer(&desc) => {
439 match call(base, agent_id, token, http, "/agents/lease/take").await {
440 Some((200..=299, _)) => {
441 tracing::info!(agent_id, from = %desc, "wan_lease: took the lease over from an instance on this computer");
442 Outcome::Held
443 }
444 Some((409, body)) => claim_outcome(Some((409, body))),
448 other => {
449 tracing::warn!(agent_id, answer = ?other.map(|(s, _)| s), "wan_lease: the relay would not take the lease over");
450 Outcome::HeldElsewhere(desc)
451 }
452 }
453 }
454 other => other,
455 };
456 record(agent_id, &outcome);
457 outcome
458}
459
460#[derive(Debug, Clone, PartialEq, Eq)]
466pub enum Holder {
467 Free,
469 Yours,
471 Other(HeldBy),
473 Unknown,
476 Unsupported,
478 Unreachable,
480}
481
482#[derive(Debug, Clone, Default, PartialEq, Eq)]
484pub struct HeldBy {
485 pub desc: String,
487 pub channel: String,
489 pub features: Vec<String>,
491 pub seal: Option<crate::backend::jekt_seal::SealOffer>,
494}
495
496const HOLDER_FRESH: Duration = Duration::from_secs(20);
499
500static HOLDER_CACHE: LazyLock<Mutex<HashMap<String, (Holder, Instant)>>> = LazyLock::new(Default::default);
501
502fn holder_key(agent: &str, token: &str) -> String {
506 use sha2::Digest;
507 format!("{}#{}", &hex::encode(sha2::Sha256::digest(token.as_bytes()))[..16], key(agent))
508}
509static HOLDER_UNSUPPORTED_UNTIL: LazyLock<Mutex<Option<Instant>>> = LazyLock::new(Default::default);
510
511pub async fn holder(base: &str, agent: &str, caller: &str, token: &str, http: &reqwest::Client) -> Holder {
515 if HOLDER_UNSUPPORTED_UNTIL.lock().unwrap_or_else(|e| e.into_inner()).is_some_and(|t| t > Instant::now()) {
516 return Holder::Unsupported;
517 }
518 if let Some((answer, at)) = HOLDER_CACHE.lock().unwrap_or_else(|e| e.into_inner()).get(&holder_key(agent, token)) {
519 if at.elapsed() < HOLDER_FRESH {
520 return answer.clone();
521 }
522 }
523 let Ok(mut url) = url::Url::parse(base) else {
524 return Holder::Unknown;
525 };
526 if let Ok(mut path) = url.path_segments_mut() {
527 path.pop_if_empty().extend(["agents", "lease", agent.trim()]);
528 }
529 let resp = http
530 .get(url)
531 .header("Authorization", format!("Bearer {token}"))
532 .header("X-Agent-ID", caller)
533 .header("X-Agent-Instance", instance_id())
534 .timeout(Duration::from_secs(5))
535 .send()
536 .await;
537 let answer = match resp {
538 Ok(r) => {
539 let status = r.status().as_u16();
540 let body = r.json::<serde_json::Value>().await.unwrap_or(serde_json::Value::Null);
541 holder_from(status, &body)
542 }
543 Err(e) => {
544 tracing::debug!(agent, error = %e, "wan_lease: holder query unreachable");
545 return Holder::Unreachable;
546 }
547 };
548 if answer == Holder::Unsupported {
549 *HOLDER_UNSUPPORTED_UNTIL.lock().unwrap_or_else(|e| e.into_inner()) = Some(Instant::now() + UNSUPPORTED_BACKOFF);
550 tracing::info!("wan_lease: relay has no lease holder query yet — routing as before");
551 }
552 HOLDER_CACHE
553 .lock()
554 .unwrap_or_else(|e| e.into_inner())
555 .insert(holder_key(agent, token), (answer.clone(), Instant::now()));
556 answer
557}
558
559fn holder_from(status: u16, body: &serde_json::Value) -> Holder {
560 match status {
561 200..=299 => match body.get("state").and_then(|s| s.as_str()) {
562 Some("free") => Holder::Free,
563 Some("yours") => Holder::Yours,
564 Some("other") => {
565 let held_by = body.get("held_by");
566 let field = |k: &str| held_by.and_then(|h| h.get(k));
567 Holder::Other(HeldBy {
568 desc: held_by.map(describe_holder).unwrap_or_default(),
569 channel: field("channel").and_then(|c| c.as_str()).unwrap_or_default().to_string(),
570 features: field("features")
571 .and_then(|f| f.as_array())
572 .map(|f| f.iter().filter_map(|v| v.as_str().map(str::to_string)).collect())
573 .unwrap_or_default(),
574 seal: field("seal").and_then(|s| serde_json::from_value(s.clone()).ok()),
575 })
576 }
577 _ => Holder::Unknown,
578 },
579 404 | 405 => Holder::Unsupported,
580 _ => Holder::Unknown,
581 }
582}
583
584#[cfg(test)]
585mod tests {
586 use super::*;
587
588 #[tokio::test]
592 async fn the_holder_query_asks_once_and_names_the_caller() {
593 let hits = std::sync::Arc::new(std::sync::Mutex::new(Vec::<(String, Option<String>, Option<String>, Option<String>)>::new()));
594 let sink = hits.clone();
595 let app = axum::Router::new().route(
596 "/agents/lease/:agent",
597 axum::routing::get(
598 move |axum::extract::Path(agent): axum::extract::Path<String>, headers: axum::http::HeaderMap| {
599 let sink = sink.clone();
600 async move {
601 let get = |k: &str| headers.get(k).and_then(|v| v.to_str().ok()).map(str::to_string);
602 sink.lock().unwrap().push((agent, get("authorization"), get("x-agent-id"), get("x-agent-instance")));
603 axum::Json(serde_json::json!({ "state": "other", "held_by": { "host": "desk-holder-test", "channel": "stable" } }))
604 }
605 },
606 ),
607 );
608 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
609 let addr = listener.local_addr().unwrap();
610 tokio::spawn(async move {
611 let _ = axum::serve(listener, app).await;
612 });
613 let base = format!("http://{addr}");
614 let http = reqwest::Client::new();
615 let agent = format!("HolderTest-{}", &uuid::Uuid::new_v4().to_string()[..8]);
616
617 let first = holder(&base, &agent, "lark", "tok", &http).await;
618 assert!(matches!(&first, Holder::Other(h) if h.desc.contains("desk-holder-test")), "{first:?}");
619 let again = holder(&base, &agent, "lark", "tok", &http).await;
620 assert_eq!(again, first);
621 let seen = hits.lock().unwrap().clone();
622 assert_eq!(seen.len(), 1, "the second answer came from the cache: {seen:?}");
623 let (path_agent, auth, caller, instance) = &seen[0];
624 assert_eq!(path_agent, &agent);
625 assert_eq!(auth.as_deref(), Some("Bearer tok"));
626 assert_eq!(caller.as_deref(), Some("lark"));
627 assert_eq!(instance.as_deref(), Some(instance_id().as_str()));
628
629 let closed = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
631 let dead = format!("http://{}", closed.local_addr().unwrap());
632 drop(closed);
633 let lost = format!("HolderLost-{}", &uuid::Uuid::new_v4().to_string()[..8]);
634 assert_eq!(holder(&dead, &lost, "lark", "tok", &http).await, Holder::Unreachable);
635 assert!(HOLDER_CACHE.lock().unwrap().get(&holder_key(&lost, "tok")).is_none());
636 }
637
638 #[test]
641 fn a_cached_holder_answer_belongs_to_its_credential() {
642 assert_eq!(holder_key("AgentY", "tok-a"), holder_key("agenty", "tok-a"));
643 assert_ne!(holder_key("agenty", "tok-a"), holder_key("agenty", "tok-b"));
644 }
645
646 const HOLDER_HOST: &str = "holder host (test)";
649
650 #[test]
653 fn a_holder_with_this_machines_name_is_this_computer() {
654 let local = crate::backend::reactive::registry::local_host_label();
655 let body = serde_json::json!({ "state": "other", "held_by": { "host": local.to_uppercase(), "channel": "stable", "version": "0.59.5" } });
656 let Holder::Other(h) = holder_from(200, &body) else { panic!("a holder that is not ours is `Other`") };
657 assert_eq!(h.desc, "this computer, channel stable, v0.59.5");
658 assert!(holder_on_this_computer(&h.desc));
659 }
660
661 #[test]
664 fn holder_answers_map_to_routes() {
665 use serde_json::json;
666 assert_eq!(holder_from(200, &json!({ "state": "free" })), Holder::Free);
667 assert_eq!(holder_from(200, &json!({ "state": "yours" })), Holder::Yours);
668 let other = holder_from(200, &json!({ "state": "other", "held_by": { "host": HOLDER_HOST, "channel": "stable", "version": "0.59.5" } }));
672 assert!(matches!(&other, Holder::Other(h) if h.desc.contains(HOLDER_HOST) && h.channel == "stable" && h.seal.is_none()), "{other:?}");
673 let seal = json!({ "instance": "i", "key_fp": "f", "key": "k", "sig": "s" });
674 let sealed = holder_from(200, &json!({ "state": "other", "held_by": { "host": HOLDER_HOST, "channel": "stable", "features": ["files-cloud-v1"], "seal": seal } }));
675 let Holder::Other(h) = sealed else { panic!("{sealed:?}") };
676 assert_eq!(h.features, vec!["files-cloud-v1".to_string()]);
677 assert_eq!(h.seal.map(|s| s.instance), Some("i".to_string()));
678 let malformed = holder_from(200, &json!({ "state": "other", "held_by": { "seal": { "instance": 3 } } }));
679 assert!(matches!(&malformed, Holder::Other(h) if h.seal.is_none()), "an offer that doesn't parse is no offer");
680 assert_eq!(holder_from(200, &json!({ "state": "unknown" })), Holder::Unknown);
681 assert_eq!(holder_from(200, &json!({ "state": "weird" })), Holder::Unknown);
682 assert_eq!(holder_from(200, &serde_json::Value::Null), Holder::Unknown);
683 assert_eq!(holder_from(404, &serde_json::Value::Null), Holder::Unsupported);
684 assert_eq!(holder_from(405, &serde_json::Value::Null), Holder::Unsupported);
685 for status in [401, 403, 429, 500] {
686 assert_eq!(holder_from(status, &serde_json::Value::Null), Holder::Unknown, "{status}");
687 }
688 }
689
690 #[tokio::test]
693 async fn forgetting_a_refusal_lets_the_next_turn_through() {
694 let agent = format!("agent-{}", uuid::Uuid::new_v4());
695 note_not_holder(&agent, &serde_json::json!({ "held_by": { "host": "desk" } }));
696 assert!(held_elsewhere(&agent).is_some());
697 forget_elsewhere(&agent.to_uppercase()).await;
698 assert_eq!(held_elsewhere(&agent), None);
699 }
700
701 #[tokio::test]
706 async fn a_409_to_a_request_from_before_a_take_over_is_ignored() {
707 let agent = format!("agent-{}", uuid::Uuid::new_v4());
708 let body = serde_json::json!({ "held_by": { "host": "desk" } });
709 let started = Instant::now();
710 tokio::time::sleep(Duration::from_millis(5)).await;
711 forget_elsewhere(&agent).await;
712 assert_eq!(note_not_holder_since(&agent, &body, started), None, "stale: not recorded, not fenced");
713 assert_eq!(held_elsewhere(&agent), None);
714
715 let later = Instant::now();
716 assert!(note_not_holder_since(&agent, &body, later).is_some(), "a fresh 409 still counts");
717 assert!(held_elsewhere(&agent).is_some());
718 }
719
720 #[tokio::test]
724 async fn forgetting_a_refusal_waits_for_a_lease_check_in_flight() {
725 let agent = format!("agent-{}", uuid::Uuid::new_v4());
726 let lock = op_lock(&agent);
727 let check = lock.lock().await;
728 let a = agent.clone();
729 let forget = tokio::spawn(async move { forget_elsewhere(&a).await });
730 tokio::time::sleep(Duration::from_millis(50)).await;
731 assert!(!forget.is_finished(), "forgetting waits for the check");
732 note_not_holder(&agent, &serde_json::json!({ "held_by": { "host": "desk" } }));
734 drop(check);
735 tokio::time::timeout(Duration::from_secs(5), forget).await.unwrap().unwrap();
736 assert_eq!(held_elsewhere(&agent), None, "the stale refusal is gone");
737 }
738
739 #[tokio::test]
742 async fn a_renewal_for_an_agent_no_longer_subscribed_claims_nothing() {
743 let hits = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
744 let counter = hits.clone();
745 let app = axum::Router::new().fallback(move || {
746 let counter = counter.clone();
747 async move {
748 counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
749 axum::Json(serde_json::json!({ "ok": true, "epoch": 1 }))
750 }
751 });
752 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
753 let base = format!("http://{}", listener.local_addr().unwrap());
754 tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
755 let agent = format!("agent-{}", uuid::Uuid::new_v4());
756 let http = reqwest::Client::new();
757
758 assert_eq!(ensure(&base, &agent, "", &http, || false).await, Outcome::Unknown);
759 assert_eq!(hits.load(std::sync::atomic::Ordering::SeqCst), 0, "no claim for an unsubscribed agent");
760 assert_eq!(ensure(&base, &agent, "", &http, || true).await, Outcome::Held);
761 assert_eq!(hits.load(std::sync::atomic::Ordering::SeqCst), 1);
762 }
763
764 #[tokio::test]
768 async fn a_release_skips_an_agent_subscribed_again() {
769 let agent = format!("agent-{}", uuid::Uuid::new_v4());
770 record(&agent, &Outcome::Held);
771 assert!(
772 !release("http://127.0.0.1:9", &agent, "", &reqwest::Client::new(), || false).await,
773 "reports that it did not let go"
774 );
775 let held = STATE.lock().unwrap().get(&key(&agent)).is_some_and(|e| e.held);
776 assert!(held, "the fresh claim is left alone");
777 }
778
779 #[tokio::test]
780 async fn a_release_waits_for_a_claim_in_progress_for_the_same_agent() {
781 let agent = format!("Agent-{}", uuid::Uuid::new_v4());
782 let lock = op_lock(&agent.to_lowercase());
783 let claim = lock.lock().await;
784 let a = agent.clone();
785 let release = tokio::spawn(async move {
786 super::release("http://127.0.0.1:9", &a, "", &reqwest::Client::new(), || true).await
787 });
788 tokio::time::sleep(Duration::from_millis(50)).await;
789 assert!(!release.is_finished(), "the release waits for the claim");
790 drop(claim);
791 tokio::time::timeout(Duration::from_secs(5), release).await.unwrap().unwrap();
792 }
793
794 #[test]
795 fn the_holder_is_described_without_account_or_instance() {
796 let held_by = serde_json::json!({ "host": "desk", "channel": "stable", "version": "0.58.0", "acquired_at": 1 });
797 assert_eq!(describe_holder(&held_by), "computer desk, channel stable, v0.58.0");
798 assert_eq!(describe_holder(&serde_json::Value::Null), "");
799 }
800
801 #[test]
804 fn a_holder_on_this_computer_is_described_as_this_computer() {
805 let here = crate::backend::reactive::registry::local_host_label();
806 let held_by = serde_json::json!({ "host": here, "channel": "local-main-x", "version": "0.57.6" });
807 assert_eq!(describe_holder(&held_by), "this computer, channel local-main-x, v0.57.6");
808 assert!(holder_on_this_computer(&describe_holder(&held_by)));
809 assert!(!holder_on_this_computer("computer desk, channel stable, v0.58.0"));
810 }
811
812 #[test]
815 fn a_same_computer_holder_gives_take_over_its_channel() {
816 let here = crate::backend::reactive::registry::local_host_label();
817 let agent = format!("agent-{}", uuid::Uuid::new_v4());
818 note_not_holder(&agent, &serde_json::json!({ "held_by": { "host": here, "channel": "local-main-x", "version": "0.57.6" } }));
819 assert_eq!(held_on_this_computer_by(&agent).as_deref(), Some("local-main-x"));
820 assert_eq!(held_on_another_computer(&agent), None);
821
822 let other = format!("agent-{}", uuid::Uuid::new_v4());
823 note_not_holder(&other, &serde_json::json!({ "held_by": { "host": "desk", "channel": "stable" } }));
824 assert_eq!(held_on_this_computer_by(&other), None);
825 assert_eq!(held_on_another_computer(&other).as_deref(), Some("computer desk, channel stable"));
826
827 assert_eq!(held_on_this_computer_by("never-seen"), None);
828 }
829
830 async fn lease_stub(
833 claim: (u16, serde_json::Value),
834 take: (u16, serde_json::Value),
835 ) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
836 use std::sync::atomic::{AtomicUsize, Ordering};
837 let (claims, takes) = (std::sync::Arc::new(AtomicUsize::new(0)), std::sync::Arc::new(AtomicUsize::new(0)));
838 let (c, t) = (claims.clone(), takes.clone());
839 let answer = |(status, body): (u16, serde_json::Value)| {
840 (axum::http::StatusCode::from_u16(status).unwrap(), axum::Json(body))
841 };
842 let app = axum::Router::new()
843 .route(
844 "/agents/lease",
845 axum::routing::post(move || {
846 c.fetch_add(1, Ordering::SeqCst);
847 let r = answer(claim.clone());
848 async move { r }
849 }),
850 )
851 .route(
852 "/agents/lease/take",
853 axum::routing::post(move || {
854 t.fetch_add(1, Ordering::SeqCst);
855 let r = answer(take.clone());
856 async move { r }
857 }),
858 );
859 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
860 let base = format!("http://{}", listener.local_addr().unwrap());
861 tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
862 (base, claims, takes)
863 }
864
865 fn held_here(channel: &str) -> serde_json::Value {
866 let here = crate::backend::reactive::registry::local_host_label();
867 serde_json::json!({ "error": "held_by_other", "held_by": { "host": here, "channel": channel, "version": "0.57.6" } })
868 }
869
870 #[tokio::test]
873 async fn take_over_takes_a_lease_an_instance_on_this_computer_kept() {
874 use std::sync::atomic::Ordering;
875 let (base, claims, takes) =
876 lease_stub((409, held_here("local-main-old")), (200, serde_json::json!({ "ok": true, "epoch": 6 }))).await;
877 let agent = format!("agent-{}", uuid::Uuid::new_v4());
878 assert_eq!(take_over(&base, &agent, "", &reqwest::Client::new()).await, Outcome::Held);
879 assert_eq!((claims.load(Ordering::SeqCst), takes.load(Ordering::SeqCst)), (1, 1));
880 assert!(is_held(&agent), "recorded, so the lease tick renews it");
881 assert_eq!(held_elsewhere(&agent), None);
882 }
883
884 #[tokio::test]
885 async fn take_over_never_takes_from_another_computer() {
886 use std::sync::atomic::Ordering;
887 let other = serde_json::json!({ "error": "held_by_other", "held_by": { "host": "some-other-desk", "channel": "stable" } });
888 let (base, _, takes) = lease_stub((409, other), (200, serde_json::json!({ "ok": true, "epoch": 6 }))).await;
889 let agent = format!("agent-{}", uuid::Uuid::new_v4());
890 assert_eq!(
891 take_over(&base, &agent, "", &reqwest::Client::new()).await,
892 Outcome::HeldElsewhere("computer some-other-desk, channel stable".into())
893 );
894 assert_eq!(takes.load(Ordering::SeqCst), 0);
895 }
896
897 #[tokio::test]
898 async fn take_over_of_a_free_lease_is_a_plain_claim() {
899 use std::sync::atomic::Ordering;
900 let (base, _, takes) = lease_stub((200, serde_json::json!({ "ok": true, "epoch": 1 })), (500, serde_json::Value::Null)).await;
901 let agent = format!("agent-{}", uuid::Uuid::new_v4());
902 assert_eq!(take_over(&base, &agent, "", &reqwest::Client::new()).await, Outcome::Held);
903 assert_eq!(takes.load(Ordering::SeqCst), 0);
904 }
905
906 #[tokio::test]
910 async fn take_over_on_a_relay_without_take_keeps_the_refusal_and_the_lease_tier() {
911 let (base, _, _) = lease_stub((409, held_here("local-main-old")), (404, serde_json::Value::Null)).await;
912 let agent = format!("agent-{}", uuid::Uuid::new_v4());
913 let outcome = take_over(&base, &agent, "", &reqwest::Client::new()).await;
914 assert!(matches!(&outcome, Outcome::HeldElsewhere(d) if holder_on_this_computer(d)), "{outcome:?}");
915 assert!(
916 UNSUPPORTED_UNTIL.lock().unwrap().is_none_or(|t| t <= Instant::now()),
917 "a missing take route is not a missing lease tier"
918 );
919 }
920
921 #[test]
922 fn claim_answers_map_to_outcomes() {
923 assert_eq!(claim_outcome(Some((200, serde_json::json!({ "ok": true, "epoch": 1 })))), Outcome::Held);
924 assert_eq!(
925 claim_outcome(Some((409, serde_json::json!({ "held_by": { "host": "desk" } })))),
926 Outcome::HeldElsewhere("computer desk".into())
927 );
928 assert_eq!(claim_outcome(None), Outcome::Unknown, "unreachable relay: fail open");
929 assert_eq!(claim_outcome(Some((500, serde_json::Value::Null))), Outcome::Unknown);
930 }
931
932 #[test]
933 fn a_not_holder_answer_is_remembered_for_the_early_check_and_cleared_by_a_grant() {
934 let agent = format!("agent-{}", uuid::Uuid::new_v4());
935 assert!(held_elsewhere(&agent).is_none());
936 let desc = note_not_holder(&agent.to_uppercase(), &serde_json::json!({ "held_by": { "host": "desk" } }));
937 assert_eq!(desc, "computer desk");
938 assert_eq!(held_elsewhere(&agent).as_deref(), Some("computer desk"), "keyed case-insensitively, like the relay");
939 record(&agent, &Outcome::Held);
940 assert!(held_elsewhere(&agent).is_none());
941 }
942
943 async fn batch_stub(
946 renew_batch: (u16, serde_json::Value),
947 ) -> (String, std::sync::Arc<std::sync::Mutex<Vec<String>>>) {
948 let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
949 let log = seen.clone();
950 let app = axum::Router::new().fallback(move |req: axum::extract::Request| {
951 let (log, renew_batch) = (log.clone(), renew_batch.clone());
952 async move {
953 let line = format!("{} {}", req.method(), req.uri().path());
954 log.lock().unwrap().push(line.clone());
955 let (status, body) = match line.as_str() {
956 "POST /agents/lease/renew-batch" => renew_batch,
957 "POST /agents/lease" => (200, serde_json::json!({ "ok": true, "epoch": 2 })),
958 _ => (404, serde_json::Value::Null),
959 };
960 (axum::http::StatusCode::from_u16(status).unwrap(), axum::Json(body))
961 }
962 });
963 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
964 let base = format!("http://{}", listener.local_addr().unwrap());
965 tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
966 (base, seen)
967 }
968
969 fn held_and_due(agent: &str) {
971 STATE.lock().unwrap().insert(key(agent), Entry { held: true, ..Default::default() });
972 }
973
974 #[tokio::test]
975 async fn one_request_renews_every_held_lease_that_is_due() {
976 let [a, b, c, d] = std::array::from_fn(|_| format!("agent-{}", uuid::Uuid::new_v4()));
977 for agent in [&a, &b, &c, &d] {
978 held_and_due(agent);
979 }
980 let results = serde_json::json!({ "results": {
981 a.clone(): { "ok": true, "epoch": 1, "ttl_ms": 60000 },
982 b.clone(): { "ok": false, "error": "not_holder", "held_by": { "host": "desk", "channel": "stable" } },
983 c.clone(): { "ok": false, "error": "not_holder", "held_by": null },
984 d.clone(): { "ok": false, "error": "unavailable" },
985 }});
986 let (base, seen) = batch_stub((200, results)).await;
987 let agents = vec![a.to_uppercase(), b.clone(), c.clone(), d.clone()];
988
989 let got = renew_held_batch(&base, &agents, "tok", &reqwest::Client::new(), |_| true).await;
990
991 assert_eq!(got.get(&a), Some(&Outcome::Held), "keyed by the lowercased name");
992 assert_eq!(got.get(&b), Some(&Outcome::HeldElsewhere("computer desk, channel stable".into())));
993 assert_eq!(got.get(&c), Some(&Outcome::Held), "nobody held it: claimed again");
994 assert_eq!(got.get(&d), None, "unavailable: left to `ensure` on its own");
995 assert_eq!(*seen.lock().unwrap(), ["POST /agents/lease/renew-batch", "POST /agents/lease"]);
996 assert_eq!(held_elsewhere(&b).as_deref(), Some("computer desk, channel stable"));
997 assert!(is_held(&a) && is_held(&c));
998 }
999
1000 #[tokio::test]
1001 async fn a_relay_without_the_batch_route_is_left_to_renew_one_by_one() {
1002 let [a, b] = std::array::from_fn(|_| format!("agent-{}", uuid::Uuid::new_v4()));
1003 held_and_due(&a);
1004 held_and_due(&b);
1005 let (base, seen) = batch_stub((404, serde_json::Value::Null)).await;
1006 let agents = vec![a.clone(), b.clone()];
1007
1008 assert!(renew_held_batch(&base, &agents, "tok", &reqwest::Client::new(), |_| true).await.is_empty());
1009 assert!(super::super::relay::batch_routes_missing(&base));
1010 assert!(
1011 UNSUPPORTED_UNTIL.lock().unwrap().is_none_or(|t| t <= Instant::now()),
1012 "a missing batch route is not a missing lease tier"
1013 );
1014 assert!(renew_held_batch(&base, &agents, "tok", &reqwest::Client::new(), |_| true).await.is_empty());
1016 assert_eq!(seen.lock().unwrap().len(), 1);
1017 }
1018
1019 #[tokio::test]
1020 async fn the_batch_skips_a_single_due_agent_and_agents_no_longer_subscribed() {
1021 let [a, b, fresh] = std::array::from_fn(|_| format!("agent-{}", uuid::Uuid::new_v4()));
1022 held_and_due(&a);
1023 held_and_due(&b);
1024 record(&fresh, &Outcome::Held); let (base, seen) = batch_stub((200, serde_json::json!({ "results": {} }))).await;
1026
1027 let one_due = vec![a.clone(), fresh.clone()];
1028 assert!(renew_held_batch(&base, &one_due, "tok", &reqwest::Client::new(), |_| true).await.is_empty());
1029 assert!(seen.lock().unwrap().is_empty(), "one due agent: the single route costs the same");
1030
1031 let both = vec![a.clone(), b.clone()];
1032 renew_held_batch(&base, &both, "tok", &reqwest::Client::new(), |agent| agent == a).await;
1033 assert_eq!(*seen.lock().unwrap(), ["POST /agents/lease/renew-batch"], "asked, but only for {a}");
1034 }
1035
1036 #[test]
1037 fn the_instance_id_is_host_and_channel() {
1038 let id = instance_id();
1039 assert_eq!(id.matches('/').count(), 1, "{id}");
1040 assert!(id.ends_with(&crate::backend::reactive::registry::local_channel_id()));
1041 }
1042}