sail-rs 0.4.2

Official Rust SDK for Sail: create and drive sailboxes (sandboxed cloud VMs) with lifecycle, streaming exec, file transfer, and ingress.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! The bound Sailbox object: a Sailbox id paired with the [`Client`] that
//! reaches it, so every operation is a method instead of an id-threading call.
//!
//! Each method is a one-line delegate to the corresponding [`Client`] method,
//! which remains the single implementation (and the surface the language
//! bridges call with plain ids). The delegation means the two surfaces cannot
//! drift: a signature change on either side fails to compile.

use crate::client::Client;
use crate::error::SailError;
use crate::exec::{ExecOptions, ExecProcess, ExecResult, RunOptions};
use crate::sailbox::api::UpgradeResult;
use crate::sailbox::fs::DirEntry;
use crate::sailbox::ssh::{EnableSshOptions, SshEndpoint};
use crate::sailbox::types::{
    CheckpointOptions, ForkOptions, IngressProtocol, SailboxCheckpoint, SailboxHandle, SailboxInfo,
    WaitForListenerOptions,
};
use crate::worker::{FileReader, FileWriter, Listener, WriteOptions};

/// Collect a generic argv parameter into the owned form the transport uses.
fn collect_argv(argv: impl IntoIterator<Item = impl Into<String>>) -> Vec<String> {
    argv.into_iter().map(Into::into).collect()
}

/// A Sailbox bound to the client that reaches it. Obtained from
/// [`Client::create_sailbox`], [`Client::create_from_checkpoint`], or
/// [`Client::sailbox`] (which binds an existing id without a network call).
///
/// Cheap to clone; clones share the underlying client transport.
///
/// ```no_run
/// # async fn demo() -> Result<(), sail::error::SailError> {
/// # let client = sail::Client::from_env()?;
/// let sb = client.sailbox("sb_abc123");
/// let result = sb.exec_shell("echo hello", Default::default()).await?.wait().await?;
/// sb.fs().write("/workspace/input.txt", b"hello\n", Default::default()).await?;
/// sb.terminate().await?;
/// # Ok(())
/// # }
/// ```
#[derive(Clone)]
pub struct Sailbox {
    client: Client,
    handle: SailboxHandle,
}

impl std::fmt::Debug for Sailbox {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Sailbox")
            .field("sailbox_id", &self.handle.sailbox_id)
            .finish_non_exhaustive()
    }
}

impl Sailbox {
    pub(crate) fn bind(client: Client, handle: SailboxHandle) -> Sailbox {
        Sailbox { client, handle }
    }

    pub(crate) fn client(&self) -> &Client {
        &self.client
    }

    /// The Sailbox's stable identifier.
    pub fn sailbox_id(&self) -> &str {
        &self.handle.sailbox_id
    }

    /// The data snapshot from the call that produced this object (create,
    /// from-checkpoint). A Sailbox bound by id via [`Client::sailbox`] carries
    /// only the id; use [`Sailbox::info`] for fresh state either way.
    pub fn handle(&self) -> &SailboxHandle {
        &self.handle
    }

    /// Consume the object, keeping just the data snapshot.
    pub fn into_handle(self) -> SailboxHandle {
        self.handle
    }

    /// Fetch this Sailbox's current state.
    pub async fn info(&self) -> Result<SailboxInfo, SailError> {
        self.client.get_sailbox(self.sailbox_id()).await
    }

    // --- lifecycle ---

    /// Terminate the Sailbox (idempotent).
    pub async fn terminate(&self) -> Result<(), SailError> {
        self.client.terminate_sailbox(self.sailbox_id()).await
    }

    /// Pause the Sailbox in memory.
    pub async fn pause(&self) -> Result<(), SailError> {
        self.client.pause_sailbox(self.sailbox_id()).await
    }

    /// Sleep the Sailbox to disk (it wakes on traffic).
    pub async fn sleep(&self) -> Result<(), SailError> {
        self.client.sleep_sailbox(self.sailbox_id()).await
    }

    /// Resume a paused or sleeping Sailbox.
    pub async fn resume(&self) -> Result<(), SailError> {
        self.client
            .resume_sailbox(self.sailbox_id())
            .await
            .map(|_| ())
    }

    /// Checkpoint the Sailbox. `options.name` labels the handle;
    /// `options.ttl`, when given, must be positive and overrides the server's
    /// default retention.
    pub async fn checkpoint(
        &self,
        options: CheckpointOptions,
    ) -> Result<SailboxCheckpoint, SailError> {
        self.client
            .checkpoint_sailbox(
                self.sailbox_id(),
                options.name.as_deref(),
                options.ttl.map(|ttl| ttl.as_secs() as i64),
            )
            .await
    }

    /// Upgrade the Sailbox runtime (now if running, else at next wake).
    pub async fn upgrade(&self) -> Result<UpgradeResult, SailError> {
        self.client.upgrade_sailbox(self.sailbox_id()).await
    }

