tensorlake 0.5.159

A Rust SDK for interacting with Tensorlake Cloud APIs.
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
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
//! CAS image build operations: start, get, wait and cancel a CAS image
//! build or import as a first-class operation (ADR 0107).
//!
//! # Scope: CAS only
//!
//! Everything in this module addresses the build operations of CAS
//! (content-addressed streaming) images. Legacy images — `tl sbx image
//! create`/`import` with `--no-cas`, `sandbox_template_` ids, `.tlsnap`
//! snapshots — have no build operation here: [`start_build`] and
//! [`start_import`] refuse options whose `cas` flag is off, and a
//! `sandbox_template_` reference is never looked up as a build id. The legacy
//! paths keep their own requests, outputs, errors and interruption behavior.
//!
//! # Operations
//!
//! - [`start_build`] / [`start_import`] admit a build and, for a Dockerfile
//!   build, upload and seal the context. They return an [`ImageBuildHandle`]
//!   without waiting, so a caller may leave the operation running.
//! - [`ImageBuildClient::get`] looks a build up by its service-generated id.
//! - [`ImageBuildHandle::refresh`] re-reads the current [`ImageBuildInfo`].
//! - [`ImageBuildHandle::wait`] polls the build to a terminal status and
//!   returns its immutable [`ImageBuildResult`] (`BuildInfo.result`). The
//!   mutable image record is never consulted to infer this build's result, so
//!   a wait returns the right answer even after the image was rebuilt.
//! - [`ImageBuildHandle::cancel`] / [`ImageBuildClient::cancel`] cancel by
//!   build id. The build id alone is sufficient: admission returns it, the CLI
//!   prints it, and `GET /builds/{id}` and the `image_build_in_progress`
//!   conflict expose it. [`CancelBuildSelector::ClientRequestId`] exists only
//!   to recover an admission whose response was lost.
//!
//! # Admission and request ids
//!
//! Every admission (`POST /builds`, `POST /images/from-snapshot`) carries an
//! opaque client request id in the `Idempotency-Key` header, generated by
//! [`new_client_request_id`] before the first attempt and retained across
//! transport retries; it is never re-minted to retry. An exact replay returns
//! the same operation. A different request for a name that already has an
//! unfinished operation is refused with [`ImageBuildError::InProgress`]; the
//! SDK never cancels or supersedes that operation on its own.
//!
//! # Waiting, deadlines and reconnects
//!
//! Status polling reconnects after transport failures, 408/429 and 5xx with
//! bounded exponential backoff, jitter and `Retry-After`, reporting each
//! reconnect as a `Status` event. Authorization, validation and not-found
//! answers are not retried. The overall wait is bounded by the
//! service-reported operation deadline plus a deployment-recovery allowance
//! ([`DEPLOYMENT_RECOVERY_ALLOWANCE`]), by an optional caller timeout
//! ([`ImageBuildWaitOptions::timeout`]), and, when the service reports no
//! deadline and the caller sets none, by [`DEFAULT_WAIT_LIMIT`]. A timeout is
//! reported as [`ImageBuildError::Timeout`] carrying the build id: the
//! operation may still be running, and it is neither failed nor cancelled by
//! the client. Every deadline bounds the requests in flight as well as the
//! retries and sleeps between them: a request the service never answers is
//! abandoned at the deadline (or after a per-request bound), so a stalled
//! connection cannot hold a wait, a lookup or the cancellation handshake
//! past its budget. [`ImageBuildClient::wait_build`] runs the initial lookup
//! inside the same interruptible, timeout-bounded operation as the wait.
//! Builder logs are followed through the sandbox API as a courtesy: losing
//! them is a warning, not the end of the wait.
//!
//! # Interruption
//!
//! Disconnecting, dropping a handle, or a process crash never cancels the
//! remote operation. Explicit interruption does: an [`InterruptSignal`]
//! triggered during [`start_build`], [`start_import`] or
//! [`ImageBuildHandle::wait`] runs a bounded cancellation handshake
//! ([`CANCEL_HANDSHAKE_BUDGET`]) and reports the outcome as
//! [`ImageBuildError::Interrupted`]: confirmed cancellation, already
//! completed, or an unconfirmed acknowledgement with the build id (or, while
//! admission is unresolved, the client request id). Only an admitted build
//! with a durable acknowledgement counts as cancelled; a `not_admitted`
//! observation is not confirmation.
//!
//! # Image ids are mutable
//!
//! An image name and its `image_` id name the *current* image; a rebuild
//! replaces what they point at. The build id and its [`ImageBuildResult`]
//! are the immutable record of one operation.

