isb-apps 1.6.6

isb's apps over stacks: deployments, builds, jobs, backups, templates and notifications. Use the `isb` crate.
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
//! Applications: the Dokploy-style object over stacks.
//!
//! An org holds projects; a project holds environments (`production` by
//! default); an environment holds apps. An app is a source (an image, or a
//! git repository plus a [`crate::build::Builder`]) and the settings it runs
//! with: environment, domains, volumes, replicas, port, health check,
//! resources, command.
//!
//! A project's environment renders to ONE ordinary stack named
//! `<project>-<env>`, each app one service in it, so apps reach each other
//! as `<app>.<project>-<env>` and the stack controller does the rolling
//! deploys. Deploying an app replaces only its own service in that stack
//! (revisions are per service), so only that app rolls.
//!
//! An environment also holds compose stacks (`stack_deploy`): each belongs
//! to exactly one project environment ([`compose`]). That is a record on
//! the project, nothing more: the stack keeps its name and its services
//! their names, and gain the environment's (`<service>.<project>-<env>`).
//!
//! Everything lives under the daemon's state directory, next to the org's
//! stacks: `apps/` in the default org, `orgs/<org>/apps/` in the others.
//!
//! ```text
//! apps/projects/<project>.json
//! apps/<app>/app.json
//! apps/<app>/deployments/<n>.json, <n>.log
//! sources/<app>/repo, known_hosts           (git checkouts)
//! ```

mod close;
pub mod compose;
pub mod database;
pub mod deploy;
pub mod env;
pub mod forge;
pub mod git;
mod image;
pub mod manifest;
pub mod preview;
mod projects;
mod removals;
pub mod webhook;

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

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

use crate::build::Builder;
use crate::error::{Error, Result};
use crate::org::OrgId;
use crate::spec::{NamedVolumeSpec, SandboxSpec, SecretDef};

pub use compose::ComposeOwner;
pub use database::{DatabaseSource, Engine};
pub use deploy::{Apps, BuildFn, ImageProbe, SecretHook};
pub use env::{EnvFile, EnvValue};
pub use git::{GitAuth, GitSource};
pub use preview::{Preview, PreviewSettings};

/// The environment a project starts with.
pub const DEFAULT_ENVIRONMENT: &str = "production";

/// Label (`user.isb.app`) on every instance of an app.
pub const LABEL_APP: &str = "isb.app";

/// Where an org's apps, projects and sources live: next to its stacks.
pub fn org_root(state: &Path, org: &OrgId) -> PathBuf {
    if org.is_default() {
        state.to_path_buf()
    } else {
        org.dir(state)
    }
}

/// A project: a named group of environments.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Project {
    pub name: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub description: String,
    pub environments: Vec<String>,
    pub created_at: u64,
    /// The compose stacks that belong to its environments.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub compose: Vec<ComposeRef>,
}

/// A compose stack's place in a project: which environment it belongs to.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ComposeRef {
    pub stack: String,
    pub environment: String,
    /// Unix seconds: the older of two stacks keeps a contested name.
    pub added_at: u64,
}

/// A project or environment name: `<project>-<env>` must be a stack name.
pub fn validate_part(kind: &str, s: &str) -> Result<()> {
    let ok = !s.is_empty()
        && s.len() <= 24
        && s.starts_with(|c: char| c.is_ascii_lowercase())
        && !s.ends_with('-')
        && s.chars()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-');
    if !ok {
        return Err(Error::invalid(format!(
            "{kind} name {s:?}: up to 24 characters of [a-z0-9-], starting with a letter"
        )));
    }
    // `<project>-<env>-pr-<n>` is a preview's stack.
    if kind == "environment" && preview::is_pr_suffix(s) {
        return Err(Error::invalid(format!(
            "environment name {s:?}: names ending in pr-<number> are kept for previews"
        )));
    }
    Ok(())
}

