sail-rs 0.1.0

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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
//! Typed client over the sailbox HTTP API (lifecycle, listeners, and volumes).
//!
//! Each method builds the request body, runs the HTTP call (with retry +
//! Idempotency-Key from [`HttpCore`]), maps a non-2xx response onto the
//! canonical [`SailError`] taxonomy, validates the echoed status, and
//! deserializes the body into a typed struct.

use serde_json::{json, Value};

use crate::error::SailError;
use crate::http::{HttpCore, IdempotencyKey, Method, RequestSpec};
use crate::retry::{RetryPolicy, DEFAULT_RETRY_POLICY, NO_RETRY};
use crate::sailbox::types::{
    CreateSailboxRequest, ListQuery, NfsVolume, SailboxCheckpoint, SailboxHandle, SailboxInfo,
    SailboxInfoWire, SailboxPage, MAX_SAILBOX_DISK_GIB, MAX_SAILBOX_MEMORY_MIB, MAX_SAILBOX_VCPUS,
    MIN_SAILBOX_MEMORY_MIB,
};
use crate::worker::Listener;

/// Validate the optional create-time resource limits against the platform bounds
/// ([`MAX_SAILBOX_VCPUS`], etc.). Bindings call this to fail fast with a clear
/// error before doing any work; `create` also calls it so every path is covered.
/// `0` (and `None`) means "use the platform default" and is always accepted.
pub fn validate_resource_limits(
    cpu: Option<i64>,
    memory_mib: Option<i64>,
    state_disk_size_gib: Option<i64>,
) -> Result<(), SailError> {
    let invalid = |message: String| Err(SailError::InvalidArgument { message });
    if let Some(cpu) = cpu {
        if cpu < 0 {
            return invalid("max_cpu must be at least 0".to_string());
        }
        if cpu > MAX_SAILBOX_VCPUS {
            return invalid(format!("max_cpu must be at most {MAX_SAILBOX_VCPUS}"));
        }
    }
    if let Some(memory) = memory_mib {
        if memory != 0 && memory < MIN_SAILBOX_MEMORY_MIB {
            return invalid(format!(
                "max_memory_mib must be at least {MIN_SAILBOX_MEMORY_MIB}"
            ));
        }
        if memory > MAX_SAILBOX_MEMORY_MIB {
            return invalid(format!(
                "max_memory_mib must be at most {MAX_SAILBOX_MEMORY_MIB}"
            ));
        }
    }
    if let Some(disk) = state_disk_size_gib {
        if disk < 0 {
            return invalid("max_disk_gib must be at least 0".to_string());
        }
        if disk > MAX_SAILBOX_DISK_GIB {
            return invalid(format!(
                "max_disk_gib must be at most {MAX_SAILBOX_DISK_GIB}"
            ));
        }
    }
    Ok(())
}

/// Result of an in-guest agent upgrade.
#[derive(Debug, Clone, serde::Serialize)]
pub struct UpgradeOutcome {
    /// True when applied immediately (running box); false when deferred to the
    /// next wake.
    pub applied: bool,
    /// Lifecycle status of the sailbox after the upgrade call.
    pub status: String,
}

/// Typed client over the sailbox HTTP API host.
pub struct SailboxApi<'a> {
    http: &'a HttpCore,
}

