sail/sailbox/object.rs
1//! The bound Sailbox object: a Sailbox id paired with the [`Client`] that
2//! reaches it, so every operation is a method instead of an id-threading call.
3//!
4//! Each method is a one-line delegate to the corresponding [`Client`] method,
5//! which remains the single implementation (and the surface the language
6//! bridges call with plain ids). The delegation means the two surfaces cannot
7//! drift: a signature change on either side fails to compile.
8
9use crate::client::Client;
10use crate::error::SailError;
11use crate::exec::{ExecOptions, ExecProcess, ExecResult, RunOptions};
12use crate::sailbox::api::UpgradeResult;
13use crate::sailbox::fs::DirEntry;
14use crate::sailbox::ssh::{EnableSshOptions, SshEndpoint};
15use crate::sailbox::types::{
16 AutoSleep, CheckpointOptions, IngressProtocol, SailboxCheckpoint, SailboxHandle, SailboxInfo,
17 WaitForListenerOptions,
18};
19use crate::worker::{FileReader, FileWriter, Listener, WriteOptions};
20use std::sync::{Arc, RwLock};
21use time::OffsetDateTime;
22
23/// Collect a generic argv parameter into the owned form the transport uses.
24fn collect_argv(argv: impl IntoIterator<Item = impl Into<String>>) -> Vec<String> {
25 argv.into_iter().map(Into::into).collect()
26}
27
28/// A Sailbox bound to the client that reaches it. Obtained from
29/// [`Client::create_sailbox`], [`Client::create_from_checkpoint`], or
30/// [`Client::sailbox`] (which binds an existing id without a network call).
31///
32/// Cheap to clone; clones share the underlying client transport.
33///
34/// ```no_run
35/// # async fn demo() -> Result<(), sail::error::SailError> {
36/// # let client = sail::Client::from_env()?;
37/// let sb = client.sailbox("sb_abc123");
38/// let result = sb.exec_shell("echo hello", Default::default()).await?.wait().await?;
39/// sb.fs().write("/workspace/input.txt", b"hello\n", Default::default()).await?;
40/// sb.terminate().await?;
41/// # Ok(())
42/// # }
43/// ```
44#[derive(Clone)]
45pub struct Sailbox {
46 client: Client,
47 handle: SailboxHandle,
48 exec_endpoint: Arc<RwLock<String>>,
49}
50
51impl std::fmt::Debug for Sailbox {
52 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53 f.debug_struct("Sailbox")
54 .field("sailbox_id", &self.handle.sailbox_id)
55 .finish_non_exhaustive()
56 }
57}
58
59impl Sailbox {
60 pub(crate) fn bind(client: Client, handle: SailboxHandle) -> Sailbox {
61 let exec_endpoint = Arc::new(RwLock::new(handle.exec_endpoint.clone()));
62 Sailbox {
63 client,
64 handle,
65 exec_endpoint,
66 }
67 }
68
69 pub(crate) fn client(&self) -> &Client {
70 &self.client
71 }
72
73 /// The Sailbox's stable identifier.
74 pub fn sailbox_id(&self) -> &str {
75 &self.handle.sailbox_id
76 }
77
78 /// The data snapshot from the call that produced this object (create,
79 /// from-checkpoint). A Sailbox bound by id via [`Client::sailbox`] carries
80 /// only the id; use [`Sailbox::info`] for fresh state either way.
81 pub fn handle(&self) -> &SailboxHandle {
82 &self.handle
83 }
84
85 /// Consume the object, keeping just the data snapshot.
86 pub fn into_handle(self) -> SailboxHandle {
87 self.handle
88 }
89
90 /// Returns the latest worker endpoint learned by this object, or an empty
91 /// string when the next operation must resolve placement first.
92 fn exec_endpoint_hint(&self) -> String {
93 self.exec_endpoint
94 .read()
95 .unwrap_or_else(std::sync::PoisonError::into_inner)
96 .clone()
97 }
98
99 /// Replaces the shared routing hint for this object and all its clones.
100 fn set_exec_endpoint_hint(&self, endpoint: String) {
101 *self
102 .exec_endpoint
103 .write()
104 .unwrap_or_else(std::sync::PoisonError::into_inner) = endpoint;
105 }
106
107 /// Clears routing after a lifecycle operation stops the current VM.
108 fn clear_exec_endpoint_hint(&self) {
109 self.set_exec_endpoint_hint(String::new());
110 }
111
112 /// Fetch this Sailbox's current state.
113 pub async fn info(&self) -> Result<SailboxInfo, SailError> {
114 self.client.get_sailbox(self.sailbox_id()).await
115 }
116
117 // --- lifecycle ---
118
119 /// Terminate the Sailbox (idempotent).
120 pub async fn terminate(&self) -> Result<(), SailError> {
121 self.client.terminate_sailbox(self.sailbox_id()).await?;
122 self.clear_exec_endpoint_hint();
123 Ok(())
124 }
125
126 /// Pause the Sailbox in memory.
127 pub async fn pause(&self) -> Result<(), SailError> {
128 self.client.pause_sailbox(self.sailbox_id()).await?;
129 self.clear_exec_endpoint_hint();
130 Ok(())
131 }
132
133 /// Sleep the Sailbox to disk (it wakes on traffic). `wake_at`, when
134 /// given, schedules a wall-clock wake before the sleep starts and
135 /// returns the effective wake time (the sooner of this request and any
136 /// wake already scheduled). If the Sailbox is sleeping when that moment
137 /// arrives, Sail restores it; a wake can fire a little late, so treat
138 /// the time as approximate. Calling sleep on an already-sleeping Sailbox
139 /// succeeds and just updates the scheduled wake.
140 pub async fn sleep(
141 &self,
142 wake_at: Option<OffsetDateTime>,
143 ) -> Result<Option<OffsetDateTime>, SailError> {
144 let effective = self
145 .client
146 .sleep_sailbox(self.sailbox_id(), wake_at)
147 .await?;
148 self.clear_exec_endpoint_hint();
149 Ok(effective)
150 }
151
152 /// Replace when Sail may sleep this Sailbox on its own.
153 ///
154 /// Each call replaces the whole setting: switching to
155 /// [`Never`](AutoSleep::Never) clears any minimum wait set earlier, and
156 /// switching back does not restore it. Calling [`sleep`](Sailbox::sleep)
157 /// yourself is unaffected, and so are `pause`, `resume`, and scheduled
158 /// wakes. Read the Sailbox again for the stored preference.
159 pub async fn set_auto_sleep(&self, auto_sleep: AutoSleep) -> Result<(), SailError> {
160 self.client
161 .set_sailbox_auto_sleep(self.sailbox_id(), auto_sleep)
162 .await
163 }
164
165 /// Resume a paused or sleeping Sailbox.
166 pub async fn resume(&self) -> Result<(), SailError> {
167 let handle = self.client.resume_sailbox(self.sailbox_id()).await?;
168 self.set_exec_endpoint_hint(handle.exec_endpoint);
169 Ok(())
170 }
171
172 /// Checkpoint the Sailbox. `options.name` labels the handle;
173 /// `options.ttl`, when given, must be positive and overrides the server's
174 /// default retention.
175 pub async fn checkpoint(
176 &self,
177 options: CheckpointOptions,
178 ) -> Result<SailboxCheckpoint, SailError> {
179 self.client
180 .checkpoint_sailbox(
181 self.sailbox_id(),
182 options.name.as_deref(),
183 options.ttl.map(crate::client::duration_to_whole_seconds),
184 )
185 .await
186 }
187
188 /// Upgrade the Sailbox runtime (now if running, else at next wake).
189 pub async fn upgrade(&self) -> Result<UpgradeResult, SailError> {
190 self.client.upgrade_sailbox(self.sailbox_id()).await
191 }
192
193 // --- exec ---
194
195 /// Run a command from an argv vector (no shell interpretation) and return
196 /// a handle to the live process. Resumes (wakes) the Sailbox to reach it.
197 /// The returned [`ExecProcess`] streams output, accepts stdin, and
198 /// resolves the exit status; dropping it detaches without killing the
199 /// command. The output pump spawns on the calling task's tokio runtime.
200 pub async fn exec(
201 &self,
202 argv: impl IntoIterator<Item = impl Into<String>>,
203 options: ExecOptions,
204 ) -> Result<ExecProcess, SailError> {
205 let exec_endpoint = self.exec_endpoint_hint();
206 self.client
207 .exec_at_endpoint(
208 self.sailbox_id(),
209 Some(&exec_endpoint),
210 collect_argv(argv),
211 options,
212 )
213 .await
214 }
215
216 /// Run a shell command via `/bin/sh -lc` (pipes, globs, and `$VAR`
217 /// expansion work), honoring the `cwd`/`background` options. Use
218 /// [`Sailbox::exec`] with an argv vector when arguments must reach the
219 /// command verbatim. Otherwise behaves like [`Sailbox::exec`].
220 pub async fn exec_shell(
221 &self,
222 command: &str,
223 options: ExecOptions,
224 ) -> Result<ExecProcess, SailError> {
225 let exec_endpoint = self.exec_endpoint_hint();
226 self.client
227 .exec_shell_at_endpoint(self.sailbox_id(), Some(&exec_endpoint), command, options)
228 .await
229 }
230
231 /// Run an argv command to completion and return its buffered
232 /// [`ExecResult`]: a one-shot convenience over [`Sailbox::exec`] followed
233 /// by [`ExecProcess::wait`]. A nonzero exit code reports through
234 /// [`ExecResult::exit_code`], not an error, and an exceeded
235 /// `options.timeout` reports through [`ExecResult::timed_out`]. Use
236 /// [`Sailbox::exec`] to stream output or feed stdin.
237 ///
238 /// ```no_run
239 /// # async fn demo() -> Result<(), sail::SailError> {
240 /// # let client = sail::Client::from_env()?;
241 /// let sb = client.sailbox("sb_abc123");
242 /// let result = sb.run(["echo", "hello"], Default::default()).await?;
243 /// assert_eq!(result.exit_code, 0);
244 /// println!("{}", result.stdout);
245 /// # Ok(())
246 /// # }
247 /// ```
248 pub async fn run(
249 &self,
250 argv: impl IntoIterator<Item = impl Into<String>>,
251 options: RunOptions,
252 ) -> Result<ExecResult, SailError> {
253 self.exec(argv, options.into_exec_options())
254 .await?
255 .wait()
256 .await
257 }
258
259 /// Run a shell command (`/bin/sh -lc`) to completion and return its
260 /// buffered [`ExecResult`], honoring `options.cwd`. Otherwise behaves
261 /// like [`Sailbox::run`].
262 pub async fn run_shell(
263 &self,
264 command: &str,
265 options: RunOptions,
266 ) -> Result<ExecResult, SailError> {
267 self.exec_shell(command, options.into_exec_options())
268 .await?
269 .wait()
270 .await
271 }
272
273 // --- files ---
274
275 /// Filesystem operations on this Sailbox's guest: read and write files
276 /// (buffered or streaming), and directory helpers.
277 pub fn fs(&self) -> SailboxFs<'_> {
278 SailboxFs { sailbox: self }
279 }
280
281 // --- listeners ---
282
283 /// Expose a guest port at runtime. Re-exposing a port under the same
284 /// protocol sets its allowlist to what you pass, so pass the whole list
285 /// every time; passing an empty one clears the restriction and reopens the
286 /// port. The returned [`Listener`] carries the resolved endpoint but
287 /// an unknown route status: the expose response does not report
288 /// reachability. Confirm with [`Sailbox::wait_for_listener`].
289 pub async fn expose(
290 &self,
291 guest_port: u32,
292 protocol: IngressProtocol,
293 allowlist: &[String],
294 ) -> Result<Listener, SailError> {
295 self.client
296 .expose_listener(self.sailbox_id(), guest_port, protocol, allowlist)
297 .await
298 }
299
300 /// Remove a runtime ingress port.
301 pub async fn unexpose(&self, guest_port: u32) -> Result<(), SailError> {
302 self.client
303 .unexpose_listener(self.sailbox_id(), guest_port)
304 .await
305 }
306
307 /// List this Sailbox's listeners without waking it.
308 pub async fn listeners(&self) -> Result<Vec<Listener>, SailError> {
309 self.client.list_listeners(self.sailbox_id()).await
310 }
311
312 /// Fetch one listener by guest port without waking the Sailbox.
313 pub async fn listener(&self, guest_port: u32) -> Result<Listener, SailError> {
314 self.client
315 .get_listener(self.sailbox_id(), guest_port)
316 .await
317 }
318
319 /// Block until the listener on `guest_port` is reachable end to end
320 /// (route active and its endpoint accepting) and return it. An HTTP
321 /// listener is probed by URL, so success means the guest server answered;
322 /// a TCP listener is ready once the guest sends bytes or holds the
323 /// connection open. This is a connectivity check, not an application
324 /// health check. Re-checks every second and fails with a timeout error
325 /// after `options.timeout`.
326 pub async fn wait_for_listener(
327 &self,
328 guest_port: u32,
329 options: WaitForListenerOptions,
330 ) -> Result<Listener, SailError> {
331 self.client
332 .wait_for_listener(self.sailbox_id(), guest_port, options.timeout)
333 .await
334 }
335
336 /// Ingress-identity headers for this Sailbox, as name/value pairs.
337 pub async fn ingress_auth_headers(&self) -> Result<Vec<(String, String)>, SailError> {
338 self.client.ingress_auth_headers(self.sailbox_id()).await
339 }
340
341 // --- ssh ---
342
343 /// Make the Sailbox reachable over SSH, returning the endpoint when
344 /// `options.wait` is set (else `None`). Installs the org SSH CA as
345 /// trusted, (re)starts `sshd`, confirms the CA-only daemon owns guest
346 /// port 22, and only then exposes the port as TCP ingress, so a failed
347 /// enable never leaves a non-CA daemon reachable. Idempotent. A non-empty
348 /// `options.allowlist` restricts port 22 to those source addresses or
349 /// ranges; when empty, a first enable is open to any source and a re-enable
350 /// keeps an existing restriction.
351 pub async fn enable_ssh(
352 &self,
353 options: EnableSshOptions,
354 ) -> Result<Option<SshEndpoint>, SailError> {
355 self.client
356 .enable_ssh(
357 self.sailbox_id(),
358 &options.allowlist,
359 options.wait,
360 options.timeout,
361 )
362 .await
363 }
364}
365
366/// Filesystem operations on a Sailbox's guest, reached via [`Sailbox::fs`]:
367/// buffered and streaming reads and writes, plus directory helpers with
368/// coreutils semantics (`mkdir -p`, `rm -rf`, `test -e`), documented per
369/// method.
370pub struct SailboxFs<'a> {
371 sailbox: &'a Sailbox,
372}
373
374impl std::fmt::Debug for SailboxFs<'_> {
375 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
376 f.debug_struct("SailboxFs")
377 .field("sailbox_id", &self.sailbox.sailbox_id())
378 .finish()
379 }
380}
381
382impl SailboxFs<'_> {
383 /// Read a guest file into memory in one call.
384 pub async fn read(&self, path: &str) -> Result<Vec<u8>, SailError> {
385 self.sailbox
386 .client
387 .read_file(self.sailbox.sailbox_id(), path)
388 .await
389 }
390
391 /// Write `data` to a guest file in one call.
392 pub async fn write(
393 &self,
394 path: &str,
395 data: &[u8],
396 options: WriteOptions,
397 ) -> Result<(), SailError> {
398 self.sailbox
399 .client
400 .write_file(self.sailbox.sailbox_id(), path, data, options)
401 .await
402 }
403
404 /// Open a streaming read of a guest file.
405 pub async fn read_stream(&self, path: &str) -> Result<FileReader, SailError> {
406 self.sailbox
407 .client
408 .read_stream(self.sailbox.sailbox_id(), path)
409 .await
410 }
411
412 /// Open a streaming write to a guest file.
413 pub async fn write_stream(
414 &self,
415 path: &str,
416 options: WriteOptions,
417 ) -> Result<FileWriter, SailError> {
418 self.sailbox
419 .client
420 .write_stream(self.sailbox.sailbox_id(), path, options)
421 .await
422 }
423
424 /// Create a directory and any missing parents (like `mkdir -p`); a no-op if
425 /// it already exists.
426 pub async fn mkdir(&self, path: &str) -> Result<(), SailError> {
427 self.sailbox
428 .client
429 .make_dir(self.sailbox.sailbox_id(), path)
430 .await
431 }
432
433 /// Remove a file or directory tree (like `rm -rf`); a no-op if it is already
434 /// absent.
435 pub async fn remove(&self, path: &str) -> Result<(), SailError> {
436 self.sailbox
437 .client
438 .remove_path(self.sailbox.sailbox_id(), path)
439 .await
440 }
441
442 /// Whether `path` exists in the guest. Follows symlinks (like `test -e`), so
443 /// a dangling symlink reports `false` even though [`ls`](Self::ls) lists it.
444 pub async fn exists(&self, path: &str) -> Result<bool, SailError> {
445 self.sailbox
446 .client
447 .path_exists(self.sailbox.sailbox_id(), path)
448 .await
449 }
450
451 /// List a directory's immediate entries as [`DirEntry`] records (no
452 /// recursion). Runs GNU `find` in the guest, which the default Debian image
453 /// ships. A missing path errors, as does a path that is not a directory and
454 /// a listing too large for the exec output cap. An entry whose name is not
455 /// valid UTF-8 fails the listing, since the path API cannot address it.
456 pub async fn ls(&self, path: &str) -> Result<Vec<DirEntry>, SailError> {
457 self.sailbox
458 .client
459 .list_dir(self.sailbox.sailbox_id(), path)
460 .await
461 }
462}
463
464impl Client {
465 /// Bind an existing Sailbox id to this client without a network call,
466 /// giving the method-style surface over it.
467 pub fn sailbox(&self, sailbox_id: impl Into<String>) -> Sailbox {
468 Sailbox::bind(
469 self.clone(),
470 SailboxHandle {
471 sailbox_id: sailbox_id.into(),
472 ..Default::default()
473 },
474 )
475 }
476}