docker-compose-config 0.1.0

Rust representations for types belonging to docker compose's configuration. Supports (de)serialization, JSON schema and merging
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
use core::fmt;
use indexmap::{IndexMap, IndexSet};
use merge_it::*;
#[cfg(feature = "schemars")]
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::cmp::Ordering;
use std::collections::{BTreeMap, BTreeSet};

type StringBTreeMap = BTreeMap<String, String>;

mod service;
pub use service::*;

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(untagged)]
pub enum StringOrNum {
	String(String),
	Num(i64),
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, PartialOrd)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(untagged)]
pub enum SingleValue {
	String(String),
	Bool(bool),
	Int(i64),
	Float(f64),
}

impl fmt::Display for SingleValue {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		match self {
			Self::String(s) => f.write_str(s),
			Self::Bool(b) => write!(f, "{b}"),
			Self::Int(i) => write!(f, "{i}"),
			Self::Float(fl) => write!(f, "{fl}"),
		}
	}
}

#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, PartialOrd, Ord)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(untagged)]
pub enum ListOrMap {
	List(BTreeSet<String>),
	Map(BTreeMap<String, String>),
}

impl ListOrMap {
	pub fn contains(&self, key: &str) -> bool {
		match self {
			Self::List(list) => list.contains(key),
			Self::Map(map) => map.contains_key(key),
		}
	}

	pub fn get(&self, key: &str) -> Option<&String> {
		match self {
			Self::List(list) => list.get(key),
			Self::Map(map) => map.get(key),
		}
	}

	pub fn is_empty(&self) -> bool {
		match self {
			Self::List(btree_set) => btree_set.is_empty(),
			Self::Map(btree_map) => btree_map.is_empty(),
		}
	}
}

impl Default for ListOrMap {
	fn default() -> Self {
		Self::List(Default::default())
	}
}

impl Merge for ListOrMap {
	fn merge(&mut self, other: Self) {
		match self {
			Self::List(left_list) => match other {
				Self::List(other_list) => {
					left_list.extend(other_list);
				}
				Self::Map(other_map) => {
					if left_list.is_empty() || !other_map.is_empty() {
						*self = Self::Map(other_map);
					}
				}
			},
			Self::Map(left_map) => match other {
				Self::List(other_list) => {
					if left_map.is_empty() || !other_list.is_empty() {
						*self = Self::List(other_list);
					}
				}
				Self::Map(other_map) => {
					left_map.extend(other_map);
				}
			},
		}
	}
}

#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, PartialOrd, Ord)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(untagged)]
pub enum StringOrList {
	String(String),
	List(Vec<String>),
}

#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, PartialOrd, Ord)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(untagged)]
pub enum StringOrSortedList {
	String(String),
	List(BTreeSet<String>),
}

impl StringOrSortedList {
	pub fn is_empty(&self) -> bool {
		match self {
			Self::String(str) => str.is_empty(),
			Self::List(list) => list.is_empty(),
		}
	}
}

impl Default for StringOrSortedList {
	fn default() -> Self {
		Self::List(Default::default())
	}
}

impl Merge for StringOrSortedList {
	fn merge(&mut self, right: Self) {
		match self {
			Self::String(left_string) => {
				match right {
					Self::List(mut right_list) => {
						let left_string = std::mem::take(left_string);

						right_list.insert(left_string);

						*self = Self::List(right_list);
					}
					Self::String(right_string) => {
						if left_string.is_empty() || !right_string.is_empty() {
							*left_string = right_string;
						}
					}
				};
			}
			Self::List(left_list) => match right {
				Self::String(right_string) => {
					left_list.insert(right_string);
				}
				Self::List(right_list) => {
					left_list.extend(right_list);
				}
			},
		}
	}
}

/// Configuration settings for a Docker Compose file.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Default, Merge)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(default)]
pub struct ComposeFile {
	/// The top-level name property is defined by the Compose Specification as the project name to be used if you don't set one explicitly.
	///
	/// See more: https://docs.docker.com/reference/compose-file/version-and-name/#name-top-level-element
	#[serde(skip_serializing_if = "Option::is_none")]
	pub name: Option<String>,

	/// Requires: Docker Compose 2.20.0 and later
	///
	/// The include top-level section is used to define the dependency on another Compose application, or sub-domain. Each path listed in the include section is loaded as an individual Compose application model, with its own project directory, in order to resolve relative paths.
	///
	/// See more: https://docs.docker.com/reference/compose-file/include/
	#[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
	pub include: BTreeSet<Include>,