use std::{
    fmt,
    time::{Duration, SystemTime, UNIX_EPOCH},
};

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::{
    error::SdkError,
    image_service_builds,
    sandbox_image_catalog::ImageServiceImage,
    sandbox_images::{
        ResolvedBuildContext, SandboxImageBuildError, SandboxImageBuildEvent,
        SandboxImageBuildOptions, SandboxImageImportOptions,
    },
    sandbox_templates::models::SandboxTemplate,
};

/// The immutable publication result of one build: the image exactly as the
/// build published it, presented in the platform template shape the merged
/// catalog answers (derived locally from the CAS image registry's trimmed
/// record, see [`ImageServiceImage::into_template`]). One image
/// representation for the SDK and the CLI.
pub type ImageBuildResult = SandboxTemplate;

/// The header carrying the client request id on admission routes.
pub const IDEMPOTENCY_KEY_HEADER: &str = "Idempotency-Key";

/// How long an explicit interruption keeps trying to confirm the remote
/// cancellation before reporting the acknowledgement as unknown.
pub const CANCEL_HANDSHAKE_BUDGET: Duration = Duration::from_secs(30);

/// Added to the service-reported operation deadline: the time a normal
/// service deployment needs to adopt the operation and finish it.
pub const DEPLOYMENT_RECOVERY_ALLOWANCE: Duration = Duration::from_secs(10 * 60);

/// Wait bound used when the service reports no operation deadline and the
/// caller sets no timeout. Every wait is bounded.
pub const DEFAULT_WAIT_LIMIT: Duration = Duration::from_secs(2 * 60 * 60);

/// Generate an opaque client request id: 128 random bits as 32 lowercase hex
/// characters. The one generator every binding uses.
pub fn new_client_request_id() -> String {
    hex::encode(rand::random::<[u8; 16]>())
}

