Skip to main content

sail_api/runtime/
transport.rs

1//! Owner-private runtime RPC, independent of cache and Cargo-job protocol versions.
2
3mod client;
4#[cfg(test)]
5mod tests;
6pub use client::Client;
7
8use super::{Capabilities, Error, Request as RuntimeRequest, Response as RuntimeResponse};
9use serde::{Deserialize, Serialize, de::DeserializeOwned};
10use std::{
11    fmt::Write as _,
12    io::{self, Read, Write},
13    os::unix::fs::{DirBuilderExt as _, FileTypeExt as _, MetadataExt as _},
14    path::{Path, PathBuf},
15    time::{Duration, Instant},
16};
17
18/// Transport framing version, independent of the payload's version.
19pub const VERSION: u32 = 1;
20/// Maximum encoded request frame, checked before allocation.
21pub const MAX_REQUEST_BYTES: usize = 128 * 1024 * 1024;
22/// Maximum encoded response frame, including byte-array JSON overhead.
23pub const MAX_RESPONSE_BYTES: usize = 640 * 1024 * 1024;
24/// Absolute deadline for control requests and frame input/output.
25pub const IO_TIMEOUT: Duration = Duration::from_secs(5);
26
27/// One bounded local request; each connection carries exactly one request.
28#[derive(Clone, Debug, Serialize, Deserialize)]
29#[serde(tag = "operation", rename_all = "snake_case", deny_unknown_fields)]
30pub enum Request {
31    /// Negotiate actual runtime readiness before dispatch.
32    Capabilities,
33    /// Execute the unchanged public runtime request.
34    Execute {
35        /// Unique active transport identity, excluded from solver evidence.
36        id: String,
37        /// Fully versioned runtime request.
38        request: RuntimeRequest,
39    },
40    /// Cancel one active execution using a separate responsive control connection.
41    Cancel {
42        /// Exact active transport identity.
43        id: String,
44    },
45}
46
47/// One complete local response; partial frames never establish a solver result.
48#[derive(Clone, Debug, Serialize, Deserialize)]
49#[serde(tag = "kind", rename_all = "snake_case")]
50pub enum Response {
51    /// Actual implementation and installation readiness.
52    Capabilities {
53        /// Same capabilities as the embedded runtime.
54        capabilities: Capabilities,
55    },
56    /// Complete execution, including unavailable or failed query outcomes.
57    Completed {
58        /// Exact transport identity of the request.
59        id: String,
60        /// Unchanged public runtime response.
61        response: RuntimeResponse,
62    },
63    /// Cancellation acknowledgement, never a theorem verdict.
64    Cancelled {
65        /// Requested transport identity.
66        id: String,
67        /// Whether an active execution was found and cancelled.
68        found: bool,
69    },
70    /// Explicit admission, overload or service failure.
71    Error {
72        /// Stable structured diagnostic.
73        error: Error,
74    },
75}
76
77#[derive(Serialize, Deserialize)]
78#[serde(deny_unknown_fields)]
79struct Envelope<T> {
80    version: u32,
81    body: T,
82}
83
84struct Bounded(Vec<u8>, usize);
85impl Write for Bounded {
86    fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
87        if bytes.len() > self.1.saturating_sub(self.0.len()) {
88            return Err(io::Error::new(
89                io::ErrorKind::InvalidData,
90                "SAIL6201: runtime frame exceeds its bound",
91            ));
92        }
93        self.0.extend_from_slice(bytes);
94        Ok(bytes.len())
95    }
96    fn flush(&mut self) -> io::Result<()> {
97        Ok(())
98    }
99}
100
101/// Write one independently versioned frame with a hard serialization bound.
102///
103/// # Errors
104/// Returns encoding, bound or output errors before any partial JSON is accepted.
105pub fn write_frame<T: Serialize>(
106    writer: &mut impl Write,
107    body: &T,
108    bound: usize,
109) -> io::Result<()> {
110    let mut encoded = Bounded(Vec::new(), bound);
111    serde_json::to_writer(
112        &mut encoded,
113        &Envelope {
114            version: VERSION,
115            body,
116        },
117    )
118    .map_err(|e| io::Error::new(e.io_error_kind().unwrap_or(io::ErrorKind::InvalidData), e))?;
119    let length = u32::try_from(encoded.0.len()).map_err(io::Error::other)?;
120    writer.write_all(&length.to_be_bytes())?;
121    writer.write_all(&encoded.0)?;
122    writer.flush()
123}
124
125/// Read one bounded fresh frame, rejecting unknown versions and malformed payloads.
126///
127/// # Errors
128/// Returns incomplete, oversized, malformed or incompatible frame errors.
129pub fn read_frame<T: DeserializeOwned>(reader: &mut impl Read, bound: usize) -> io::Result<T> {
130    let mut header = [0_u8; 4];
131    reader.read_exact(&mut header)?;
132    let length = usize::try_from(u32::from_be_bytes(header)).map_err(io::Error::other)?;
133    if length == 0 || length > bound {
134        return Err(io::Error::new(
135            io::ErrorKind::InvalidData,
136            "SAIL6201: runtime frame exceeds its bound",
137        ));
138    }
139    let mut bytes = vec![0_u8; length];
140    reader.read_exact(&mut bytes)?;
141    let envelope: Envelope<T> = crate::temporal::decode(&bytes).map_err(io::Error::other)?;
142    if envelope.version != VERSION {
143        return Err(io::Error::new(
144            io::ErrorKind::InvalidData,
145            "SAIL6201: incompatible runtime endpoint; restart sail serve",
146        ));
147    }
148    Ok(envelope.body)
149}
150
151/// The runtime endpoint derived from the same canonical cache namespace as jobs.
152#[must_use]
153pub fn socket_path(cache_socket: &Path) -> PathBuf {
154    let jobs = crate::jobs::socket_path(cache_socket);
155    let hash = sail_key::sha256(jobs.as_os_str().as_encoded_bytes());
156    let mut suffix = String::new();
157    for byte in hash.iter().take(8) {
158        let _ = write!(suffix, "{byte:02x}");
159    }
160    jobs.with_file_name(format!("rt-{suffix}")).join("v1.sock")
161}
162
163/// Verify or create the immediate owner-private directory of a runtime socket.
164///
165/// # Errors
166/// Refuses symlinks, foreign ownership and any group or other permission bits.
167pub fn private_parent(socket: &Path, create: bool) -> io::Result<()> {
168    let parent = socket
169        .parent()
170        .ok_or_else(|| io::Error::other("SAIL6201: runtime endpoint has no parent"))?;
171    if create {
172        let mut builder = std::fs::DirBuilder::new();
173        builder.mode(0o700);
174        if let Err(e) = builder.create(parent)
175            && e.kind() != io::ErrorKind::AlreadyExists
176        {
177            return Err(e);
178        }
179    }
180    let metadata = std::fs::symlink_metadata(parent)?;
181    if !metadata.is_dir()
182        || metadata.uid() != rustix::process::geteuid().as_raw()
183        || metadata.mode() & 0o777 != 0o700
184    {
185        return Err(io::Error::new(
186            io::ErrorKind::PermissionDenied,
187            "SAIL6201: runtime parent must be an owned real directory with mode 0700",
188        ));
189    }
190    Ok(())
191}
192
193/// Authenticate the local filesystem ownership boundary before connecting.
194///
195/// # Errors
196/// Returns explicit unavailable or permission diagnostics, never a solver fallback.
197pub fn validate_socket(socket: &Path) -> io::Result<()> {
198    private_parent(socket, false)?;
199    let metadata = std::fs::symlink_metadata(socket)?;
200    if !metadata.file_type().is_socket()
201        || metadata.uid() != rustix::process::geteuid().as_raw()
202        || metadata.mode() & 0o777 != 0o600
203    {
204        return Err(io::Error::new(
205            io::ErrorKind::PermissionDenied,
206            "SAIL6201: runtime endpoint must be an owned socket with mode 0600",
207        ));
208    }
209    Ok(())
210}
211
212/// One Unix stream with an absolute read/write deadline, including trickle input.
213pub struct Deadline<'a> {
214    stream: &'a std::os::unix::net::UnixStream,
215    until: Instant,
216    prepared: bool,
217}
218impl<'a> Deadline<'a> {
219    /// Apply one absolute deadline to an entire frame exchange.
220    #[must_use]
221    pub fn new(stream: &'a std::os::unix::net::UnixStream, duration: Duration) -> Self {
222        Self {
223            stream,
224            until: Instant::now() + duration,
225            prepared: false,
226        }
227    }
228    fn remaining(&self) -> io::Result<Duration> {
229        self.until
230            .checked_duration_since(Instant::now())
231            .filter(|duration| !duration.is_zero())
232            .ok_or_else(|| {
233                io::Error::new(
234                    io::ErrorKind::TimedOut,
235                    "SAIL6201: runtime frame deadline expired",
236                )
237            })
238    }
239}
240impl Deadline<'_> {
241    fn prepare(&mut self) -> io::Result<()> {
242        if !self.prepared {
243            self.stream.set_nonblocking(true)?;
244            self.prepared = true;
245        }
246        Ok(())
247    }
248    fn pause(&self) -> io::Result<()> {
249        std::thread::sleep(self.remaining()?.min(Duration::from_millis(2)));
250        Ok(())
251    }
252}
253impl Read for Deadline<'_> {
254    fn read(&mut self, bytes: &mut [u8]) -> io::Result<usize> {
255        self.prepare()?;
256        loop {
257            self.remaining()?;
258            match self.stream.read(bytes) {
259                Err(e) if e.kind() == io::ErrorKind::WouldBlock => self.pause()?,
260                Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
261                result => return result,
262            }
263        }
264    }
265}
266impl Write for Deadline<'_> {
267    fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
268        self.prepare()?;
269        loop {
270            self.remaining()?;
271            match self.stream.write(bytes) {
272                Err(e) if e.kind() == io::ErrorKind::WouldBlock => self.pause()?,
273                Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
274                result => return result,
275            }
276        }
277    }
278    fn flush(&mut self) -> io::Result<()> {
279        self.stream.flush()
280    }
281}