compose-lens 0.1.7

Loss-aware parsing, processing, validation, and rendering of Compose projects
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
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
//! Deterministic construction of new Compose documents from reviewed native values.

use std::{error::Error, fmt};

use crate::{model::ComposeDocument, source::SourceId, syntax::SyntaxDocument};

use super::write_quoted;

/// A generated Compose value is empty or contains a NUL byte.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum GenerationError {
    /// A required value is empty.
    EmptyValue(&'static str),
    /// A value contains a NUL byte and cannot represent native container intent safely.
    ContainsNul(&'static str),
    /// An environment name contains Compose list-form's `=` separator.
    InvalidEnvironmentName,
    /// A short-form component contains its reserved separator.
    InvalidShortComponent(&'static str),
    /// A short bind spelling needed for `SELinux` cannot be encoded unambiguously.
    InvalidSelinuxBind,
    /// A singleton field was configured more than once.
    DuplicateField(&'static str),
    /// A named generated collection contains the same name more than once.
    DuplicateName {
        /// Collection whose name collided.
        kind: &'static str,
        /// Duplicate non-sensitive name.
        name: String,
    },
    /// A generated port used target port zero.
    InvalidPort,
    /// An `SCTP` port selected a host address without a published port.
    UnrepresentableSctpHostIp,
    /// A generated project contains no services.
    MissingService,
    /// `ComposeLens` could not parse its own deterministic generated bytes.
    InternalInvariant(&'static str),
}

impl fmt::Display for GenerationError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyValue(kind) => write!(formatter, "generated {kind} must not be empty"),
            Self::ContainsNul(kind) => write!(formatter, "generated {kind} must not contain a NUL byte"),
            Self::InvalidEnvironmentName => formatter.write_str("generated environment name must not contain `=`"),
            Self::InvalidShortComponent(kind) => {
                write!(formatter, "generated {kind} contains its reserved short-form separator")
            }
            Self::InvalidSelinuxBind => formatter
                .write_str("generated SELinux bind source and target must not contain the short-syntax `:` separator"),
            Self::DuplicateField(field) => write!(formatter, "generated field `{field}` was configured more than once"),
            Self::DuplicateName { kind, name } => {
                write!(formatter, "generated {kind} `{name}` was added more than once")
            }
            Self::InvalidPort => formatter.write_str("generated container target port must be greater than zero"),
            Self::UnrepresentableSctpHostIp => formatter.write_str(
                "generated SCTP port with a host address also requires a published port for Compose short syntax",
            ),
            Self::MissingService => formatter.write_str("generated Compose project requires at least one service"),
            Self::InternalInvariant(stage) => write!(formatter, "generated Compose document failed {stage} validation"),
        }
    }
}

impl Error for GenerationError {}

/// A plain or sensitive string used by generated Compose fields.
#[derive(Clone, Eq, PartialEq)]
pub struct GeneratedString {
    value: String,
    sensitive: bool,
}

impl GeneratedString {
    /// Creates a non-sensitive generated string.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::ContainsNul`] when the value contains a NUL byte.
    pub fn plain(value: impl Into<String>) -> Result<Self, GenerationError> {
        Self::new(value.into(), false)
    }

    /// Creates a sensitive generated string whose debug representation is redacted.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::ContainsNul`] when the value contains a NUL byte.
    pub fn sensitive(value: impl Into<String>) -> Result<Self, GenerationError> {
        Self::new(value.into(), true)
    }

    fn new(value: String, sensitive: bool) -> Result<Self, GenerationError> {
        if value.contains('\0') {
            return Err(GenerationError::ContainsNul("string"));
        }
        Ok(Self { value, sensitive })
    }

    /// Returns the generated value through an explicit access boundary.
    #[must_use]
    pub fn expose(&self) -> &str {
        &self.value
    }

    /// Reports whether debug output must redact this value.
    #[must_use]
    pub const fn is_sensitive(&self) -> bool {
        self.sensitive
    }
}

impl fmt::Debug for GeneratedString {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("GeneratedString")
            .field("value", &if self.sensitive { "<redacted>" } else { &self.value })
            .field("sensitive", &self.sensitive)
            .finish()
    }
}

