sail-rs 0.2.15

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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
//! 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. The
/// default is `Other("")`: the status of a handle no server response has
/// filled in yet.
#[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 Default for SailboxStatus {
    fn default() -> Self {
        SailboxStatus::Other(String::new())
    }
}

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 [`ListSailboxesQuery`]. 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 ListenerProtocol {
    /// Raw TCP.
    Tcp,
    /// HTTP.
    Http,
    /// A protocol this SDK version does not recognize, kept verbatim.
    Other(String),
}

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

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

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

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

impl<'de> Deserialize<'de> for ListenerProtocol {
    fn deserialize<D: serde::Deserializer<'de>>(
        deserializer: D,
    ) -> Result<ListenerProtocol, D::Error> {
        Ok(ListenerProtocol::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 user-facing string for this status. The backend's proto spelling
    /// (`LISTENER_ROUTE_STATUS_*`) is normalized here, once, so no wrapper
    /// ever sees it.
    pub fn as_str(&self) -> &str {
        match self {
            ListenerRouteStatus::Unspecified => "unspecified",
            ListenerRouteStatus::Pending => "pending",
            ListenerRouteStatus::Active => "active",
            ListenerRouteStatus::Restoring => "restoring",
            ListenerRouteStatus::Unavailable => "unavailable",
            ListenerRouteStatus::Other(s) => s,
        }
    }
}

impl From<&str> for ListenerRouteStatus {
    /// Parse either the backend's proto spelling or the friendly form (so a
    /// serialized [`Listener`](crate::worker::Listener) round-trips).
    fn from(s: &str) -> ListenerRouteStatus {
        match s {
            "LISTENER_ROUTE_STATUS_UNSPECIFIED" | "unspecified" => ListenerRouteStatus::Unspecified,
            "LISTENER_ROUTE_STATUS_PENDING" | "pending" => ListenerRouteStatus::Pending,
            "LISTENER_ROUTE_STATUS_ACTIVE" | "active" => ListenerRouteStatus::Active,
            "LISTENER_ROUTE_STATUS_RESTORING" | "restoring" => ListenerRouteStatus::Restoring,
            "LISTENER_ROUTE_STATUS_UNAVAILABLE" | "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 [`ListenerProtocol`], 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())
    }
}

/// Options for [`Sailbox::checkpoint`](crate::Sailbox::checkpoint).
#[derive(Debug, Clone, Default)]
pub struct CheckpointOptions {
    /// Human-readable label for the checkpoint.
    pub name: Option<String>,
    /// Retention override; must be positive when given.
    pub ttl: Option<std::time::Duration>,
}

/// Backends report kernel spellings (`x86_64`, `aarch64`); the SDK speaks the
/// create-side vocabulary (`amd64`, `arm64`).
fn normalized_architecture<'de, D: serde::Deserializer<'de>>(
    deserializer: D,
) -> Result<String, D::Error> {
    let raw = String::deserialize(deserializer)?;
    Ok(match raw.as_str() {
        "x86_64" | "amd64" => "amd64".to_string(),
        "aarch64" | "arm64" => "arm64".to_string(),
        _ => raw,
    })
}

/// Named sailbox resource size. Sailboxes are offered in a small discrete CPU
/// menu rather than free-form vCPU/memory/disk. Each size sets the vCPU count
/// plus default memory and disk; the scheduler owns the exact numbers. Billing
/// is by observed usage, so a larger size is a higher ceiling, not a higher
/// bill.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SailboxSize {
    /// Small (1 vCPU): fastest cold starts, forks, and resumes, with
    /// lower ceilings that cap what a runaway workload can consume.
    Small,
    /// Medium (4 vCPU, default).
    Medium,
}

impl SailboxSize {
    /// The wire string for this size.
    pub fn as_str(&self) -> &'static str {
        match self {
            SailboxSize::Small => "s",
            SailboxSize::Medium => "m",
        }
    }

    /// Parse a wire string, returning `None` for an unsupported size.
    pub fn parse(s: &str) -> Option<SailboxSize> {
        match s {
            "s" => Some(SailboxSize::Small),
            "m" => Some(SailboxSize::Medium),
            _ => None,
        }
    }

    /// The allowed size labels in ascending order, for error messages and help.
    pub fn allowed() -> &'static [&'static str] {
        &["s", "m"]
    }
}

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