/// Whether `id` is a request id the CAS image API accepts: 1 to 128 printable
/// ASCII characters. Ids from other generators are opaque, not parsed.
pub fn validate_client_request_id(id: &str) -> Result<(), String> {
    if id.is_empty() || id.len() > 128 {
        return Err("client request id must be 1 to 128 characters".to_string());
    }
    if !id.bytes().all(|b| (0x21..=0x7e).contains(&b)) {
        return Err("client request id must be printable ASCII without spaces".to_string());
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Build state
// ---------------------------------------------------------------------------

macro_rules! wire_enum {
    (
        $(#[$meta:meta])*
        $name:ident { $($(#[$variant_meta:meta])* $variant:ident => $wire:literal),+ $(,)? }
    ) => {
        $(#[$meta])*
        #[derive(Debug, Clone, PartialEq, Eq, Hash)]
        pub enum $name {
            $($(#[$variant_meta])* $variant,)+
            /// A value this SDK does not know; newer services may add some.
            Unknown(String),
        }

        impl $name {
            /// The wire spelling.
            pub fn as_str(&self) -> &str {
                match self {
                    $(Self::$variant => $wire,)+
                    Self::Unknown(value) => value.as_str(),
                }
            }
        }

        impl From<String> for $name {
            fn from(value: String) -> Self {
                match value.as_str() {
                    $($wire => Self::$variant,)+
                    _ => Self::Unknown(value),
                }
            }
        }

        impl From<&str> for $name {
            fn from(value: &str) -> Self {
                Self::from(value.to_string())
            }
        }

        impl From<$name> for String {
            fn from(value: $name) -> Self {
                value.as_str().to_string()
            }
        }

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

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

        impl<'de> Deserialize<'de> for $name {
            fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
                Ok(Self::from(String::deserialize(deserializer)?))
            }
        }
    };
}

wire_enum! {
    /// The lifecycle status of a build. `Succeeded`, `Failed` and `Cancelled`
    /// are terminal; failed and cancelled are distinct outcomes.
    ImageBuildStatus {
        Pending => "pending",
        Running => "running",
        Succeeded => "succeeded",
        Failed => "failed",
        Cancelled => "cancelled",
    }
}

impl ImageBuildStatus {
    /// Whether the build will not change any more.
    pub fn is_terminal(&self) -> bool {
        matches!(self, Self::Succeeded | Self::Failed | Self::Cancelled)
    }
}

wire_enum! {
    /// Where an unfinished build is in its workflow.
    ImageBuildPhase {
        AwaitingContext => "awaiting_context",
        StartingBuilder => "starting_builder",
        Executing => "executing",
        Snapshotting => "snapshotting",
        Publishing => "publishing",
        Finished => "finished",
    }
}

wire_enum! {
    /// What kind of operation a build record is.
    ImageBuildKind {
        Import => "import",
        Dockerfile => "dockerfile",
        /// A direct publication (`POST /images`, `POST /images/from-snapshot`)
        /// that outlived its bounded inline wait.
        Direct => "direct",
    }
}

/// Where a Dockerfile build uploads its context, issued at admission (and
/// re-issued on an exact replay) while the context is unsealed. Carried by
/// the admission response only; it never appears on [`ImageBuildInfo`], so
/// no `info()` output, `--json` print or binding record leaks the signed URL.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ContextUploadCapability {
    pub url: String,
    #[serde(default)]
    pub max_bytes: Option<u64>,
}

/// One CAS image build or import, as the CAS image API reports it (the twelve-field
/// `BuildInfo`). Unknown fields are ignored so newer services remain
/// readable.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ImageBuildInfo {
    pub build_id: String,
    #[serde(default = "unknown_kind")]
    pub kind: ImageBuildKind,
    /// The image name the operation publishes.
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default = "unknown_status")]
    pub status: ImageBuildStatus,
    #[serde(default)]
    pub phase: Option<ImageBuildPhase>,
    /// Builder executions so far.
    #[serde(default)]
    pub attempt_no: u64,
    /// The builder sandbox of the active attempt, while the build is running.
    #[serde(default)]
    pub builder_sandbox_id: Option<String>,
    /// When the service gives the whole operation up, as epoch milliseconds.
    /// The SDK adds [`DEPLOYMENT_RECOVERY_ALLOWANCE`] when bounding a wait.
    #[serde(default)]
    pub operation_deadline_ms: Option<u64>,
    #[serde(default)]
    pub created_at_ms: Option<u64>,
    #[serde(default)]
    pub updated_at_ms: Option<u64>,
    /// The immutable publication result of a succeeded build, in the
    /// template shape (decoded from the service's trimmed record).
    #[serde(default, deserialize_with = "deserialize_result")]
    pub result: Option<ImageBuildResult>,
    #[serde(default)]
    pub error: Option<String>,
}

/// The service reports `result` as its trimmed image record; the SDK keeps
/// the template-shaped projection of it.
fn deserialize_result<'de, D>(deserializer: D) -> Result<Option<ImageBuildResult>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let wire: Option<ImageServiceImage> = Option::deserialize(deserializer)?;
    Ok(wire.map(ImageServiceImage::into_template))
}

fn unknown_kind() -> ImageBuildKind {
    ImageBuildKind::Unknown(String::new())
}

fn unknown_status() -> ImageBuildStatus {
    ImageBuildStatus::Unknown(String::new())
}

impl ImageBuildInfo {
    /// Decode a service build record, ignoring fields this SDK does not know.
    pub fn from_json(value: Value) -> Result<Self, serde_json::Error> {
        serde_json::from_value(value)
    }

    /// The service-informed wall-clock bound on this operation, with the
    /// deployment-recovery allowance added. `None` when the service reports
    /// no deadline.
    pub fn operation_deadline(&self) -> Option<SystemTime> {
        self.operation_deadline_ms
            .map(|ms| UNIX_EPOCH + Duration::from_millis(ms) + DEPLOYMENT_RECOVERY_ALLOWANCE)
    }
}

// ---------------------------------------------------------------------------
// Cancellation
// ---------------------------------------------------------------------------

/// Which build a cancellation addresses. The build id is the sufficient,
/// documented selector. The client request id — the admission's
/// `Idempotency-Key` — is a recovery aid for an admission whose response was
/// lost; it resolves through the project's request-id index and never admits
/// anything.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CancelBuildSelector {
    BuildId(String),
    ClientRequestId(String),
}

impl CancelBuildSelector {
    pub(crate) fn body(&self) -> Value {
        match self {
            Self::BuildId(build_id) => serde_json::json!({ "build_id": build_id }),
            Self::ClientRequestId(id) => serde_json::json!({ "client_request_id": id }),
        }
    }
}

wire_enum! {
    /// What the service observed when asked to cancel.
    CancelBuildOutcome {
        /// The cancellation decision is durable. The build will not publish.
        Cancelled => "cancelled",
        AlreadyCancelled => "already_cancelled",
        /// Publication won: the build's result stands.
        AlreadyCompleted => "already_completed",
        AlreadyFailed => "already_failed",
        /// No build is indexed under the client request id. An observation of
        /// absence, not a promise: a delayed original admission may still
        /// create the build.
        NotAdmitted => "not_admitted",
    }
}

/// The service's answer to a cancellation.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CancelBuildResponse {
    pub outcome: CancelBuildOutcome,
    /// The build as observed, absent for `not_admitted`.
    #[serde(default)]
    pub build: Option<ImageBuildInfo>,
}

/// An explicit interruption request for a CAS operation.
///
/// Triggering it while [`start_build`], [`start_import`] or
/// [`ImageBuildHandle::wait`] is running stops the operation locally and
/// runs the bounded remote cancellation handshake. Dropping the signal, or a
/// handle, does nothing remotely.
#[derive(Debug, Clone, Default)]
pub struct InterruptSignal {
    token: tokio_util::sync::CancellationToken,
}

impl InterruptSignal {
    pub fn new() -> Self {
        Self::default()
    }

    /// Request cancellation. Idempotent.
    pub fn trigger(&self) {
        self.token.cancel();
    }

    pub fn is_triggered(&self) -> bool {
        self.token.is_cancelled()
    }

    /// Resolves once the signal is triggered.
    pub async fn triggered(&self) {
        self.token.cancelled().await
    }
}

/// How an explicit interruption ended.
#[derive(Debug, Clone, PartialEq)]
pub enum InterruptionOutcome {
    /// Confirmed: the build is admitted and the cancellation is durable.
    Cancelled,
    /// Publication won the race; the build's result stands.
    AlreadyCompleted(Option<Box<ImageBuildResult>>),
    AlreadyCancelled,
    AlreadyFailed(Option<String>),
    /// The admission was unresolved and the service has nothing under the
    /// client request id. Not a confirmation: a delayed admission may still
    /// create the build, which can then be cancelled by the request id.
    NotAdmitted,
    /// The handshake ran out of its budget without a durable answer.
    Unconfirmed(String),
}

/// What an interrupted operation reports: the build id when admission
/// resolved, the client request id while it did not, and the outcome.
#[derive(Debug, Clone, PartialEq)]
pub struct InterruptionReport {
    pub build_id: Option<String>,
    pub client_request_id: Option<String>,
    pub outcome: InterruptionOutcome,
}

impl InterruptionOutcome {
    /// A stable machine-readable name for bindings.
    pub fn name(&self) -> &'static str {
        match self {
            Self::Cancelled => "cancelled",
            Self::AlreadyCompleted(_) => "already_completed",
            Self::AlreadyCancelled => "already_cancelled",
            Self::AlreadyFailed(_) => "already_failed",
            Self::NotAdmitted => "not_admitted",
            Self::Unconfirmed(_) => "unconfirmed",
        }
    }
}

