Skip to main content

lean_ctx_cloud/workers/
register.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Worker registration and the instance card on Cloud (C0 2.0 §3.17.1,
3//! §3.18.1): E10 `POST /v1/workers` and E44 `PATCH /v1/instances/{id}/card`
4//! are signed by the instance key as `domain ‖ canonical_json(body)`;
5//! E11 `PATCH /v1/workers/{wkr}` rides on the instance token alone.
6
7use base64::Engine as _;
8use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64URL;
9use ed25519_dalek::Signer as _;
10use serde::{Deserialize, Serialize};
11use serde_json::{Value, json};
12
13use super::super::CloudError;
14use super::super::instance_key::InstanceKeys;
15use super::super::transport::CloudClient;
16use super::card::WorkerCard;
17use super::{WorkerAliasKey, alias_signing_key, check_name, key_id};
18
19pub const WORKER_DOMAIN: &str = "leanctx.cloud.worker.v1\n";
20pub const INSTANCE_CARD_DOMAIN: &str = "leanctx.cloud.instance_card.v1\n";
21
22/// Who is registered: the workspace worker, or its alias in one public
23/// vault or swarm (`place_ref` = `"{kind}:{id}"`).
24pub struct Registration<'a> {
25    pub instance_id: &'a str,
26    pub host_app: &'a str,
27    pub role: &'a str,
28    pub name: &'a str,
29    pub card: &'a WorkerCard,
30    pub alias_place: Option<&'a str>,
31}
32
33/// Add `key_id` and the instance signature over the body without them.
34fn sign(keys: &InstanceKeys, domain: &str, mut body: Value) -> Result<Value, CloudError> {
35    let signer = keys.signing_key();
36    body["key_id"] = key_id(signer).into();
37    let input = lean_ctx_protocol::cloud::signing_input(domain, &body)
38        .map_err(|e| CloudError::Local(e.to_string()))?;
39    body["signature"] = hex::encode(signer.sign(&input).to_bytes()).into();
40    Ok(body)
41}
42
43/// The signed E10 body. The name passes the local rule first
44/// (`invalid_name`, SPEC-ENGINE §3.6).
45pub fn register_body(keys: &InstanceKeys, reg: &Registration<'_>) -> Result<Value, CloudError> {
46    let name = check_name(reg.name)
47        .map_err(|refusal| CloudError::Config(format!("invalid_name: {}", refusal.message())))?;
48    let card = serde_json::to_value(reg.card).map_err(|e| CloudError::Local(e.to_string()))?;
49    let mut body = json!({
50        "host_app": reg.host_app,
51        "role": reg.role,
52        "name": name,
53        "card": card,
54    });
55    match reg.alias_place {
56        None => {
57            body["worker_id"] =
58                super::workspace_worker_id(reg.instance_id, reg.host_app, reg.role).into();
59        }
60        Some(place) => {
61            let alias = WorkerAliasKey::of(keys);
62            body["worker_id"] = alias.worker_id(reg.host_app, reg.role, place).into();
63            body["place"] = place.into();
64            body["alias_pubkey"] = B64URL
65                .encode(alias_signing_key(keys, place).verifying_key().as_bytes())
66                .into();
67            body["hlc_node"] = alias.hlc_node(place).into();
68        }
69    }
70    sign(keys, WORKER_DOMAIN, body)
71}
72
73/// Consent channel the engine reports; the server derives the real one
74/// from the bound presence key and a card can only downgrade it.
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
76#[serde(rename_all = "snake_case")]
77pub enum ConsentChannel {
78    OsPresence,
79    TtyOnly,
80}
81
82/// The signed E44 body. `clear_presence_key` sends `presence_key: null`,
83/// which drops the bound key (e.g. after the helper was removed); a card
84/// can never set or replace one.
85pub fn instance_card_body(
86    keys: &InstanceKeys,
87    instance_version: &str,
88    consent_channel: ConsentChannel,
89    clear_presence_key: bool,
90) -> Result<Value, CloudError> {
91    let mut body = json!({
92        "instance_version": instance_version,
93        "consent_channel": consent_channel,
94    });
95    if clear_presence_key {
96        body["presence_key"] = Value::Null;
97    }
98    sign(keys, INSTANCE_CARD_DOMAIN, body)
99}
100
101/// E10 response: the worker as Cloud stored it.
102#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
103pub struct RegisteredWorker {
104    pub id: String,
105    pub name: String,
106    pub place: Option<String>,
107    pub status: String,
108    pub registered_at: u64,
109}
110
111#[derive(Deserialize)]
112struct WorkerEnvelope {
113    worker: RegisteredWorker,
114}
115
116/// The bound presence key, as E44 returns it.
117#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
118pub struct PresenceKey {
119    pub alg: String,
120    pub key_id: String,
121    pub hardware: bool,
122    pub bound_at: u64,
123}
124
125#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
126pub struct Account {
127    pub user_id: String,
128    /// C0 says string; a Cloud that answers `null` for an account without
129    /// a handle must not stop the card from being read.
130    #[serde(default)]
131    pub handle: Option<String>,
132}
133
134#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
135pub struct CardState {
136    pub instance_version: String,
137    pub consent_channel: ConsentChannel,
138    pub updated_at: u64,
139}
140
141/// E44 response.
142#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
143pub struct InstanceCard {
144    pub card: CardState,
145    pub account: Account,
146    pub presence_key: Option<PresenceKey>,
147}
148
149/// Largest answer of these routes.
150const MAX_ANSWER: usize = 64 * 1024;
151
152/// A C0 2.0 refusal in the person's words (SPEC-ENGINE §3.6, WEB §4.4);
153/// `None` leaves it to the generic mapping.
154fn worded(code: &str, reason: &str) -> Option<String> {
155    Some(match (code, reason) {
156        (_, "confusable") => "This name mixes alphabets. Use one alphabet.".into(),
157        (_, "reserved") => {
158            "Names may not contain cloud, thinkery, leanctx or moderator. Pick another name.".into()
159        }
160        ("worker_not_owned", _) => {
161            "worker_not_owned: LeanCTX Cloud has bound this worker id to another instance.".into()
162        }
163        (_, "worker_cap_reached") => {
164            "worker_cap_reached: this instance already has 32 workers on LeanCTX Cloud.".into()
165        }
166        (_, "presence_key_locked") => "The presence key can only be cleared here; bind a new one with `lean-ctx cloud connect --bind-presence-key`.".into(),
167        _ => return None,
168    })
169}
170
171/// Send, then parse a 2xx answer or word the refusal.
172fn call<T: for<'de> Deserialize<'de>>(
173    client: &CloudClient,
174    method: &str,
175    path: &str,
176    body: &Value,
177    what: &str,
178) -> Result<T, CloudError> {
179    let (status, answer) = client.send_answer(method, path, Some(body), MAX_ANSWER)?;
180    if !(200..300).contains(&status) {
181        let code = answer["error"]["code"].as_str().unwrap_or_default();
182        let reason = answer["error"]["reason"].as_str().unwrap_or_default();
183        return Err(worded(code, reason).map_or_else(
184            || CloudError::from_response(status, &answer),
185            CloudError::Config,
186        ));
187    }
188    parse(answer, what)
189}
190
191fn parse<T: for<'de> Deserialize<'de>>(value: Value, what: &str) -> Result<T, CloudError> {
192    serde_json::from_value(value).map_err(|e| CloudError::Protocol(format!("{what}: {e}")))
193}
194
195/// E10.
196pub fn register(
197    client: &CloudClient,
198    keys: &InstanceKeys,
199    reg: &Registration<'_>,
200) -> Result<RegisteredWorker, CloudError> {
201    let body = register_body(keys, reg)?;
202    Ok(call::<WorkerEnvelope>(client, "POST", "/workers", &body, "worker registration")?.worker)
203}
204
205/// E44 for the enrolled instance, at `cloud connect` and engine start.
206/// The engine reports `os_presence` only with a bound presence key
207/// (§3.8.4); the server derives the real channel.
208pub fn announce_instance(session: &crate::auth::Session) -> Result<InstanceCard, CloudError> {
209    let keys = InstanceKeys::load(&session.store)?;
210    let channel = if crate::consent::broker::bound_presence_key(&session.store).is_some() {
211        ConsentChannel::OsPresence
212    } else {
213        ConsentChannel::TtyOnly
214    };
215    let minor = std::cell::Cell::new(None);
216    let exchanged = session.with_client(|client| {
217        let (status, answer) =
218            card_exchange(client, &keys, &session.instance.instance_id, channel, false)?;
219        minor.set(client.answered_minor());
220        if status == 401 {
221            // The session renews the token and asks once more.
222            return Err(CloudError::from_response(status, &answer));
223        }
224        Ok((status, answer))
225    });
226    // E44 exists only on a C0 2.0 Cloud: its status (not the body, whose
227    // details may change) tells the relay which bus protocol to speak, and
228    // the answer's `Cloud-Protocol` minor which 2.x writes it takes.
229    let speaks = match &exchanged {
230        Ok((status, _)) if (200..300).contains(status) => Some(true),
231        Ok((404, _)) | Err(CloudError::NotFound) => Some(false),
232        _ => None,
233    };
234    if let Some(v2) = speaks {
235        crate::bus::relay_v2::record_protocol_minor(&session.store, v2, minor.get())?;
236    }
237    // V9: what the server accepts (`session_ref`), cached for this origin.
238    // A failure keeps the last answer and never fails the card.
239    let _ = session.with_client(|client| {
240        crate::session_ref::refresh(&session.store, &session.instance.url, client)
241    });
242    let result = exchanged.and_then(|(status, answer)| card_from(status, answer));
243    // The owner account web consents are checked against (§3.8.2 step 6).
244    if let Ok(card) = &result {
245        session
246            .store
247            .write_config(crate::consent::broker::ACCOUNT_FILE, &card.account)?;
248    }
249    result
250}
251
252/// Retire one worker of this instance on Cloud (C0 2.2
253/// `DELETE /v1/workers/{id}`): it no longer counts against the 32-worker
254/// cap. Done as well when Cloud says it does not know the worker (404
255/// `not_found`) or that another instance owns it (409
256/// `worker_not_owned`): nothing of this instance is left to free. A 404
257/// without that code (a Cloud that has no such route) is not done: the
258/// worker still counts there.
259pub fn retire(client: &CloudClient, worker_id: &str) -> Result<(), CloudError> {
260    if !crate::bus::address::is_worker_id(worker_id) {
261        return Err(CloudError::Config(format!(
262            "{worker_id} is not a worker id"
263        )));
264    }
265    let (status, answer) =
266        client.send_answer("DELETE", &format!("/workers/{worker_id}"), None, MAX_ANSWER)?;
267    let code = answer["error"]["code"].as_str().unwrap_or_default();
268    if (200..300).contains(&status)
269        || (status == 404 && code == "not_found")
270        || code == "worker_not_owned"
271    {
272        return Ok(());
273    }
274    Err(CloudError::from_response(status, &answer))
275}
276
277/// Retire on Cloud the workers the book gave up for new ones (see
278/// `attach::attach`), so a registration is not refused with
279/// `worker_cap_reached`. Every queued worker is tried; one Cloud could not
280/// retire now stays queued, and the first such error is returned.
281pub fn retire_evicted(session: &crate::auth::Session) -> Result<(), CloudError> {
282    let instance_id = &session.instance.instance_id;
283    let mut first_error = None;
284    for worker_id in super::attach::retired(&session.store, instance_id)? {
285        match session.with_client(|client| retire(client, &worker_id)) {
286            Ok(()) => super::attach::retirement_done(&session.store, instance_id, &worker_id)?,
287            Err(error) => {
288                first_error.get_or_insert(error);
289            }
290        }
291    }
292    first_error.map_or(Ok(()), Err)
293}
294
295/// How long a worker no session used stays before the sync retires it
296/// (`lean-ctx cloud worker retire --idle` defaults to the same).
297pub const IDLE_RETIRE: std::time::Duration = std::time::Duration::from_hours(24);
298/// How long the worker of an ended app session stays (its role is never
299/// attached again once the session is gone).
300pub const SESSION_IDLE_RETIRE: std::time::Duration = std::time::Duration::from_secs(3600);
301/// See [`on_session_end`].
302const SESSION_END_GRACE: std::time::Duration = std::time::Duration::from_secs(600);
303
304/// The sync's sweep (owner 09.11.: workers that are not active do not
305/// count): give up the workers idle for [`IDLE_RETIRE`] and those of ended
306/// app sessions idle for [`SESSION_IDLE_RETIRE`], then retire on Cloud every
307/// worker queued so far. The ids given up now.
308pub fn sweep(session: &crate::auth::Session) -> Result<Vec<String>, CloudError> {
309    let instance_id = &session.instance.instance_id;
310    let mut gone = super::attach::give_up_idle(&session.store, instance_id, IDLE_RETIRE, false)?;
311    gone.extend(super::attach::give_up_idle(
312        &session.store,
313        instance_id,
314        SESSION_IDLE_RETIRE,
315        true,
316    )?);
317    retire_evicted(session)?;
318    Ok(gone)
319}
320
321/// When an agent session ends: give up the workers of app sessions that no
322/// active session holds and none attached in the last `SESSION_END_GRACE`
323/// (a session still starting up). No request; Cloud hears of them with the
324/// next sync or registration ([`retire_evicted`]). A worker the ending
325/// session still holds goes with the sync's [`sweep`].
326pub fn on_session_end(store: &crate::state::CloudStore) {
327    let Ok(Some(instance)) = store.instance() else {
328        return;
329    };
330    match super::attach::give_up_idle(store, &instance.instance_id, SESSION_END_GRACE, true) {
331        Ok(gone) if !gone.is_empty() => {
332            tracing::debug!("cloud: workers of ended sessions given up: {gone:?}");
333        }
334        Ok(_) => {}
335        Err(error) => tracing::debug!("cloud: workers of ended sessions not given up: {error}"),
336    }
337}
338
339/// Register the worker a session attached to, once (E10 on the first
340/// event or bus post, SPEC-ENGINE §3.6), and remember it in the book.
341/// An already registered worker costs no request. Workers the book gave
342/// up are retired on Cloud first; one that cannot be retired now (offline,
343/// a Cloud without the route) is recorded and tried again next time, and
344/// the registration goes ahead (Cloud may still have room).
345pub fn ensure_registered(
346    session: &crate::auth::Session,
347    attached: &super::attach::LocalWorker,
348    card: &WorkerCard,
349) -> Result<super::attach::LocalWorker, CloudError> {
350    if attached.registered_at.is_some() {
351        return Ok(attached.clone());
352    }
353    if let Err(error) = retire_evicted(session) {
354        session
355            .store
356            .record_error(&format!("worker retirement: {error}"));
357    }
358    let keys = InstanceKeys::load(&session.store)?;
359    let instance = &session.instance;
360    let name = attached.name.clone().unwrap_or_else(|| {
361        super::default_name(
362            &instance.label,
363            &super::attach::host_display(&attached.host_app),
364            &attached.role,
365        )
366    });
367    let reg = Registration {
368        instance_id: &instance.instance_id,
369        host_app: &attached.host_app,
370        role: &attached.role,
371        name: &name,
372        card,
373        alias_place: None,
374    };
375    let worker = session.with_client(|client| register(client, &keys, &reg))?;
376    if worker.id != attached.worker_id {
377        return Err(CloudError::Protocol(format!(
378            "LeanCTX Cloud registered {} for {}",
379            worker.id, attached.worker_id
380        )));
381    }
382    super::attach::update_book(&session.store, &instance.instance_id, |workers| {
383        let entry = workers.iter_mut().find(|w| w.worker_id == worker.id)?;
384        entry.registered_at = Some(worker.registered_at);
385        entry.name = Some(worker.name.clone());
386        Some(entry.clone())
387    })?
388    .ok_or_else(|| CloudError::Local(format!("{} left the worker book", worker.id)))
389}
390
391/// E11: rename and/or a new card.
392pub fn patch(
393    client: &CloudClient,
394    worker_id: &str,
395    name: Option<&str>,
396    card: Option<&WorkerCard>,
397) -> Result<RegisteredWorker, CloudError> {
398    if !crate::bus::address::is_worker_id(worker_id) {
399        return Err(CloudError::Config(format!(
400            "{worker_id} is not a worker id"
401        )));
402    }
403    let mut body = json!({});
404    if let Some(name) = name {
405        body["name"] = check_name(name)
406            .map_err(|r| CloudError::Config(format!("invalid_name: {}", r.message())))?
407            .into();
408    }
409    if let Some(card) = card {
410        body["card"] = serde_json::to_value(card).map_err(|e| CloudError::Local(e.to_string()))?;
411    }
412    if body.as_object().is_none_or(serde_json::Map::is_empty) {
413        return Err(CloudError::Config("nothing to change".into()));
414    }
415    let path = format!("/workers/{worker_id}");
416    Ok(call::<WorkerEnvelope>(client, "PATCH", &path, &body, "worker update")?.worker)
417}
418
419/// E44.
420pub fn send_instance_card(
421    client: &CloudClient,
422    keys: &InstanceKeys,
423    instance_id: &str,
424    consent_channel: ConsentChannel,
425    clear_presence_key: bool,
426) -> Result<InstanceCard, CloudError> {
427    let (status, answer) = card_exchange(
428        client,
429        keys,
430        instance_id,
431        consent_channel,
432        clear_presence_key,
433    )?;
434    card_from(status, answer)
435}
436
437fn card_exchange(
438    client: &CloudClient,
439    keys: &InstanceKeys,
440    instance_id: &str,
441    consent_channel: ConsentChannel,
442    clear_presence_key: bool,
443) -> Result<(u16, Value), CloudError> {
444    let body = instance_card_body(
445        keys,
446        env!("CARGO_PKG_VERSION"),
447        consent_channel,
448        clear_presence_key,
449    )?;
450    let path = format!("/instances/{instance_id}/card");
451    client.send_answer("PATCH", &path, Some(&body), MAX_ANSWER)
452}
453
454fn card_from(status: u16, answer: Value) -> Result<InstanceCard, CloudError> {
455    if !(200..300).contains(&status) {
456        let code = answer["error"]["code"].as_str().unwrap_or_default();
457        let reason = answer["error"]["reason"].as_str().unwrap_or_default();
458        return Err(worded(code, reason).map_or_else(
459            || CloudError::from_response(status, &answer),
460            CloudError::Config,
461        ));
462    }
463    parse(answer, "instance card")
464}
465
466#[cfg(test)]
467mod tests {
468    use super::super::card::{Availability, Budget};
469    use super::*;
470
471    const FIXTURES: &str = concat!(
472        concat!(env!("CARGO_MANIFEST_DIR"), "/../.."),
473        "/crates/lean-ctx-protocol/tests/fixtures/cloud-v2/"
474    );
475
476    fn fixture(name: &str) -> Value {
477        let text = std::fs::read_to_string(format!("{FIXTURES}{name}")).unwrap();
478        serde_json::from_str(&text).unwrap()
479    }
480
481    fn instance_a() -> InstanceKeys {
482        InstanceKeys::from_seeds([0x49; 32], [0x01; 32])
483    }
484
485    #[test]
486    fn workspace_registration_matches_the_fixture_byte_for_byte() {
487        let card = WorkerCard::new(
488            "claude-code",
489            Some("claude-opus-5-5"),
490            ["ctx_read", "ctx_search", "ctx_shell"].map(String::from),
491            Budget {
492                tasks_per_day: Some(20),
493                usd_cents_per_day: None,
494            },
495            Availability::Online,
496        );
497        let body = register_body(
498            &instance_a(),
499            &Registration {
500                instance_id: "6f2b9c4e-1a3d-4e5f-8a7b-0c1d2e3f4a5b",
501                host_app: "claude-code",
502                role: "backend",
503                name: "yves-mac · Claude Code · backend",
504                card: &card,
505                alias_place: None,
506            },
507        )
508        .unwrap();
509        assert_eq!(body, fixture("routes/worker_register.request.json"));
510    }
511
512    #[test]
513    fn alias_registration_matches_the_fixture_byte_for_byte() {
514        let card = WorkerCard::new(
515            "codex",
516            None,
517            Vec::new(),
518            Budget::default(),
519            Availability::Idle,
520        );
521        let body = register_body(
522            &instance_a(),
523            &Registration {
524                instance_id: "6f2b9c4e-1a3d-4e5f-8a7b-0c1d2e3f4a5b",
525                host_app: "codex",
526                role: "general",
527                name: "Codex · general",
528                card: &card,
529                alias_place: Some("vault:3f1c2b6a-8d4e-4a7b-9c10-5e2f6a7b8c01"),
530            },
531        )
532        .unwrap();
533        let want = fixture("routes/worker_register.alias.request.json");
534        assert_eq!(body, want);
535        // Nothing in the alias body names the instance.
536        assert!(!body.to_string().contains("6f2b9c4e"));
537    }
538
539    #[test]
540    fn instance_cards_match_the_fixtures_and_can_only_clear() {
541        let keys = instance_a();
542        assert_eq!(
543            instance_card_body(&keys, "3.12.0", ConsentChannel::OsPresence, false).unwrap(),
544            fixture("routes/instance_card.request.json")
545        );
546        assert_eq!(
547            instance_card_body(&keys, "3.12.0", ConsentChannel::TtyOnly, true).unwrap(),
548            fixture("routes/instance_card.clear.request.json")
549        );
550        let card: InstanceCard =
551            parse(fixture("routes/instance_card.response.json"), "card").unwrap();
552        assert_eq!(card.presence_key.unwrap().key_id, "ef1bd9c792ccc768");
553        assert_eq!(card.account.handle.as_deref(), Some("yves"));
554        // An account without a handle (dogfood finding 25.10.) still reads,
555        // and only the status decides the protocol.
556        let mut nameless = fixture("routes/instance_card.response.json");
557        nameless["account"]["handle"] = Value::Null;
558        let card = card_from(200, nameless).unwrap();
559        assert_eq!(card.account.handle, None);
560        assert!(card_from(404, json!({"error": {"code": "not_found"}})).is_err());
561    }
562
563    #[test]
564    fn a_mixed_alphabet_name_is_refused_before_it_leaves() {
565        let card = WorkerCard::new(
566            "codex",
567            None,
568            Vec::new(),
569            Budget::default(),
570            Availability::Idle,
571        );
572        let err = register_body(
573            &instance_a(),
574            &Registration {
575                instance_id: "6f2b9c4e-1a3d-4e5f-8a7b-0c1d2e3f4a5b",
576                host_app: "codex",
577                role: "general",
578                name: "аdmin",
579                card: &card,
580                alias_place: None,
581            },
582        )
583        .unwrap_err();
584        assert!(err.to_string().contains("invalid_name"), "{err}");
585    }
586
587    #[test]
588    fn refusals_reach_the_person_in_their_words() {
589        let locked = fixture("routes/instance_card.error.presence_key_locked.json");
590        let text = worded(
591            locked["error"]["code"].as_str().unwrap(),
592            locked["error"]["reason"].as_str().unwrap(),
593        )
594        .unwrap();
595        assert!(text.contains("--bind-presence-key"), "{text}");
596        assert_eq!(
597            worded("invalid_request", "confusable").unwrap(),
598            "This name mixes alphabets. Use one alphabet."
599        );
600        assert!(
601            worded("worker_not_owned", "")
602                .unwrap()
603                .starts_with("worker_not_owned")
604        );
605        assert_eq!(worded("invalid_request", "other"), None);
606    }
607
608    #[test]
609    fn responses_parse() {
610        let w: WorkerEnvelope =
611            parse(fixture("routes/worker_register.response.json"), "w").unwrap();
612        assert_eq!(w.worker.id, "wkr_vk4oelpv5lzjmev44hun");
613        let p: WorkerEnvelope = parse(fixture("routes/worker_patch.response.json"), "p").unwrap();
614        assert!(p.worker.name.contains("payments"));
615        // A retired worker registered again comes back like any other.
616        let r: WorkerEnvelope = parse(
617            fixture("routes/worker_register.reactivated.response.json"),
618            "r",
619        )
620        .unwrap();
621        assert!(r.worker.id.starts_with("wkr_"));
622    }
623
624    /// A one-request-per-connection Cloud that answers `DELETE /v1/workers/*`
625    /// with `(status, body)` and records the request lines.
626    fn retiring_cloud(
627        status: u16,
628        body: String,
629    ) -> (String, std::sync::Arc<std::sync::Mutex<Vec<String>>>) {
630        use std::io::{BufRead as _, BufReader, Write as _};
631        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
632        let origin = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
633        let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
634        let recorded = std::sync::Arc::clone(&seen);
635        std::thread::spawn(move || {
636            for stream in listener.incoming().flatten() {
637                let mut writer = stream.try_clone().unwrap();
638                let mut reader = BufReader::new(stream);
639                let mut line = String::new();
640                if reader.read_line(&mut line).unwrap_or(0) == 0 {
641                    continue;
642                }
643                loop {
644                    let mut header = String::new();
645                    reader.read_line(&mut header).unwrap();
646                    if header.trim_end().is_empty() {
647                        break;
648                    }
649                }
650                recorded.lock().unwrap().push(line.trim_end().to_string());
651                let _ = write!(
652                    writer,
653                    "HTTP/1.1 {status} X\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
654                    body.len()
655                );
656            }
657        });
658        (origin, seen)
659    }
660
661    /// `DELETE /v1/workers/{id}` as C0 2.2 fixes it (`routes/worker_retire.*`):
662    /// 204, an unknown or placed worker (404 not_found) and one of another
663    /// instance (409 worker_not_owned) are all done for this instance;
664    /// anything else keeps the worker queued.
665    #[test]
666    fn retiring_a_worker_is_done_unless_cloud_could_not_answer() {
667        let route = fixture("routes/worker_retire.request.json");
668        let id = route["path"]
669            .as_str()
670            .unwrap()
671            .strip_prefix("/v1/workers/")
672            .unwrap()
673            .to_string();
674        assert_eq!(route["method"], "DELETE");
675        assert_eq!(route["response"]["status"], 204);
676        for (status, body) in [
677            (204, String::new()),
678            (
679                404,
680                fixture("routes/worker_retire.error.not_found.json").to_string(),
681            ),
682            (
683                409,
684                fixture("routes/worker_retire.error.not_owned.json").to_string(),
685            ),
686        ] {
687            let (origin, seen) = retiring_cloud(status, body);
688            let client = CloudClient::new(&origin).unwrap();
689            retire(&client, &id).unwrap_or_else(|e| panic!("{status}: {e}"));
690            assert_eq!(
691                seen.lock().unwrap().as_slice(),
692                [format!("DELETE /v1/workers/{id} HTTP/1.1")]
693            );
694        }
695        let (origin, _) = retiring_cloud(503, r#"{"error":{"code":"unavailable"}}"#.into());
696        assert!(retire(&CloudClient::new(&origin).unwrap(), &id).is_err());
697        // A Cloud without the route: its 404 frees nothing there.
698        let (origin, _) = retiring_cloud(404, String::new());
699        assert!(retire(&CloudClient::new(&origin).unwrap(), &id).is_err());
700        assert!(retire(&CloudClient::new(&origin).unwrap(), "../admin").is_err());
701    }
702}