impl<'a> SailboxApi<'a> {
    /// Build a client bound to a sailbox-API `HttpCore`.
    pub fn new(http: &'a HttpCore) -> SailboxApi<'a> {
        SailboxApi { http }
    }

    /// Create a sailbox (`POST /v1/sailboxes`) and wait for it to come up.
    ///
    /// Optional CPU, memory, and state-disk sizes are included only when set.
    /// A non-2xx response or an echoed `failed` status maps to
    /// [`SailError::Creation`]; the returned handle requires a `running` status.
    pub async fn create(&self, req: &CreateSailboxRequest) -> Result<SailboxHandle, SailError> {
        validate_resource_limits(req.cpu, req.memory_mib, req.state_disk_size_gib)?;
        let mut body = json!({
            "app_id": req.app_id,
            "name": req.name,
            "ingress_ports": req.ingress_ports,
            "volume_mounts": req.volume_mounts,
            "image": req.image,
        });
        if let Some(cpu) = req.cpu {
            body["cpu"] = json!(cpu);
        }
        if let Some(mem) = req.memory_mib {
            body["memory_mib"] = json!(mem);
        }
        if let Some(disk) = req.state_disk_size_gib {
            body["state_disk_size_gib"] = json!(disk);
        }
        let (status, data) = self.post("/v1/sailboxes", &body).await?;
        // create's documented failure type is Creation; only auth stays
        // PermissionDenied.
        raise_for_create_status(status, &data)?;
        if data.get("status").and_then(Value::as_str) == Some("failed") {
            return Err(SailError::Creation {
                message: format!(
                    "Sailbox creation failed: {}",
                    data.get("error_message")
                        .and_then(Value::as_str)
                        .unwrap_or("")
                ),
                status,
                body: data,
            });
        }
        require_status(&data, "running", status).map_err(|_| SailError::Creation {
            message: format!(
                "Sailbox creation returned unexpected status: {}",
                data.get("status").and_then(Value::as_str).unwrap_or("")
            ),
            status,
            body: data.clone(),
        })?;
        Ok(handle_from(&data, &req.name))
    }

    /// Fetch the current state of one sailbox (`GET /v1/sailboxes/{id}`).
    pub async fn get(&self, sailbox_id: &str) -> Result<SailboxInfo, SailError> {
        let (status, data) = self
            .get_request(&format!("/v1/sailboxes/{sailbox_id}"), &[])
            .await?;
        raise_api_error(status, &data, &format!("Sailbox {sailbox_id:?}"))?;
        info_from(data)
    }

    /// List sailboxes (`GET /v1/sailboxes`) with paging and optional filters.
    ///
    /// App, status, search, and max-guest-schema-version filters are sent only
    /// when present; returns one page plus the paging cursor fields.
    pub async fn list(&self, query: &ListQuery) -> Result<SailboxPage, SailError> {
        let mut params: Vec<(String, String)> = vec![
            ("limit".to_string(), query.limit.to_string()),
            ("offset".to_string(), query.offset.to_string()),
        ];
        if let Some(app) = &query.app {
            params.push(("app".to_string(), app.clone()));
        }
        if let Some(s) = &query.status {
            params.push(("status".to_string(), s.clone()));
        }
        if let Some(s) = &query.search {
            params.push(("search".to_string(), s.clone()));
        }
        if let Some(v) = query.max_guest_schema_version {
            params.push(("max_guest_schema_version".to_string(), v.to_string()));
        }
        let (status, data) = self.get_request("/v1/sailboxes", &params).await?;
        raise_api_error(status, &data, "")?;
        let items = data
            .get("data")
            .and_then(Value::as_array)
            .ok_or_else(|| missing_field("data"))?
            .iter()
            .cloned()
            .map(info_from)
            .collect::<Result<Vec<_>, _>>()?;
        Ok(SailboxPage {
            items,
            limit: int_field(&data, "limit")?,
            offset: int_field(&data, "offset")?,
            total: int_field(&data, "total")?,
            has_more: data
                .get("has_more")
                .and_then(Value::as_bool)
                .unwrap_or(false),
        })
    }

    /// Idempotent: a resource-miss 404 is the same outcome as a fresh terminate.
    pub async fn terminate(&self, sailbox_id: &str) -> Result<(), SailError> {
        let (status, data) = self
            .post(&format!("/v1/sailboxes/{sailbox_id}/terminate"), &json!({}))
            .await?;
        if status == 404 && is_resource_not_found(&data) {
            return Ok(());
        }
        raise_api_error(status, &data, "")
    }

    /// Pause a sailbox (`POST /v1/sailboxes/{id}/pause`), keeping it in memory.
    ///
    /// Requires the echoed status to be `paused`.
    pub async fn pause(&self, sailbox_id: &str) -> Result<(), SailError> {
        self.stop(sailbox_id, "pause", "paused").await
    }

    /// Sleep a sailbox (`POST /v1/sailboxes/{id}/sleep`), persisting it to disk.
    ///
    /// Requires the echoed status to be `sleeping`.
    pub async fn sleep(&self, sailbox_id: &str) -> Result<(), SailError> {
        self.stop(sailbox_id, "sleep", "sleeping").await
    }

    async fn stop(&self, sailbox_id: &str, action: &str, expected: &str) -> Result<(), SailError> {
        let (status, data) = self
            .post(&format!("/v1/sailboxes/{sailbox_id}/{action}"), &json!({}))
            .await?;
        raise_api_error(status, &data, "")?;
        require_status(&data, expected, status)
    }

    /// Resume a paused or sleeping sailbox (`POST /v1/sailboxes/{id}/resume`).
    ///
    /// A `terminal_unavailable` resume state maps to [`SailError::NotFound`]
    /// since a terminated sailbox cannot be brought back; otherwise requires a
    /// `running` status and returns a fresh handle.
    pub async fn resume(&self, sailbox_id: &str) -> Result<SailboxHandle, SailError> {
        let (status, data) = self
            .post(&format!("/v1/sailboxes/{sailbox_id}/resume"), &json!({}))
            .await?;
        raise_api_error(status, &data, "")?;
        if data.get("resume_state").and_then(Value::as_str) == Some("terminal_unavailable") {
            // A terminated sailbox is gone for good; NotFound maps to the
            // binding's lookup error.
            return Err(SailError::NotFound {
                message: data
                    .get("error_message")
                    .and_then(Value::as_str)
                    .filter(|s| !s.is_empty())
                    .unwrap_or("sailbox cannot be resumed")
                    .to_string(),
            });
        }
        require_status(&data, "running", status)?;
        Ok(handle_from(&data, ""))
    }

    /// Checkpoint a running sailbox (`POST /v1/sailboxes/{id}/checkpoint`).
    ///
    /// Returns the new checkpoint's id and generation; a response missing
    /// `checkpoint_id` is treated as an [`SailError::Api`] failure.
    pub async fn checkpoint(&self, sailbox_id: &str) -> Result<SailboxCheckpoint, SailError> {
        let (status, data) = self
            .post(
                &format!("/v1/sailboxes/{sailbox_id}/checkpoint"),
                &json!({}),
            )
            .await?;
        raise_api_error(status, &data, "")?;
        let checkpoint_id = data
            .get("checkpoint_id")
            .and_then(Value::as_str)
            .filter(|s| !s.is_empty());
        let checkpoint_id = if let Some(id) = checkpoint_id {
            id.to_string()
        } else {
            require_status(&data, "running", status)?;
            return Err(SailError::Api {
                status,
                message: "checkpoint sailbox did not return checkpoint_id".to_string(),
                body: data,
            });
        };
        Ok(SailboxCheckpoint {
            checkpoint_id,
            sailbox_id: data
                .get("sailbox_id")
                .and_then(Value::as_str)
                .unwrap_or(sailbox_id)
                .to_string(),
            checkpoint_generation: data
                .get("checkpoint_generation")
                .and_then(Value::as_i64)
                .unwrap_or(0),
            status: data
                .get("status")
                .and_then(Value::as_str)
                .unwrap_or("")
                .to_string(),
        })
    }

    /// Create a sailbox from an existing checkpoint
    /// (`POST /v1/sailboxes/from_checkpoint`).
    ///
    /// `checkpoint_id` must be non-empty and `timeout_seconds`, when given, must
    /// be positive; both are validated as [`SailError::InvalidArgument`] before
    /// the call. Requires a `running` status and returns the new sailbox handle.
    pub async fn from_checkpoint(
        &self,
        checkpoint_id: &str,
        name: Option<&str>,
        timeout_seconds: Option<i64>,
    ) -> Result<SailboxHandle, SailError> {
        if checkpoint_id.is_empty() {
            return Err(SailError::InvalidArgument {
                message: "checkpoint_id is required".to_string(),
            });
        }
        let mut body = json!({ "checkpoint_id": checkpoint_id });
        if let Some(name) = name {
            body["name"] = json!(name);
        }
        if let Some(timeout) = timeout_seconds {
            if timeout <= 0 {
                return Err(SailError::InvalidArgument {
                    message: "timeout_seconds must be greater than 0".to_string(),
                });
            }
            body["timeout_seconds"] = json!(timeout);
        }
        let (status, data) = self.post("/v1/sailboxes/from_checkpoint", &body).await?;
        raise_api_error(status, &data, "")?;
        require_status(&data, "running", status)?;
        Ok(handle_from(&data, name.unwrap_or("")))
    }

    /// Upgrade a sailbox's in-guest agent (`POST /v1/sailboxes/{id}/upgrade`).
    ///
    /// The returned [`UpgradeOutcome`] reports whether the upgrade applied
    /// immediately (running box) or was deferred to the next wake.
    pub async fn upgrade(&self, sailbox_id: &str) -> Result<UpgradeOutcome, SailError> {
        let (status, data) = self
            .post(&format!("/v1/sailboxes/{sailbox_id}/upgrade"), &json!({}))
            .await?;
        raise_api_error(status, &data, "")?;
        Ok(UpgradeOutcome {
            applied: data
                .get("applied")
                .and_then(Value::as_bool)
                .unwrap_or(false),
            status: data
                .get("status")
                .and_then(Value::as_str)
                .unwrap_or("")
                .to_string(),
        })
    }

    /// Expose a runtime ingress port; returns the add-listener response for the
    /// binding to render (URL/host formatting stays presentation-side).
    pub async fn expose(
        &self,
        sailbox_id: &str,
        guest_port: u32,
        protocol: &str,
        allowlist: &[String],
    ) -> Result<Value, SailError> {
        let mut body = json!({ "guest_port": guest_port, "protocol": protocol });
        if !allowlist.is_empty() {
            body["allowlist"] = json!(allowlist);
        }
        let (status, data) = self
            .post(&format!("/v1/sailboxes/{sailbox_id}/listeners"), &body)
            .await?;
        raise_api_error(status, &data, "")?;
        Ok(data)
    }

    /// Remove a runtime ingress listener
    /// (`DELETE /v1/sailboxes/{id}/listeners/{guest_port}`).
    ///
    /// Runs without retry so a lost response on a committed delete does not
    /// re-issue the call and surface an already-unexposed port as an error.
    pub async fn unexpose(&self, sailbox_id: &str, guest_port: u32) -> Result<(), SailError> {
        // No retry: a committed DELETE whose response is lost would, on retry,
        // hit the scheduler as an already-unexposed port (NotFound) and raise
        // even though the port was removed.
        let (status, data) = self
            .request(
                Method::Delete,
                &format!("/v1/sailboxes/{sailbox_id}/listeners/{guest_port}"),
                &[],
                None,
                NO_RETRY,
            )
            .await?;
        raise_api_error(status, &data, "")
    }

    /// List a sailbox's ingress listeners
    /// (`GET /v1/sailboxes/{id}/listeners`). Served from the control plane, so
    /// it does not resume (wake) a paused or sleeping box.
    pub async fn list_listeners(&self, sailbox_id: &str) -> Result<Vec<Listener>, SailError> {
        let (status, data) = self
            .get_request(&format!("/v1/sailboxes/{sailbox_id}/listeners"), &[])
            .await?;
        raise_api_error(status, &data, &format!("Sailbox {sailbox_id:?}"))?;
        let rows = data.get("data").cloned().unwrap_or(Value::Null);
        serde_json::from_value(rows).map_err(|e| SailError::Internal {
            message: format!("failed to parse listeners: {e}"),
        })
    }

    /// Fetch one ingress listener by guest port
    /// (`GET /v1/sailboxes/{id}/listeners/{guest_port}`); a missing port is a
    /// [`SailError::NotFound`]. Served without resuming the box.
    pub async fn get_listener(
        &self,
        sailbox_id: &str,
        guest_port: u32,
    ) -> Result<Listener, SailError> {
        let (status, data) = self
            .get_request(
                &format!("/v1/sailboxes/{sailbox_id}/listeners/{guest_port}"),
                &[],
            )
            .await?;
        raise_api_error(
            status,
            &data,
            &format!("Listener {sailbox_id:?}:{guest_port}"),
        )?;
        serde_json::from_value(data).map_err(|e| SailError::Internal {
            message: format!("failed to parse listener: {e}"),
        })
    }

    /// Ingress-identity headers for this sailbox.
    pub async fn ingress_auth_headers(
        &self,
        sailbox_id: &str,
    ) -> Result<Vec<(String, String)>, SailError> {
        let (status, data) = self
            .get_request(&format!("/v1/sailboxes/{sailbox_id}/ingress-auth"), &[])
            .await?;
        raise_api_error(status, &data, &format!("Sailbox {sailbox_id:?}"))?;
        let headers = data
            .get("headers")
            .and_then(Value::as_object)
            .ok_or_else(|| missing_field("headers"))?;
        Ok(headers
            .iter()
            .map(|(k, v)| (k.clone(), v.as_str().unwrap_or("").to_string()))
            .collect())
    }

    // --- NFS volumes (sailbox-volume API on the same host) ---

    /// Look up an NFS volume by name (`POST /v1/sailbox-volumes/get`),
    /// optionally creating it when missing.
    ///
    /// `name` must be non-empty. When `mint_if_missing` is set the volume is
    /// created if it does not yet exist.
    pub async fn get_volume(
        &self,
        name: &str,
        mint_if_missing: bool,
    ) -> Result<NfsVolume, SailError> {
        if name.trim().is_empty() {
            return Err(SailError::InvalidArgument {
                message: "name is required".to_string(),
            });
        }
        let body = json!({
            "name": name,
            "backend": "nfs",
            "mint_if_missing": mint_if_missing,
            "create_if_missing": mint_if_missing,
        });
        let (status, data) = self.post("/v1/sailbox-volumes/get", &body).await?;
        raise_api_error(status, &data, "")?;
        volume_from(data)
    }

    /// List the org's NFS volumes (`GET /v1/sailbox-volumes`).
    ///
    /// `max_objects`, when given, caps the number returned and must be
    /// non-negative.
    pub async fn list_volumes(
        &self,
        max_objects: Option<i64>,
    ) -> Result<Vec<NfsVolume>, SailError> {
        let mut query: Vec<(String, String)> = Vec::new();
        if let Some(max) = max_objects {
            if max < 0 {
                return Err(SailError::InvalidArgument {
                    message: "max_objects cannot be negative".to_string(),
                });
            }
            query.push(("max_objects".to_string(), max.to_string()));
        }
        let (status, data) = self.get_request("/v1/sailbox-volumes", &query).await?;
        raise_api_error(status, &data, "")?;
        data.get("volumes").and_then(Value::as_array).map_or_else(
            || Ok(Vec::new()),
            |rows| rows.iter().cloned().map(volume_from).collect(),
        )
    }

    /// Delete a volume by id; `Ok(None)` on a 204 (no body), the deleted handle
    /// otherwise.
    pub async fn delete_volume(
        &self,
        volume_id: &str,
        allow_missing: bool,
    ) -> Result<Option<NfsVolume>, SailError> {
        if volume_id.trim().is_empty() {
            return Err(SailError::InvalidArgument {
                message: "volume_id is required".to_string(),
            });
        }
        let path = format!("/v1/sailbox-volumes/{}", volume_id.trim());
        let query: Vec<(String, String)> = if allow_missing {
            vec![("allow_missing".to_string(), "true".to_string())]
        } else {
            Vec::new()
        };
        let policy = if allow_missing {
            DEFAULT_RETRY_POLICY
        } else {
            NO_RETRY
        };
        let (status, data) = self
            .request(Method::Delete, &path, &query, None, policy)
            .await?;
        if status == 204 {
            return Ok(None);
        }
        raise_api_error(status, &data, "")?;
        Ok(Some(volume_from(data)?))
    }

    // --- transport helpers ---

    async fn post(&self, path: &str, body: &Value) -> Result<(u16, Value), SailError> {
        let bytes = serde_json::to_vec(body).map_err(|e| SailError::Internal {
            message: format!("failed to serialize request body: {e}"),
        })?;
        self.request(Method::Post, path, &[], Some(bytes), DEFAULT_RETRY_POLICY)
            .await
    }

    async fn get_request(
        &self,
        path: &str,
        query: &[(String, String)],
    ) -> Result<(u16, Value), SailError> {
        self.request(Method::Get, path, query, None, DEFAULT_RETRY_POLICY)
            .await
    }

    async fn request(
        &self,
        method: Method,
        path: &str,
        query: &[(String, String)],
        body: Option<Vec<u8>>,
        policy: RetryPolicy,
    ) -> Result<(u16, Value), SailError> {
        let spec = RequestSpec {
            method,
            path: path.to_string(),
            query: query.to_vec(),
            body,
            extra_headers: Vec::new(),
            timeout: None,
            policy,
            idempotency_key: IdempotencyKey::Auto,
        };
        self.http.request(&spec).await
    }
}

fn handle_from(data: &Value, fallback_name: &str) -> SailboxHandle {
    SailboxHandle {
        sailbox_id: data
            .get("sailbox_id")
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_string(),
        name: data
            .get("name")
            .and_then(Value::as_str)
            .unwrap_or(fallback_name)
            .to_string(),
        status: "running".to_string(),
        worker_address: data
            .get("worker_address")
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_string(),
        exec_endpoint: data
            .get("exec_proxy_endpoint")
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_string(),
    }
}

fn info_from(data: Value) -> Result<SailboxInfo, SailError> {
    serde_json::from_value::<SailboxInfoWire>(data)
        .map(SailboxInfo::from)
        .map_err(|e| SailError::Internal {
            message: format!("failed to parse sailbox: {e}"),
        })
}

fn volume_from(data: Value) -> Result<NfsVolume, SailError> {
    serde_json::from_value::<NfsVolume>(data).map_err(|e| SailError::Internal {
        message: format!("failed to parse volume: {e}"),
    })
}

fn int_field(data: &Value, key: &str) -> Result<i64, SailError> {
    data.get(key)
        .and_then(Value::as_i64)
        .ok_or_else(|| missing_field(key))
}

fn missing_field(key: &str) -> SailError {
    SailError::Internal {
        message: format!("API response missing field {key:?}"),
    }
}

/// A 404 body the API tags as a real missing resource (vs a route-level 404).
fn is_resource_not_found(data: &Value) -> bool {
    data.get("error")
        .and_then(|e| e.get("type"))
        .and_then(Value::as_str)
        == Some("not_found_error")
}

fn api_error_message(data: &Value) -> String {
    data.get("error")
        .and_then(|e| e.get("message"))
        .and_then(Value::as_str)
        .filter(|s| !s.is_empty())
        .unwrap_or("request failed")
        .to_string()
}

/// Map a non-2xx lifecycle/monitoring response onto the canonical taxonomy:
/// resource-miss 404 → NotFound, 401/403 → PermissionDenied, 400 →
/// InvalidArgument, any other → Api (a transient/unexpected API failure).
fn raise_api_error(status: u16, data: &Value, context: &str) -> Result<(), SailError> {
    if status < 300 {
        return Ok(());
    }
    let mut message = api_error_message(data);
    if !context.is_empty() {
        message = format!("{context}: {message}");
    }
    if status == 404 && is_resource_not_found(data) {
        return Err(SailError::NotFound { message });
    }
    if status == 401 || status == 403 {
        return Err(SailError::PermissionDenied { message });
    }
    if status == 400 {
        return Err(SailError::InvalidArgument { message });
    }
    Err(SailError::Api {
        status,
        message,
        body: data.clone(),
    })
}

/// create's ladder: every non-2xx except auth is a Creation failure.
fn raise_for_create_status(status: u16, data: &Value) -> Result<(), SailError> {
    if status < 300 {
        return Ok(());
    }
    let message = api_error_message(data);
    if status == 401 || status == 403 {
        return Err(SailError::PermissionDenied { message });
    }
    Err(SailError::Creation {
        message,
        status,
        body: data.clone(),
    })
}

/// Raise an Api error when the echoed status is not the expected one.
fn require_status(data: &Value, expected: &str, status: u16) -> Result<(), SailError> {
    let got = data.get("status").and_then(Value::as_str).unwrap_or("");
    if got == expected {
        return Ok(());
    }
    Err(SailError::Api {
        status,
        message: format!("lifecycle call returned unexpected status: {got}"),
        body: data.clone(),
    })
}

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

