alien-core 3.3.59

Deploy software into your customers' cloud accounts and keep it fully managed
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
//! Authoring conveniences shared by stack frontends.
//!
//! A serialized [`Stack`](crate::Stack) is precise but unpleasant to write: memory in bytes,
//! CPU as `{ min, desired }`, scale policies spelled out in full. Frontends let developers
//! write `memory = "16Gi"` or `machines = 2` instead and resolve it here, so every frontend
//! produces the same `Stack` from the same intent.
//!
//! The TypeScript SDK (`packages/core`) predates this module and still carries its own
//! copy of these rules. The `alien.toml` differential tests resolve the same stacks through
//! both and require identical JSON, which keeps the two copies from drifting.

mod inputs;
mod operations;
mod pool;
mod types;

pub use inputs::*;
pub use operations::*;
pub use pool::*;
pub use types::*;

use crate::error::{ErrorData, Result};
use crate::instance_catalog::Architecture;
use crate::{
    CapacityGroup, CapacityGroupScalePolicy, ComputeChoiceRange, DaemonRuntime, DaemonRuntimeMount,
    DataDiskRequirement, GpuSpec, MachineProfile, ResourceSpec, StackInputDefaultValue,
    StackInputKind, StackInputValidation,
};
use alien_error::AlienError;
use serde::{Deserialize, Serialize};

const GIB: u64 = 1024 * 1024 * 1024;

/// Root disk size a pool asks for when it does not say.
pub const DEFAULT_EPHEMERAL_STORAGE: &str = "20Gi";

/// Largest stop grace period a daemon accepts, in seconds (24 hours).
pub const MAX_STOP_GRACE_PERIOD_SECONDS: u32 = 86_400;

fn invalid(field: &str, reason: impl Into<String>) -> AlienError<ErrorData> {
    AlienError::new(ErrorData::StackDefinitionInvalid {
        field: field.to_string(),
        reason: reason.into(),
    })
}

/// Parses a memory or storage quantity such as `"16Gi"`, `"500M"` or `"1024"` into bytes.
///
/// Binary (`Ki`, `Mi`, `Gi`, `Ti`) and decimal (`k`, `M`, `G`, `T`) suffixes are accepted;
/// a bare number is bytes. Fractions round to the nearest byte. Whitespace, signs and
/// exponents are rejected, so a typo never turns into a surprising size.
pub fn parse_quantity_bytes(field: &str, value: &str) -> Result<u64> {
    quantity_bytes(value).map_err(|reason| invalid(field, reason))
}

/// [`parse_quantity_bytes`] without a field name; the error is what is wrong with `value`.
pub fn quantity_bytes(value: &str) -> std::result::Result<u64, String> {
    let (number, multiplier) = [
        ("Ki", 1024_f64),
        ("Mi", 1024_f64.powi(2)),
        ("Gi", 1024_f64.powi(3)),
        ("Ti", 1024_f64.powi(4)),
        ("k", 1e3),
        ("M", 1e6),
        ("G", 1e9),
        ("T", 1e12),
    ]
    .into_iter()
    .find_map(|(suffix, multiplier)| Some((value.strip_suffix(suffix)?, multiplier)))
    .unwrap_or((value, 1.0));

    let (whole, fraction) = match number.split_once('.') {
        Some((whole, fraction)) => (whole, Some(fraction)),
        None => (number, None),
    };
    let is_digits = |part: &str| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit());
    if !is_digits(whole) || fraction.is_some_and(|fraction| !is_digits(fraction)) {
        return Err(format!(
            "'{value}' is not a quantity; use a number with an optional unit such as \"512Mi\", \"16Gi\" or \"1Ti\""
        ));
    }

    let amount: f64 = number
        .parse()
        .map_err(|_| format!("'{value}' is not a quantity"))?;
    let bytes = (amount * multiplier).round();
    if bytes >= u64::MAX as f64 {
        return Err(format!("'{value}' is too large"));
    }
    Ok(bytes as u64)
}

/// Parses a duration such as `"90s"`, `"10m"`, `"24h"` or `"1h30m"` into whole seconds.
///
/// Units are `ms`, `s`, `m`, `h` and `d`; each part is a whole number followed by its unit.
/// A duration that is not a whole number of seconds (`"1500ms"`) is rejected.
pub fn parse_duration_seconds(field: &str, value: &str) -> Result<u64> {
    let millis = duration_millis(value).map_err(|reason| invalid(field, reason))?;
    if millis % 1_000 != 0 {
        return Err(invalid(
            field,
            format!("'{value}' is not a whole number of seconds"),
        ));
    }
    Ok(millis / 1_000)
}

