sail_api/runtime/
transport.rs1mod 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
18pub const VERSION: u32 = 1;
20pub const MAX_REQUEST_BYTES: usize = 128 * 1024 * 1024;
22pub const MAX_RESPONSE_BYTES: usize = 640 * 1024 * 1024;
24pub const IO_TIMEOUT: Duration = Duration::from_secs(5);
26
27#[derive(Clone, Debug, Serialize, Deserialize)]
29#[serde(tag = "operation", rename_all = "snake_case", deny_unknown_fields)]
30pub enum Request {
31 Capabilities,
33 Execute {
35 id: String,
37 request: RuntimeRequest,
39 },
40 Cancel {
42 id: String,
44 },
45}
46
47#[derive(Clone, Debug, Serialize, Deserialize)]
49#[serde(tag = "kind", rename_all = "snake_case")]
50pub enum Response {
51 Capabilities {
53 capabilities: Capabilities,
55 },
56 Completed {
58 id: String,
60 response: RuntimeResponse,
62 },
63 Cancelled {
65 id: String,
67 found: bool,
69 },
70 Error {
72 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
101pub 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
125pub 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#[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
163pub 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
193pub 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
212pub struct Deadline<'a> {
214 stream: &'a std::os::unix::net::UnixStream,
215 until: Instant,
216 prepared: bool,
217}
218impl<'a> Deadline<'a> {
219 #[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}