sail-rs 0.2.10

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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
//! Typed domain models for the sailbox API: lifecycle, listing, ingress
//! listeners, and volumes.
//!
//! The core owns the wire schema: it deserializes API responses into these
//! structs (applying the wire-schema field defaults) and serializes them back
//! out for bindings. A binding maps a struct onto its own public type by field
//! name without re-parsing the wire shape.

use serde::{Deserialize, Serialize};
use time::OffsetDateTime;

/// Lifecycle status of a sailbox. An unrecognized server value is preserved in
/// `Other` so a status a newer backend introduces never fails parsing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SailboxStatus {
    /// Running and serving.
    Running,
    /// Paused in memory.
    Paused,
    /// Sleeping (checkpointed to disk).
    Sleeping,
    /// In a failed state.
    Failed,
    /// Terminated.
    Terminated,
    /// A status this SDK version does not recognize, kept verbatim.
    Other(String),
}

impl SailboxStatus {
    /// The wire string for this status.
    pub fn as_str(&self) -> &str {
        match self {
            SailboxStatus::Running => "running",
            SailboxStatus::Paused => "paused",
            SailboxStatus::Sleeping => "sleeping",
            SailboxStatus::Failed => "failed",
            SailboxStatus::Terminated => "terminated",
            SailboxStatus::Other(s) => s,
        }
    }
}

impl From<&str> for SailboxStatus {
    fn from(s: &str) -> SailboxStatus {
        match s {
            "running" => SailboxStatus::Running,
            "paused" => SailboxStatus::Paused,
            "sleeping" => SailboxStatus::Sleeping,
            "failed" => SailboxStatus::Failed,
            "terminated" => SailboxStatus::Terminated,
            other => SailboxStatus::Other(other.to_string()),
        }
    }
}

impl std::fmt::Display for SailboxStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl Serialize for SailboxStatus {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for SailboxStatus {
    fn deserialize<D: serde::Deserializer<'de>>(
        deserializer: D,
    ) -> Result<SailboxStatus, D::Error> {
        Ok(SailboxStatus::from(
            String::deserialize(deserializer)?.as_str(),
        ))
    }
}

/// A lifecycle status a client can filter by in [`ListQuery`]. A closed set: a
/// client only filters by statuses the SDK knows. Server responses use the open
/// [`SailboxStatus`], which tolerates a status a newer backend introduces.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SailboxStatusFilter {
    /// Running and serving.
    Running,
    /// Paused in memory.
    Paused,
    /// Sleeping (checkpointed to disk).
    Sleeping,
    /// In a failed state.
    Failed,
    /// Terminated.
    Terminated,
}

impl SailboxStatusFilter {
    /// The wire string for this status.
    pub fn as_str(&self) -> &'static str {
        match self {
            SailboxStatusFilter::Running => "running",
            SailboxStatusFilter::Paused => "paused",
            SailboxStatusFilter::Sleeping => "sleeping",
            SailboxStatusFilter::Failed => "failed",
            SailboxStatusFilter::Terminated => "terminated",
        }
    }

    /// Parse a wire string, returning `None` for a status the SDK does not know.
    pub fn parse(s: &str) -> Option<SailboxStatusFilter> {
        match s {
            "running" => Some(SailboxStatusFilter::Running),
            "paused" => Some(SailboxStatusFilter::Paused),
            "sleeping" => Some(SailboxStatusFilter::Sleeping),
            "failed" => Some(SailboxStatusFilter::Failed),
            "terminated" => Some(SailboxStatusFilter::Terminated),
            _ => None,
        }
    }
}

/// Wire protocol for an ingress port or listener. An unrecognized value is
/// preserved in `Other` so a protocol a newer backend introduces never fails.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Protocol {
    /// Raw TCP.
    Tcp,
    /// HTTP.
    Http,
    /// A protocol this SDK version does not recognize, kept verbatim.
    Other(String),
}

impl Protocol {
    /// The wire string for this protocol.
    pub fn as_str(&self) -> &str {
        match self {
            Protocol::Tcp => "tcp",
            Protocol::Http => "http",
            Protocol::Other(s) => s,
        }
    }
}

impl From<&str> for Protocol {
    fn from(s: &str) -> Protocol {
        match s {
            "tcp" => Protocol::Tcp,
            "http" => Protocol::Http,
            other => Protocol::Other(other.to_string()),
        }
    }
}