    #[test]
    fn info_applies_cross_field_defaults() {
        let info = info_from(json!({
            "sailbox_id": "sb-1", "app_id": "app-1", "app_name": "a", "name": "n",
            "status": "running", "memory_mib": 2048, "vcpu_count": 4,
            "state_disk_size_gib": 10, "architecture": "amd64",
            "created_at": "t0", "updated_at": "t1"
        }))
        .unwrap();
        // Requested-resource fields fall back to the configured size.
        assert_eq!(info.cpu_requested_vcpu, 4);
        assert_eq!(info.memory_requested_bytes, 2048 * 1024 * 1024);
        assert_eq!(info.disk_requested_bytes, 10 * 1024 * 1024 * 1024);
        assert_eq!(info.memory_used_bytes, 0);
        assert_eq!(info.guest_schema_version, None);
        assert_eq!(info.checkpoint_generation, 0);
    }

    #[test]
    fn api_error_ladder_maps_statuses() {
        let not_found = json!({"error": {"type": "not_found_error", "message": "gone"}});
        assert!(matches!(
            raise_api_error(404, &not_found, ""),
            Err(SailError::NotFound { .. })
        ));
        // A route-level 404 (no not_found_error type) is transient, not a miss.
        let route_404 = json!({"error": {"message": "no route"}});
        assert!(matches!(
            raise_api_error(404, &route_404, ""),
            Err(SailError::Api { .. })
        ));
        let auth = json!({"error": {"message": "nope"}});
        assert!(matches!(
            raise_api_error(403, &auth, ""),
            Err(SailError::PermissionDenied { .. })
        ));
        assert!(matches!(
            raise_api_error(400, &auth, ""),
            Err(SailError::InvalidArgument { .. })
        ));
        assert!(matches!(
            raise_api_error(503, &auth, ""),
            Err(SailError::Api { status: 503, .. })
        ));
        assert!(raise_api_error(200, &json!({}), "").is_ok());
    }