impl InterruptionReport {
    /// Whether the remote operation is confirmed not to publish: cancelled
    /// now or earlier, or already failed.
    pub fn is_confirmed_cancelled(&self) -> bool {
        matches!(
            self.outcome,
            InterruptionOutcome::Cancelled
                | InterruptionOutcome::AlreadyCancelled
                | InterruptionOutcome::AlreadyFailed(_)
        )
    }
}

impl fmt::Display for InterruptionReport {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let build = self.build_id.as_deref();
        match &self.outcome {
            InterruptionOutcome::Cancelled => {
                write!(f, "Build {} cancelled", build.unwrap_or("-"))
            }
            InterruptionOutcome::AlreadyCompleted(result) => {
                write!(f, "Build {} already completed", build.unwrap_or("-"))?;
                if let Some(result) = result {
                    write!(
                        f,
                        " (image '{}', {})",
                        result.name.as_deref().unwrap_or("-"),
                        result.id.as_deref().unwrap_or("-")
                    )?;
                }
                Ok(())
            }
            InterruptionOutcome::AlreadyCancelled => {
                write!(f, "Build {} was already cancelled", build.unwrap_or("-"))
            }
            InterruptionOutcome::AlreadyFailed(error) => {
                write!(f, "Build {} had already failed", build.unwrap_or("-"))?;
                if let Some(error) = error {
                    write!(f, ": {error}")?;
                }
                Ok(())
            }
            InterruptionOutcome::NotAdmitted => write!(
                f,
                "No build was admitted for client request id {}; a delayed admission may still \
                 create one, which can be cancelled by that request id",
                self.client_request_id.as_deref().unwrap_or("-")
            ),
            InterruptionOutcome::Unconfirmed(reason) => match (build, &self.client_request_id) {
                (Some(build_id), _) => write!(
                    f,
                    "Cancellation of build {build_id} was not confirmed: {reason}"
                ),
                (None, Some(request_id)) => write!(
                    f,
                    "Cancellation of the build admitted with client request id {request_id} was \
                     not confirmed: {reason}"
                ),
                (None, None) => write!(f, "Cancellation was not confirmed: {reason}"),
            },
        }
    }
}

// ---------------------------------------------------------------------------
// Errors
// ---------------------------------------------------------------------------