/// Compose command form selected for a generated service.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum GeneratedCommand {
    /// Execute an exact argument vector without Compose shell parsing.
    Exec(Vec<GeneratedString>),
    /// Execute one Compose shell-form command.
    Shell(GeneratedString),
    /// Explicitly clear the image command.
    Empty,
}

/// One ordered Compose environment entry.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GeneratedEnvironment {
    name: String,
    value: Option<GeneratedString>,
}

impl GeneratedEnvironment {
    /// Creates a literal `NAME=value` entry.
    ///
    /// # Errors
    ///
    /// Rejects an empty/NUL-bearing name or a name containing `=`.
    pub fn literal(name: impl Into<String>, value: GeneratedString) -> Result<Self, GenerationError> {
        Ok(Self {
            name: environment_name(name.into())?,
            value: Some(value),
        })
    }

    /// Creates a host-resolved key-only environment entry.
    ///
    /// # Errors
    ///
    /// Rejects an empty/NUL-bearing name or a name containing `=`.
    pub fn host(name: impl Into<String>) -> Result<Self, GenerationError> {
        Ok(Self {
            name: environment_name(name.into())?,
            value: None,
        })
    }

    /// Returns the environment name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the optional literal value.
    #[must_use]
    pub const fn value(&self) -> Option<&GeneratedString> {
        self.value.as_ref()
    }
}

/// One ordered Compose `extra_hosts` relationship.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GeneratedExtraHost {
    hostname: String,
    address: String,
}

impl GeneratedExtraHost {
    /// Creates a short-form `hostname=address` relationship.
    ///
    /// # Errors
    ///
    /// Rejects empty/NUL-bearing values and the unambiguous short-form separator `=`.
    pub fn new(hostname: impl Into<String>, address: impl Into<String>) -> Result<Self, GenerationError> {
        let hostname = short_component("extra-host hostname", hostname.into(), '=')?;
        let address = short_component("extra-host address", address.into(), '=')?;
        Ok(Self { hostname, address })
    }

    /// Returns the hostname.
    #[must_use]
    pub fn hostname(&self) -> &str {
        &self.hostname
    }

    /// Returns the address or implementation token.
    #[must_use]
    pub fn address(&self) -> &str {
        &self.address
    }
}

/// Transport protocol for one generated published port.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum GeneratedProtocol {
    /// Transmission Control Protocol.
    Tcp,
    /// User Datagram Protocol.
    Udp,
    /// Stream Control Transmission Protocol.
    Sctp,
}

impl GeneratedProtocol {
    const fn as_str(self) -> &'static str {
        match self {
            Self::Tcp => "tcp",
            Self::Udp => "udp",
            Self::Sctp => "sctp",
        }
    }
}

/// One generated Compose port entry with protocol-aware syntax selection.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GeneratedPort {
    target: u16,
    published: Option<u16>,
    host_ip: Option<String>,
    protocol: GeneratedProtocol,
}

impl GeneratedPort {
    /// Creates a generated port without normalizing its declared transport.
    ///
    /// # Errors
    ///
    /// Rejects target port zero, an empty/NUL-bearing host address, and an `SCTP` host address
    /// without a published port. `SCTP` uses Compose short syntax because the specification's
    /// long form only defines `tcp` and `udp` protocols.
    pub fn new(
        target: u16,
        published: Option<u16>,
        host_ip: Option<String>,
        protocol: GeneratedProtocol,
    ) -> Result<Self, GenerationError> {
        if target == 0 {
            return Err(GenerationError::InvalidPort);
        }
        if let Some(host_ip) = host_ip.as_deref() {
            required("port host address", host_ip.to_owned())?;
            if protocol == GeneratedProtocol::Sctp && published.is_none() {
                return Err(GenerationError::UnrepresentableSctpHostIp);
            }
        }
        Ok(Self {
            target,
            published,
            host_ip,
            protocol,
        })
    }

    /// Returns the container port.
    #[must_use]
    pub const fn target(&self) -> u16 {
        self.target
    }

    /// Returns the optional host port.
    #[must_use]
    pub const fn published(&self) -> Option<u16> {
        self.published
    }