	/// Defines the services for the Compose application.
	///
	/// See more: https://docs.docker.com/reference/compose-file/services/
	#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
	#[cfg(feature = "presets")]
	pub services: BTreeMap<String, ServicePresetRef>,
	#[cfg(not(feature = "presets"))]
	pub services: BTreeMap<String, Service>,

	/// Defines or references configuration data that is granted to services in your Compose application.
	///
	/// See more: https://docs.docker.com/reference/compose-file/configs/
	#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
	pub configs: BTreeMap<String, TopLevelConfig>,

	/// The top-level models section declares AI models that are used by your Compose application. These models are typically pulled as OCI artifacts, run by a model runner, and exposed as an API that your service containers can consume.
	///
	/// See more: https://docs.docker.com/reference/compose-file/models/
	#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
	pub models: BTreeMap<String, TopLevelModel>,

	/// The named networks for the Compose application.
	///
	/// See more: https://docs.docker.com/reference/compose-file/networks/
	#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
	pub networks: BTreeMap<String, TopLevelNetwork>,

	/// The named secrets for the Compose application.
	///
	/// See more: https://docs.docker.com/reference/compose-file/secrets/
	#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
	pub secrets: BTreeMap<String, TopLevelSecret>,

	/// The named volumes for the Compose application.
	///
	/// See more: https://docs.docker.com/reference/compose-file/volumes/
	#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
	pub volumes: BTreeMap<String, TopLevelVolume>,

	#[serde(flatten, skip_serializing_if = "BTreeMap::is_empty")]
	pub extensions: BTreeMap<String, Value>,
}

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

/// Compose application or sub-projects to be included.
///
/// See more: https://docs.docker.com/reference/compose-file/include/#long-syntax
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default, Eq)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
#[serde(default)]
pub struct IncludeSettings {
	/// Defines the location of the Compose file(s) to be parsed and included into the local Compose model.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub path: Option<StringOrSortedList>,

	/// Defines a base path to resolve relative paths set in the Compose file. It defaults to the directory of the included Compose file.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub project_directory: Option<String>,

	/// Defines an environment file(s) to use to define default values when interpolating variables in the Compose file being parsed. It defaults to .env file in the project_directory for the Compose file being parsed.
	///
	/// See more: https://docs.docker.com/reference/compose-file/include/#env_file
	#[serde(skip_serializing_if = "Option::is_none")]
	pub env_file: Option<StringOrList>,
}

impl PartialOrd for IncludeSettings {
	fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
		Some(self.cmp(other))
	}
}

impl Ord for IncludeSettings {
	fn cmp(&self, other: &Self) -> Ordering {
		self.path.cmp(&other.path)
	}
}

#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, PartialOrd, Ord, Eq)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(untagged)]
pub enum Include {
	Short(String),
	Long(IncludeSettings),
}

impl Default for Include {
	fn default() -> Self {
		Self::Short(Default::default())
	}
}

#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(untagged)]
pub enum Ulimit {
	Single(StringOrNum),
	SoftHard {
		soft: StringOrNum,
		hard: StringOrNum,
	},
}