/// The `409 image_build_in_progress` conflict: the name already has an
/// unfinished operation. Cancel it (by `active_build_id`) before starting
/// another; the SDK never does so automatically.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ImageBuildConflict {
    pub image_name: Option<String>,
    pub active_build_id: Option<String>,
    pub active_kind: Option<ImageBuildKind>,
    pub active_status: Option<ImageBuildStatus>,
    /// The service's message, which names the kind and status.
    pub message: String,
}

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

/// Everything a build operation can fail with. Terminal service outcomes
/// (`Failed`, `Cancelled`) are distinct from the client giving up
/// (`Timeout`) and from an explicit interruption (`Interrupted`).
#[derive(Debug, thiserror::Error)]
pub enum ImageBuildError {
    #[error("{0}")]
    Usage(String),
    #[error("{0}")]
    Auth(String),
    /// Unknown, foreign or retired: a finished build is kept only while it
    /// is its image's current build; a later build of the image or deleting
    /// the image retires it (ADR 0108).
    #[error(
        "build {build_id} not found: finished builds are kept only while they are their image's \
         current build; a later build of the image or deleting the image retires them"
    )]
    NotFound { build_id: String },
    #[error("{0}")]
    InProgress(ImageBuildConflict),
    #[error(
        "client request id {client_request_id} was already used for a different request: {message}"
    )]
    IdempotencyKeyReused {
        client_request_id: String,
        message: String,
    },
    #[error("build {build_id} failed: {error}")]
    Failed {
        build_id: String,
        error: String,
        info: Box<ImageBuildInfo>,
    },
    #[error("build {build_id} was cancelled")]
    Cancelled {
        build_id: String,
        info: Box<ImageBuildInfo>,
    },
    /// The client stopped waiting. The operation may still be running; it was
    /// neither failed nor cancelled.
    #[error(
        "build {build_id} did not finish within {}s of waiting; it may still be running (check it \
         by build id)",
        waited.as_secs()
    )]
    Timeout { build_id: String, waited: Duration },
    #[error("{0}")]
    Interrupted(InterruptionReport),
    #[error("CAS image API request failed (HTTP {status}): {message}")]
    Service { status: u16, message: String },
    #[error("{0}")]
    Sdk(#[from] SdkError),
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
    #[error("{0}")]
    Json(#[from] serde_json::Error),
    #[error("{0}")]
    Other(String),
}

impl ImageBuildError {
    pub(crate) fn other(message: impl Into<String>) -> Self {
        Self::Other(message.into())
    }

    pub(crate) fn usage(message: impl Into<String>) -> Self {
        Self::Usage(message.into())
    }

    /// The build id this error is about, when one is known.
    pub fn build_id(&self) -> Option<&str> {
        match self {
            Self::NotFound { build_id }
            | Self::Failed { build_id, .. }
            | Self::Cancelled { build_id, .. }
            | Self::Timeout { build_id, .. } => Some(build_id),
            Self::Interrupted(report) => report.build_id.as_deref(),
            Self::InProgress(conflict) => conflict.active_build_id.as_deref(),
            _ => None,
        }
    }

    /// The structured form the Python and Node bindings expose: `code`,
    /// `message`, `build_id`, and the outcome-specific fields (conflict
    /// details, the failure error and record, the interruption outcome).
    pub fn to_json(&self) -> Value {
        let mut payload = serde_json::json!({
            "code": self.code(),
            "message": self.to_string(),
            "build_id": self.build_id(),
        });
        let object = payload.as_object_mut().expect("object");
        match self {
            Self::InProgress(conflict) => {
                object.insert("image_name".into(), serde_json::json!(conflict.image_name));
                object.insert(
                    "active_build_id".into(),
                    serde_json::json!(conflict.active_build_id),
                );
                object.insert(
                    "active_kind".into(),
                    serde_json::json!(conflict.active_kind.as_ref().map(ImageBuildKind::as_str)),
                );
                object.insert(
                    "active_status".into(),
                    serde_json::json!(
                        conflict
                            .active_status
                            .as_ref()
                            .map(ImageBuildStatus::as_str)
                    ),
                );
            }
            Self::IdempotencyKeyReused {
                client_request_id, ..
            } => {
                object.insert(
                    "client_request_id".into(),
                    serde_json::json!(client_request_id),
                );
            }
            Self::Failed { error, info, .. } => {
                object.insert("error".into(), serde_json::json!(error));
                object.insert(
                    "info".into(),
                    serde_json::to_value(info).unwrap_or(Value::Null),
                );
            }
            Self::Cancelled { info, .. } => {
                object.insert(
                    "info".into(),
                    serde_json::to_value(info).unwrap_or(Value::Null),
                );
            }
            Self::Timeout { waited, .. } => {
                object.insert("waited_secs".into(), serde_json::json!(waited.as_secs()));
            }
            Self::Interrupted(report) => {
                object.insert(
                    "client_request_id".into(),
                    serde_json::json!(report.client_request_id),
                );
                object.insert("outcome".into(), serde_json::json!(report.outcome.name()));
                object.insert(
                    "confirmed".into(),
                    serde_json::json!(report.is_confirmed_cancelled()),
                );
                if let InterruptionOutcome::AlreadyCompleted(Some(result)) = &report.outcome {
                    object.insert(
                        "result".into(),
                        serde_json::to_value(result).unwrap_or(Value::Null),
                    );
                }
            }
            Self::Service { status, .. } => {
                object.insert("status".into(), serde_json::json!(status));
            }
            _ => {}
        }
        payload
    }

    /// A stable machine-readable code for bindings.
    pub fn code(&self) -> &'static str {
        match self {
            Self::Usage(_) => "usage",
            Self::Auth(_) => "auth",
            Self::NotFound { .. } => "not_found",
            Self::InProgress(_) => "image_build_in_progress",
            Self::IdempotencyKeyReused { .. } => "client_request_id_mismatch",
            Self::Failed { .. } => "failed",
            Self::Cancelled { .. } => "cancelled",
            Self::Timeout { .. } => "timeout",
            Self::Interrupted(_) => "interrupted",
            Self::Service { .. } => "service",
            Self::Sdk(_) | Self::Io(_) | Self::Json(_) | Self::Other(_) => "internal",
        }
    }
}