    /// Returns the optional host-address spelling.
    #[must_use]
    pub fn host_ip(&self) -> Option<&str> {
        self.host_ip.as_deref()
    }

    /// Returns the transport protocol.
    #[must_use]
    pub const fn protocol(&self) -> GeneratedProtocol {
        self.protocol
    }
}

/// `SELinux` relabel option that requires Compose short bind syntax.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum GeneratedSelinux {
    /// Private unshared relabel (`Z`).
    Private,
    /// Shared relabel (`z`).
    Shared,
}

impl GeneratedSelinux {
    const fn as_str(self) -> &'static str {
        match self {
            Self::Private => "Z",
            Self::Shared => "z",
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
enum GeneratedMountKind {
    Volume {
        source: String,
    },
    Bind {
        source: String,
        selinux: Option<GeneratedSelinux>,
    },
    Anonymous,
}

/// One generated service mount with deliberate short/long syntax selection.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GeneratedMount {
    kind: GeneratedMountKind,
    target: String,
    read_only: bool,
}

impl GeneratedMount {
    /// Creates a long-form named-volume mount.
    ///
    /// # Errors
    ///
    /// Rejects empty or NUL-bearing source and target values.
    pub fn volume(
        source: impl Into<String>,
        target: impl Into<String>,
        read_only: bool,
    ) -> Result<Self, GenerationError> {
        Ok(Self {
            kind: GeneratedMountKind::Volume {
                source: required("volume source", source.into())?,
            },
            target: required("mount target", target.into())?,
            read_only,
        })
    }

    /// Creates a bind mount. `SELinux` relabel intent selects short syntax deliberately.
    ///
    /// # Errors
    ///
    /// Rejects empty/NUL-bearing values. When `selinux` is present, also rejects `:` in source or
    /// target because Compose only honors the relabel option in the short form used here.
    pub fn bind(
        source: impl Into<String>,
        target: impl Into<String>,
        read_only: bool,
        selinux: Option<GeneratedSelinux>,
    ) -> Result<Self, GenerationError> {
        let source = required("bind source", source.into())?;
        let target = required("mount target", target.into())?;
        if selinux.is_some() && (source.contains(':') || target.contains(':')) {
            return Err(GenerationError::InvalidSelinuxBind);
        }
        Ok(Self {
            kind: GeneratedMountKind::Bind { source, selinux },
            target,
            read_only,
        })
    }

    /// Creates a long-form anonymous-volume mount.
    ///
    /// # Errors
    ///
    /// Rejects an empty or NUL-bearing target.
    pub fn anonymous(target: impl Into<String>, read_only: bool) -> Result<Self, GenerationError> {
        Ok(Self {
            kind: GeneratedMountKind::Anonymous,
            target: required("mount target", target.into())?,
            read_only,
        })
    }

    /// Returns the container target path.
    #[must_use]
    pub fn target(&self) -> &str {
        &self.target
    }

    /// Reports whether the mount is read-only.
    #[must_use]
    pub const fn read_only(&self) -> bool {
        self.read_only
    }
}

/// One generated service network attachment and its ordered aliases.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GeneratedNetworkAttachment {
    name: String,
    aliases: Vec<String>,
}

impl GeneratedNetworkAttachment {
    /// Creates an attachment without aliases.
    ///
    /// # Errors
    ///
    /// Rejects an empty or NUL-bearing network name.
    pub fn new(name: impl Into<String>) -> Result<Self, GenerationError> {
        Ok(Self {
            name: required("network name", name.into())?,
            aliases: Vec::new(),
        })
    }

    /// Adds one ordered alias.
    ///
    /// # Errors
    ///
    /// Rejects an empty or NUL-bearing alias.
    pub fn add_alias(&mut self, alias: impl Into<String>) -> Result<(), GenerationError> {
        self.aliases.push(required("network alias", alias.into())?);
        Ok(())
    }

    /// Returns the network name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns aliases in insertion order.
    #[must_use]
    pub fn aliases(&self) -> &[String] {
        &self.aliases
    }
}