    /// Fork this Sailbox into a new running child in one call. The child copies
    /// this Sailbox's memory and writable disk as they are now, so it branches
    /// from the parent's live state while the parent keeps running. The copy is
    /// transient: there is no separate artifact to keep or reuse. To branch
    /// from a saved point in time instead, take a durable [`Sailbox::checkpoint`]
    /// and start children from it with [`Client::create_from_checkpoint`], which
    /// works even after the parent is gone.
    ///
    /// The child is a new independent Sailbox: commands still running in the
    /// parent do not continue in the child (their on-disk effects up to the
    /// fork are preserved); start fresh execs on the child.
    pub async fn fork(&self, options: ForkOptions) -> Result<Sailbox, SailError> {
        self.client
            .fork_sailbox(self.sailbox_id(), options.name.as_deref(), options.timeout)
            .await
    }

    // --- exec ---

    /// Run a command from an argv vector (no shell interpretation) and return
    /// a handle to the live process. Resumes (wakes) the Sailbox to reach it.
    /// The returned [`ExecProcess`] streams output, accepts stdin, and
    /// resolves the exit status; dropping it detaches without killing the
    /// command. The output pump spawns on the calling task's tokio runtime.
    pub async fn exec(
        &self,
        argv: impl IntoIterator<Item = impl Into<String>>,
        options: ExecOptions,
    ) -> Result<ExecProcess, SailError> {
        self.client
            .exec(self.sailbox_id(), collect_argv(argv), options)
            .await
    }

    /// Run a shell command via `/bin/sh -lc` (pipes, globs, and `$VAR`
    /// expansion work), honoring the `cwd`/`background` options. Use
    /// [`Sailbox::exec`] with an argv vector when arguments must reach the
    /// command verbatim. Otherwise behaves like [`Sailbox::exec`].
    pub async fn exec_shell(
        &self,
        command: &str,
        options: ExecOptions,
    ) -> Result<ExecProcess, SailError> {
        self.client
            .exec_shell(self.sailbox_id(), command, options)
            .await
    }

    /// Run an argv command to completion and return its buffered
    /// [`ExecResult`]: a one-shot convenience over [`Sailbox::exec`] followed
    /// by [`ExecProcess::wait`]. A nonzero exit code reports through
    /// [`ExecResult::exit_code`], not an error, and an exceeded
    /// `options.timeout` reports through [`ExecResult::timed_out`]. Use
    /// [`Sailbox::exec`] to stream output or feed stdin.
    ///
    /// ```no_run
    /// # async fn demo() -> Result<(), sail::SailError> {
    /// # let client = sail::Client::from_env()?;
    /// let sb = client.sailbox("sb_abc123");
    /// let result = sb.run(["echo", "hello"], Default::default()).await?;
    /// assert_eq!(result.exit_code, 0);
    /// println!("{}", result.stdout);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn run(
        &self,
        argv: impl IntoIterator<Item = impl Into<String>>,
        options: RunOptions,
    ) -> Result<ExecResult, SailError> {
        self.exec(argv, options.into_exec_options())
            .await?
            .wait()
            .await
    }

    /// Run a shell command (`/bin/sh -lc`) to completion and return its
    /// buffered [`ExecResult`], honoring `options.cwd`. Otherwise behaves
    /// like [`Sailbox::run`].
    pub async fn run_shell(
        &self,
        command: &str,
        options: RunOptions,
    ) -> Result<ExecResult, SailError> {
        self.exec_shell(command, options.into_exec_options())
            .await?
            .wait()
            .await
    }

    // --- files ---

    /// Filesystem operations on this Sailbox's guest: read and write files
    /// (buffered or streaming), and directory helpers.
    pub fn fs(&self) -> SailboxFs<'_> {
        SailboxFs { sailbox: self }
    }

    // --- listeners ---

    /// Expose a guest port at runtime. The returned [`Listener`] carries the
    /// resolved endpoint but an unknown route status: the expose response
    /// does not report reachability. Confirm with
    /// [`Sailbox::wait_for_listener`].
    pub async fn expose(
        &self,
        guest_port: u32,
        protocol: IngressProtocol,
        allowlist: &[String],
    ) -> Result<Listener, SailError> {
        self.client
            .expose_listener(self.sailbox_id(), guest_port, protocol, allowlist)
            .await
    }

    /// Remove a runtime ingress port.
    pub async fn unexpose(&self, guest_port: u32) -> Result<(), SailError> {
        self.client
            .unexpose_listener(self.sailbox_id(), guest_port)
            .await
    }

    /// List this Sailbox's listeners without waking it.
    pub async fn listeners(&self) -> Result<Vec<Listener>, SailError> {
        self.client.list_listeners(self.sailbox_id()).await
    }

    /// Fetch one listener by guest port without waking the box.
    pub async fn listener(&self, guest_port: u32) -> Result<Listener, SailError> {
        self.client
            .get_listener(self.sailbox_id(), guest_port)
            .await
    }

    /// Block until the listener on `guest_port` is reachable end to end
    /// (route active and its endpoint accepting) and return it. An HTTP
    /// listener is probed by URL, so success means the guest server answered;
    /// a TCP listener is ready once the guest sends bytes or holds the
    /// connection open. This is a connectivity check, not an application
    /// health check. Re-checks every second and fails with a timeout error
    /// after `options.timeout`.
    pub async fn wait_for_listener(
        &self,
        guest_port: u32,
        options: WaitForListenerOptions,
    ) -> Result<Listener, SailError> {
        self.client
            .wait_for_listener(self.sailbox_id(), guest_port, options.timeout)
            .await
    }

    /// Ingress-identity headers for this Sailbox, as name/value pairs.
    pub async fn ingress_auth_headers(&self) -> Result<Vec<(String, String)>, SailError> {
        self.client.ingress_auth_headers(self.sailbox_id()).await
    }

    // --- ssh ---

    /// Make the Sailbox reachable over SSH, returning the endpoint when
    /// `options.wait` is set (else `None`). Installs the org SSH CA as
    /// trusted, (re)starts `sshd`, confirms the CA-only daemon owns guest
    /// port 22, and only then exposes the port as TCP ingress, so a failed
    /// enable never leaves a non-CA daemon reachable. Idempotent. A non-empty
    /// `options.allowlist` restricts port 22 to those source CIDRs; when
    /// empty, a first enable is open to any source and a re-enable keeps an
    /// existing restriction.
    pub async fn enable_ssh(
        &self,
        options: EnableSshOptions,
    ) -> Result<Option<SshEndpoint>, SailError> {
        self.client
            .enable_ssh(
                self.sailbox_id(),
                &options.allowlist,
                options.wait,
                options.timeout,
            )
            .await
    }
}