/// A duration such as `"90s"`, `"250ms"` or `"1h30m"` in milliseconds; the error is what is
/// wrong with `value`.
pub fn duration_millis(value: &str) -> std::result::Result<u64, String> {
    let malformed = || {
        format!("'{value}' is not a duration; use whole numbers with units, such as \"30s\", \"10m\" or \"24h\"")
    };
    if value.is_empty() {
        return Err(malformed());
    }

    let mut total: u64 = 0;
    let mut rest = value;
    while !rest.is_empty() {
        let digits = rest.bytes().take_while(u8::is_ascii_digit).count();
        if digits == 0 {
            return Err(malformed());
        }
        let amount: u64 = rest[..digits].parse().map_err(|_| malformed())?;
        let unit_length = rest[digits..]
            .bytes()
            .take_while(u8::is_ascii_alphabetic)
            .count();
        let millis_per_unit = match &rest[digits..digits + unit_length] {
            "ms" => 1,
            "s" => 1_000,
            "m" => 60_000,
            "h" => 3_600_000,
            "d" => 86_400_000,
            _ => return Err(malformed()),
        };
        total = amount
            .checked_mul(millis_per_unit)
            .and_then(|millis| total.checked_add(millis))
            .ok_or_else(|| format!("'{value}' is too long"))?;
        rest = &rest[digits + unit_length..];
    }
    Ok(total)
}

/// Validates a resource ID against the common cloud naming constraints.
///
/// Resource IDs become part of cloud resource names, so the strictest common pattern across
/// GCP, AWS and Azure applies: `[a-z0-9]([a-z0-9-]*[a-z0-9])?` with no consecutive hyphens.
/// The error says what is wrong.
pub fn validate_resource_id(id: &str) -> std::result::Result<(), &'static str> {
    let (Some(&first), Some(&last)) = (id.as_bytes().first(), id.as_bytes().last()) else {
        return Err("must not be empty");
    };
    if !first.is_ascii_lowercase() && !first.is_ascii_digit() {
        return Err("must start with a lowercase letter or digit");
    }
    if !last.is_ascii_lowercase() && !last.is_ascii_digit() {
        return Err("must end with a lowercase letter or digit");
    }
    if !id
        .bytes()
        .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
    {
        return Err("must only contain lowercase letters, digits, and hyphens");
    }
    if id.contains("--") {
        return Err("must not contain consecutive hyphens");
    }
    Ok(())
}

/// Most repositories a stack may approve for containers created after installation.
pub const MAX_DYNAMIC_CONTAINER_REPOSITORIES: usize = 16;

/// Whether `repository` is a fully qualified OCI repository such as `ghcr.io/acme/tools`:
/// a registry host (with an optional port) followed by at least one lowercase path segment.
pub fn is_repository_name(repository: &str) -> bool {
    let is_alphanumeric = |byte: u8| byte.is_ascii_lowercase() || byte.is_ascii_digit();
    let is_segment = |part: &str, separators: &[u8]| {
        let bytes = part.as_bytes();
        matches!((bytes.first(), bytes.last()), (Some(&first), Some(&last))
            if is_alphanumeric(first) && is_alphanumeric(last))
            && bytes
                .iter()
                .all(|&byte| is_alphanumeric(byte) || separators.contains(&byte))
    };

    let Some((authority, path)) = repository.split_once('/') else {
        return false;
    };
    if !path.split('/').all(|part| is_segment(part, b"._-")) {
        return false;
    }
    let mut authority = authority.split(':');
    let host = authority.next().unwrap_or_default();
    let port = authority.next();
    authority.next().is_none()
        && port.is_none_or(|port| !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit()))
        && host.split('.').all(|label| is_segment(label, b"-"))
}

/// Checks the OCI repositories a stack approves for containers created after installation:
/// 1 to 16 distinct, fully qualified names. The error field names the offending entry
/// (`dynamicContainerRepositories.2`) when one entry is at fault.
pub fn validate_dynamic_container_repositories(repositories: &[String]) -> Result<()> {
    const FIELD: &str = "dynamicContainerRepositories";
    if repositories.is_empty() || repositories.len() > MAX_DYNAMIC_CONTAINER_REPOSITORIES {
        return Err(invalid(
            FIELD,
            format!(
                "must list 1 to {MAX_DYNAMIC_CONTAINER_REPOSITORIES} repositories, found {}",
                repositories.len()
            ),
        ));
    }
    for (index, repository) in repositories.iter().enumerate() {
        let field = format!("{FIELD}.{index}");
        if !is_repository_name(repository) {
            return Err(invalid(
                &field,
                format!(
                    "'{repository}' is not a fully qualified OCI repository; write the registry host and the path, such as \"ghcr.io/acme/tools\""
                ),
            ));
        }
        if repositories[..index].contains(repository) {
            return Err(invalid(&field, format!("'{repository}' is listed twice")));
        }
    }
    Ok(())
}