impl std::fmt::Display for Protocol {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl Serialize for Protocol {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for Protocol {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Protocol, D::Error> {
        Ok(Protocol::from(String::deserialize(deserializer)?.as_str()))
    }
}

/// Status of a listener's ingress route. An unrecognized value is preserved in
/// `Other` so a status a newer backend introduces never fails to parse.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ListenerRouteStatus {
    /// The route state is not yet known.
    Unspecified,
    /// The route is being set up.
    Pending,
    /// The route is active and ready to carry traffic.
    Active,
    /// The route is being restored after a checkpoint or migration.
    Restoring,
    /// The route is temporarily unavailable.
    Unavailable,
    /// A status this SDK version does not recognize, kept verbatim.
    Other(String),
}

impl ListenerRouteStatus {
    /// The wire string for this status.
    pub fn as_str(&self) -> &str {
        match self {
            ListenerRouteStatus::Unspecified => "LISTENER_ROUTE_STATUS_UNSPECIFIED",
            ListenerRouteStatus::Pending => "LISTENER_ROUTE_STATUS_PENDING",
            ListenerRouteStatus::Active => "LISTENER_ROUTE_STATUS_ACTIVE",
            ListenerRouteStatus::Restoring => "LISTENER_ROUTE_STATUS_RESTORING",
            ListenerRouteStatus::Unavailable => "LISTENER_ROUTE_STATUS_UNAVAILABLE",
            ListenerRouteStatus::Other(s) => s,
        }
    }
}

impl From<&str> for ListenerRouteStatus {
    fn from(s: &str) -> ListenerRouteStatus {
        match s {
            "LISTENER_ROUTE_STATUS_UNSPECIFIED" => ListenerRouteStatus::Unspecified,
            "LISTENER_ROUTE_STATUS_PENDING" => ListenerRouteStatus::Pending,
            "LISTENER_ROUTE_STATUS_ACTIVE" => ListenerRouteStatus::Active,
            "LISTENER_ROUTE_STATUS_RESTORING" => ListenerRouteStatus::Restoring,
            "LISTENER_ROUTE_STATUS_UNAVAILABLE" => ListenerRouteStatus::Unavailable,
            other => ListenerRouteStatus::Other(other.to_string()),
        }
    }
}

impl std::fmt::Display for ListenerRouteStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl Serialize for ListenerRouteStatus {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for ListenerRouteStatus {
    fn deserialize<D: serde::Deserializer<'de>>(
        deserializer: D,
    ) -> Result<ListenerRouteStatus, D::Error> {
        Ok(ListenerRouteStatus::from(
            String::deserialize(deserializer)?.as_str(),
        ))
    }
}

/// Transport protocol a client requests when exposing an ingress port. A closed
/// set: a client can only request a protocol the SDK supports. Server responses
/// use the open [`Protocol`], which tolerates a protocol a newer backend adds.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IngressProtocol {
    /// Raw TCP.
    Tcp,
    /// HTTP.
    Http,
}

impl IngressProtocol {
    /// The wire string for this protocol.
    pub fn as_str(&self) -> &'static str {
        match self {
            IngressProtocol::Tcp => "tcp",
            IngressProtocol::Http => "http",
        }
    }

    /// Parse a wire string, returning `None` for a protocol the SDK does not
    /// support.
    pub fn parse(s: &str) -> Option<IngressProtocol> {
        match s {
            "tcp" => Some(IngressProtocol::Tcp),
            "http" => Some(IngressProtocol::Http),
            _ => None,
        }
    }
}

impl std::fmt::Display for IngressProtocol {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl Serialize for IngressProtocol {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.as_str())
    }
}

/// A running-sailbox handle: the fields needed to exec/file/listener against a
/// live box. Returned by create/resume/from_checkpoint.
#[derive(Debug, Clone, Serialize)]
pub struct SailboxHandle {
    /// The sailbox's stable identifier.
    pub sailbox_id: String,
    /// The caller-supplied sailbox name.
    pub name: String,
    /// The sailbox's lifecycle status (for example `running`).
    pub status: SailboxStatus,
    /// Network address of the worker hosting the sailbox.
    pub worker_address: String,
    /// Endpoint used to open exec/file/listener streams to the box.
    pub exec_endpoint: String,
}