/// One top-level network or volume lifecycle definition.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GeneratedResource {
    name: String,
    external: bool,
    custom_name: Option<String>,
}

impl GeneratedResource {
    /// Creates an application-owned resource definition.
    ///
    /// # Errors
    ///
    /// Rejects an empty or NUL-bearing name.
    pub fn application(name: impl Into<String>) -> Result<Self, GenerationError> {
        Ok(Self {
            name: required("resource name", name.into())?,
            external: false,
            custom_name: None,
        })
    }

    /// Creates an externally managed resource definition.
    ///
    /// # Errors
    ///
    /// Rejects an empty or NUL-bearing name.
    pub fn external(name: impl Into<String>) -> Result<Self, GenerationError> {
        Ok(Self {
            name: required("resource name", name.into())?,
            external: true,
            custom_name: None,
        })
    }

    /// Sets the exact platform-level resource name once.
    ///
    /// This prevents Compose project scoping from changing a reviewed runtime resource name.
    ///
    /// # Errors
    ///
    /// Rejects an empty/NUL-bearing name and duplicate configuration.
    pub fn set_custom_name(&mut self, name: impl Into<String>) -> Result<(), GenerationError> {
        let name = required("custom resource name", name.into())?;
        set_once(&mut self.custom_name, name, "resource name")
    }

    /// Returns the resource name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Reports whether Compose should reuse an external resource.
    #[must_use]
    pub const fn is_external(&self) -> bool {
        self.external
    }

    /// Returns the optional exact platform-level resource name.
    #[must_use]
    pub fn custom_name(&self) -> Option<&str> {
        self.custom_name.as_deref()
    }
}

/// A typed generated Compose service definition.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GeneratedService {
    name: String,
    image: Option<GeneratedString>,
    command: Option<GeneratedCommand>,
    environment: Vec<GeneratedEnvironment>,
    user: Option<GeneratedString>,
    userns_mode: Option<GeneratedString>,
    group_add: Vec<GeneratedString>,
    working_dir: Option<GeneratedString>,
    read_only: Option<bool>,
    extra_hosts: Vec<GeneratedExtraHost>,
    ports: Vec<GeneratedPort>,
    mounts: Vec<GeneratedMount>,
    networks: Vec<GeneratedNetworkAttachment>,
}

impl GeneratedService {
    /// Creates an empty service with a validated name.
    ///
    /// # Errors
    ///
    /// Rejects an empty or NUL-bearing name.
    pub fn new(name: impl Into<String>) -> Result<Self, GenerationError> {
        Ok(Self {
            name: required("service name", name.into())?,
            image: None,
            command: None,
            environment: Vec::new(),
            user: None,
            userns_mode: None,
            group_add: Vec::new(),
            working_dir: None,
            read_only: None,
            extra_hosts: Vec::new(),
            ports: Vec::new(),
            mounts: Vec::new(),
            networks: Vec::new(),
        })
    }

    /// Returns the service name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Sets the service image exactly once.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::EmptyValue`] for an empty image or
    /// [`GenerationError::DuplicateField`] when already configured.
    pub fn set_image(&mut self, image: GeneratedString) -> Result<(), GenerationError> {
        require_generated_string("service image", &image)?;
        set_once(&mut self.image, image, "image")
    }

    /// Sets the Compose command form exactly once.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::DuplicateField`] when already configured.
    pub fn set_command(&mut self, command: GeneratedCommand) -> Result<(), GenerationError> {
        set_once(&mut self.command, command, "command")
    }

    /// Adds one ordered environment entry.
    pub fn add_environment(&mut self, environment: GeneratedEnvironment) {
        self.environment.push(environment);
    }

    /// Sets the combined Compose `user[:group]` value exactly once.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::DuplicateField`] when already configured.
    pub fn set_user(&mut self, user: GeneratedString) -> Result<(), GenerationError> {
        set_once(&mut self.user, user, "user")
    }

    /// Sets the user-namespace mode exactly once.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::EmptyValue`] for an empty mode or
    /// [`GenerationError::DuplicateField`] when already configured.
    pub fn set_userns_mode(&mut self, mode: GeneratedString) -> Result<(), GenerationError> {
        require_generated_string("user namespace mode", &mode)?;
        set_once(&mut self.userns_mode, mode, "userns_mode")
    }