/// Network configuration for the Compose application.
///
/// See more: https://docs.docker.com/reference/compose-file/networks/
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct TopLevelNetwork {
	/// If set to true, it specifies that this network’s lifecycle is maintained outside of that of the application. Compose doesn't attempt to create these networks, and returns an error if one doesn't exist.
	///
	/// See more: https://docs.docker.com/reference/compose-file/networks/#external
	#[serde(skip_serializing_if = "Option::is_none")]
	pub external: Option<bool>,
	/// Custom name for this network.
	///
	/// See more: https://docs.docker.com/reference/compose-file/networks/#name

	#[serde(skip_serializing_if = "Option::is_none")]
	#[serde(default)]
	pub name: Option<String>,

	/// By default, Compose provides external connectivity to networks. internal, when set to true, lets you create an externally isolated network.
	#[serde(skip_serializing_if = "Option::is_none")]
	#[serde(default)]
	pub internal: Option<bool>,

	/// Specifies which driver should be used for this network. Compose returns an error if the driver is not available on the platform.
	///
	/// For more information on drivers and available options, see [Network drivers](https://docs.docker.com/engine/network/drivers/).
	#[serde(skip_serializing_if = "Option::is_none")]
	#[serde(default)]
	pub driver: Option<String>,

	/// If `attachable` is set to `true`, then standalone containers should be able to attach to this network, in addition to services. If a standalone container attaches to the network, it can communicate with services and other standalone containers that are also attached to the network.
	#[serde(skip_serializing_if = "Option::is_none")]
	#[serde(default)]
	pub attachable: Option<bool>,

	/// Can be used to disable IPv4 address assignment.
	#[serde(skip_serializing_if = "Option::is_none")]
	#[serde(default)]
	enable_ipv4: Option<bool>,

	/// Enables IPv6 address assignment.
	#[serde(skip_serializing_if = "Option::is_none")]
	#[serde(default)]
	pub enable_ipv6: Option<bool>,

	/// Specifies a custom IPAM configuration.
	///
	/// See more: https://docs.docker.com/reference/compose-file/networks/#ipam
	#[serde(skip_serializing_if = "Option::is_none")]
	#[serde(default)]
	pub ipam: Option<Ipam>,

	/// A list of options as key-value pairs to pass to the driver. These options are driver-dependent.
	///
	/// Consult the [network drivers documentation](https://docs.docker.com/engine/network/) for more information.
	#[serde(skip_serializing_if = "Option::is_none")]
	#[serde(default)]
	pub driver_opts: Option<BTreeMap<String, Option<SingleValue>>>,

	#[serde(skip_serializing_if = "Option::is_none")]
	#[serde(default)]
	pub labels: Option<ListOrMap>,
}

/// Specifies a custom IPAM configuration.
///
/// See more: https://docs.docker.com/reference/compose-file/networks/#ipam
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, Default)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
#[serde(default)]
pub struct Ipam {
	/// Custom IPAM driver, instead of the default.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub driver: Option<String>,

	/// A list with zero or more configuration elements.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub config: Option<BTreeSet<IpamConfig>>,

	/// Driver-specific options as a key-value mapping.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub options: Option<StringBTreeMap>,
}

/// IPAM specific configurations.
///
/// See more: https://docs.docker.com/reference/compose-file/networks/#ipam
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, Default)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
#[serde(default)]
pub struct IpamConfig {
	/// Subnet in CIDR format that represents a network segment
	#[serde(skip_serializing_if = "Option::is_none")]
	pub subnet: Option<String>,

	/// Range of IPs from which to allocate container IPs.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub ip_range: Option<String>,

	/// IPv4 or IPv6 gateway for the master subnet
	#[serde(skip_serializing_if = "Option::is_none")]
	pub gateway: Option<String>,

	/// Auxiliary IPv4 or IPv6 addresses used by Network driver.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub aux_addresses: Option<StringBTreeMap>,
}

impl PartialOrd for IpamConfig {
	fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
		Some(self.cmp(other))
	}
}

impl Ord for IpamConfig {
	fn cmp(&self, other: &Self) -> Ordering {
		self.subnet.cmp(&other.subnet)
	}
}

/// Specifies a service discovery method for external clients connecting to a service. See more: https://docs.docker.com/reference/compose-file/deploy/#endpoint_mode
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "lowercase")]
pub enum EndpointMode {
	/// Assigns the service a virtual IP (VIP) that acts as the front end for clients to reach the service on a network. Platform routes requests between the client and nodes running the service, without client knowledge of how many nodes are participating in the service or their IP addresses or ports.
	Vip,

	/// Platform sets up DNS entries for the service such that a DNS query for the service name returns a list of IP addresses (DNS round-robin), and the client connects directly to one of these.
	Dnsrr,
}

/// Defines the replication model used to run a service or job. See more: https://docs.docker.com/reference/compose-file/deploy/#mode
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "kebab-case")]
pub enum DeployMode {
	/// Ensures exactly one task continuously runs per physical node until stopped.
	Global,

	/// Continuously runs a specified number of tasks across nodes until stopped (default).
	Replicated,

	/// Executes a defined number of tasks until a completion state (exits with code 0)'.
	/// Total tasks are determined by replicas.
	/// Concurrency can be limited using the max-concurrent option (CLI only).
	ReplicatedJob,

	/// Executes one task per physical node with a completion state (exits with code 0).
	/// Automatically runs on new nodes as they are added.
	GlobalJob,
}