impl From<SandboxImageBuildError> for ImageBuildError {
    fn from(error: SandboxImageBuildError) -> Self {
        match error {
            SandboxImageBuildError::Build(error) => error,
            SandboxImageBuildError::Usage(message) => Self::Usage(message),
            SandboxImageBuildError::Auth(message) => Self::Auth(message),
            SandboxImageBuildError::Http(error) => Self::Sdk(SdkError::Http(error)),
            SandboxImageBuildError::Io(error) => Self::Io(error),
            SandboxImageBuildError::Json(error) => Self::Json(error),
            SandboxImageBuildError::Sdk(error) => Self::Sdk(error),
            other => Self::Other(other.to_string()),
        }
    }
}

// ---------------------------------------------------------------------------
// Client, handle and entry points
// ---------------------------------------------------------------------------

/// Credentials and scope for build operations. The same rules as the
/// convenience builders: API keys are self-scoping; a personal access token
/// (`use_scope_headers`) needs the organization and project.
#[derive(Debug, Clone)]
pub struct ImageBuildClientOptions {
    pub api_url: String,
    pub bearer_token: String,
    pub use_scope_headers: bool,
    pub organization_id: Option<String>,
    pub project_id: Option<String>,
    /// The sandbox namespace builder logs are followed in.
    pub namespace: String,
    pub user_agent: Option<String>,
}

/// How long [`ImageBuildHandle::wait`] waits and what it follows.
#[derive(Debug, Clone, Default)]
pub struct ImageBuildWaitOptions {
    /// A caller bound on the wait, applied on top of the service-informed
    /// deadline. Expiry raises [`ImageBuildError::Timeout`] and leaves the
    /// operation running.
    pub timeout: Option<Duration>,
    /// Follow `tl-image-builder` output from the builder sandbox while an
    /// attempt is running. Off by default for non-interactive callers.
    pub follow_logs: bool,
}

/// A client for looking up and cancelling builds by id.
#[derive(Clone)]
pub struct ImageBuildClient {
    pub(crate) client: crate::Client,
    pub(crate) ctx: ResolvedBuildContext,
}

impl ImageBuildClient {
    pub fn new(options: ImageBuildClientOptions) -> Result<Self, ImageBuildError> {
        image_service_builds::image_build_client(options)
    }

    /// Look a build up by its service-generated id. Unknown and foreign builds
    /// are the same [`ImageBuildError::NotFound`]. A `sandbox_template_` or
    /// `image_` reference is refused locally: it is not a build id.
    pub async fn get(&self, build_id: &str) -> Result<ImageBuildHandle, ImageBuildError> {
        reject_legacy_reference(build_id)?;
        let info = image_service_builds::get_build(&self.client, build_id).await?;
        Ok(ImageBuildHandle {
            client: self.clone(),
            build_id: info.build_id.clone(),
            // The service no longer reports the admission key; a handle from
            // a lookup cancels by build id, which is the sufficient selector.
            client_request_id: None,
            info,
        })
    }