/// Checks the IDs of the container resources whose images a stack approves: non-empty and
/// distinct. The error field names the offending entry when one entry is at fault.
pub fn validate_dynamic_container_image_resources(resource_ids: &[String]) -> Result<()> {
    const FIELD: &str = "dynamicContainerImageResources";
    if resource_ids.is_empty() {
        return Err(invalid(FIELD, "must list at least one container"));
    }
    for (index, id) in resource_ids.iter().enumerate() {
        if resource_ids[..index].contains(id) {
            return Err(invalid(
                &format!("{FIELD}.{index}"),
                format!("'{id}' is listed twice"),
            ));
        }
    }
    Ok(())
}

/// Validates a daemon stop grace period: 1 second through 24 hours.
pub fn stop_grace_period_seconds(field: &str, seconds: u64) -> Result<u32> {
    match u32::try_from(seconds) {
        Ok(seconds) if (1..=MAX_STOP_GRACE_PERIOD_SECONDS).contains(&seconds) => Ok(seconds),
        _ => Err(invalid(
            field,
            format!("{seconds} seconds is outside 1 second to 24 hours"),
        )),
    }
}

/// A CPU amount written as a number of cores (`2`, `0.5`) or a quantity string (`"500m"`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(untagged)]
pub enum CpuAmount {
    /// Whole cores.
    Integer(i64),
    /// Fractional cores.
    Float(f64),
    /// A Kubernetes-style quantity, passed through verbatim.
    Quantity(String),
}

impl CpuAmount {
    /// The canonical string form: numbers print like JavaScript does (`2`, `0.5`).
    pub fn to_quantity(&self, field: &str) -> Result<String> {
        let positive = |cores: f64| {
            if cores > 0.0 && cores.is_finite() {
                Ok(())
            } else {
                Err(invalid(field, "CPU must be greater than zero"))
            }
        };
        match self {
            CpuAmount::Integer(cores) => {
                positive(*cores as f64)?;
                Ok(cores.to_string())
            }
            CpuAmount::Float(cores) => {
                positive(*cores)?;
                Ok(cores.to_string())
            }
            CpuAmount::Quantity(quantity) => {
                let cores = crate::instance_catalog::parse_cpu(quantity)
                    .map_err(|reason| invalid(field, reason))?;
                positive(cores)?;
                Ok(quantity.clone())
            }
        }
    }

    /// A workload request that asks for exactly this much CPU.
    pub fn to_resource_spec(&self, field: &str) -> Result<ResourceSpec> {
        let quantity = self.to_quantity(field)?;
        Ok(ResourceSpec {
            min: quantity.clone(),
            desired: quantity,
        })
    }
}

/// A workload memory request that asks for exactly `size` (for example `"4Gi"`).
pub fn memory_resource_spec(field: &str, size: &str) -> Result<ResourceSpec> {
    if parse_quantity_bytes(field, size)? == 0 {
        return Err(invalid(field, "memory must be greater than zero"));
    }
    Ok(ResourceSpec {
        min: size.to_string(),
        desired: size.to_string(),
    })
}

impl DaemonRuntime {
    /// Full access to the host: privileged, the host's PID namespace and network,
    /// the host root mounted at `/host`, running as root.
    ///
    /// This is what host agents and loaders that install or supervise native host
    /// processes need. On AWS, GCP and Azure it cannot be combined with `permissions`.
    pub fn host_access() -> Self {
        DaemonRuntime {
            privileged: Some(true),
            pid_namespace: Some("host".to_string()),
            network_mode: Some("host".to_string()),
            mounts: vec![DaemonRuntimeMount {
                source: "/".to_string(),
                target: "/host".to_string(),
                options: None,
            }],
            user: Some("0".to_string()),
        }
    }
}

/// A machine count: one exact number, or a range a deployment chooses from.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(untagged)]
pub enum ComputeChoice {
    /// Every deployment uses this number.
    Exactly(u32),
    /// Each deployment picks from `min..=max`, `default` when it does not pick.
    Range(ComputeChoiceRange),
}