    #[test]
    fn create_ladder_maps_non_auth_to_creation() {
        let body = json!({"error": {"message": "no capacity"}});
        assert!(matches!(
            raise_for_create_status(503, &body),
            Err(SailError::Creation { .. })
        ));
        assert!(matches!(
            raise_for_create_status(401, &body),
            Err(SailError::PermissionDenied { .. })
        ));
    }

    #[test]
    fn resource_limits_accept_defaults_and_in_range() {
        // None and 0 mean "platform default"; in-range values pass.
        validate_resource_limits(None, None, None).unwrap();
        validate_resource_limits(Some(0), Some(0), Some(0)).unwrap();
        validate_resource_limits(Some(4), Some(1024), Some(32)).unwrap();
        validate_resource_limits(Some(2), Some(8192), Some(10)).unwrap();
    }

    #[test]
    fn resource_limits_reject_out_of_range() {
        let msg = |r: Result<(), SailError>| match r {
            Err(SailError::InvalidArgument { message }) => message,
            other => panic!("expected InvalidArgument, got {other:?}"),
        };
        assert!(msg(validate_resource_limits(Some(-1), None, None))
            .contains("max_cpu must be at least 0"));
        assert!(msg(validate_resource_limits(Some(5), None, None))
            .contains("max_cpu must be at most 4"));
        assert!(msg(validate_resource_limits(None, Some(512), None))
            .contains("max_memory_mib must be at least 1024"));
        assert!(msg(validate_resource_limits(None, Some(8193), None))
            .contains("max_memory_mib must be at most 8192"));
        assert!(msg(validate_resource_limits(None, None, Some(-1)))
            .contains("max_disk_gib must be at least 0"));
        assert!(msg(validate_resource_limits(None, None, Some(33)))
            .contains("max_disk_gib must be at most 32"));
    }
}