/// Compose Deploy Specification https://docs.docker.com/reference/compose-file/deploy
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Default)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
#[serde(default)]
pub struct Deploy {
	/// Specifies a service discovery method for external clients connecting to a service. See more: https://docs.docker.com/reference/compose-file/deploy/#endpoint_mode
	#[serde(skip_serializing_if = "Option::is_none")]
	pub endpoint_mode: Option<EndpointMode>,

	/// Defines the replication model used to run a service or job. See more: https://docs.docker.com/reference/compose-file/deploy/#mode
	#[serde(skip_serializing_if = "Option::is_none")]
	pub mode: Option<DeployMode>,

	/// If the service is replicated (which is the default), replicas specifies the number of containers that should be running at any given time. See more: https://docs.docker.com/reference/compose-file/deploy/#replicas
	#[serde(skip_serializing_if = "Option::is_none")]
	pub replicas: Option<i64>,

	/// Specifies metadata for the service. These labels are only set on the service and not on any containers for the service. This assumes the platform has some native concept of "service" that can match the Compose application model. See more: https://docs.docker.com/reference/compose-file/deploy/#labels
	#[serde(skip_serializing_if = "Option::is_none")]
	pub labels: Option<ListOrMap>,

	/// Configures how the service should be rolled back in case of a failing update. See more: https://docs.docker.com/reference/compose-file/deploy/#rollback_config
	#[serde(skip_serializing_if = "Option::is_none")]
	pub rollback_config: Option<RollbackConfig>,

	/// Configures how the service should be updated. Useful for configuring rolling updates. See more: https://docs.docker.com/reference/compose-file/deploy/#update_config
	#[serde(skip_serializing_if = "Option::is_none")]
	pub update_config: Option<UpdateConfig>,

	/// Configures physical resource constraints for container to run on platform. See more: https://docs.docker.com/reference/compose-file/deploy/#resources
	#[serde(skip_serializing_if = "Option::is_none")]
	pub resources: Option<Resources>,

	/// Configures if and how to restart containers when they exit. If restart_policy is not set, Compose considers the restart field set by the service configuration. See more: https://docs.docker.com/reference/compose-file/deploy/#restart_policy
	#[serde(skip_serializing_if = "Option::is_none")]
	pub restart_policy: Option<RestartPolicy>,

	/// Specifies constraints and preferences for the platform to select a physical node to run service containers. See more: https://docs.docker.com/reference/compose-file/deploy/#placement
	#[serde(skip_serializing_if = "Option::is_none")]
	pub placement: Option<Placement>,
}

/// Resource constraints and reservations for the service.
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, Default)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
#[serde(default)]
pub struct Limits {
	/// Limit for how much of the available CPU resources, as number of cores, a container can use.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub cpus: Option<StringOrNum>,

	/// Limit on the amount of memory a container can allocate (e.g., '1g', '1024m').
	#[serde(skip_serializing_if = "Option::is_none")]
	pub memory: Option<String>,

	/// Maximum number of PIDs available to the container.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub pids: Option<StringOrNum>,
}

/// Resource reservations for the service containers.
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, Default)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(default)]
#[serde(deny_unknown_fields)]
pub struct Reservations {
	/// Reservation for how much of the available CPU resources, as number of cores, a container can use.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub cpus: Option<StringOrNum>,

	/// Reservation on the amount of memory a container can allocate (e.g., '1g', '1024m').
	#[serde(skip_serializing_if = "Option::is_none")]
	pub memory: Option<String>,

	/// User-defined resources to reserve.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub generic_resources: Option<BTreeSet<GenericResource>>,

	/// Device reservations for the container.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub devices: Option<BTreeSet<Device>>,
}

/// User-defined resources for services, allowing services to reserve specialized hardware resources.
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, Default, PartialOrd, Ord)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(default)]
#[serde(deny_unknown_fields)]
pub struct GenericResource {
	/// Specification for discrete (countable) resources.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub discrete_resource_spec: Option<DiscreteResourceSpec>,
}

/// Specification for discrete (countable) resources.
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, Default)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(default)]
#[serde(deny_unknown_fields)]
pub struct DiscreteResourceSpec {
	/// Type of resource (e.g., 'GPU', 'FPGA', 'SSD').
	#[serde(skip_serializing_if = "Option::is_none")]
	pub kind: Option<String>,

	/// Number of resources of this kind to reserve.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub value: Option<StringOrNum>,
}

impl PartialOrd for DiscreteResourceSpec {
	fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
		Some(self.cmp(other))
	}
}