/// Filesystem operations on a Sailbox's guest, reached via [`Sailbox::fs`]:
/// buffered and streaming reads and writes, plus directory helpers with
/// coreutils semantics (`mkdir -p`, `rm -rf`, `test -e`), documented per
/// method.
pub struct SailboxFs<'a> {
    sailbox: &'a Sailbox,
}

impl std::fmt::Debug for SailboxFs<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SailboxFs")
            .field("sailbox_id", &self.sailbox.sailbox_id())
            .finish()
    }
}

impl SailboxFs<'_> {
    /// Read a guest file into memory in one call.
    pub async fn read(&self, path: &str) -> Result<Vec<u8>, SailError> {
        self.sailbox
            .client
            .read_file(self.sailbox.sailbox_id(), path)
            .await
    }

    /// Write `data` to a guest file in one call.
    pub async fn write(
        &self,
        path: &str,
        data: &[u8],
        options: WriteOptions,
    ) -> Result<(), SailError> {
        self.sailbox
            .client
            .write_file(self.sailbox.sailbox_id(), path, data, options)
            .await
    }

    /// Open a streaming read of a guest file.
    pub async fn read_stream(&self, path: &str) -> Result<FileReader, SailError> {
        self.sailbox
            .client
            .read_stream(self.sailbox.sailbox_id(), path)
            .await
    }

    /// Open a streaming write to a guest file.
    pub async fn write_stream(
        &self,
        path: &str,
        options: WriteOptions,
    ) -> Result<FileWriter, SailError> {
        self.sailbox
            .client
            .write_stream(self.sailbox.sailbox_id(), path, options)
            .await
    }

    /// Create a directory and any missing parents (like `mkdir -p`); a no-op if
    /// it already exists.
    pub async fn mkdir(&self, path: &str) -> Result<(), SailError> {
        self.sailbox
            .client
            .make_dir(self.sailbox.sailbox_id(), path)
            .await
    }

    /// Remove a file or directory tree (like `rm -rf`); a no-op if it is already
    /// absent.
    pub async fn remove(&self, path: &str) -> Result<(), SailError> {
        self.sailbox
            .client
            .remove_path(self.sailbox.sailbox_id(), path)
            .await
    }

    /// Whether `path` exists in the guest. Follows symlinks (like `test -e`), so
    /// a dangling symlink reports `false` even though [`ls`](Self::ls) lists it.
    pub async fn exists(&self, path: &str) -> Result<bool, SailError> {
        self.sailbox
            .client
            .path_exists(self.sailbox.sailbox_id(), path)
            .await
    }

    /// List a directory's immediate entries as [`DirEntry`] records (no
    /// recursion). Runs GNU `find` in the guest, which the default Debian image
    /// ships. A missing path errors, as does a path that is not a directory and
    /// a listing too large for the exec output cap. An entry whose name is not
    /// valid UTF-8 fails the listing, since the path API cannot address it.
    pub async fn ls(&self, path: &str) -> Result<Vec<DirEntry>, SailError> {
        self.sailbox
            .client
            .list_dir(self.sailbox.sailbox_id(), path)
            .await
    }
}

impl Client {
    /// Bind an existing Sailbox id to this client without a network call,
    /// giving the method-style surface over it.
    pub fn sailbox(&self, sailbox_id: impl Into<String>) -> Sailbox {
        Sailbox {
            client: self.clone(),
            handle: SailboxHandle {
                sailbox_id: sailbox_id.into(),
                ..Default::default()
            },
        }
    }
}