/// The stack a project's environment renders to.
pub fn stack_name(project: &str, environment: &str) -> Result<String> {
    let n = format!("{project}-{environment}");
    crate::stack::validate_stack_name(&n).map_err(|_| {
        Error::invalid(format!(
            "{project} + {environment}: the stack name {n:?} is over 30 characters; shorten one"
        ))
    })?;
    Ok(n)
}

/// Where an app's code or image comes from.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase", deny_unknown_fields)]
pub enum Source {
    /// An image as a compose `image:` takes it (`docker:nginx:1.27`,
    /// `ghcr:org/app:tag`, a local alias).
    Image(String),
    Git(GitSource),
    /// A database engine's official image (docs/guides/databases.md).
    Database(DatabaseSource),
}

/// How a git source becomes an image.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BuildSettings {
    pub builder: Builder,
    /// Build-time variables (Dockerfile `ARG`s, buildpack env).
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub args: BTreeMap<String, String>,
    /// Build in a VM (default) rather than a container.
    #[serde(default = "yes")]
    pub untrusted: bool,
}

fn yes() -> bool {
    true
}

/// CPU and memory limits per replica. Either may be written as a number
/// (`{"cpus": 2}`); it is kept as the string it spells.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Resources {
    /// `limits.cpu`: a count, e.g. `2`.
    #[serde(
        default,
        deserialize_with = "crate::flex::opt_string_or_null",
        skip_serializing_if = "Option::is_none"
    )]
    pub cpus: Option<String>,
    /// `512m`, `2g`, `2GiB`; a bare number is bytes.
    #[serde(
        default,
        deserialize_with = "crate::flex::opt_string_or_null",
        skip_serializing_if = "Option::is_none"
    )]
    pub memory: Option<String>,
}

/// The JSON schema of `resources` in the app and database tools.
pub fn resources_schema() -> Value {
    serde_json::json!({
        "type": "object",
        "additionalProperties": false,
        "properties": {
            "cpus": {"type": ["string", "integer", "null"], "description": "CPUs per replica (limits.cpu), e.g. 2 or \"2\". null (app_update) removes the limit."},
            "memory": {"type": ["string", "integer", "null"], "description": "Memory per replica: 512m, 2g, 2GiB, or a number of bytes. null (app_update) removes the limit."}
        }
    })
}

/// What a user sets on an app.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AppSpec {
    pub name: String,
    pub project: String,
    #[serde(default = "default_env")]
    pub environment: String,
    pub source: Source,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub build: Option<BuildSettings>,
    /// `.env` text, or a `{KEY: value | {secret: NAME}}` map.
    #[serde(default)]
    pub env: EnvFile,
    /// The ingress' `domains:` list (`{host, path?, port?, https?,
    /// redirect?}`), passed to the rendered service as is. `port`
    /// defaults to the app's `port`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub domains: Vec<serde_json::Map<String, Value>>,
    /// Named volumes, `NAME:/path[:ro]`. Each is the app's own
    /// (`<stack>_<app>_<name>`), shared by its replicas. Host paths are
    /// not allowed.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub volumes: Vec<String>,
    /// Published host ports, compose syntax (`127.0.0.1:8080:80`),
    /// load-balanced over healthy replicas.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub ports: Vec<String>,
    #[serde(default = "one")]
    pub replicas: u32,
    /// The port the app listens on inside its instances.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub port: Option<u16>,
    /// A compose `healthcheck`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub healthcheck: Option<Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resources: Option<Resources>,
    /// A compose `command`: argv, or a line split like a shell would.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub command: Option<Value>,
    /// Preview deployments per pull request (git sources).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub previews: Option<PreviewSettings>,
    /// Files in the app's instances, each an org secret's value (config
    /// files, certificates). Delivered like a stack's file secrets.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub files: Vec<AppFile>,
    /// The user the app runs as; numeric (`uid[:gid]`) on an OCI image.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub user: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub working_dir: Option<String>,
    /// What a new version of a secret the app uses (in `env` or `files`)
    /// does to its replicas: `roll` (default), `restart` in place, or
    /// `none` (files updated, replicas stale until they next start).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub secret_on_change: Option<crate::spec::OnChange>,
}