    /// Look `build_id` up and wait for it in one interruptible operation:
    /// [`Self::get`] followed by [`ImageBuildHandle::wait`], with the lookup
    /// itself under `interrupt` and under `options.timeout`. Ctrl+C during a
    /// slow or stalled first request therefore cancels the build (its id is
    /// the sufficient selector) rather than ending the process silently,
    /// and a short timeout bounds the lookup too.
    pub async fn wait_build<F>(
        &self,
        build_id: &str,
        options: ImageBuildWaitOptions,
        interrupt: &InterruptSignal,
        emit: F,
    ) -> Result<ImageBuildResult, ImageBuildError>
    where
        F: FnMut(SandboxImageBuildEvent),
    {
        reject_legacy_reference(build_id)?;
        let info = image_service_builds::lookup_and_wait(
            &self.client,
            Some(&self.ctx),
            build_id,
            &options,
            interrupt,
            emit,
        )
        .await?;
        image_service_builds::terminal_result(&info)
    }

    /// Cancel one build, bounded by [`CANCEL_HANDSHAKE_BUDGET`]. The outcome
    /// says what the service observed; `not_admitted` is not a cancellation.
    pub async fn cancel(
        &self,
        selector: CancelBuildSelector,
    ) -> Result<CancelBuildResponse, ImageBuildError> {
        if let CancelBuildSelector::BuildId(build_id) = &selector {
            reject_legacy_reference(build_id)?;
        }
        image_service_builds::cancel_build(&self.client, &selector, CANCEL_HANDSHAKE_BUDGET).await
    }
}

/// One admitted build. Stores the build identity and the caller's context;
/// dropping it performs no network I/O.
#[derive(Clone)]
pub struct ImageBuildHandle {
    pub(crate) client: ImageBuildClient,
    pub(crate) build_id: String,
    pub(crate) client_request_id: Option<String>,
    pub(crate) info: ImageBuildInfo,
}

impl ImageBuildHandle {
    pub fn build_id(&self) -> &str {
        &self.build_id
    }

    /// The admission's client request id, when this handle started the build
    /// or the service reports it. Not needed to cancel.
    pub fn client_request_id(&self) -> Option<&str> {
        self.client_request_id.as_deref()
    }

    /// The last observed state.
    pub fn info(&self) -> &ImageBuildInfo {
        &self.info
    }

    /// Re-read the current state.
    pub async fn refresh(&mut self) -> Result<&ImageBuildInfo, ImageBuildError> {
        self.info = image_service_builds::get_build(&self.client.client, &self.build_id).await?;
        Ok(&self.info)
    }

    /// Poll to a terminal status and return the build's immutable result.
    /// `interrupt` triggers the remote cancellation handshake; see the module
    /// docs for deadlines and reconnects.
    pub async fn wait<F>(
        &mut self,
        options: ImageBuildWaitOptions,
        interrupt: &InterruptSignal,
        emit: F,
    ) -> Result<ImageBuildResult, ImageBuildError>
    where
        F: FnMut(SandboxImageBuildEvent),
    {
        let info = image_service_builds::wait_for_terminal(
            &self.client.client,
            Some(&self.client.ctx),
            &self.build_id,
            self.client_request_id.as_deref(),
            Some(self.info.clone()),
            &options,
            interrupt,
            emit,
        )
        .await?;
        self.info = info;
        image_service_builds::terminal_result(&self.info)
    }

    /// Cancel this build by its id.
    pub async fn cancel(&self) -> Result<CancelBuildResponse, ImageBuildError> {
        self.client
            .cancel(CancelBuildSelector::BuildId(self.build_id.clone()))
            .await
    }
}

/// Admit a Dockerfile build and upload and seal its context, without
/// waiting. `options.common.cas` must be set: legacy builds have no build
/// operation. `docker_config_json` is forwarded as for the convenience
/// builders. The returned handle's info is the admission response.
pub async fn start_build<F>(
    options: SandboxImageBuildOptions,
    docker_config_json: Option<String>,
    interrupt: &InterruptSignal,
    emit: F,
) -> Result<ImageBuildHandle, ImageBuildError>
where
    F: FnMut(SandboxImageBuildEvent),
{
    crate::sandbox_images::start_cas_build(options, docker_config_json, interrupt, emit).await
}

/// Admit a registry import without waiting. `options.common.cas` must be
/// set.
pub async fn start_import<F>(
    options: SandboxImageImportOptions,
    docker_config_json: Option<String>,
    interrupt: &InterruptSignal,
    emit: F,
) -> Result<ImageBuildHandle, ImageBuildError>
where
    F: FnMut(SandboxImageBuildEvent),
{
    crate::sandbox_images::start_cas_import(options, docker_config_json, interrupt, emit).await
}