impl ComputeChoice {
    fn range(&self, field: &str) -> Result<ComputeChoiceRange> {
        match self {
            ComputeChoice::Exactly(count) => Ok(ComputeChoiceRange {
                min: *count,
                max: *count,
                default: *count,
            }),
            ComputeChoice::Range(range) => {
                if range.min <= range.default && range.default <= range.max {
                    Ok(range.clone())
                } else {
                    Err(invalid(
                        field,
                        format!(
                            "needs min <= default <= max, got min {}, default {}, max {}",
                            range.min, range.default, range.max
                        ),
                    ))
                }
            }
        }
    }
}

/// How many machines a pool runs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PoolScale {
    /// A fixed number of machines.
    Fixed { machines: ComputeChoice },
    /// An autoscaling group between `min` and `max` machines.
    Autoscale {
        min: ComputeChoice,
        max: ComputeChoice,
    },
}

/// The extra empty data disk each machine must provide.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(untagged)]
pub enum DataDiskSize {
    /// One size for every deployment, for example `"1Ti"`.
    Fixed(String),
    /// Sizes a deployment chooses from. A `min` of `"0Gi"` lets a deployment go without one.
    Range {
        /// Smallest size a deployment may choose.
        min: String,
        /// Size used when a deployment does not choose.
        default: String,
        /// Largest size a deployment may choose.
        max: String,
    },
}

/// Hardware a pool's machines must have.
#[derive(Debug, Clone, PartialEq)]
pub struct PoolRequirements {
    pub cpu: CpuAmount,
    pub memory: String,
    /// Size of the disk holding the operating system. Defaults to [`DEFAULT_EPHEMERAL_STORAGE`].
    pub ephemeral_storage: Option<String>,
    pub architecture: Option<Architecture>,
    pub nested_virtualization: Option<bool>,
    pub gpu: Option<GpuSpec>,
    pub data_disk: Option<DataDiskSize>,
}

/// A compute pool as a developer declares it: what the machines need and how many run.
#[derive(Debug, Clone, PartialEq)]
pub struct ComputePool {
    pub requirements: PoolRequirements,
    pub scale: PoolScale,
}

impl ComputePool {
    /// Resolves the pool into the capacity group the stack carries.
    ///
    /// Errors name the failing field the way the TypeScript SDK does (`memory`,
    /// `ephemeralStorage`, `dataDisk.size.min`, `scale.machines`, ...).
    pub fn to_capacity_group(&self, group_id: &str) -> Result<CapacityGroup> {
        let requirements = &self.requirements;
        let (scale_policy, min_size, max_size) = match &self.scale {
            PoolScale::Fixed { machines } => {
                let machines = machines.range("scale.machines")?;
                let selected = machines.default;
                (
                    CapacityGroupScalePolicy::Fixed { machines },
                    selected,
                    selected,
                )
            }
            PoolScale::Autoscale { min, max } => {
                let min = min.range("scale.min")?;
                let max = max.range("scale.max")?;
                if min.default > max.default {
                    return Err(invalid(
                        "scale",
                        format!(
                            "the default minimum ({}) is above the default maximum ({})",
                            min.default, max.default
                        ),
                    ));
                }
                let (min_size, max_size) = (min.default, max.default);
                (
                    CapacityGroupScalePolicy::Autoscale { min, max },
                    min_size,
                    max_size,
                )
            }
        };

        let data_disk_gib_range = match &requirements.data_disk {
            Some(DataDiskSize::Range { min, default, max }) => {
                let range = ComputeChoiceRange {
                    min: whole_gib("dataDisk.size.min", min)?,
                    max: whole_gib("dataDisk.size.max", max)?,
                    default: whole_gib("dataDisk.size.default", default)?,
                };
                if !(range.min <= range.default && range.default <= range.max) {
                    return Err(invalid(
                        "dataDisk.size",
                        format!("needs min <= default <= max: {min}, {default}, {max}"),
                    ));
                }
                if range.max == 0 {
                    return Err(invalid("dataDisk.size.max", "must be greater than zero"));
                }
                Some(range)
            }
            Some(DataDiskSize::Fixed(_)) | None => None,
        };
        let data_disk = match &requirements.data_disk {
            None => None,
            Some(DataDiskSize::Fixed(size)) => {
                let size_bytes = parse_quantity_bytes("dataDisk.size", size)?;
                if size_bytes == 0 {
                    return Err(invalid(
                        "dataDisk.size",
                        format!("must be greater than zero: {size}"),
                    ));
                }
                Some(DataDiskRequirement { size_bytes })
            }
            // A range's default stands for the pool; a default of 0 means no data disk.
            Some(DataDiskSize::Range { .. }) => data_disk_gib_range
                .as_ref()
                .filter(|range| range.default > 0)
                .map(|range| DataDiskRequirement {
                    size_bytes: u64::from(range.default) * GIB,
                }),
        };

        let profile = MachineProfile {
            cpu: requirements.cpu.to_quantity("cpu")?,
            memory_bytes: parse_quantity_bytes("memory", &requirements.memory)?,
            ephemeral_storage_bytes: parse_quantity_bytes(
                "ephemeralStorage",
                requirements
                    .ephemeral_storage
                    .as_deref()
                    .unwrap_or(DEFAULT_EPHEMERAL_STORAGE),
            )?,
            architecture: requirements.architecture,
            gpu: requirements.gpu.clone(),
            data_disk,
        };

        Ok(CapacityGroup {
            group_id: group_id.to_string(),
            instance_type: None,
            profile: Some(profile),
            min_size,
            max_size,
            scale_policy: Some(scale_policy),
            nested_virtualization: requirements.nested_virtualization,
            data_disk_gib_range,
        })
    }
}