    /// Adds one ordered supplementary group.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::EmptyValue`] for an empty group.
    pub fn add_supplementary_group(&mut self, group: GeneratedString) -> Result<(), GenerationError> {
        require_generated_string("supplementary group", &group)?;
        self.group_add.push(group);
        Ok(())
    }

    /// Sets the container working directory exactly once.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::EmptyValue`] for an empty directory or
    /// [`GenerationError::DuplicateField`] when already configured.
    pub fn set_working_dir(&mut self, directory: GeneratedString) -> Result<(), GenerationError> {
        require_generated_string("working directory", &directory)?;
        set_once(&mut self.working_dir, directory, "working_dir")
    }

    /// Sets the read-only-root choice exactly once.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::DuplicateField`] when already configured.
    pub fn set_read_only(&mut self, read_only: bool) -> Result<(), GenerationError> {
        set_once(&mut self.read_only, read_only, "read_only")
    }

    /// Adds one ordered host mapping.
    pub fn add_extra_host(&mut self, host: GeneratedExtraHost) {
        self.extra_hosts.push(host);
    }

    /// Adds one ordered published-port declaration.
    pub fn add_port(&mut self, port: GeneratedPort) {
        self.ports.push(port);
    }

    /// Adds one ordered mount.
    pub fn add_mount(&mut self, mount: GeneratedMount) {
        self.mounts.push(mount);
    }

    /// Adds one uniquely named network attachment.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::DuplicateName`] when the service already uses the network.
    pub fn add_network(&mut self, network: GeneratedNetworkAttachment) -> Result<(), GenerationError> {
        if self.networks.iter().any(|candidate| candidate.name == network.name) {
            return Err(GenerationError::DuplicateName {
                kind: "service network",
                name: network.name,
            });
        }
        self.networks.push(network);
        Ok(())
    }

    fn is_sensitive(&self) -> bool {
        self.image.as_ref().is_some_and(GeneratedString::is_sensitive)
            || self.command.as_ref().is_some_and(command_is_sensitive)
            || self
                .environment
                .iter()
                .filter_map(GeneratedEnvironment::value)
                .any(GeneratedString::is_sensitive)
            || [self.user.as_ref(), self.userns_mode.as_ref(), self.working_dir.as_ref()]
                .into_iter()
                .flatten()
                .any(GeneratedString::is_sensitive)
            || self.group_add.iter().any(GeneratedString::is_sensitive)
    }
}

/// Builder for one new deterministic Compose document.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct ComposeDocumentBuilder {
    name: Option<String>,
    services: Vec<GeneratedService>,
    networks: Vec<GeneratedResource>,
    volumes: Vec<GeneratedResource>,
}