/// A file an app gets: the value of org secret `secret` at `path`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AppFile {
    /// Absolute path in the instance.
    pub path: String,
    /// The org secret holding the content.
    pub secret: String,
    /// Octal mode (default `0400`, owned by the app's numeric user or root).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mode: Option<String>,
}

fn default_env() -> String {
    DEFAULT_ENVIRONMENT.into()
}

fn one() -> u32 {
    1
}

/// An app as stored: what the user set, plus bookkeeping.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct App {
    pub spec: AppSpec,
    pub created_at: u64,
    pub updated_at: u64,
    /// The number the next deployment gets.
    #[serde(default = "one_u64")]
    pub next_deployment: u64,
    /// The deployment running now (the last one that finished `done`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub current: Option<u64>,
}

fn one_u64() -> u64 {
    1
}

impl AppSpec {
    pub fn stack(&self) -> Result<String> {
        stack_name(&self.project, &self.environment)
    }

    /// Check everything that does not need the host.
    pub fn validate(&self) -> Result<()> {
        validate_app_name(&self.name)?;
        validate_part("project", &self.project)?;
        validate_part("environment", &self.environment)?;
        let stack = self.stack()?;
        // Long names are shortened; this refuses only what cannot fit at all.
        crate::stack::instance_name(&stack, &self.name, self.replicas.max(1), "0000")
            .map_err(|e| Error::invalid(format!("app {}: {e}", self.name)))?;
        match (&self.source, &self.build) {
            (Source::Image(i), None) => {
                crate::plan::ImageSource::parse(i)?;
            }
            (Source::Image(_), Some(_)) => {
                return Err(Error::invalid("an image source is not built; drop `build`"));
            }
            (Source::Git(g), Some(_)) => {
                g.validate()?;
            }
            (Source::Git(_), None) => {
                return Err(Error::invalid(
                    "a git source needs `build` (e.g. {builder: {type: railpack}})",
                ));
            }
            (Source::Database(db), _) => database::validate(self, db)?,
        }
        if self.replicas > 100 {
            return Err(Error::invalid("replicas: at most 100"));
        }
        for v in &self.volumes {
            parse_volume(v)?;
        }
        if let Some(p) = &self.previews {
            p.validate(self)?;
        }
        let mut paths = std::collections::BTreeSet::new();
        for f in &self.files {
            if !f.path.starts_with('/') || f.path.ends_with('/') || f.path.contains("/../") {
                return Err(Error::invalid(format!(
                    "file {:?}: the path must be an absolute file path",
                    f.path
                )));
            }
            if !paths.insert(f.path.as_str()) {
                return Err(Error::invalid(format!("file {:?} is given twice", f.path)));
            }
            crate::secrets::validate_name(&f.secret)?;
        }
        for d in &self.domains {
            let host = d.get("host").and_then(Value::as_str).unwrap_or("");
            if host.is_empty() {
                return Err(Error::invalid("every domain needs a host"));
            }
            if !d.contains_key("port") && self.port.is_none() {
                return Err(Error::invalid(format!(
                    "domain {host}: give it a port, or set the app's port"
                )));
            }
        }
        Ok(())
    }

    /// The webhook secret's name in the org's store.
    pub fn webhook_secret(&self) -> String {
        webhook_secret(&self.name)
    }
}

pub fn webhook_secret(app: &str) -> String {
    format!("app.{app}.webhook")
}

pub fn deploy_key_secret(app: &str) -> String {
    format!("app.{app}.deploy-key")
}

/// An app name: a service name in its stack and a DNS label.
pub fn validate_app_name(s: &str) -> Result<()> {
    let ok = !s.is_empty()
        && s.len() <= 30
        && s.starts_with(|c: char| c.is_ascii_lowercase())
        && !s.ends_with('-')
        && s.chars()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-');
    if ok {
        Ok(())
    } else {
        Err(Error::invalid(format!(
            "app name {s:?}: up to 30 characters of [a-z0-9-], starting with a letter"
        )))
    }
}