impl Ord for DiscreteResourceSpec {
	fn cmp(&self, other: &Self) -> Ordering {
		self.kind.cmp(&other.kind)
	}
}

/// Device reservations for containers, allowing services to access specific hardware devices.
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct Device {
	/// Device driver to use (e.g., 'nvidia').
	#[serde(skip_serializing_if = "Option::is_none")]
	#[serde(default)]
	pub driver: Option<String>,

	/// Number of devices of this type to reserve.
	#[serde(skip_serializing_if = "Option::is_none")]
	#[serde(default)]
	pub count: Option<StringOrNum>,

	/// List of specific device IDs to reserve.
	#[serde(skip_serializing_if = "Option::is_none")]
	#[serde(default)]
	pub device_ids: Option<BTreeSet<String>>,

	/// List of capabilities the device needs to have (e.g., 'gpu', 'compute', 'utility').
	#[serde(skip_serializing_if = "BTreeSet::is_empty")]
	pub capabilities: BTreeSet<String>,

	/// Driver-specific options for the device.
	#[serde(skip_serializing_if = "Option::is_none")]
	#[serde(default)]
	pub options: Option<ListOrMap>,
}

impl PartialOrd for Device {
	fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
		Some(self.cmp(other))
	}
}

impl Ord for Device {
	fn cmp(&self, other: &Self) -> Ordering {
		self.driver.cmp(&other.driver)
	}
}

/// Specifies constraints and preferences for the platform to select a physical node to run service containers. See more: https://docs.docker.com/reference/compose-file/deploy/#placement
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, Default)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(default)]
#[serde(deny_unknown_fields)]
pub struct Placement {
	/// Defines a required property the platform's node must fulfill to run the service container.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub constraints: Option<BTreeSet<String>>,

	/// Defines a strategy (currently spread is the only supported strategy) to spread tasks evenly over the values of the datacenter node label.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub preferences: Option<BTreeSet<Preferences>>,
}

/// Defines a strategy (currently spread is the only supported strategy) to spread tasks evenly over the values of the datacenter node label.
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, PartialOrd, Ord)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct Preferences {
	pub spread: String,
}

/// Configures physical resource constraints for container to run on platform.
///
/// See more: https://docs.docker.com/reference/compose-file/deploy/#resources
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, Default)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
#[serde(default)]
pub struct Resources {
	/// The platform must prevent the container from allocating more resources.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub limits: Option<Limits>,
	/// The platform must guarantee the container can allocate at least the configured amount.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub reservations: Option<Reservations>,
}

/// The condition that should trigger a restart.
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "kebab-case")]
pub enum RestartPolicyCondition {
	/// Containers are not automatically restarted regardless of the exit status.
	None,

	/// The container is restarted if it exits due to an error, which manifests as a non-zero exit code.
	OnFailure,

	/// (default) Containers are restarted regardless of the exit status.
	Any,
}

/// Configures if and how to restart containers when they exit. If restart_policy is not set, Compose considers the restart field set by the service configuration.
///
/// See more: https://docs.docker.com/reference/compose-file/deploy/#restart_policy
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, Default)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(default)]
#[serde(deny_unknown_fields)]
pub struct RestartPolicy {
	/// The condition that should trigger a restart.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub condition: Option<RestartPolicyCondition>,

	/// How long to wait between restart attempts, specified as a duration. The default is 0, meaning restart attempts can occur immediately.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub delay: Option<String>,

	/// The maximum number of failed restart attempts allowed before giving up. (Default: unlimited retries.) A failed attempt only counts toward max_attempts if the container does not successfully restart within the time defined by window. For example, if max_attempts is set to 2 and the container fails to restart within the window on the first try, Compose continues retrying until two such failed attempts occur, even if that means trying more than twice.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub max_attempts: Option<i64>,

	/// The amount of time to wait after a restart to determine whether it was successful, specified as a duration (default: the result is evaluated immediately after the restart).
	#[serde(skip_serializing_if = "Option::is_none")]
	pub window: Option<String>,
}

/// What to do if an update fails.
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "kebab-case")]
pub enum UpdateFailureAction {
	Continue,
	Rollback,
	Pause,
}

/// What to do if an update fails.
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "kebab-case")]
pub enum RollbackFailureAction {
	Continue,
	Pause,
}

/// What to do if an update fails.
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(rename_all = "kebab-case")]
pub enum OperationsOrder {
	StartFirst,
	StopFirst,
}