fn whole_gib(field: &str, value: &str) -> Result<u32> {
    let bytes = parse_quantity_bytes(field, value)?;
    if bytes % GIB != 0 {
        return Err(invalid(
            field,
            format!("must be a whole number of GiB: {value}"),
        ));
    }
    u32::try_from(bytes / GIB).map_err(|_| invalid(field, format!("'{value}' is too large")))
}

/// Validates a pool's failure-domain spread: an integer from 1 to 255.
pub fn failure_domain_spread(field: &str, spread: i64) -> Result<u8> {
    u8::try_from(spread)
        .ok()
        .filter(|spread| *spread >= 1)
        .ok_or_else(|| {
            invalid(
                field,
                format!("must be an integer from 1 to 255, got {spread}"),
            )
        })
}

/// The validation block a stack input carries.
///
/// Every kind except boolean accepts constraints, and its definition carries a validation
/// block even when no constraint is set (`{}`); a boolean carries none. This is the shape
/// the TypeScript SDK has always produced, kept so a stack does not change when it moves
/// between frontends.
pub fn input_validation(
    kind: &StackInputKind,
    validation: StackInputValidation,
) -> Option<StackInputValidation> {
    match kind {
        StackInputKind::Boolean => None,
        _ => Some(validation),
    }
}

/// A stack input value as written: a default, or a numeric constraint.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(untagged)]
pub enum InputValue {
    /// Text.
    String(String),
    /// A whole number.
    Integer(i64),
    /// A number with a fractional part.
    Float(f64),
    /// A flag.
    Boolean(bool),
    /// A list of text values.
    StringList(Vec<String>),
}

impl InputValue {
    fn describe(&self) -> &'static str {
        match self {
            InputValue::String(_) => "a string",
            InputValue::Integer(_) => "an integer",
            InputValue::Float(_) => "a number",
            InputValue::Boolean(_) => "a boolean",
            InputValue::StringList(_) => "a list of strings",
        }
    }
}

/// The default value of an input of `kind`, typed the way the stack stores it.
pub fn input_default(kind: &StackInputKind, value: &InputValue) -> Result<StackInputDefaultValue> {
    let mismatch = |expected: &str| {
        invalid(
            "default",
            format!(
                "expected {expected} for a {kind:?} input, got {}",
                value.describe()
            ),
        )
    };
    match (kind, value) {
        (StackInputKind::Secret, _) => Err(invalid(
            "default",
            "secret inputs cannot have a default value",
        )),
        (StackInputKind::String | StackInputKind::Enum, InputValue::String(text)) => {
            Ok(StackInputDefaultValue::String(text.clone()))
        }
        (StackInputKind::String | StackInputKind::Enum, _) => Err(mismatch("a string")),
        (StackInputKind::Number | StackInputKind::Integer, _) => Ok(
            StackInputDefaultValue::Number(input_number("default", kind, value)?),
        ),
        (StackInputKind::Boolean, InputValue::Boolean(flag)) => {
            Ok(StackInputDefaultValue::Boolean(*flag))
        }
        (StackInputKind::Boolean, _) => Err(mismatch("a boolean")),
        (StackInputKind::StringList, InputValue::StringList(items)) => {
            Ok(StackInputDefaultValue::StringList(items.clone()))
        }
        (StackInputKind::StringList, _) => Err(mismatch("a list of strings")),
    }
}