/// `NAME:/path[:ro|rw]`: a named volume.
pub(crate) fn parse_volume(v: &str) -> Result<(String, String, Option<String>)> {
    let mut parts = v.splitn(3, ':');
    let name = parts.next().unwrap_or("");
    let target = parts.next().unwrap_or("");
    let opts = parts.next().map(String::from);
    let name_ok = !name.is_empty()
        && name.len() <= 30
        && name.starts_with(|c: char| c.is_ascii_lowercase() || c.is_ascii_digit())
        && name
            .chars()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-');
    if !name_ok {
        return Err(Error::invalid(format!(
            "volume {v:?}: NAME:/path with NAME of [a-z0-9-] (apps take named volumes only, never host paths)"
        )));
    }
    if !target.starts_with('/') {
        return Err(Error::invalid(format!(
            "volume {v:?}: the target must be an absolute path"
        )));
    }
    if let Some(o) = &opts {
        if !matches!(o.as_str(), "ro" | "rw") {
            return Err(Error::invalid(format!(
                "volume {v:?}: options are ro or rw"
            )));
        }
    }
    Ok((name.to_string(), target.to_string(), opts))
}

/// One app rendered for its stack: the service plus the top-level secrets
/// and volumes it uses. Stored with every deployment, so a rollback puts
/// back exactly what ran.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Rendered {
    pub service: SandboxSpec,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub secrets: BTreeMap<String, SecretDef>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub volumes: BTreeMap<String, NamedVolumeSpec>,
}

/// The top-level secret key an app's env reference renders to.
fn secret_key(app: &str, name: &str) -> String {
    format!("{app}.{name}")
}

fn volume_key(app: &str, name: &str) -> String {
    format!("{app}_{name}")
}

/// Whether the compose parser takes a service's `domains:` (the ingress
/// adds it). Until it does, an app's domains stay in the app record and
/// out of the rendered service.
pub fn compose_takes_domains() -> bool {
    serde_json::from_value::<SandboxSpec>(json!({"image": "x", "domains": []})).is_ok()
}