/// Configures how the service should be rolled back in case of a failing update.
///
/// See more: https://docs.docker.com/reference/compose-file/deploy/#rollback_config
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Default)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(default)]
#[serde(deny_unknown_fields)]
pub struct RollbackConfig {
	/// The number of containers to rollback at a time.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub parallelism: Option<i64>,
	/// The time to wait between each container group's rollback
	#[serde(skip_serializing_if = "Option::is_none")]
	pub delay: Option<String>,
	/// What to do if a rollback fails. One of continue or pause (default pause)
	#[serde(skip_serializing_if = "Option::is_none")]
	pub failure_action: Option<RollbackFailureAction>,
	/// Duration after each task update to monitor for failure (ns|us|ms|s|m|h) (default 0s).
	#[serde(skip_serializing_if = "Option::is_none")]
	pub monitor: Option<String>,
	/// Failure rate to tolerate during a rollback.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub max_failure_ratio: Option<f64>,

	/// Order of operations during rollbacks. One of stop-first (old task is stopped before starting new one), or start-first (new task is started first, and the running tasks briefly overlap) (default stop-first).
	#[serde(skip_serializing_if = "Option::is_none")]
	pub order: Option<OperationsOrder>,
}

/// Configures how the service should be updated. Useful for configuring rolling updates.
///
/// See more: https://docs.docker.com/reference/compose-file/deploy/#update_config
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Default)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
#[serde(default)]
pub struct UpdateConfig {
	/// The number of containers to update at a time.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub parallelism: Option<i64>,
	/// The time to wait between updating a group of containers.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub delay: Option<String>,
	/// What to do if an update fails. One of continue, rollback, or pause (default: pause).
	#[serde(skip_serializing_if = "Option::is_none")]
	pub failure_action: Option<UpdateFailureAction>,
	/// Duration after each task update to monitor for failure (ns|us|ms|s|m|h) (default 0s).
	#[serde(skip_serializing_if = "Option::is_none")]
	pub monitor: Option<String>,
	/// Failure rate to tolerate during an update.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub max_failure_ratio: Option<f64>,

	/// Order of operations during updates. One of stop-first (old task is stopped before starting new one), or start-first (new task is started first, and the running tasks briefly overlap) (default stop-first).
	#[serde(skip_serializing_if = "Option::is_none")]
	pub order: Option<OperationsOrder>,
}

/// Secret configuration for the Compose application.
///
/// See more: https://docs.docker.com/reference/compose-file/secrets/
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(deny_unknown_fields, rename_all = "snake_case")]
pub enum TopLevelSecret {
	/// Path to a file containing the secret value.
	File(String),
	/// Path to a file containing the secret value.
	Environment(String),
	#[serde(untagged)]
	External {
		/// Specifies that this secret already exists and was created outside of Compose.
		external: bool,
		/// Specifies the name of the external secret.
		name: String,
	},
}

/// Configuration for service configs or secrets, defining how they are mounted in the container.
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, PartialOrd, Ord)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(untagged)]
pub enum ServiceConfigOrSecret {
	/// Name of the config or secret to grant access to.
	String(String),
	/// Detailed configuration for a config or secret.
	Advanced(ServiceConfigOrSecretSettings),
}

impl PartialOrd for ServiceConfigOrSecretSettings {
	fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
		Some(self.cmp(other))
	}
}

impl Ord for ServiceConfigOrSecretSettings {
	fn cmp(&self, other: &Self) -> Ordering {
		self.source.cmp(&other.source)
	}
}

/// Configuration for service configs or secrets, defining how they are mounted in the container.
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct ServiceConfigOrSecretSettings {
	/// Name of the config or secret as defined in the top-level configs or secrets section.
	pub source: String,

	/// Path in the container where the config or secret will be mounted. Defaults to /<source> for configs and /run/secrets/<source> for secrets.
	#[serde(skip_serializing_if = "Option::is_none")]
	#[serde(default)]
	pub target: Option<String>,

	/// UID of the file in the container. Default is 0 (root).
	#[serde(skip_serializing_if = "Option::is_none")]
	#[serde(default)]
	pub uid: Option<String>,

	/// GID of the file in the container. Default is 0 (root).
	#[serde(skip_serializing_if = "Option::is_none")]
	#[serde(default)]
	pub gid: Option<String>,

	/// File permission mode inside the container, in octal. Default is 0444 for configs and 0400 for secrets.
	#[serde(skip_serializing_if = "Option::is_none")]
	#[serde(default)]
	pub mode: Option<StringOrNum>,
}