/// Read-only snapshot from get/list. Deliberately omits worker_address /
/// exec_endpoint (the list/get endpoints do not return them).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SailboxInfo {
    /// The sailbox's stable identifier.
    pub sailbox_id: String,
    /// Identifier of the owning app.
    pub app_id: String,
    /// Name of the owning app.
    pub app_name: String,
    /// Identifier of the image the sailbox was created from.
    pub image_id: String,
    /// The caller-supplied sailbox name.
    pub name: String,
    /// The sailbox's lifecycle status (for example `running`).
    pub status: SailboxStatus,
    /// Configured memory size, in mebibytes.
    pub memory_mib: i64,
    /// Configured number of virtual CPUs.
    pub vcpu_count: i64,
    /// Configured state-disk size, in gibibytes.
    pub state_disk_size_gib: i64,
    /// Requested CPU allocation, in vCPUs.
    pub cpu_requested_vcpu: i64,
    /// Current CPU usage, in vCPUs.
    pub cpu_used_vcpu: f64,
    /// Requested memory allocation, in bytes.
    pub memory_requested_bytes: i64,
    /// Current memory usage, in bytes.
    pub memory_used_bytes: i64,
    /// Requested disk allocation, in bytes.
    pub disk_requested_bytes: i64,
    /// Current disk usage, in bytes.
    pub disk_used_bytes: i64,
    /// CPU architecture of the sailbox (for example `x86_64` or `arm64`).
    pub architecture: String,
    /// Guest schema version the box is running, when reported by the backend.
    #[serde(default)]
    pub guest_schema_version: Option<i64>,
    /// Human-readable error detail, present when the box is in an error state.
    #[serde(default)]
    pub error_message: Option<String>,
    /// Monotonic checkpoint generation counter for the sailbox.
    pub checkpoint_generation: i64,
    /// When the box last started, if it has started.
    #[serde(with = "time::serde::rfc3339::option", default)]
    pub started_at: Option<OffsetDateTime>,
    /// When the most recent checkpoint was taken, if any.
    #[serde(with = "time::serde::rfc3339::option", default)]
    pub last_checkpointed_at: Option<OffsetDateTime>,
    /// When the sailbox was created.
    #[serde(with = "time::serde::rfc3339")]
    pub created_at: OffsetDateTime,
    /// When the sailbox was last updated.
    #[serde(with = "time::serde::rfc3339")]
    pub updated_at: OffsetDateTime,
}

/// One page of list results plus the pagination envelope.
#[derive(Debug, Clone, Serialize)]
pub struct SailboxPage {
    /// The sailboxes in this page.
    pub items: Vec<SailboxInfo>,
    /// Maximum number of items requested for this page.
    pub limit: i64,
    /// Zero-based offset of the first item in this page.
    pub offset: i64,
    /// Total number of sailboxes matching the query across all pages.
    pub total: i64,
    /// True when further pages exist beyond this one.
    pub has_more: bool,
}

/// A durable checkpoint handle. `status` echoes the source sailbox's lifecycle
/// status after checkpointing (a running box is snapshotted; a paused/sleeping
/// one returns its existing checkpoint), so the binding can sync its handle.
#[derive(Debug, Clone, Serialize)]
pub struct SailboxCheckpoint {
    /// Stable identifier of the checkpoint.
    pub checkpoint_id: String,
    /// Identifier of the sailbox the checkpoint was taken from.
    pub sailbox_id: String,
    /// Checkpoint generation counter captured by this checkpoint.
    pub checkpoint_generation: i64,
    /// Source sailbox's lifecycle status after checkpointing.
    pub status: SailboxStatus,
}

/// Filters for list/list_page.
#[derive(Debug, Clone)]
pub struct ListQuery {
    /// Restrict results to sailboxes owned by this app (id or name).
    pub app: Option<String>,
    /// Restrict results to sailboxes in this lifecycle status.
    pub status: Option<SailboxStatusFilter>,
    /// Free-text search filter applied by the backend.
    pub search: Option<String>,
    /// Exclude sailboxes whose guest schema version exceeds this value.
    pub max_guest_schema_version: Option<i64>,
    /// Maximum number of items to return.
    pub limit: i64,
    /// Zero-based offset of the first item to return.
    pub offset: i64,
}

/// Default page size for listing, matching the sailbox API's own default. The
/// API rejects `limit=0`, so the derived all-zero default cannot be used.
pub const DEFAULT_LIST_LIMIT: i64 = 50;

/// Resource-limit bounds enforced at create time. These mirror the scheduler's
/// authoritative limits so every binding (CLI, Python, future SDKs) fails fast
/// with the same error instead of round-tripping to a backend rejection.
pub const MAX_SAILBOX_VCPUS: i64 = 4;
/// Minimum requested memory in MiB (0 is allowed and means "use the default").
pub const MIN_SAILBOX_MEMORY_MIB: i64 = 1024;
/// Maximum requested memory in MiB.
pub const MAX_SAILBOX_MEMORY_MIB: i64 = 8192;
/// Maximum requested state-disk size in GiB.
pub const MAX_SAILBOX_DISK_GIB: i64 = 32;

impl Default for ListQuery {
    fn default() -> ListQuery {
        ListQuery {
            app: None,
            status: None,
            search: None,
            max_guest_schema_version: None,
            limit: DEFAULT_LIST_LIMIT,
            offset: 0,
        }
    }
}

