Skip to main content

rcp/
selector.rs

1//! selector.rs โ€” choose ONE backend from several reachable engines.
2//!
3//! Mirrors the C++/Python/Node `Selector`: list candidate engines (by hand or
4//! from an `rcp.json` registry) and pick one โ€” by id, by required capability, or
5//! by priority with liveness fallback. Connection is lazy; the result is a
6//! fully-connected `Client`.
7
8use crate::client::Client;
9use crate::json::Json;
10use crate::types::{Capability, Errc, RcpError};
11
12/// How to reach one backend. Inert until selected; exactly one of `argv` (stdio)
13/// or `url` (HTTP) is set.
14#[derive(Clone, Debug)]
15pub struct EngineSpec {
16    pub id: String,
17    pub argv: Vec<String>,
18    pub url: String,
19    pub priority: i64,
20    pub weight: f64,
21    pub required: bool,
22}
23
24impl EngineSpec {
25    fn open(&self) -> Result<Client, RcpError> {
26        if !self.argv.is_empty() {
27            Client::connect_stdio(&self.argv)
28        } else if !self.url.is_empty() {
29            Client::connect_http(&self.url)
30        } else {
31            Err(RcpError::new(
32                Errc::INVALID_PARAMS,
33                format!("engine '{}' has no transport", self.id),
34            ))
35        }
36    }
37
38    /// Parse one registry entry (spec ยง16.1).
39    pub fn from_json(entry: &Json) -> Result<EngineSpec, RcpError> {
40        let id = entry
41            .get_str("id")
42            .ok_or_else(|| RcpError::new(Errc::INVALID_PARAMS, "registry entry needs an 'id'"))?
43            .to_string();
44        let transport = entry.get_str("transport").unwrap_or("");
45        let command = entry.get("command").or_else(|| entry.get("argv"));
46        let url = entry.get_str("url").unwrap_or("");
47        let mut spec = EngineSpec {
48            id,
49            argv: Vec::new(),
50            url: String::new(),
51            priority: entry.get("priority").and_then(|v| v.as_i64()).unwrap_or(0),
52            weight: entry.get("weight").and_then(|v| v.as_f64()).unwrap_or(1.0),
53            required: entry.get("required").and_then(|v| v.as_bool()).unwrap_or(false),
54        };
55        let has_command = command
56            .and_then(|c| c.as_array())
57            .is_some_and(|a| !a.is_empty());
58        if transport == "stdio" || (transport.is_empty() && has_command) {
59            let arr = command.and_then(|c| c.as_array()).ok_or_else(|| {
60                RcpError::new(
61                    Errc::INVALID_PARAMS,
62                    format!("stdio engine '{}' needs a 'command' array", spec.id),
63                )
64            })?;
65            spec.argv = arr.iter().filter_map(|v| v.as_str().map(String::from)).collect();
66            if spec.argv.is_empty() {
67                return Err(RcpError::new(
68                    Errc::INVALID_PARAMS,
69                    format!("stdio engine '{}' needs a non-empty 'command'", spec.id),
70                ));
71            }
72        } else if transport == "http" || (transport.is_empty() && !url.is_empty()) {
73            if url.is_empty() {
74                return Err(RcpError::new(
75                    Errc::INVALID_PARAMS,
76                    format!("http engine '{}' needs a 'url'", spec.id),
77                ));
78            }
79            spec.url = url.to_string();
80        } else {
81            return Err(RcpError::new(
82                Errc::INVALID_PARAMS,
83                format!("engine '{}' has no usable transport", spec.id),
84            ));
85        }
86        Ok(spec)
87    }
88}
89
90/// A registry of candidate engines; selection connects and returns a `Client`.
91#[derive(Clone, Debug, Default)]
92pub struct Selector {
93    specs: Vec<EngineSpec>,
94}
95
96impl Selector {
97    pub fn new() -> Selector {
98        Selector { specs: Vec::new() }
99    }
100
101    /// Build a Selector from a registry JSON file.
102    pub fn load(path: &str) -> Result<Selector, RcpError> {
103        let text = std::fs::read_to_string(path)
104            .map_err(|e| RcpError::new(Errc::INVALID_PARAMS, format!("cannot read {}: {}", path, e)))?;
105        Selector::loads(&text)
106    }
107
108    /// Build a Selector from a registry JSON string (`{"engines": [ ... ]}`).
109    pub fn loads(text: &str) -> Result<Selector, RcpError> {
110        let doc = Json::parse(text)
111            .map_err(|e| RcpError::new(Errc::PARSE_ERROR, format!("invalid registry JSON: {}", e)))?;
112        let mut sel = Selector::new();
113        if let Some(engines) = doc.get("engines").and_then(|v| v.as_array()) {
114            for entry in engines {
115                sel.specs.push(EngineSpec::from_json(entry)?);
116            }
117        }
118        Ok(sel)
119    }
120
121    pub fn add_stdio(&mut self, id: &str, argv: &[&str], priority: i64) -> &mut Self {
122        self.specs.push(EngineSpec {
123            id: id.to_string(),
124            argv: argv.iter().map(|s| s.to_string()).collect(),
125            url: String::new(),
126            priority,
127            weight: 1.0,
128            required: false,
129        });
130        self
131    }
132
133    pub fn add_http(&mut self, id: &str, url: &str, priority: i64) -> &mut Self {
134        self.specs.push(EngineSpec {
135            id: id.to_string(),
136            argv: Vec::new(),
137            url: url.to_string(),
138            priority,
139            weight: 1.0,
140            required: false,
141        });
142        self
143    }
144
145    pub fn size(&self) -> usize {
146        self.specs.len()
147    }
148
149    /// Connect the engine with the given id (or error if unknown).
150    pub fn select(&self, id: &str) -> Result<Client, RcpError> {
151        for spec in &self.specs {
152            if spec.id == id {
153                return spec.open();
154            }
155        }
156        Err(RcpError::new(
157            Errc::INVALID_PARAMS,
158            format!("no engine with id '{}'", id),
159        ))
160    }
161
162    /// Connect the highest-priority engine that answers (liveness fallback).
163    pub fn select_primary(&self) -> Result<Client, RcpError> {
164        let mut last: Option<RcpError> = None;
165        for spec in self.by_priority() {
166            match spec.open() {
167                Ok(c) => return Ok(c),
168                Err(e) => last = Some(e),
169            }
170        }
171        Err(last.unwrap_or_else(|| RcpError::new(Errc::BACKEND_UNAVAILABLE, "no engines configured")))
172    }
173
174    /// Connect the highest-priority engine that answers AND advertises `cap`.
175    pub fn select_capable(&self, cap: Capability) -> Result<Client, RcpError> {
176        let mut last: Option<RcpError> = None;
177        for spec in self.by_priority() {
178            match spec.open() {
179                Ok(mut c) => {
180                    if c.supports(cap) {
181                        return Ok(c);
182                    }
183                    c.shutdown();
184                    last = Some(RcpError::new(
185                        Errc::CAPABILITY_MISSING,
186                        format!("engine '{}' lacks '{}'", spec.id, cap.wire_key()),
187                    ));
188                }
189                Err(e) => last = Some(e),
190            }
191        }
192        Err(last.unwrap_or_else(|| RcpError::new(Errc::BACKEND_UNAVAILABLE, "no capable engine")))
193    }
194
195    /// Specs sorted by descending priority (stable for equal priority).
196    fn by_priority(&self) -> Vec<&EngineSpec> {
197        let mut v: Vec<&EngineSpec> = self.specs.iter().collect();
198        v.sort_by(|a, b| b.priority.cmp(&a.priority));
199        v
200    }
201}