/// Render `spec` running `image` as its stack service. `notes` gets what
/// was left out and why.
#[expect(
    clippy::too_many_lines,
    reason = "predates the lint ratchet; split it when next changed"
)]
pub fn render(spec: &AppSpec, image: &str, notes: &mut Vec<String>) -> Result<Rendered> {
    let effective;
    let spec = match &spec.source {
        Source::Database(db) => {
            effective = database::effective(spec, db);
            &effective
        }
        _ => spec,
    };
    let mut environment = serde_json::Map::new();
    let mut secrets = BTreeMap::new();
    for (k, v) in spec.env.vars() {
        match v {
            EnvValue::Plain(s) => {
                environment.insert(k.to_string(), json!(s));
            }
            EnvValue::Secret { secret } => {
                let key = secret_key(&spec.name, secret);
                environment.insert(k.to_string(), json!({"secret": key}));
                secrets.insert(
                    key,
                    SecretDef {
                        external: true,
                        name: Some(secret.clone()),
                        on_change: spec.secret_on_change,
                        ..Default::default()
                    },
                );
            }
        }
    }
    // A database's passwords take effect inside it before its replicas
    // get them; its engine reads them only when the data is first made.
    if let Source::Database(db) = &spec.source {
        let mut rotate = |name: String, root: bool| {
            if let Some(d) = secrets.get_mut(&secret_key(&spec.name, &name)) {
                d.rotate = Some(db.engine.rotate_command(root));
            }
        };
        rotate(database::password_secret(&spec.name), false);
        if db.engine.has_root_password() {
            rotate(database::root_password_secret(&spec.name), true);
        }
    }
    let mut volumes = BTreeMap::new();
    let mut mounts = Vec::new();
    for v in &spec.volumes {
        let (name, target, opts) = parse_volume(v)?;
        let key = volume_key(&spec.name, &name);
        mounts.push(match opts {
            Some(o) => format!("{key}:{target}:{o}"),
            None => format!("{key}:{target}"),
        });
        volumes.insert(key, NamedVolumeSpec::default());
    }
    let mut labels = serde_json::Map::new();
    labels.insert(LABEL_APP.into(), json!(spec.name));
    // A shared volume and two live replicas of a database do not mix:
    // apps with volumes replace stop-first, the rest start-first.
    let order = if spec.volumes.is_empty() {
        "start-first"
    } else {
        "stop-first"
    };
    let mut svc = json!({
        "image": image,
        "labels": labels,
        "deploy": {"replicas": spec.replicas, "update_config": {"order": order}},
    });
    if !environment.is_empty() {
        svc["environment"] = Value::Object(environment);
    }
    if !mounts.is_empty() {
        svc["volumes"] = json!(mounts);
    }
    if !spec.ports.is_empty() {
        svc["ports"] = json!(spec.ports);
    }
    if let Some(c) = &spec.command {
        svc["command"] = c.clone();
    }
    if let Some(h) = &spec.healthcheck {
        svc["healthcheck"] = h.clone();
    }
    if !spec.files.is_empty() {
        let mut refs = Vec::new();
        for f in &spec.files {
            let key = secret_key(&spec.name, &f.secret);
            let mut r = json!({"source": key, "target": f.path});
            if let Some(m) = &f.mode {
                r["mode"] = json!(m);
            }
            refs.push(r);
            secrets.insert(
                key,
                SecretDef {
                    external: true,
                    name: Some(f.secret.clone()),
                    on_change: spec.secret_on_change,
                    ..Default::default()
                },
            );
        }
        svc["secrets"] = json!(refs);
    }
    if let Some(u) = &spec.user {
        svc["user"] = json!(u);
    }
    if let Some(w) = &spec.working_dir {
        svc["working_dir"] = json!(w);
    }
    if let Some(r) = &spec.resources {
        if let Some(c) = &r.cpus {
            svc["cpus"] = json!(c);
        }
        if let Some(m) = &r.memory {
            svc["mem_limit"] = json!(m);
        }
    }
    let parse = |v: Value| {
        serde_json::from_value::<SandboxSpec>(v)
            .map_err(|e| Error::invalid(format!("app {}: {e}", spec.name)))
    };
    let service = if spec.domains.is_empty() {
        parse(svc)?
    } else {
        let domains: Vec<Value> = spec
            .domains
            .iter()
            .map(|d| {
                let mut d = d.clone();
                if let (false, Some(p)) = (d.contains_key("port"), spec.port) {
                    d.insert("port".into(), json!(p));
                }
                Value::Object(d)
            })
            .collect();
        let mut with = svc.clone();
        with["domains"] = json!(domains);
        if compose_takes_domains() {
            parse(with)?
        } else {
            notes.push(format!(
                "domains ({}) are kept with the app; this isb has no ingress to serve them yet",
                spec.domains
                    .iter()
                    .filter_map(|d| d.get("host").and_then(Value::as_str))
                    .collect::<Vec<_>>()
                    .join(", ")
            ));
            parse(svc)?
        }
    };
    Ok(Rendered {
        service,
        secrets,
        volumes,
    })
}

/// The stack file with `app`'s service replaced by `r` (or removed, with
/// `None`), the rest untouched, and top-level secrets and volumes no
/// service uses any more dropped.
pub fn splice(
    current: Option<&crate::spec::ComposeFile>,
    stack: &str,
    app: &str,
    r: Option<&Rendered>,
) -> crate::spec::ComposeFile {
    let mut f = current.cloned().unwrap_or_default();
    f.name = Some(stack.to_string());
    f.services.remove(app);
    if let Some(r) = r {
        f.services.insert(app.to_string(), r.service.clone());
        for (k, v) in &r.secrets {
            f.secrets.insert(k.clone(), v.clone());
        }
        for (k, v) in &r.volumes {
            f.volumes.insert(k.clone(), v.clone());
        }
    }
    let used_secrets = crate::stack::secrets::used_keys(&f);
    f.secrets.retain(|k, _| used_secrets.contains(k));
    let used_volumes: std::collections::BTreeSet<String> = f
        .services
        .values()
        .flat_map(|s| s.volumes.iter().map(|v| v.source.clone()))
        .collect();
    f.volumes.retain(|k, _| used_volumes.contains(k));
    f
}