/// New operations address the CAS image registry only. A reference that is
/// positively a legacy template id, or an image id rather than a build id,
/// is refused before any request.
pub(crate) fn reject_legacy_reference(build_id: &str) -> Result<(), ImageBuildError> {
    let build_id = build_id.trim();
    if build_id.is_empty() {
        return Err(ImageBuildError::usage("build id must not be empty"));
    }
    if build_id.starts_with(crate::sandbox_image_catalog::SANDBOX_TEMPLATE_ID_PREFIX) {
        return Err(ImageBuildError::usage(format!(
            "'{build_id}' is a legacy image id; legacy images have no build operation to \
             get, wait for or cancel"
        )));
    }
    if build_id.starts_with(crate::sandbox_image_catalog::IMAGE_SERVICE_ID_PREFIX) {
        return Err(ImageBuildError::usage(format!(
            "'{build_id}' is a CAS image id, not a build id; look the CAS image up with \
             describe, or use the build id admission returned"
        )));
    }
    Ok(())
}

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

    /// A missing build is the same error whether it never existed, belongs to
    /// another project or was retired; the message says why a known id can
    /// stop resolving (ADR 0108 retirement).
    #[test]
    fn not_found_explains_retirement() {
        let error = ImageBuildError::NotFound {
            build_id: "build-x".to_string(),
        };
        let message = error.to_string();
        assert!(message.starts_with("build build-x not found"), "{message}");
        assert!(message.contains("current build"), "{message}");
        assert!(message.contains("retires them"), "{message}");
        assert_eq!(error.code(), "not_found");
        assert_eq!(error.build_id(), Some("build-x"));
    }

    #[test]
    fn client_request_ids_are_32_hex_and_validate() {
        let id = new_client_request_id();
        assert_eq!(id.len(), 32);
        assert!(
            id.bytes()
                .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
        );
        assert_ne!(id, new_client_request_id());
        validate_client_request_id(&id).unwrap();
        assert!(validate_client_request_id("").is_err());
        assert!(validate_client_request_id(&"a".repeat(129)).is_err());
        assert!(validate_client_request_id("has space").is_err());
        validate_client_request_id("opaque-Key_1").unwrap();
    }

    #[test]
    fn build_info_ignores_unknown_fields_and_keeps_unknown_enum_values() {
        let info = ImageBuildInfo::from_json(serde_json::json!({
            "build_id": "build-1",
            "kind": "dockerfile",
            "status": "paused",
            "phase": "warming",
            "future_field": {"x": 1},
            "result": null,
            "cleanup_pending": true,
            "context_upload": {"url": "https://upload.test/ctx", "max_bytes": 8192},
            "operation_deadline_ms": 1_000,
        }))
        .unwrap();
        assert_eq!(info.status, ImageBuildStatus::Unknown("paused".to_string()));
        assert_eq!(
            info.phase,
            Some(ImageBuildPhase::Unknown("warming".to_string()))
        );
        // Removed pre-trim fields and the upload capability are not part of
        // the record: `info()` output never carries the signed URL.
        let json = serde_json::to_value(&info).unwrap();
        assert!(json.get("cleanup_pending").is_none(), "{json}");
        assert!(json.get("context_upload").is_none(), "{json}");
        assert!(!json.to_string().contains("upload.test"), "{json}");
        assert_eq!(
            info.operation_deadline(),
            Some(UNIX_EPOCH + Duration::from_millis(1_000) + DEPLOYMENT_RECOVERY_ALLOWANCE)
        );
        assert_eq!(
            serde_json::to_value(&info.status).unwrap(),
            Value::String("paused".to_string())
        );
        assert!(!ImageBuildStatus::Running.is_terminal());
        assert!(ImageBuildStatus::Cancelled.is_terminal());
    }

    #[test]
    fn legacy_references_are_refused_before_any_request() {
        assert!(reject_legacy_reference("sandbox_template_1").is_err());
        assert!(reject_legacy_reference("image_abc").is_err());
        assert!(reject_legacy_reference("  ").is_err());
        reject_legacy_reference("build-1").unwrap();
    }

    #[test]
    fn interruption_reports_distinguish_not_admitted_from_cancelled() {
        let report = InterruptionReport {
            build_id: None,
            client_request_id: Some("rid".to_string()),
            outcome: InterruptionOutcome::NotAdmitted,
        };
        assert!(!report.is_confirmed_cancelled());
        assert!(report.to_string().contains("No build was admitted"));
        let report = InterruptionReport {
            build_id: Some("build-1".to_string()),
            client_request_id: None,
            outcome: InterruptionOutcome::Cancelled,
        };
        assert!(report.is_confirmed_cancelled());
        assert_eq!(report.to_string(), "Build build-1 cancelled");
    }
}