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