Skip to main content

degenbot_cli_core/
operator.rs

1//! The operator command-channel client: JSON-lines over a Unix domain socket
2//! (ADR-051 D6;).
3//!
4//! `degenbot fleet posture [show|set]` and `degenbot path [add|discover]` are
5//! clients of a LIVE bot's `OperatorServer`. The versioned wire protocol is
6//! documented in `src/degenbot/operator/operator_channel.py`; that header +
7//! the server's framing are read-only contract and this module must not drift
8//! from them.
9//!
10//! # Wire shape (one JSON object per line, newline-terminated)
11//!
12//! Request lines nest the payload at the top level (the exact shape Python's
13//! `send_command` writes and the server's `_decode_request` reads):
14//!
15//! ```text
16//! {"op": "add_path", "payload": {"steps": [...], "directions": [true]}}
17//! {"op": "discover", "payload": {"bound": 5}}
18//! {"op": "set_fleet_posture", "payload": {"cordon_enter_events": 2}}
19//! {"op": "get_fleet_posture", "payload": {}}
20//! ```
21//!
22//! Response lines:
23//!
24//! ```text
25//! {"ok": true, "detail": "..."}
26//! {"ok": true, "detail": "", "effective": {...}}
27//! {"ok": false, "error": "..."}
28//! ```
29//!
30//! # Division of validation
31//!
32//! This client adds **wire hygiene only** - an unknown `cordon_*` key, an empty
33//! posture patch, an unknown hop-family string - refused BEFORE the socket is
34//! touched by [`validate_posture_patch`] / [`parse_hop_token`]. The six cordon
35//! values are DOMAIN validation and stay the authority of the server
36//! (`PosturePolicyPatch::validate` in the workers core); this crate deliberately
37//! does not import or re-implement it, so a client built earlier never second-
38//! guesses a host built later.
39//!
40//! # Socket resolution
41//!
42//! `--socket` > `DEGENBOT_OPERATOR_SOCKET` (the shell-environment layer, read
43//! through the `degenbot-config` `EnvVars` seam) > `~/.config/degenbot/operator.sock`
44//! (the example driver's plug-in default). No typed config-file key exists for
45//! the operator socket, so the env layer is the only config surface; a future
46//! typed key would slot in above the env layer at exactly one site.
47
48#[cfg(unix)]
49use std::future::Future;
50use std::path::{Path, PathBuf};
51#[cfg(unix)]
52use std::time::Duration;
53
54use degenbot_config::EnvVars;
55use serde_json::{json, Map, Value};
56#[cfg(unix)]
57use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
58#[cfg(unix)]
59use tokio::net::UnixStream;
60
61use crate::error::{CliError, UnknownVariant};
62
63/// The environment variable naming the live bot's operator socket (the shell
64/// layer of the cascade). Empty is treated exactly like unset.
65pub const SOCKET_ENV: &str = "DEGENBOT_OPERATOR_SOCKET";
66
67/// The plug-in default socket path (the settlement-bot example's
68/// `--operator-socket` default family). The leading `~` expands against `HOME`.
69pub const SOCKET_DEFAULT: &str = "~/.config/degenbot/operator.sock";
70
71/// The `HOME` layer used to expand a leading `~` in the default.
72const HOME_ENV: &str = "HOME";
73
74/// Per-request connect/read timeout (mirrors the server's `request_timeout`
75/// default of 60s).
76#[cfg(unix)]
77const REQUEST_TIMEOUT: Duration = Duration::from_secs(60);
78
79/// The refusal `send_request` returns on a host with no Unix domain socket.
80/// The channel is a UDS protocol end to end (the Python `OperatorServer`
81/// cannot bind one on Windows either), so off Unix the command arms stay
82/// compiled and fail here, at the one transport site.
83#[cfg(not(unix))]
84const UDS_UNSUPPORTED: &str = "the operator command channel requires a Unix domain socket, \
85     which this platform does not provide";
86
87/// The six fleet-posture threshold key names `set_fleet_posture` accepts (the
88/// typed `DEGENBOT_FLEET_CORDON_*` keys). Anything else is refused at the wire
89/// before it reaches the host.
90pub const FLEET_POSTURE_THRESHOLD_KEYS: [&str; 6] = [
91    "cordon_enter_events",
92    "cordon_enter_window_ms",
93    "cordon_duty_percent",
94    "cordon_duty_window_ms",
95    "cordon_exit_clean_ms",
96    "cordon_sim_intake_floor",
97];
98
99/// The documented sentinel for `--cordon-sim-intake-floor`: the literal
100/// `null` (case-insensitive) restores half the slot cap; any other value is a
101/// threshold. The host's `PosturePolicyPatch` carries this as the
102/// `Some(None)` override.
103pub const SIM_INTAKE_FLOOR_RESTORE: &str = "null";
104
105/// A pool family on the operator wire (`V2` / `V3` / `V4`) — the canonical
106/// pool-family taxonomy, re-exported under its wire name.
107///
108/// One taxonomy, one owner: the variant set, the discriminants, and the wire
109/// tags live on [`degenbot_db::PoolKind`] (re-exported from the
110/// `degenbot-pathfinding` graph vocabulary this crate's DB surface already
111/// projects through). This shell adds only the operator channel's lenient
112/// parse; a family added to the canonical enum compiles here without an edit
113/// and inherits its tag, where the second enum this re-export replaced would
114/// have drifted silently.
115pub use degenbot_db::PoolKind as PathFamily;
116
117/// Parse a case-insensitive operator-wire family token (`v2`/`V2`, ...
118/// `v4`/`V4`) into the canonical [`PathFamily`].
119///
120/// The canonical enum's own `TryFrom<&str>` parses the *persisted* `kind`
121/// strings (`uniswap_v2`, ...), so the wire spelling keeps its own entry
122/// point rather than overloading that contract.
123///
124/// # Errors
125///
126/// [`UnknownVariant`] for a family outside the canonical taxonomy, naming the
127/// raw input and the known wire tags: a hop naming no family on the wire is
128/// refused before the socket is touched, never silently routed.
129pub fn path_family_from_wire(raw: &str) -> Result<PathFamily, UnknownVariant> {
130    let upper = raw.to_ascii_uppercase();
131    PathFamily::ALL
132        .iter()
133        .find(|family| family.tag() == upper)
134        .copied()
135        .ok_or_else(|| UnknownVariant {
136            raw: raw.to_owned(),
137            known: PathFamily::ALL.iter().map(|family| family.tag()).collect(),
138        })
139}
140
141/// One hop in an `add_path` `steps` array.
142#[derive(Debug, Clone, PartialEq, Eq)]
143pub struct PathStep {
144    /// The hop's pool family.
145    pub family: PathFamily,
146    /// The pool address (`0x` + 40 hex).
147    pub address: String,
148    /// The V4 pool id (`0x` + 64 hex); `None` for V2/V3 and for a V4 hop that
149    /// omitted it.
150    pub hash: Option<String>,
151}
152
153/// A `--direction` choice: one bit applied to every hop.
154#[derive(Debug, Clone, Copy, PartialEq, Eq)]
155pub enum PathDirection {
156    /// Zero-for-one: `true` for each hop.
157    Zfo,
158    /// One-for-zero: `false` for each hop.
159    Ozf,
160}
161
162impl PathDirection {
163    /// Every direction, in declaration order — the set an unrecognized argv
164    /// spelling is judged against.
165    pub const ALL: [Self; 2] = [Self::Zfo, Self::Ozf];
166
167    /// The argv spelling.
168    #[must_use]
169    pub const fn as_str(self) -> &'static str {
170        match self {
171            Self::Zfo => "zfo",
172            Self::Ozf => "ozf",
173        }
174    }
175
176    /// The per-hop wire bit.
177    #[must_use]
178    pub const fn is_zfo(self) -> bool {
179        matches!(self, Self::Zfo)
180    }
181}
182
183impl TryFrom<&str> for PathDirection {
184    type Error = UnknownVariant;
185
186    /// Parse the argv spelling (case-sensitive, mirroring click's Choice).
187    ///
188    /// # Errors
189    ///
190    /// [`UnknownVariant`] for a spelling outside the closed set, naming the
191    /// raw input and the known spellings.
192    fn try_from(raw: &str) -> Result<Self, Self::Error> {
193        match raw {
194            "zfo" => Ok(Self::Zfo),
195            "ozf" => Ok(Self::Ozf),
196            _ => Err(UnknownVariant {
197                raw: raw.to_owned(),
198                known: Self::ALL.iter().map(|d| d.as_str()).collect(),
199            }),
200        }
201    }
202}
203
204/// Parse one `FAMILY:ADDRESS[:HASH]` hop token into a wire [`PathStep`]
205/// (mirrors `_parse_hop`). Family is case-insensitive; the V4 hash is carried
206/// only for V4 and only when non-empty.
207///
208/// # Errors
209///
210/// [`CliError::OperatorHygiene`] when the family is not V2/V3/V4 or the
211/// address is absent/empty - refused before any socket work.
212pub fn parse_hop_token(hop: &str) -> Result<PathStep, CliError> {
213    let parts: Vec<&str> = hop.split(':').collect();
214    let raw_family = parts.first().copied().unwrap_or_default();
215    let family = path_family_from_wire(raw_family).map_err(|_| {
216        CliError::OperatorHygiene(format!("--hop family must be V2|V3|V4, got {raw_family:?}"))
217    })?;
218    let address = parts
219        .get(1)
220        .copied()
221        .filter(|address| !address.is_empty())
222        .ok_or_else(|| CliError::OperatorHygiene(format!("--hop {hop:?} is missing an address")))?;
223    let hash = if family == PathFamily::V4 {
224        parts
225            .get(2)
226            .copied()
227            .filter(|hash| !hash.is_empty())
228            .map(ToString::to_string)
229    } else {
230        None
231    };
232    Ok(PathStep {
233        family,
234        address: address.to_string(),
235        hash,
236    })
237}
238
239/// A `set_fleet_posture` threshold value.
240///
241/// The wire carries integers for the five count/window keys and a float for
242/// `cordon_duty_percent`; `Null` is the `cordon_sim_intake_floor` restore
243/// sentinel.
244#[derive(Debug, Clone, Copy, PartialEq)]
245pub enum PosturePatchValue {
246    /// An integer threshold.
247    Int(u64),
248    /// A float threshold (`cordon_duty_percent`).
249    Float(f64),
250    /// Restore half the slot cap (`cordon_sim_intake_floor` only).
251    Null,
252}
253
254impl PosturePatchValue {
255    /// The JSON value the wire carries. A non-finite float cannot cross JSON
256    /// and degrades to `null` (the host then rejects it - domain validation
257    /// stays server-side).
258    #[must_use]
259    pub fn json_value(self) -> Value {
260        match self {
261            Self::Int(value) => Value::from(value),
262            Self::Float(value) => {
263                serde_json::Number::from_f64(value).map_or(Value::Null, Value::Number)
264            }
265            Self::Null => Value::Null,
266        }
267    }
268}
269
270/// One `cordon_*` entry in a partial posture patch.
271#[derive(Debug, Clone, PartialEq)]
272pub struct PosturePatchEntry {
273    /// One of [`FLEET_POSTURE_THRESHOLD_KEYS`].
274    pub key: String,
275    /// The threshold value.
276    pub value: PosturePatchValue,
277}
278
279impl PosturePatchEntry {
280    /// Build an entry from a key + typed value.
281    #[must_use]
282    pub fn new(key: impl Into<String>, value: PosturePatchValue) -> Self {
283        Self {
284            key: key.into(),
285            value,
286        }
287    }
288
289    /// Build an integer entry.
290    #[must_use]
291    pub fn int(key: impl Into<String>, value: u64) -> Self {
292        Self::new(key, PosturePatchValue::Int(value))
293    }
294
295    /// Build a float entry.
296    #[must_use]
297    pub fn float(key: impl Into<String>, value: f64) -> Self {
298        Self::new(key, PosturePatchValue::Float(value))
299    }
300}
301
302/// Parse the `cordon_sim_intake_floor` flag text: the literal `null`
303/// (case-insensitive) is the documented restore sentinel
304/// ([`SIM_INTAKE_FLOOR_RESTORE`]), anything else must be an unsigned integer.
305///
306/// # Errors
307///
308/// [`CliError::OperatorHygiene`] when the text is neither the sentinel nor an
309/// unsigned integer.
310pub fn parse_sim_intake_floor(raw: &str) -> Result<PosturePatchValue, CliError> {
311    if raw.eq_ignore_ascii_case(SIM_INTAKE_FLOOR_RESTORE) {
312        return Ok(PosturePatchValue::Null);
313    }
314    raw.trim()
315        .parse::<u64>()
316        .map(PosturePatchValue::Int)
317        .map_err(|_| {
318            CliError::OperatorHygiene(format!(
319                "cordon_sim_intake_floor must be an integer or {SIM_INTAKE_FLOOR_RESTORE:?} to                  restore half the slot cap, got {raw:?}"
320            ))
321        })
322}
323
324/// Client-side wire hygiene for a posture patch: no unknown `cordon_*` key and
325/// no empty patch. Mirrors the host's `handle_fleet_posture_op` guard messages;
326/// the host's typed `PosturePolicyPatch::validate` remains the value authority.
327///
328/// # Errors
329///
330/// [`CliError::OperatorHygiene`] with the refused key list or the empty-patch
331/// message.
332pub fn validate_posture_patch(patch: &[PosturePatchEntry]) -> Result<(), CliError> {
333    let mut unknown: Vec<&str> = patch
334        .iter()
335        .map(|entry| entry.key.as_str())
336        .filter(|key| !FLEET_POSTURE_THRESHOLD_KEYS.contains(key))
337        .collect();
338    unknown.sort_unstable();
339    unknown.dedup();
340    if !unknown.is_empty() {
341        return Err(CliError::OperatorHygiene(format!(
342            "unknown fleet-posture threshold key(s): {}",
343            unknown.join(", ")
344        )));
345    }
346    if patch.is_empty() {
347        return Err(CliError::OperatorHygiene(
348            "set_fleet_posture needs at least one threshold key (empty patch)".to_string(),
349        ));
350    }
351    Ok(())
352}
353
354/// The four ops the live host serves, encoded as one request line.
355#[derive(Debug, Clone, PartialEq)]
356pub enum WireRequest {
357    /// `add_path`: enqueue one specific path.
358    AddPath {
359        /// The hop steps, in path order.
360        steps: Vec<PathStep>,
361        /// Per-hop direction bits, or `None` to let the host auto-resolve.
362        directions: Option<Vec<bool>>,
363    },
364    /// `discover`: one bounded on-demand discovery sweep.
365    Discover {
366        /// Maximum paths to process, or `None` for the host's default.
367        bound: Option<u64>,
368    },
369    /// `set_fleet_posture`: a partial patch over the six `cordon_*` keys.
370    SetFleetPosture {
371        /// The patch entries (must already pass [`validate_posture_patch`]).
372        patch: Vec<PosturePatchEntry>,
373    },
374    /// `get_fleet_posture`: read the live thresholds + posture.
375    GetFleetPosture,
376}
377
378impl WireRequest {
379    /// The wire op name.
380    #[must_use]
381    pub const fn op_name(&self) -> &'static str {
382        match self {
383            Self::AddPath { .. } => "add_path",
384            Self::Discover { .. } => "discover",
385            Self::SetFleetPosture { .. } => "set_fleet_posture",
386            Self::GetFleetPosture => "get_fleet_posture",
387        }
388    }
389
390    /// The request payload object.
391    #[must_use]
392    pub fn payload(&self) -> Value {
393        match self {
394            Self::AddPath { steps, directions } => {
395                let steps: Vec<Value> = steps.iter().map(step_json).collect();
396                let directions = directions.as_ref().map_or(Value::Null, |bits| json!(bits));
397                json!({ "steps": steps, "directions": directions })
398            }
399            Self::Discover { bound } => json!({ "bound": bound }),
400            Self::SetFleetPosture { patch } => {
401                let mut payload = Map::new();
402                for entry in patch {
403                    payload.insert(entry.key.clone(), entry.value.json_value());
404                }
405                Value::Object(payload)
406            }
407            Self::GetFleetPosture => json!({}),
408        }
409    }
410
411    /// Encode the one request line the server reads (JSON object + newline).
412    #[must_use]
413    pub fn encode_line(&self) -> String {
414        let mut envelope = Map::new();
415        envelope.insert("op".to_string(), Value::from(self.op_name()));
416        envelope.insert("payload".to_string(), self.payload());
417        let mut line =
418            serde_json::to_string(&Value::Object(envelope)).unwrap_or_else(|_| "{}".to_string());
419        line.push('\n');
420        line
421    }
422}
423
424/// One wire `steps` entry (only the V4 hash key is carried, and only when set).
425fn step_json(step: &PathStep) -> Value {
426    let mut object = Map::new();
427    object.insert("family".to_string(), Value::from(step.family.tag()));
428    object.insert("address".to_string(), Value::from(step.address.clone()));
429    if let Some(hash) = &step.hash {
430        object.insert("hash".to_string(), Value::from(hash.clone()));
431    }
432    Value::Object(object)
433}
434
435/// A decoded response frame.
436#[derive(Debug, Clone, PartialEq)]
437pub enum WireResponse {
438    /// `{"ok": true, ...}`.
439    Ok {
440        /// The `detail` string (`""` when absent).
441        detail: String,
442        /// The `effective` policy object, when the op echoes one.
443        effective: Option<Value>,
444    },
445    /// `{"ok": false, "error": "..."}` - including the host's unknown-op reply.
446    Err {
447        /// The `error` string.
448        error: String,
449    },
450}
451
452impl WireResponse {
453    /// Whether the host accepted the command.
454    #[must_use]
455    pub const fn is_ok(&self) -> bool {
456        matches!(self, Self::Ok { .. })
457    }
458
459    /// The success detail (`""` for an error frame).
460    #[must_use]
461    pub fn detail(&self) -> &str {
462        match self {
463            Self::Ok { detail, .. } => detail,
464            Self::Err { .. } => "",
465        }
466    }
467
468    /// The echoed effective policy, when present.
469    #[must_use]
470    pub fn effective(&self) -> Option<&Value> {
471        match self {
472            Self::Ok { effective, .. } => effective.as_ref(),
473            Self::Err { .. } => None,
474        }
475    }
476
477    /// The host's error string, when the frame was a refusal.
478    #[must_use]
479    pub fn error(&self) -> Option<&str> {
480        match self {
481            Self::Err { error } => Some(error),
482            Self::Ok { .. } => None,
483        }
484    }
485}
486
487/// Decode one response line. A malformed/non-object/missing-`ok` frame is a
488/// protocol error; a well-formed `{"ok": false, ...}` frame (including the
489/// host's unknown-op reply) is [`WireResponse::Err`], never a panic.
490///
491/// # Errors
492///
493/// [`CliError::OperatorProtocol`] for an empty line, invalid UTF-8/JSON, a
494/// non-object frame, or an `ok` field that is missing/non-boolean.
495pub fn decode_response(line: &str) -> Result<WireResponse, CliError> {
496    let trimmed = line.trim_end_matches(['\n', '\r']);
497    if trimmed.is_empty() {
498        return Err(CliError::OperatorProtocol(
499            "operator host sent an empty response line".to_string(),
500        ));
501    }
502    let value: Value = serde_json::from_str(trimmed).map_err(|err| {
503        CliError::OperatorProtocol(format!("invalid operator response JSON: {err}"))
504    })?;
505    let Some(object) = value.as_object() else {
506        return Err(CliError::OperatorProtocol(
507            "operator response is not a JSON object".to_string(),
508        ));
509    };
510    match object.get("ok") {
511        Some(Value::Bool(true)) => Ok(WireResponse::Ok {
512            detail: object
513                .get("detail")
514                .and_then(Value::as_str)
515                .unwrap_or_default()
516                .to_string(),
517            effective: object.get("effective").cloned(),
518        }),
519        Some(Value::Bool(false)) => Ok(WireResponse::Err {
520            error: object
521                .get("error")
522                .and_then(Value::as_str)
523                .unwrap_or("operator host reported failure without an error message")
524                .to_string(),
525        }),
526        Some(_) => Err(CliError::OperatorProtocol(
527            "operator response 'ok' is not a boolean".to_string(),
528        )),
529        None => Err(CliError::OperatorProtocol(
530            "operator response is missing 'ok'".to_string(),
531        )),
532    }
533}
534
535/// Render an `effective` object as one compact JSON object with its top-level
536/// keys sorted - the Python CLI's `json.dumps(effective, sort_keys=True)`.
537/// `None` renders `{}` (the Python `response.get("effective", {})` default).
538///
539/// The effective policy is a flat object by protocol, so sorting the top level
540/// is equivalent to Python's recursive `sort_keys`.
541#[must_use]
542pub fn render_json_sorted(value: Option<&Value>) -> String {
543    match value {
544        Some(Value::Object(map)) => {
545            let mut entries: Vec<(&String, &Value)> = map.iter().collect();
546            entries.sort_by(|a, b| a.0.cmp(b.0));
547            let inner = entries
548                .iter()
549                .map(|(key, value)| {
550                    let key = serde_json::to_string(key).unwrap_or_default();
551                    let value = serde_json::to_string(value).unwrap_or_default();
552                    format!("{key}: {value}")
553                })
554                .collect::<Vec<_>>()
555                .join(", ");
556            format!("{{{inner}}}")
557        }
558        Some(other) => serde_json::to_string(other).unwrap_or_default(),
559        None => "{}".to_string(),
560    }
561}
562
563/// Resolve the operator socket: `--socket` > `DEGENBOT_OPERATOR_SOCKET` >
564/// `~/.config/degenbot/operator.sock`. The winning value has a leading `~`
565/// expanded against `HOME` through the env seam.
566#[must_use]
567pub fn resolve_socket(env: &dyn EnvVars, cli_socket: Option<&str>) -> PathBuf {
568    let env_value = env.get(SOCKET_ENV);
569    let raw = match (non_empty(cli_socket), non_empty(env_value.as_deref())) {
570        (Some(cli), _) => cli,
571        (None, Some(value)) => value,
572        (None, None) => SOCKET_DEFAULT,
573    };
574    expand_tilde(env, raw)
575}
576
577/// Treat an empty string exactly like an absent layer.
578fn non_empty(value: Option<&str>) -> Option<&str> {
579    value.filter(|value| !value.is_empty())
580}
581
582/// Expand a leading `~` (or `~`/) against `HOME` from the env seam (mirrors
583/// the `degenbot-config` resolver's expansion for the database-path default).
584fn expand_tilde(env: &dyn EnvVars, raw: &str) -> PathBuf {
585    let home = env.get(HOME_ENV).filter(|home| !home.is_empty());
586    if raw == "~" {
587        if let Some(home) = home {
588            return PathBuf::from(home);
589        }
590    } else if let Some(rest) = raw.strip_prefix("~/") {
591        if let Some(home) = home {
592            return Path::new(&home).join(rest);
593        }
594    }
595    PathBuf::from(raw)
596}
597
598/// Send one request to the operator host and decode its single response line.
599///
600/// The arms build a [`WireRequest`] and call this; the transport is a
601/// short-lived `tokio` runtime over a Unix-domain socket (the arms are sync).
602///
603/// # Errors
604///
605/// [`CliError::OperatorProtocol`] when the socket is unreachable, the exchange
606/// times out, or the response is malformed; [`CliError::RuntimeNested`] when
607/// called from inside an existing `tokio` runtime.
608pub fn send_request(socket: &Path, request: &WireRequest) -> Result<WireResponse, CliError> {
609    let line = request.encode_line();
610    exchange_blocking(socket, line)
611}
612
613/// Drive one encoded request line to its response line over the operator
614/// socket.
615#[cfg(unix)]
616fn exchange_blocking(socket: &Path, line: String) -> Result<WireResponse, CliError> {
617    block_on_operator(exchange(socket, line))?
618}
619
620/// Off Unix there is no Unix domain socket to reach: the same
621/// [`CliError::OperatorProtocol`] the unreachable-socket arm raises reports it.
622#[cfg(not(unix))]
623fn exchange_blocking(socket: &Path, line: String) -> Result<WireResponse, CliError> {
624    let _ = (socket, line);
625    Err(CliError::OperatorProtocol(UDS_UNSUPPORTED.to_string()))
626}
627
628/// Drive the exchange future on a self-built runtime, reusing the console's one
629/// runtime helper. Only `RuntimeNested` is reachable from
630/// [`crate::block::block_on`]; any other mapping is a build failure and is
631/// reported as the operator-protocol error it is.
632#[cfg(unix)]
633fn block_on_operator<F: Future>(future: F) -> Result<F::Output, CliError> {
634    crate::block::block_on(future).map_err(|err| match err {
635        CliError::RuntimeNested => err,
636        other => CliError::OperatorProtocol(other.message()),
637    })
638}
639
640/// One request line out, one response line in (the server closes after the
641/// reply). Unix-only: the wire rides a Unix domain socket.
642///
643/// The production budget is the single [`REQUEST_TIMEOUT`]; the body takes it
644/// as a parameter so tests can pin the deadline arithmetic with a short one.
645#[cfg(unix)]
646async fn exchange(socket: &Path, line: String) -> Result<WireResponse, CliError> {
647    exchange_within(socket, line, REQUEST_TIMEOUT).await
648}
649
650/// The exchange body under ONE deadline shared by connect + write + flush +
651/// read.
652///
653/// Every phase spends the *remaining* budget, never a fresh copy of it, so a
654/// peer that stalls any single phase cannot stretch the whole exchange past
655/// `request_timeout` (the old three-phase shape let a stalling peer spend the
656/// bound three times over).
657///
658/// The read side is additionally **resumable**. `read_until` appends into the
659/// CALLER-OWNED `buffer`, and a `timeout` that fires drops only the in-flight
660/// future - never the bytes it already pushed into that buffer. So a timeout
661/// need not abandon a partial line: the loop re-arms against the SAME buffer
662/// under the SAME deadline, and the terminal timeout reports how many partial
663/// bytes it gave up.
664///
665/// # Cancel safety
666///
667/// **Cancel-safe on the READ side only**: the `read_until` loop appends into
668/// the CALLER-OWNED `buffer`, and a cancelled `timeout(.., read_until(..))`
669/// future drops only the in-flight read — never the bytes it already pushed
670/// into that buffer. So cancellation mid-read leaves the accumulated prefix
671/// intact and a resumed loop re-arms against the same buffer under the same
672/// deadline (this is exactly the resumability the phased-body doc documents).
673/// The `connect`/`write_all`/`flush` arms are single `await`s that lose
674/// nothing on drop; each surfaces a terminal `CliError::OperatorProtocol` on
675/// timeout or I/O failure rather than a partial success.
676///
677/// **The unsafe remainder — the accumulated prefix is discarded with no
678/// observer**: if the CALLER drops this future mid-exchange, the local
679/// `buffer` is dropped with it. Any partial response bytes read so far vanish,
680/// and because the drop is silent there is no telemetry, no error, and no
681/// partial-line report — the caller just never sees a `WireResponse`. The
682/// resumability above is resumability WITHIN one `exchange_within` call, not
683/// across a cancellation: a dropped future does not hand its `buffer` back.
684/// The caller's obligation is therefore to treat a cancelled exchange as a
685/// total loss of the in-flight line (re-issue the request fresh), not as a
686/// resumable partial — "resumable" describes the deadline lap, never the
687/// cancelled future.
688#[cfg(unix)]
689async fn exchange_within(
690    socket: &Path,
691    line: String,
692    request_timeout: Duration,
693) -> Result<WireResponse, CliError> {
694    let deadline = tokio::time::Instant::now() + request_timeout;
695
696    let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
697    let connect = tokio::time::timeout(remaining, UnixStream::connect(socket))
698        .await
699        .map_err(|_| {
700            CliError::OperatorProtocol(format!(
701                "timed out connecting to operator socket {}",
702                socket.display()
703            ))
704        })?;
705    let mut stream = connect.map_err(|err| {
706        CliError::OperatorProtocol(format!(
707            "cannot reach operator socket {}: {err}",
708            socket.display()
709        ))
710    })?;
711
712    let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
713    tokio::time::timeout(remaining, stream.write_all(line.as_bytes()))
714        .await
715        .map_err(|_| {
716            CliError::OperatorProtocol(format!(
717                "timed out writing to operator socket {}",
718                socket.display()
719            ))
720        })?
721        .map_err(|err| {
722            CliError::OperatorProtocol(format!(
723                "failed writing to operator socket {}: {err}",
724                socket.display()
725            ))
726        })?;
727
728    let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
729    tokio::time::timeout(remaining, stream.flush())
730        .await
731        .map_err(|_| {
732            CliError::OperatorProtocol(format!(
733                "timed out flushing operator socket {}",
734                socket.display()
735            ))
736        })?
737        .map_err(|err| {
738            CliError::OperatorProtocol(format!(
739                "failed flushing operator socket {}: {err}",
740                socket.display()
741            ))
742        })?;
743
744    let mut reader = BufReader::new(stream);
745    let mut buffer = Vec::new();
746    // Resume against the one deadline: a dropped `read_until` future leaves the
747    // bytes it already appended in `buffer` (the buffer is caller-owned), so a
748    // slow-dribbling server keeps its accumulated prefix across laps rather
749    // than losing everything to a single per-read timeout.
750    loop {
751        let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
752        if remaining.is_zero() {
753            return Err(CliError::OperatorProtocol(format!(
754                "timed out waiting for a response from operator socket {} (discarded {} partial bytes)",
755                socket.display(),
756                buffer.len()
757            )));
758        }
759        match tokio::time::timeout(remaining, reader.read_until(b'\n', &mut buffer)).await {
760            // A full line (or EOF-after-bytes, which the decode below rejects).
761            Ok(Ok(read)) if read > 0 => break,
762            Ok(Ok(_)) => {
763                return Err(CliError::OperatorProtocol(format!(
764                    "no response from operator server at {}",
765                    socket.display()
766                )));
767            }
768            Ok(Err(err)) => {
769                return Err(CliError::OperatorProtocol(format!(
770                    "failed reading from operator socket {}: {err}",
771                    socket.display()
772                )));
773            }
774            // Timed out mid-line: the partial prefix stays in `buffer`
775            // (caller-owned), so the (empty) arm falls through to loop back
776            // and resume the SAME buffer under the SAME deadline - the bytes
777            // already received are never abandoned.
778            Err(_) => {}
779        }
780    }
781    let text = String::from_utf8(buffer).map_err(|err| {
782        CliError::OperatorProtocol(format!("operator response is not valid UTF-8: {err}"))
783    })?;
784    decode_response(&text)
785}
786
787#[cfg(test)]
788mod tests {
789    #![expect(clippy::unwrap_used)]
790
791    use super::*;
792
793    #[test]
794    fn path_family_wire_parse_is_case_insensitive() {
795        assert_eq!(path_family_from_wire("v2"), Ok(PathFamily::V2));
796        assert_eq!(path_family_from_wire("V3"), Ok(PathFamily::V3));
797        assert_eq!(path_family_from_wire("v4"), Ok(PathFamily::V4));
798    }
799
800    #[test]
801    fn path_family_wire_parse_unknown_names_the_raw_value_and_known_set() {
802        let err = path_family_from_wire("v5").unwrap_err();
803        assert_eq!(err.raw, "v5");
804        let message = err.to_string();
805        assert!(message.contains("v5"), "raw value missing from: {message}");
806        assert!(
807            message.contains("V2") && message.contains("V3") && message.contains("V4"),
808            "known set missing from: {message}"
809        );
810    }
811
812    #[test]
813    fn path_direction_try_from_round_trips_the_argv_spellings() {
814        for direction in PathDirection::ALL {
815            assert_eq!(PathDirection::try_from(direction.as_str()), Ok(direction));
816        }
817    }
818
819    #[test]
820    fn path_direction_try_from_unknown_names_the_raw_value_and_known_set() {
821        let err = PathDirection::try_from("zof").unwrap_err();
822        assert_eq!(err.raw, "zof");
823        let message = err.to_string();
824        assert!(
825            message.contains("zof") && message.contains("zfo") && message.contains("ozf"),
826            "raw value and known set missing from: {message}"
827        );
828    }
829
830    // -- the transport deadline -------------------------------------------------
831
832    /// Bind `socket`, accept one connection, drain the request line, then write
833    /// `partial` (no newline) and stall well past the client's budget. The line
834    /// is never terminated, so a per-read timeout can only make progress by
835    /// RETAINING the prefix it already buffered.
836    #[cfg(unix)]
837    fn dribble_once(socket: &Path, partial: &'static [u8]) {
838        use std::io::{BufRead, BufReader, Write};
839        use std::os::unix::net::UnixListener;
840
841        let listener = UnixListener::bind(socket).unwrap();
842        std::thread::spawn(move || {
843            let (mut stream, _) = listener.accept().unwrap();
844            let mut reader = BufReader::new(stream.try_clone().unwrap());
845            let mut line = String::new();
846            reader.read_line(&mut line).unwrap();
847            stream.write_all(partial).unwrap();
848            stream.flush().unwrap();
849            // Stall far longer than the client's short budget; the newline
850            // never arrives.
851            std::thread::sleep(Duration::from_secs(5));
852        });
853    }
854
855    /// The whole exchange is bounded by ONE deadline, not a fresh full budget
856    /// per phase. A server that dribbles a few bytes and then stalls must make
857    /// the client return at roughly its small TOTAL budget - and the terminal
858    /// timeout must report the partial bytes it gave up (the observability
859    /// win that proves the prefix survived the dropped read future).
860    #[cfg(unix)]
861    #[test]
862    fn a_dribbling_server_is_bounded_by_the_total_deadline() {
863        use std::time::Instant as StdInstant;
864
865        let dir = tempfile::tempdir().unwrap();
866        let socket = dir.path().join("operator.sock");
867        let partial = b"{\"ok\": true, \"det";
868        dribble_once(&socket, partial);
869
870        let request_timeout = Duration::from_millis(250);
871        let runtime = tokio::runtime::Builder::new_current_thread()
872            .enable_all()
873            .build()
874            .unwrap();
875        let started = StdInstant::now();
876        let err = runtime
877            .block_on(exchange_within(
878                &socket,
879                "{\"op\": \"get_fleet_posture\", \"payload\": {}}\n".to_string(),
880                request_timeout,
881            ))
882            .unwrap_err();
883        let elapsed = started.elapsed();
884
885        assert!(matches!(err, CliError::OperatorProtocol(_)), "got {err:?}");
886        let message = err.message();
887        assert!(
888            message.contains("timed out waiting for a response from operator socket"),
889            "kept prefix missing: {message}"
890        );
891        // The partial-byte suffix is additive; the retained prefix is nonempty
892        // (and no larger than what the server actually sent).
893        let count = message
894            .split("discarded ")
895            .nth(1)
896            .and_then(|rest| rest.split_whitespace().next())
897            .and_then(|n| n.parse::<usize>().ok());
898        assert!(
899            matches!(count, Some(retained) if retained > 0 && retained <= partial.len()),
900            "prefix was not retained across the timeout (count {count:?}): {message}"
901        );
902        // ONE deadline: roughly the small budget, never a fresh per-phase
903        // timeout (which here would be the full 60s read budget).
904        assert!(
905            elapsed >= request_timeout,
906            "returned before the budget: {elapsed:?}"
907        );
908        assert!(
909            elapsed < request_timeout * 4,
910            "the exchange outran its single deadline: {elapsed:?}"
911        );
912    }
913
914    /// The happy path under the same short-budget seam: a complete line is
915    /// decoded, proving `exchange_within` did not regress the one-line read.
916    #[cfg(unix)]
917    #[test]
918    fn exchange_within_reads_a_full_line_under_a_short_budget() {
919        use std::io::{BufRead, BufReader, Write};
920        use std::os::unix::net::UnixListener;
921
922        let dir = tempfile::tempdir().unwrap();
923        let socket = dir.path().join("operator.sock");
924        let listener = UnixListener::bind(&socket).unwrap();
925        let handle = std::thread::spawn(move || {
926            let (mut stream, _) = listener.accept().unwrap();
927            let mut reader = BufReader::new(stream.try_clone().unwrap());
928            let mut line = String::new();
929            reader.read_line(&mut line).unwrap();
930            stream
931                .write_all(b"{\"ok\": true, \"detail\": \"short budget ok\"}\n")
932                .unwrap();
933            stream.flush().unwrap();
934            line
935        });
936
937        let runtime = tokio::runtime::Builder::new_current_thread()
938            .enable_all()
939            .build()
940            .unwrap();
941        let response = runtime
942            .block_on(exchange_within(
943                &socket,
944                "{\"op\": \"get_fleet_posture\", \"payload\": {}}\n".to_string(),
945                Duration::from_secs(5),
946            ))
947            .unwrap();
948        assert_eq!(response.detail(), "short budget ok");
949        let line = handle.join().unwrap();
950        assert!(line.contains("get_fleet_posture"), "got {line:?}");
951    }
952}