impl Serialize for SailboxSize {
    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, Default, 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, in the create-side vocabulary
    /// (`amd64` or `arm64`).
    #[serde(deserialize_with = "normalized_architecture", default)]
    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,
    /// When the handle expires and becomes eligible for garbage collection;
    /// `None` for a handle that carries no fresh retention bound (a paused or
    /// sleeping source).
    #[serde(with = "time::serde::rfc3339::option")]
    pub expires_at: Option<OffsetDateTime>,
    /// Source sailbox's lifecycle status after checkpointing.
    pub status: SailboxStatus,
}

/// Filters for list/list_page.
#[derive(Debug, Clone)]
pub struct ListSailboxesQuery {
    /// Restrict results to sailboxes owned by the app with this id.
    pub app_id: 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;

impl Default for ListSailboxesQuery {
    fn default() -> ListSailboxesQuery {
        ListSailboxesQuery {
            app_id: 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 VolumeInfo {
    /// 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>,
}

/// The wire shape of the add-listener response: the scheduler resolves the
/// public endpoint in the response (so a caller renders it without a second
/// lookup) but reports nothing about routing, so it converts to a [`Listener`]
/// with an unspecified route status.
#[derive(Debug, Clone, Deserialize)]
pub(crate) struct AddListenerWire {
    pub(crate) guest_port: u32,
    pub(crate) protocol: ListenerProtocol,
    #[serde(default)]
    pub(crate) public_url: String,
    #[serde(default, rename = "tcp_public_host")]
    pub(crate) public_host: String,
    #[serde(default, rename = "tcp_public_port")]
    pub(crate) public_port: u32,
}

impl From<AddListenerWire> for crate::worker::Listener {
    fn from(wire: AddListenerWire) -> crate::worker::Listener {
        crate::worker::Listener {
            guest_port: wire.guest_port,
            protocol: wire.protocol,
            // The expose response says nothing about reachability; confirm
            // with wait_for_listener or re-fetch via get/list.
            route_status: ListenerRouteStatus::Unspecified,
            public_url: wire.public_url,
            public_host: wire.public_host,
            public_port: wire.public_port,
        }
    }
}

/// 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,
}

/// How to reach an exposed listener: a routable HTTPS URL for `http`
/// listeners, or a host/port any TCP client can dial for `tcp` listeners.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ListenerEndpoint {
    /// The HTTPS URL to reach the guest service.
    Http {
        /// Routable URL.
        url: String,
    },
    /// The address to dial for a raw-TCP listener.
    Tcp {
        /// Hostname to dial.
        host: String,
        /// Port to dial.
        port: u32,
    },
}

impl std::fmt::Display for ListenerEndpoint {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ListenerEndpoint::Http { url } => f.write_str(url),
            ListenerEndpoint::Tcp { host, port } => write!(f, "{host}:{port}"),
        }
    }
}

/// 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 resource size; defaults server-side when absent.
    pub size: Option<SailboxSize>,
    /// Optional memory limit in whole GiB, within the size's range; the
    /// size's default when absent.
    pub memory_gib: Option<u32>,
    /// Optional disk size in whole GiB, within the size's range; the size's
    /// default when absent.
    pub disk_gib: Option<u32>,
    /// Optional idle timeout in minutes after which the platform may autosleep.
    pub autosleep_timeout_minutes: Option<i64>,
    /// Enable SSH on the new sailbox after create: trust the org SSH CA, start
    /// `sshd`, and expose guest port 22 as TCP once the CA-only daemon owns it.
    /// An explicit port-22 ingress entry contributes just its allowlist.
    pub ssh: bool,
}

impl Default for CreateSailboxRequest {
    /// An empty request for a plain Debian-base sailbox: fill in `app_id` and
    /// `name`, override the rest as needed.
    fn default() -> CreateSailboxRequest {
        CreateSailboxRequest {
            app_id: String::new(),
            name: String::new(),
            ingress_ports: Vec::new(),
            volume_mounts: Vec::new(),
            image: crate::image::ImageSpec {
                base: Some(crate::image::BaseImage::Debian),
                ..crate::image::ImageSpec::default()
            },
            size: None,
            memory_gib: None,
            disk_gib: None,
            autosleep_timeout_minutes: None,
            ssh: false,
        }
    }
}

#[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 = ListSailboxesQuery::default();
        assert_eq!(query.limit, DEFAULT_LIST_LIMIT);
        assert!(query.limit > 0);
        assert_eq!(query.offset, 0);
    }
}