/// Merge `patch` into `base` (RFC 7396): `null` removes a key.
pub fn merge_patch(base: &mut Value, patch: &Value) {
    match (base, patch) {
        (Value::Object(b), Value::Object(p)) => {
            for (k, v) in p {
                if v.is_null() {
                    b.remove(k);
                } else {
                    merge_patch(b.entry(k.clone()).or_insert(Value::Null), v);
                }
            }
        }
        (b, p) => *b = p.clone(),
    }
}

/// The OCI reference `image` pinned to `digest`
/// (`docker:traefik/whoami:v1` -> `docker:traefik/whoami@sha256:...`), or
/// `None` for an image that is not from an OCI registry.
pub fn pin(image: &str, digest: &str) -> Option<String> {
    let (prefix, rest) = image.split_once(':')?;
    if !matches!(prefix, "docker" | "ghcr" | "quay" | "oci") || !digest.starts_with("sha256:") {
        return None;
    }
    let rest = rest.split('@').next().unwrap_or(rest);
    let (dir, last) = match rest.rsplit_once('/') {
        Some((d, l)) => (Some(d), l),
        None => (None, rest),
    };
    let last = last.split(':').next().unwrap_or(last);
    Some(match dir {
        Some(d) => format!("{prefix}:{d}/{last}@{digest}"),
        None => format!("{prefix}:{last}@{digest}"),
    })
}