impl ComposeDocumentBuilder {
    /// Creates an empty generated project.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            name: None,
            services: Vec::new(),
            networks: Vec::new(),
            volumes: Vec::new(),
        }
    }

    /// Sets the optional top-level Compose project name exactly once.
    ///
    /// # Errors
    ///
    /// Rejects empty/NUL-bearing names and duplicate configuration.
    pub fn set_name(&mut self, name: impl Into<String>) -> Result<(), GenerationError> {
        let name = required("project name", name.into())?;
        set_once(&mut self.name, name, "name")
    }

    /// Adds one uniquely named service in output order.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::DuplicateName`] for a duplicate service name.
    pub fn add_service(&mut self, service: GeneratedService) -> Result<(), GenerationError> {
        insert_named(&mut self.services, service, "service", GeneratedService::name)
    }

    /// Adds one uniquely named top-level network in output order.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::DuplicateName`] for a duplicate network name.
    pub fn add_network(&mut self, network: GeneratedResource) -> Result<(), GenerationError> {
        insert_named(&mut self.networks, network, "network", GeneratedResource::name)
    }

    /// Adds one uniquely named top-level volume in output order.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::DuplicateName`] for a duplicate volume name.
    pub fn add_volume(&mut self, volume: GeneratedResource) -> Result<(), GenerationError> {
        insert_named(&mut self.volumes, volume, "volume", GeneratedResource::name)
    }

    /// Generates YAML and parses it back through `ComposeLens`'s syntax and typed-model boundaries.
    ///
    /// # Errors
    ///
    /// Returns [`GenerationError::MissingService`] for an empty project or
    /// [`GenerationError::InternalInvariant`] if `ComposeLens` cannot parse its own output.
    pub fn build(self, source_id: SourceId) -> Result<GeneratedComposeDocument, GenerationError> {
        if self.services.is_empty() {
            return Err(GenerationError::MissingService);
        }
        let sensitive = self.services.iter().any(GeneratedService::is_sensitive);
        let text = render_document(&self);
        let syntax = SyntaxDocument::parse(source_id, text.clone())
            .map_err(|_| GenerationError::InternalInvariant("syntax-tree"))?;
        if !syntax.is_valid() {
            return Err(GenerationError::InternalInvariant("syntax"));
        }
        let model = ComposeDocument::parse(syntax.document());
        if !model.is_valid() {
            return Err(GenerationError::InternalInvariant("typed-model"));
        }
        let document = model
            .document()
            .cloned()
            .ok_or(GenerationError::InternalInvariant("document-root"))?;
        Ok(GeneratedComposeDocument {
            text,
            sensitive,
            document,
        })
    }
}

/// Parse-back-validated deterministic generated Compose document.
#[derive(Clone, Eq, PartialEq)]
pub struct GeneratedComposeDocument {
    text: String,
    sensitive: bool,
    document: ComposeDocument,
}

impl GeneratedComposeDocument {
    /// Returns the deployable generated YAML through an explicit access boundary.
    #[must_use]
    pub fn text(&self) -> &str {
        &self.text
    }

    /// Returns the parse-back-validated native Compose model.
    #[must_use]
    pub const fn document(&self) -> &ComposeDocument {
        &self.document
    }

    /// Reports whether generated output contains a caller-marked sensitive value.
    #[must_use]
    pub const fn is_sensitive(&self) -> bool {
        self.sensitive
    }
}

impl fmt::Debug for GeneratedComposeDocument {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("GeneratedComposeDocument")
            .field("text", &if self.sensitive { "<redacted>" } else { &self.text })
            .field("sensitive", &self.sensitive)
            .field("document", &if self.sensitive { "<redacted>" } else { "validated" })
            .finish()
    }
}

fn render_document(project: &ComposeDocumentBuilder) -> String {
    let mut output = String::new();
    if let Some(name) = &project.name {
        output.push_str("name: ");
        write_quoted(&mut output, name);
        output.push('\n');
    }
    output.push_str("services:\n");
    for service in &project.services {
        write_indent(&mut output, 1);
        write_quoted(&mut output, &service.name);
        output.push_str(":\n");
        render_service(&mut output, service);
    }
    render_resources(&mut output, "networks", &project.networks);
    render_resources(&mut output, "volumes", &project.volumes);
    output
}

fn render_service(output: &mut String, service: &GeneratedService) {
    render_optional_string(output, "image", service.image.as_ref());
    if let Some(command) = &service.command {
        render_command(output, command);
    }
    render_environment(output, &service.environment);
    render_optional_string(output, "user", service.user.as_ref());
    render_optional_string(output, "userns_mode", service.userns_mode.as_ref());
    render_string_sequence(output, "group_add", &service.group_add);
    render_optional_string(output, "working_dir", service.working_dir.as_ref());
    if let Some(read_only) = service.read_only {
        write_field(output, 2, "read_only");
        output.push_str(if read_only { "true\n" } else { "false\n" });
    }
    render_extra_hosts(output, &service.extra_hosts);
    render_ports(output, &service.ports);
    render_mounts(output, &service.mounts);
    render_networks(output, &service.networks);
}

fn render_optional_string(output: &mut String, key: &str, value: Option<&GeneratedString>) {
    if let Some(value) = value {
        write_field(output, 2, key);
        write_quoted(output, value.expose());
        output.push('\n');
    }
}