/// A number for a number or integer input (a default, `min` or `max`), as the stack stores
/// it: decimal text printed the way JavaScript prints numbers. Integer inputs take whole
/// numbers only.
pub fn input_number(field: &str, kind: &StackInputKind, value: &InputValue) -> Result<String> {
    let number = match value {
        InputValue::Integer(number) => return Ok(number.to_string()),
        InputValue::Float(number) => *number,
        other => {
            return Err(invalid(
                field,
                format!("expected a number, got {}", other.describe()),
            ))
        }
    };
    if !number.is_finite() {
        return Err(invalid(field, "must be a finite number"));
    }
    if *kind == StackInputKind::Integer && number.fract() != 0.0 {
        return Err(invalid(field, format!("{number} is not a whole number")));
    }
    Ok(number.to_string())
}

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

    fn field_of(error: AlienError<ErrorData>) -> String {
        match error.error.expect("error data") {
            ErrorData::StackDefinitionInvalid { field, .. } => field,
            other => panic!("unexpected error {other:?}"),
        }
    }

    #[test]
    fn quantities_match_the_typescript_sdk() {
        assert_eq!(parse_quantity_bytes("m", "16Gi").unwrap(), 17_179_869_184);
        assert_eq!(parse_quantity_bytes("m", "1Ti").unwrap(), 1_099_511_627_776);
        assert_eq!(parse_quantity_bytes("m", "500M").unwrap(), 500_000_000);
        assert_eq!(parse_quantity_bytes("m", "1.5Gi").unwrap(), 1_610_612_736);
        assert_eq!(parse_quantity_bytes("m", "2k").unwrap(), 2_000);
        assert_eq!(parse_quantity_bytes("m", "1024").unwrap(), 1_024);
        // Math.round(0.3 * 1024) in the TS SDK.
        assert_eq!(parse_quantity_bytes("m", "0.3Ki").unwrap(), 307);
        for bad in [
            "", "Gi", "16 Gi", " 16Gi", "16gi", "-1Gi", "1e3", "1.Gi", ".5Gi", "16GiB",
        ] {
            assert_eq!(
                field_of(parse_quantity_bytes("memory", bad).unwrap_err()),
                "memory",
                "{bad:?} must be rejected"
            );
        }
    }

    #[test]
    fn repository_names_match_the_typescript_sdk() {
        for good in [
            "ghcr.io/acme/tools",
            "localhost:5000/acme",
            "registry.example.com:443/a/b-c/d.e_f",
            "alpine/git",
            "123456789012.dkr.ecr.us-east-1.amazonaws.com/acme",
        ] {
            assert!(is_repository_name(good), "{good:?} must be accepted");
        }
        for bad in [
            "",
            "alpine",
            "ghcr.io/",
            "ghcr.io//acme",
            "/acme",
            "GHCR.io/acme",
            "ghcr.io/Acme",
            "ghcr.io/acme:latest",
            "ghcr.io/acme@sha256:abc",
            "ghcr.io:/acme",
            "ghcr.io:80:81/acme",
            "ghcr..io/acme",
            "-ghcr.io/acme",
            "ghcr.io/-acme",
            "ghcr.io/acme-",
            "ghcr.io/acme/ tools",
            "https://ghcr.io/acme",
        ] {
            assert!(!is_repository_name(bad), "{bad:?} must be rejected");
        }
    }

    #[test]
    fn dynamic_container_lists_are_bounded_and_distinct() {
        let names = |items: &[&str]| {
            items
                .iter()
                .map(|item| item.to_string())
                .collect::<Vec<_>>()
        };
        validate_dynamic_container_repositories(&names(&["ghcr.io/acme/a", "ghcr.io/acme/b"]))
            .unwrap();
        assert_eq!(
            field_of(validate_dynamic_container_repositories(&[]).unwrap_err()),
            "dynamicContainerRepositories"
        );
        let seventeen: Vec<String> = (0..17).map(|i| format!("ghcr.io/acme/r{i}")).collect();
        assert_eq!(
            field_of(validate_dynamic_container_repositories(&seventeen).unwrap_err()),
            "dynamicContainerRepositories"
        );
        validate_dynamic_container_repositories(&seventeen[..16]).unwrap();
        assert_eq!(
            field_of(
                validate_dynamic_container_repositories(&names(&["ghcr.io/acme/a", "alpine"]))
                    .unwrap_err()
            ),
            "dynamicContainerRepositories.1"
        );
        assert_eq!(
            field_of(
                validate_dynamic_container_repositories(&names(&[
                    "ghcr.io/acme/a",
                    "ghcr.io/acme/a"
                ]))
                .unwrap_err()
            ),
            "dynamicContainerRepositories.1"
        );

        validate_dynamic_container_image_resources(&names(&["api", "web"])).unwrap();
        assert_eq!(
            field_of(validate_dynamic_container_image_resources(&[]).unwrap_err()),
            "dynamicContainerImageResources"
        );
        assert_eq!(
            field_of(
                validate_dynamic_container_image_resources(&names(&["api", "api"])).unwrap_err()
            ),
            "dynamicContainerImageResources.1"
        );
    }

    #[test]
    fn durations() {
        assert_eq!(parse_duration_seconds("d", "90s").unwrap(), 90);
        assert_eq!(parse_duration_seconds("d", "10m").unwrap(), 600);
        assert_eq!(parse_duration_seconds("d", "24h").unwrap(), 86_400);
        assert_eq!(parse_duration_seconds("d", "1h30m").unwrap(), 5_400);
        assert_eq!(parse_duration_seconds("d", "1d").unwrap(), 86_400);
        assert_eq!(parse_duration_seconds("d", "2000ms").unwrap(), 2);
        assert_eq!(duration_millis("250ms").unwrap(), 250);
        assert_eq!(duration_millis("1h30m").unwrap(), 5_400_000);
        for bad in ["", "10", "h", "1.5h", "10 m", "-1s", "1h30", "1x", "5mm"] {
            assert!(
                parse_duration_seconds("d", bad).is_err(),
                "{bad:?} must be rejected"
            );
        }
        assert_eq!(
            field_of(parse_duration_seconds("grace", "1500ms").unwrap_err()),
            "grace",
            "a fraction of a second is not a whole number of seconds"
        );
        assert_eq!(stop_grace_period_seconds("g", 86_400).unwrap(), 86_400);
        assert!(stop_grace_period_seconds("g", 86_401).is_err());
        assert!(stop_grace_period_seconds("g", 0).is_err());
    }

    #[test]
    fn cpu_amounts_print_like_javascript_numbers() {
        assert_eq!(CpuAmount::Integer(2).to_quantity("cpu").unwrap(), "2");
        assert_eq!(CpuAmount::Float(0.5).to_quantity("cpu").unwrap(), "0.5");
        assert_eq!(CpuAmount::Float(2.0).to_quantity("cpu").unwrap(), "2");
        assert_eq!(
            CpuAmount::Quantity("500m".into())
                .to_quantity("cpu")
                .unwrap(),
            "500m"
        );
        assert!(CpuAmount::Integer(0).to_quantity("cpu").is_err());
        assert!(CpuAmount::Quantity("lots".into())
            .to_quantity("cpu")
            .is_err());
    }

    fn pool(scale: PoolScale, data_disk: Option<DataDiskSize>) -> ComputePool {
        ComputePool {
            requirements: PoolRequirements {
                cpu: CpuAmount::Integer(4),
                memory: "16Gi".into(),
                ephemeral_storage: None,
                architecture: Some(Architecture::X86_64),
                nested_virtualization: Some(true),
                gpu: None,
                data_disk,
            },
            scale,
        }
    }

    #[test]
    fn fixed_pool_selects_the_default_machine_count() {
        let group = pool(
            PoolScale::Fixed {
                machines: ComputeChoice::Range(ComputeChoiceRange {
                    min: 1,
                    max: 5,
                    default: 2,
                }),
            },
            None,
        )
        .to_capacity_group("general")
        .unwrap();

        assert_eq!(
            group,
            CapacityGroup {
                group_id: "general".into(),
                instance_type: None,
                profile: Some(MachineProfile {
                    cpu: "4".into(),
                    memory_bytes: 16 * GIB,
                    ephemeral_storage_bytes: 20 * GIB,
                    architecture: Some(Architecture::X86_64),
                    gpu: None,
                    data_disk: None,
                }),
                min_size: 2,
                max_size: 2,
                scale_policy: Some(CapacityGroupScalePolicy::Fixed {
                    machines: ComputeChoiceRange {
                        min: 1,
                        max: 5,
                        default: 2
                    }
                }),
                nested_virtualization: Some(true),
                data_disk_gib_range: None,
            }
        );
    }

    #[test]
    fn autoscale_pool_uses_default_bounds() {
        let group = pool(
            PoolScale::Autoscale {
                min: ComputeChoice::Exactly(1),
                max: ComputeChoice::Range(ComputeChoiceRange {
                    min: 2,
                    max: 10,
                    default: 4,
                }),
            },
            None,
        )
        .to_capacity_group("workers")
        .unwrap();
        assert_eq!((group.min_size, group.max_size), (1, 4));

        let inverted = pool(
            PoolScale::Autoscale {
                min: ComputeChoice::Exactly(5),
                max: ComputeChoice::Exactly(2),
            },
            None,
        );
        assert_eq!(
            field_of(inverted.to_capacity_group("w").unwrap_err()),
            "scale"
        );
    }

    #[test]
    fn data_disk_ranges_resolve_their_default() {
        let fixed = |machines| PoolScale::Fixed {
            machines: ComputeChoice::Exactly(machines),
        };
        let range = |min: &str, default: &str, max: &str| DataDiskSize::Range {
            min: min.into(),
            default: default.into(),
            max: max.into(),
        };

        let group = pool(fixed(1), Some(range("0Gi", "200Gi", "4Ti")))
            .to_capacity_group("g")
            .unwrap();
        assert_eq!(
            group.data_disk_gib_range,
            Some(ComputeChoiceRange {
                min: 0,
                max: 4096,
                default: 200
            })
        );
        assert_eq!(
            group.profile.unwrap().data_disk,
            Some(DataDiskRequirement {
                size_bytes: 200 * GIB
            })
        );

        let no_default_disk = pool(fixed(1), Some(range("0Gi", "0Gi", "1Ti")))
            .to_capacity_group("g")
            .unwrap();
        assert_eq!(no_default_disk.profile.unwrap().data_disk, None);

        // A fixed size stands to the byte, unlike a range.
        let decimal = pool(fixed(1), Some(DataDiskSize::Fixed("500G".into())))
            .to_capacity_group("g")
            .unwrap();
        assert_eq!(decimal.data_disk_gib_range, None);
        assert_eq!(
            decimal.profile.unwrap().data_disk,
            Some(DataDiskRequirement {
                size_bytes: 500_000_000_000
            })
        );

        let cases = [
            (range("1Gi", "500M", "2Gi"), "dataDisk.size.default"),
            (range("2Gi", "1Gi", "3Gi"), "dataDisk.size"),
            (range("0Gi", "0Gi", "0Gi"), "dataDisk.size.max"),
            (DataDiskSize::Fixed("0Gi".into()), "dataDisk.size"),
        ];
        for (data_disk, field) in cases {
            let error = pool(fixed(1), Some(data_disk.clone()))
                .to_capacity_group("g")
                .unwrap_err();
            assert_eq!(field_of(error), field, "{data_disk:?}");
        }
    }

    #[test]
    fn failure_domain_spread_bounds() {
        assert_eq!(failure_domain_spread("f", 3).unwrap(), 3);
        assert!(failure_domain_spread("f", 0).is_err());
        assert!(failure_domain_spread("f", 256).is_err());
    }

    #[test]
    fn host_access_is_the_full_host_runtime() {
        let runtime = DaemonRuntime::host_access();
        assert_eq!(runtime.privileged, Some(true));
        assert_eq!(runtime.pid_namespace.as_deref(), Some("host"));
        assert_eq!(runtime.network_mode.as_deref(), Some("host"));
        assert_eq!(runtime.user.as_deref(), Some("0"));
        assert_eq!(
            runtime.mounts,
            vec![DaemonRuntimeMount {
                source: "/".into(),
                target: "/host".into(),
                options: None
            }]
        );
    }

    #[test]
    fn input_defaults_are_typed_by_kind() {
        use StackInputDefaultValue as Default;
        let text = InputValue::String("eu".into());
        assert_eq!(
            input_default(&StackInputKind::Enum, &text).unwrap(),
            Default::String("eu".into())
        );
        assert_eq!(
            input_default(&StackInputKind::Number, &InputValue::Float(0.5)).unwrap(),
            Default::Number("0.5".into())
        );
        assert_eq!(
            input_default(&StackInputKind::Integer, &InputValue::Float(3.0)).unwrap(),
            Default::Number("3".into())
        );
        assert_eq!(
            input_default(&StackInputKind::Integer, &InputValue::Integer(180_000)).unwrap(),
            Default::Number("180000".into())
        );
        assert_eq!(
            input_default(&StackInputKind::StringList, &InputValue::StringList(vec![])).unwrap(),
            Default::StringList(vec![])
        );
        for (kind, value) in [
            (StackInputKind::Secret, text.clone()),
            (StackInputKind::Integer, InputValue::Float(1.5)),
            (StackInputKind::Boolean, text.clone()),
            (StackInputKind::String, InputValue::Integer(1)),
            (StackInputKind::StringList, text.clone()),
        ] {
            assert_eq!(
                field_of(input_default(&kind, &value).unwrap_err()),
                "default"
            );
        }
    }
}