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