/// One guest ingress port to reserve at create time.
#[derive(Debug, Clone, Serialize)]
pub struct IngressPort {
    /// Port inside the guest to expose for ingress.
    pub guest_port: u32,
    /// Transport protocol for the port (for example `tcp`).
    pub protocol: IngressProtocol,
    /// Source addresses allowed to reach the port; empty means all sources are
    /// allowed. Always sent (even when empty) so the request states it
    /// explicitly rather than relying on an omitted field.
    pub allowlist: Vec<String>,
}

/// One NFS volume mount.
#[derive(Debug, Clone, Serialize)]
pub struct VolumeMount {
    /// Identifier of the NFS volume to mount.
    pub volume_id: String,
    /// Absolute path inside the guest where the volume is mounted.
    pub mount_path: String,
}

/// A managed NFS volume as returned by the sailbox-volume API. (The local
/// mount path is a binding-side concern and not part of this wire type.)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NfsVolume {
    /// Stable identifier of the volume.
    pub volume_id: String,
    /// Caller-supplied volume name.
    pub name: String,
    /// Storage backend serving the volume.
    pub backend: String,
    /// Lifecycle status of the volume.
    pub status: String,
    /// When the volume was created, if reported.
    #[serde(with = "time::serde::rfc3339::option", default)]
    pub created_at: Option<OffsetDateTime>,
    /// When the volume was last updated, if reported.
    #[serde(with = "time::serde::rfc3339::option", default)]
    pub updated_at: Option<OffsetDateTime>,
}

/// Response from exposing a runtime ingress port (`expose`). The scheduler
/// resolves the public endpoint in this response, so a caller renders it
/// without a second lookup.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AddListenerResponse {
    /// The in-guest port now exposed.
    pub guest_port: u32,
    /// Wire protocol exposed, e.g. `tcp` or `http`.
    pub protocol: Protocol,
    /// Publicly reachable URL, when the listener has one (typically `http`).
    #[serde(default)]
    pub public_url: String,
    /// Public hostname for a raw-TCP listener.
    #[serde(default)]
    pub tcp_public_host: String,
    /// Public port for a raw-TCP listener.
    #[serde(default)]
    pub tcp_public_port: u32,
}

/// A CA-signed SSH user certificate plus the key id that identifies the signing
/// org (`org=<id>;fp=...;iat=...`).
#[derive(Debug, Clone)]
pub struct IssuedUserCert {
    /// The OpenSSH certificate (`<type>-cert-v01@openssh.com AAAA...`).
    pub certificate: String,
    /// The certificate key id.
    pub key_id: String,
}

impl AddListenerResponse {
    /// The reachable endpoint: `public_url` if present, else `host:port` for a
    /// raw-TCP listener, else `None` (e.g. a local stack returns neither).
    pub fn endpoint(&self) -> Option<String> {
        if !self.public_url.is_empty() {
            return Some(self.public_url.clone());
        }
        if !self.tcp_public_host.is_empty() && self.tcp_public_port != 0 {
            return Some(format!("{}:{}", self.tcp_public_host, self.tcp_public_port));
        }
        None
    }
}

/// Inputs to create a sailbox. The image is a typed [`ImageSpec`](crate::image::ImageSpec)
/// (the higher-level image builder lives in the language wrapper); the lifecycle
/// envelope is owned by the core.
#[derive(Debug, Clone)]
pub struct CreateSailboxRequest {
    /// Identifier of the app that will own the sailbox.
    pub app_id: String,
    /// Caller-supplied name for the sailbox.
    pub name: String,
    /// Guest ingress ports to reserve at create time.
    pub ingress_ports: Vec<IngressPort>,
    /// NFS volumes to mount into the guest.
    pub volume_mounts: Vec<VolumeMount>,
    /// The image to create the sailbox from. Serialized to canonical proto-JSON
    /// and sent as the `image` field.
    pub image: crate::image::ImageSpec,
    /// Requested CPU allocation in vCPUs; defaults server-side when absent.
    pub cpu: Option<i64>,
    /// Requested memory size in mebibytes; defaults server-side when absent.
    pub memory_mib: Option<i64>,
    /// Requested state-disk size in gibibytes; defaults server-side when absent.
    pub state_disk_size_gib: Option<i64>,
    /// Optional idle timeout in minutes after which the platform may autosleep.
    pub autosleep_timeout_min: Option<i64>,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn list_query_default_uses_a_valid_nonzero_limit() {
        // The sailbox API rejects limit=0, so the default must be the API's own
        // page size, not the derived zero.
        let query = ListQuery::default();
        assert_eq!(query.limit, DEFAULT_LIST_LIMIT);
        assert!(query.limit > 0);
        assert_eq!(query.offset, 0);
    }
}