/// Defines or references configuration data that is granted to services in your Compose application.
///
/// See more: https://docs.docker.com/reference/compose-file/configs/
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Default, Eq)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(default)]
#[serde(deny_unknown_fields)]
pub struct TopLevelConfig {
	/// The name of the config object in the container engine to look up. This field can be used to reference configs that contain special characters. The name is used as is and will not be scoped with the project name.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub name: Option<String>,

	/// If set to true, external specifies that this config has already been created. Compose does not attempt to create it, and if it does not exist, an error occurs.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub external: Option<bool>,

	/// The content is created with the inlined value. Introduced in Docker Compose version 2.23.1.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub content: Option<String>,

	/// The config content is created with the value of an environment variable.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub environment: Option<String>,

	/// The config is created with the contents of the file at the specified path.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub file: Option<String>,
}

/// Adds hostname mappings to the container network interface configuration (/etc/hosts for Linux).
///
/// See more: https://docs.docker.com/reference/compose-file/services/#extra_hosts
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, PartialOrd, Ord)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(untagged)]
pub enum ExtraHosts {
	/// List of host:IP mappings in the format 'hostname:IP'.
	List(BTreeSet<String>),

	/// List mapping hostnames to IP addresses.
	Map(BTreeMap<String, StringOrSortedList>),
}

impl Merge for ExtraHosts {
	fn merge(&mut self, other: Self) {
		if let Self::List(left_list) = self
			&& let Self::List(right_list) = other
		{
			left_list.extend(right_list);
		} else if let Self::Map(left_map) = self
			&& let Self::Map(right_map) = other
		{
			left_map.extend(right_map);
		} else {
			*self = other;
		}
	}
}

/// Language Model for the Compose application.
///
/// See more: https://docs.docker.com/reference/compose-file/models/
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct TopLevelModel {
	/// Language Model to run.
	pub model: String,

	/// Custom name for this model.
	#[serde(skip_serializing_if = "Option::is_none")]
	#[serde(default)]
	pub name: Option<String>,

	/// The context window size for the model.
	#[serde(skip_serializing_if = "Option::is_none")]
	#[serde(default)]
	pub context_size: Option<u64>,

	/// Raw runtime flags to pass to the inference engine.
	#[serde(skip_serializing_if = "Option::is_none")]
	#[serde(default)]
	pub runtime_flags: Option<Vec<String>>,
}

impl PartialOrd for TopLevelModel {
	fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
		Some(self.cmp(other))
	}
}

impl Ord for TopLevelModel {
	fn cmp(&self, other: &Self) -> Ordering {
		self.name
			.cmp(&other.name)
			.then_with(|| self.model.cmp(&other.model))
	}
}

/// Volume configuration for the Compose application.
///
/// See more: https://docs.docker.com/reference/compose-file/volumes/
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct TopLevelVolume {
	/// If set to true, it specifies that this volume already exists on the platform and its lifecycle is managed outside of that of the application.
	///
	/// See more: https://docs.docker.com/reference/compose-file/volumes/#external
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub external: Option<bool>,

	/// Sets a custom name for a volume.
	///
	/// See more: https://docs.docker.com/reference/compose-file/volumes/#name
	#[serde(skip_serializing_if = "Option::is_none")]
	#[serde(default)]
	pub name: Option<String>,

	/// Specifies which volume driver should be used. If the driver is not available, Compose returns an error and doesn't deploy the application.
	#[serde(skip_serializing_if = "Option::is_none")]
	#[serde(default)]
	pub driver: Option<String>,

	/// Specifies a list of options as key-value pairs to pass to the driver for this volume. The options are driver-dependent.
	#[serde(skip_serializing_if = "BTreeMap::is_empty")]
	#[serde(default)]
	pub driver_opts: BTreeMap<String, SingleValue>,

	/// Labels are used to add metadata to volumes. You can use either an array or a dictionary.
	///
	/// It's recommended that you use reverse-DNS notation to prevent your labels from conflicting with those used by other software.
	///
	/// See more: https://docs.docker.com/reference/compose-file/volumes/#labels
	#[serde(skip_serializing_if = "Option::is_none")]
	#[serde(default)]
	pub labels: Option<ListOrMap>,
}