/// Atomic write (temp file, fsync, rename), 0600.
#[doc(hidden)]
pub fn write_atomic(path: &Path, data: &[u8]) -> Result<()> {
    use std::io::Write;
    use std::os::unix::fs::OpenOptionsExt;
    if let Some(d) = path.parent() {
        std::fs::create_dir_all(d)?;
    }
    let tmp = path.with_extension(format!("tmp-{}", git::random_hex(4)));
    let mut f = std::fs::OpenOptions::new()
        .write(true)
        .create(true)
        .truncate(true)
        .mode(0o600)
        .open(&tmp)?;
    f.write_all(data)?;
    f.sync_all()?;
    std::fs::rename(&tmp, path)?;
    Ok(())
}

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

    /// Tools take JSON; YAML here is only for brevity.
    fn spec(y: &str) -> AppSpec {
        try_spec(y).unwrap()
    }

    fn try_spec(y: &str) -> std::result::Result<AppSpec, serde_json::Error> {
        serde_json::from_value(serde_yaml_ng::from_str::<Value>(y).unwrap())
    }

    #[test]
    fn spec_forms_and_validation() {
        let a = spec(
            "name: web\nproject: shop\nsource: {image: 'docker:traefik/whoami'}\nenv: {A: '1', T: {secret: tok}}\n",
        );
        assert_eq!(a.environment, "production");
        assert_eq!(a.replicas, 1);
        assert_eq!(a.stack().unwrap(), "shop-production");
        a.validate().unwrap();
        let g = spec(
            "name: api\nproject: shop\nsource: {git: {url: 'https://h/o/r', ref: dev}}\nbuild: {builder: {type: railpack}}\n",
        );
        g.validate().unwrap();
        assert!(g.build.as_ref().unwrap().untrusted);
        let mut bad = g.clone();
        bad.build = None;
        assert!(bad.validate().is_err());
        let mut bad = a.clone();
        bad.volumes = vec!["/etc:/x".into()];
        assert!(bad.validate().is_err());
        bad.volumes = vec!["data:/var/lib/x".into()];
        bad.validate().unwrap();
        bad.domains = vec![serde_json::from_str(r#"{"host":"a.example.com"}"#).unwrap()];
        assert!(bad.validate().is_err(), "a domain needs a port");
        bad.port = Some(80);
        bad.validate().unwrap();
        let mut bad = a.clone();
        bad.project = "a-very-long-project-name".into();
        bad.environment = "staging-environment".into();
        assert!(bad.validate().is_err());
        assert!(try_spec("name: x\nproject: p\nsource: {image: x}\nbogus: 1\n").is_err());
        assert!(try_spec("name: x\nproject: p\nsource: {image: x, git: {url: u}}\n").is_err());
    }

    #[test]
    fn long_names_validate_and_resources_take_numbers() {
        // `<stack>-<app>-<slot>-<id>` is 70 characters: shortened, not refused.
        let a = spec(
            "name: project-management-postgres\nproject: project-management\nsource: {image: x}\n",
        );
        a.validate().unwrap();
        let r = spec(
            "name: x\nproject: p\nsource: {image: x}\nresources: {cpus: 2, memory: 536870912}\n",
        )
        .resources
        .unwrap();
        assert_eq!(
            (r.cpus.as_deref(), r.memory.as_deref()),
            (Some("2"), Some("536870912"))
        );
        // Strings are kept exactly, so stored specs serialize as before.
        let s =
            spec("name: x\nproject: p\nsource: {image: x}\nresources: {cpus: '2', memory: 1g}\n");
        assert_eq!(
            serde_json::to_value(&s.resources).unwrap(),
            serde_json::json!({"cpus": "2", "memory": "1g"})
        );
        let n =
            spec("name: x\nproject: p\nsource: {image: x}\nresources: {cpus: null, memory: 1g}\n");
        assert_eq!(n.resources.unwrap().cpus, None);
        assert!(
            try_spec("name: x\nproject: p\nsource: {image: x}\nresources: {cpus: 1.5}\n").is_err()
        );
    }

    #[test]
    fn renders_one_service() {
        let a = spec(concat!(
            "name: web\nproject: shop\nsource: {image: 'docker:traefik/whoami'}\n",
            "env: \"# c\\nA=1\\nT=${{secret.tok}}\\n\"\n",
            "volumes: ['data:/data']\nports: ['127.0.0.1:18080:80']\nreplicas: 2\nport: 80\n",
            "command: [/whoami, --port, '80']\n",
            "healthcheck: {test: [CMD, /whoami, --help], interval: 5s}\n",
            "resources: {cpus: '1', memory: 256m}\n",
        ));
        let mut notes = vec![];
        let r = render(&a, "docker:traefik/whoami@sha256:ab", &mut notes).unwrap();
        let s = &r.service;
        assert_eq!(s.image, "docker:traefik/whoami@sha256:ab");
        assert_eq!(s.env["A"], "1");
        assert_eq!(s.env.secrets["T"], "web.tok");
        assert_eq!(r.secrets["web.tok"].name.as_deref(), Some("tok"));
        assert!(r.secrets["web.tok"].external);
        assert_eq!(s.volumes[0].source, "web_data");
        assert!(r.volumes.contains_key("web_data"));
        assert_eq!(s.replicas(), 2);
        assert_eq!(s.labels[LABEL_APP], "web");
        assert_eq!(s.cpus.as_deref(), Some("1"));
        assert_eq!(s.memory.as_deref(), Some("256m"));
        assert!(s.healthcheck.is_some());
        assert_eq!(s.ports.len(), 1);
        assert!(notes.is_empty());
    }

    #[test]
    fn secret_on_change_reaches_every_secret_the_app_uses() {
        let base = concat!(
            "name: web\nproject: shop\nsource: {image: 'docker:traefik/whoami'}\n",
            "env: \"T=${{secret.tok}}\\n\"\nfiles: [{path: /etc/app.conf, secret: conf}]\n",
        );
        let r = render(&spec(base), "x", &mut vec![]).unwrap();
        assert!(r.secrets.values().all(|d| d.on_change.is_none()));
        let a = spec(&format!("{base}secret_on_change: restart\n"));
        let r = render(&a, "x", &mut vec![]).unwrap();
        assert_eq!(r.secrets.len(), 2);
        assert!(
            r.secrets
                .values()
                .all(|d| d.on_change == Some(crate::spec::OnChange::Restart))
        );
        assert!(try_spec(&format!("{base}secret_on_change: sometimes\n")).is_err());
    }

    #[test]
    fn domains_follow_the_parser() {
        let mut a = spec("name: web\nproject: shop\nsource: {image: x}\nport: 8080\n");
        a.domains = vec![serde_json::from_str(r#"{"host":"shop.example.com"}"#).unwrap()];
        let mut notes = vec![];
        let r = render(&a, "x", &mut notes).unwrap();
        if compose_takes_domains() {
            let v = serde_json::to_value(&r.service).unwrap();
            assert_eq!(v["domains"][0]["port"], 8080);
            assert!(notes.is_empty());
        } else {
            assert_eq!(notes.len(), 1, "{notes:?}");
        }
    }

    #[test]
    fn splice_touches_only_the_app() {
        let mut notes = vec![];
        let web = spec(
            "name: web\nproject: shop\nsource: {image: x}\nenv: {T: {secret: tok}}\nvolumes: ['d:/d']\n",
        );
        let api = spec("name: api\nproject: shop\nsource: {image: y}\nenv: {T: {secret: tok}}\n");
        let rw = render(&web, "x", &mut notes).unwrap();
        let ra = render(&api, "y", &mut notes).unwrap();
        let f1 = splice(None, "shop-production", "web", Some(&rw));
        let f2 = splice(Some(&f1), "shop-production", "api", Some(&ra));
        assert_eq!(f2.services.len(), 2);
        assert_eq!(f2.services["web"], f1.services["web"]);
        assert_eq!(
            f2.secrets.keys().collect::<Vec<_>>(),
            ["api.tok", "web.tok"]
        );
        // The revision of the app not deployed stays the same.
        let def = |f: &crate::spec::ComposeFile| crate::stack::StackDef {
            source: None,
            domains: Default::default(),
            name: "shop-production".into(),
            org: OrgId::default_org(),
            file: f.clone(),
            base_dir: "/".into(),
            secrets: Default::default(),
            force: Default::default(),
            images: Default::default(),
            deployed_at: 0,
            deployed_by: String::new(),
            previous: None,
        };
        let mut web2 = web.clone();
        web2.env.set("B", EnvValue::Plain("2".into()));
        let rw2 = render(&web2, "x", &mut notes).unwrap();
        let f3 = splice(Some(&f2), "shop-production", "web", Some(&rw2));
        assert_eq!(
            def(&f2).revision("api").unwrap(),
            def(&f3).revision("api").unwrap()
        );
        assert_ne!(
            def(&f2).revision("web").unwrap(),
            def(&f3).revision("web").unwrap()
        );
        // Removing web drops its secret key and volume, keeps api's.
        let f4 = splice(Some(&f3), "shop-production", "web", None);
        assert_eq!(f4.services.keys().collect::<Vec<_>>(), ["api"]);
        assert_eq!(f4.secrets.keys().collect::<Vec<_>>(), ["api.tok"]);
        assert!(f4.volumes.is_empty());
    }

    #[test]
    fn pins_digests() {
        let d = "sha256:abc";
        assert_eq!(
            pin("docker:traefik/whoami", d).unwrap(),
            "docker:traefik/whoami@sha256:abc"
        );
        assert_eq!(
            pin("docker:nginx:1.27", d).unwrap(),
            "docker:nginx@sha256:abc"
        );
        assert_eq!(
            pin("oci:reg.example.com:5000/team/app:v2", d).unwrap(),
            "oci:reg.example.com:5000/team/app@sha256:abc"
        );
        assert_eq!(
            pin("ghcr:o/a@sha256:old", d).unwrap(),
            "ghcr:o/a@sha256:abc"
        );
        assert!(pin("dev-base", d).is_none());
        assert!(pin("images:debian/12", d).is_none());
    }

    #[test]
    fn merge_patch_rfc7396() {
        let mut b = json!({"a": 1, "b": {"c": 2, "d": 3}});
        merge_patch(&mut b, &json!({"a": null, "b": {"c": 9}, "e": [1]}));
        assert_eq!(b, json!({"b": {"c": 9, "d": 3}, "e": [1]}));
    }
}