Skip to main content

rcp/
transport.rs

1//! transport.rs — the request/reply seam (subprocess pipe or HTTP/1.1).
2//!
3//! A `Transport` is a total function `&Json -> Result<Json, RcpError>`. Two
4//! concrete transports mirror the other SDKs, both built on `std` alone:
5//!
6//!   * `StdioTransport` — newline-delimited JSON over a child's stdin/stdout.
7//!   * `HttpTransport`   — minimal HTTP/1.1 POST to `<base>/<method>`.
8
9use crate::json::Json;
10use crate::types::{Errc, RcpError};
11use std::io::{BufRead, BufReader, Read, Write};
12use std::net::TcpStream;
13use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
14
15/// One JSON-RPC request → one reply.
16pub trait Transport {
17    fn call(&mut self, request: &Json) -> Result<Json, RcpError>;
18    fn close(&mut self);
19}
20
21/// Newline-delimited JSON over a subprocess' stdio. Replies are correlated by
22/// JSON-RPC id; server notifications (frames carrying `method`) and stray
23/// mismatched-id replies are skipped (spec §4.7).
24pub struct StdioTransport {
25    child: Child,
26    stdin: ChildStdin,
27    stdout: BufReader<ChildStdout>,
28}
29
30impl StdioTransport {
31    pub fn spawn(argv: &[String]) -> Result<StdioTransport, RcpError> {
32        if argv.is_empty() {
33            return Err(RcpError::new(
34                Errc::INVALID_PARAMS,
35                "server command must be non-empty",
36            ));
37        }
38        let mut child = Command::new(&argv[0])
39            .args(&argv[1..])
40            .stdin(Stdio::piped())
41            .stdout(Stdio::piped())
42            // stderr inherits: server diagnostics reach the launching terminal.
43            .spawn()
44            .map_err(|e| {
45                RcpError::new(
46                    Errc::BACKEND_UNAVAILABLE,
47                    format!("cannot spawn {}: {}", argv[0], e),
48                )
49            })?;
50        let stdin = child.stdin.take().expect("piped stdin");
51        let stdout = BufReader::new(child.stdout.take().expect("piped stdout"));
52        Ok(StdioTransport {
53            child,
54            stdin,
55            stdout,
56        })
57    }
58}
59
60impl Transport for StdioTransport {
61    fn call(&mut self, request: &Json) -> Result<Json, RcpError> {
62        let mut line = request.dump();
63        line.push('\n');
64        self.stdin
65            .write_all(line.as_bytes())
66            .and_then(|_| self.stdin.flush())
67            .map_err(|_| RcpError::new(Errc::BACKEND_UNAVAILABLE, "write to server failed"))?;
68
69        let want_id = request.get("id").cloned();
70        loop {
71            let mut buf = String::new();
72            let n = self.stdout.read_line(&mut buf).map_err(|e| {
73                RcpError::new(Errc::BACKEND_UNAVAILABLE, format!("read failed: {}", e))
74            })?;
75            if n == 0 {
76                return Err(RcpError::new(
77                    Errc::BACKEND_UNAVAILABLE,
78                    "server closed the connection",
79                ));
80            }
81            let trimmed = buf.trim();
82            if trimmed.is_empty() {
83                continue;
84            }
85            let reply = Json::parse(trimmed).map_err(|e| RcpError::new(Errc::PARSE_ERROR, e))?;
86            if reply.contains_key("method") {
87                continue; // server-initiated notification
88            }
89            if let (Some(want), Some(got)) = (&want_id, reply.get("id")) {
90                if want != got {
91                    continue; // stray reply for an earlier request
92                }
93            }
94            return Ok(reply);
95        }
96    }
97
98    fn close(&mut self) {
99        let _ = self.stdin.flush();
100        let _ = self.child.kill();
101        let _ = self.child.wait();
102    }
103}
104
105impl Drop for StdioTransport {
106    fn drop(&mut self) {
107        // Never orphan the child: std's Child::drop detaches by default.
108        let _ = self.child.kill();
109        let _ = self.child.wait();
110    }
111}
112
113/// Minimal HTTP/1.1 client: POST the request to `<base_url>/<method>`. The server
114/// ignores the path and dispatches on the body's `method`. Maps HTTP 429 →
115/// RateLimited and 503 → BackendUnavailable (spec §5.2).
116pub struct HttpTransport {
117    base: String,
118}
119
120impl HttpTransport {
121    pub fn new(base_url: &str) -> HttpTransport {
122        HttpTransport {
123            base: base_url.trim_end_matches('/').to_string(),
124        }
125    }
126}
127
128impl Transport for HttpTransport {
129    fn call(&mut self, request: &Json) -> Result<Json, RcpError> {
130        let method = request.get_str("method").unwrap_or("");
131        let url = format!("{}/{}", self.base, method);
132        let (host, port, path) = parse_http_url(&url)?;
133        let body = request.dump();
134        let req = format!(
135            "POST {} HTTP/1.1\r\nHost: {}\r\nContent-Type: application/json\r\n\
136             Content-Length: {}\r\nConnection: close\r\n\r\n{}",
137            path,
138            host,
139            body.len(),
140            body
141        );
142        let mut stream = TcpStream::connect((host.as_str(), port))
143            .map_err(|e| RcpError::new(Errc::BACKEND_UNAVAILABLE, format!("connect failed: {}", e)))?;
144        stream
145            .write_all(req.as_bytes())
146            .map_err(|e| RcpError::new(Errc::BACKEND_UNAVAILABLE, format!("write failed: {}", e)))?;
147        let mut resp = Vec::new();
148        stream
149            .read_to_end(&mut resp)
150            .map_err(|e| RcpError::new(Errc::BACKEND_UNAVAILABLE, format!("read failed: {}", e)))?;
151
152        let (status, body_bytes) = parse_http_response(&resp)?;
153        if status == 429 {
154            return Err(RcpError::new(Errc::RATE_LIMITED, "HTTP 429"));
155        }
156        if status == 503 {
157            return Err(RcpError::new(Errc::BACKEND_UNAVAILABLE, "HTTP 503"));
158        }
159        let text = String::from_utf8_lossy(body_bytes);
160        if !(200..300).contains(&status) && text.trim().is_empty() {
161            return Err(RcpError::new(
162                Errc::BACKEND_UNAVAILABLE,
163                format!("HTTP {}", status),
164            ));
165        }
166        Json::parse(text.trim()).map_err(|e| RcpError::new(Errc::PARSE_ERROR, e))
167    }
168
169    fn close(&mut self) {}
170}
171
172/// Split `http://host[:port]/path` into `(host, port, path)`.
173fn parse_http_url(url: &str) -> Result<(String, u16, String), RcpError> {
174    let rest = url
175        .strip_prefix("http://")
176        .ok_or_else(|| RcpError::new(Errc::INVALID_PARAMS, "only http:// URLs are supported"))?;
177    let (authority, path) = match rest.find('/') {
178        Some(i) => (&rest[..i], &rest[i..]),
179        None => (rest, "/"),
180    };
181    let (host, port) = match authority.rsplit_once(':') {
182        Some((h, p)) => (
183            h.to_string(),
184            p.parse::<u16>()
185                .map_err(|_| RcpError::new(Errc::INVALID_PARAMS, "bad port"))?,
186        ),
187        None => (authority.to_string(), 80),
188    };
189    Ok((host, port, path.to_string()))
190}
191
192/// Return `(status_code, body_slice)` from a raw HTTP/1.1 response.
193fn parse_http_response(resp: &[u8]) -> Result<(u16, &[u8]), RcpError> {
194    let sep = find_subslice(resp, b"\r\n\r\n")
195        .ok_or_else(|| RcpError::new(Errc::BACKEND_UNAVAILABLE, "malformed HTTP response"))?;
196    let head = &resp[..sep];
197    let body = &resp[sep + 4..];
198    // Status line: "HTTP/1.1 200 OK"
199    let line_end = find_subslice(head, b"\r\n").unwrap_or(head.len());
200    let status_line = String::from_utf8_lossy(&head[..line_end]);
201    let status = status_line
202        .split_whitespace()
203        .nth(1)
204        .and_then(|s| s.parse::<u16>().ok())
205        .ok_or_else(|| RcpError::new(Errc::BACKEND_UNAVAILABLE, "no HTTP status"))?;
206    Ok((status, body))
207}
208
209fn find_subslice(haystack: &[u8], needle: &[u8]) -> Option<usize> {
210    haystack
211        .windows(needle.len())
212        .position(|w| w == needle)
213}