fn render_command(output: &mut String, command: &GeneratedCommand) {
    match command {
        GeneratedCommand::Exec(arguments) if arguments.is_empty() => output.push_str("    command: []\n"),
        GeneratedCommand::Exec(arguments) => render_string_sequence(output, "command", arguments),
        GeneratedCommand::Shell(command) => render_optional_string(output, "command", Some(command)),
        GeneratedCommand::Empty => output.push_str("    command: []\n"),
    }
}

fn render_environment(output: &mut String, environment: &[GeneratedEnvironment]) {
    if environment.is_empty() {
        return;
    }
    output.push_str("    environment:\n");
    for variable in environment {
        output.push_str("      - ");
        let value = variable.value.as_ref().map_or_else(
            || variable.name.clone(),
            |value| format!("{}={}", variable.name, value.expose()),
        );
        write_quoted(output, &value);
        output.push('\n');
    }
}

fn render_string_sequence(output: &mut String, key: &str, values: &[GeneratedString]) {
    if values.is_empty() {
        return;
    }
    write_indent(output, 2);
    output.push_str(key);
    output.push_str(":\n");
    for value in values {
        output.push_str("      - ");
        write_quoted(output, value.expose());
        output.push('\n');
    }
}

fn render_extra_hosts(output: &mut String, hosts: &[GeneratedExtraHost]) {
    if hosts.is_empty() {
        return;
    }
    output.push_str("    extra_hosts:\n");
    for host in hosts {
        output.push_str("      - ");
        write_quoted(output, &format!("{}={}", host.hostname, host.address));
        output.push('\n');
    }
}

fn render_ports(output: &mut String, ports: &[GeneratedPort]) {
    if ports.is_empty() {
        return;
    }
    output.push_str("    ports:\n");
    for port in ports {
        if port.protocol == GeneratedProtocol::Sctp {
            render_short_sctp_port(output, port);
            continue;
        }
        output.push_str("      - target: ");
        output.push_str(&port.target.to_string());
        output.push('\n');
        if let Some(published) = port.published {
            output.push_str("        published: ");
            write_quoted(output, &published.to_string());
            output.push('\n');
        }
        if let Some(host_ip) = &port.host_ip {
            output.push_str("        host_ip: ");
            write_quoted(output, host_ip);
            output.push('\n');
        }
        output.push_str("        protocol: ");
        write_quoted(output, port.protocol.as_str());
        output.push('\n');
    }
}

fn render_short_sctp_port(output: &mut String, port: &GeneratedPort) {
    let mut value = String::new();
    if let Some(host_ip) = &port.host_ip {
        if host_ip.contains(':') && !(host_ip.starts_with('[') && host_ip.ends_with(']')) {
            value.push('[');
            value.push_str(host_ip);
            value.push(']');
        } else {
            value.push_str(host_ip);
        }
        value.push(':');
    }
    if let Some(published) = port.published {
        value.push_str(&published.to_string());
        value.push(':');
    }
    value.push_str(&port.target.to_string());
    value.push_str("/sctp");

    output.push_str("      - ");
    write_quoted(output, &value);
    output.push('\n');
}

fn render_mounts(output: &mut String, mounts: &[GeneratedMount]) {
    if mounts.is_empty() {
        return;
    }
    output.push_str("    volumes:\n");
    for mount in mounts {
        match &mount.kind {
            GeneratedMountKind::Bind {
                source,
                selinux: Some(selinux),
            } => render_selinux_bind(output, source, mount, *selinux),
            kind => render_long_mount(output, kind, mount),
        }
    }
}

fn render_selinux_bind(output: &mut String, source: &str, mount: &GeneratedMount, selinux: GeneratedSelinux) {
    let mut value = format!("{source}:{}:{}", mount.target, selinux.as_str());
    if mount.read_only {
        value.push_str(",ro");
    }
    output.push_str("      - ");
    write_quoted(output, &value);
    output.push('\n');
}

fn render_long_mount(output: &mut String, kind: &GeneratedMountKind, mount: &GeneratedMount) {
    let (mount_type, source) = match kind {
        GeneratedMountKind::Volume { source } => ("volume", Some(source.as_str())),
        GeneratedMountKind::Bind { source, selinux: None } => ("bind", Some(source.as_str())),
        GeneratedMountKind::Anonymous => ("volume", None),
        GeneratedMountKind::Bind { selinux: Some(_), .. } => return,
    };
    output.push_str("      - type: ");
    write_quoted(output, mount_type);
    output.push('\n');
    if let Some(source) = source {
        output.push_str("        source: ");
        write_quoted(output, source);
        output.push('\n');
    }
    output.push_str("        target: ");
    write_quoted(output, &mount.target);
    output.push('\n');
    if mount.read_only {
        output.push_str("        read_only: true\n");
    }
}

fn render_networks(output: &mut String, networks: &[GeneratedNetworkAttachment]) {
    if networks.is_empty() {
        return;
    }
    output.push_str("    networks:\n");
    for network in networks {
        output.push_str("      ");
        write_quoted(output, &network.name);
        if network.aliases.is_empty() {
            output.push_str(": {}\n");
        } else {
            output.push_str(":\n        aliases:\n");
            for alias in &network.aliases {
                output.push_str("          - ");
                write_quoted(output, alias);
                output.push('\n');
            }
        }
    }
}

fn render_resources(output: &mut String, section: &str, resources: &[GeneratedResource]) {
    if resources.is_empty() {
        return;
    }
    output.push_str(section);
    output.push_str(":\n");
    for resource in resources {
        output.push_str("  ");
        write_quoted(output, &resource.name);
        if !resource.external && resource.custom_name.is_none() {
            output.push_str(": {}\n");
            continue;
        }
        output.push_str(":\n");
        if let Some(custom_name) = &resource.custom_name {
            output.push_str("    name: ");
            write_quoted(output, custom_name);
            output.push('\n');
        }
        if resource.external {
            output.push_str("    external: true\n");
        }
    }
}

fn write_field(output: &mut String, depth: usize, key: &str) {
    write_indent(output, depth);
    output.push_str(key);
    output.push_str(": ");
}

fn write_indent(output: &mut String, depth: usize) {
    for _ in 0..depth {
        output.push_str("  ");
    }
}

fn required(kind: &'static str, value: String) -> Result<String, GenerationError> {
    if value.is_empty() {
        return Err(GenerationError::EmptyValue(kind));
    }
    if value.contains('\0') {
        return Err(GenerationError::ContainsNul(kind));
    }
    Ok(value)
}

fn require_generated_string(kind: &'static str, value: &GeneratedString) -> Result<(), GenerationError> {
    if value.expose().is_empty() {
        return Err(GenerationError::EmptyValue(kind));
    }
    Ok(())
}

fn environment_name(value: String) -> Result<String, GenerationError> {
    let value = required("environment name", value)?;
    if value.contains('=') {
        return Err(GenerationError::InvalidEnvironmentName);
    }
    Ok(value)
}

fn short_component(kind: &'static str, value: String, separator: char) -> Result<String, GenerationError> {
    let value = required(kind, value)?;
    if value.contains(separator) {
        return Err(GenerationError::InvalidShortComponent(kind));
    }
    Ok(value)
}

fn set_once<T>(slot: &mut Option<T>, value: T, field: &'static str) -> Result<(), GenerationError> {
    if slot.is_some() {
        return Err(GenerationError::DuplicateField(field));
    }
    *slot = Some(value);
    Ok(())
}

fn insert_named<T>(
    values: &mut Vec<T>,
    value: T,
    kind: &'static str,
    name: impl Fn(&T) -> &str,
) -> Result<(), GenerationError> {
    let value_name = name(&value);
    if values.iter().any(|candidate| name(candidate) == value_name) {
        return Err(GenerationError::DuplicateName {
            kind,
            name: value_name.to_owned(),
        });
    }
    values.push(value);
    Ok(())
}

fn command_is_sensitive(command: &GeneratedCommand) -> bool {
    match command {
        GeneratedCommand::Exec(arguments) => arguments.iter().any(GeneratedString::is_sensitive),
        GeneratedCommand::Shell(command) => command.is_sensitive(),
        GeneratedCommand::Empty => false,
    }
}