1use std::fmt;
12use std::str::FromStr;
13
14use serde::{Deserialize, Deserializer, Serialize, Serializer};
15use serde_json::{Map, Number, Value};
16
17use crate::did::DidNostr;
18use crate::encoding;
19use crate::pod_path::{ParsePodPathError, PodPath};
20
21pub const MAX_CONTAINERS: usize = 8;
23
24pub const MIN_TIMEOUT_SECS: u64 = 240;
27
28pub const MIN_MEMORY_BYTES: u64 = 6 * 1024 * 1024;
31
32pub const MEMORY_STEP_BYTES: u64 = 4096;
36
37pub const MAX_LABEL_CHARS: usize = 128;
39
40const IMAGE_ID_PREFIX: &str = "sha256:";
42
43const STAND_IN_OWNER: &str = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798";
46
47#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
66pub struct ImageId(String);
67
68impl ImageId {
69 pub fn from_digest(digest: [u8; 32]) -> Self {
71 Self(format!("{IMAGE_ID_PREFIX}{}", hex::encode(digest)))
72 }
73
74 pub fn as_str(&self) -> &str {
76 &self.0
77 }
78
79 pub fn hex(&self) -> &str {
81 &self.0[IMAGE_ID_PREFIX.len()..]
82 }
83}
84
85impl FromStr for ImageId {
86 type Err = ParseImageIdError;
87
88 fn from_str(text: &str) -> Result<Self, Self::Err> {
90 let digits = text
91 .strip_prefix(IMAGE_ID_PREFIX)
92 .ok_or(ParseImageIdError)?;
93 if digits.len() == 64 && encoding::is_lower_hex(digits) {
94 Ok(Self(text.to_owned()))
95 } else {
96 Err(ParseImageIdError)
97 }
98 }
99}
100
101impl fmt::Display for ImageId {
102 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103 f.write_str(&self.0)
104 }
105}
106
107impl fmt::Debug for ImageId {
108 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109 write!(f, "ImageId({})", self.0)
110 }
111}
112
113impl Serialize for ImageId {
114 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
115 serializer.serialize_str(&self.0)
116 }
117}
118
119impl<'de> Deserialize<'de> for ImageId {
120 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
121 let text = String::deserialize(deserializer)?;
122 text.parse().map_err(serde::de::Error::custom)
123 }
124}
125
126#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
136#[error("image id is not sha256: followed by 64 lower-case hex digits")]
137pub struct ParseImageIdError;
138
139#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
163pub struct MilliCpus(u32);
164
165impl MilliCpus {
166 pub const fn new(millicpus: u32) -> Self {
168 Self(millicpus)
169 }
170
171 pub const fn get(self) -> u32 {
173 self.0
174 }
175
176 pub fn cpu_max(self) -> String {
179 format!("{} 100000", u64::from(self.0) * 100)
180 }
181
182 pub fn nano_cpus(self) -> u64 {
184 u64::from(self.0) * 1_000_000
185 }
186
187 fn from_number(number: &Number) -> Result<Self, CpusError> {
189 if let Some(whole) = number.as_u64() {
190 return whole
191 .checked_mul(1000)
192 .and_then(|m| u32::try_from(m).ok())
193 .map(Self)
194 .ok_or(CpusError::TooLarge);
195 }
196 if number.as_i64().is_some() {
197 return Err(CpusError::NotPositive);
198 }
199 let value = number.as_f64().ok_or(CpusError::Precision)?;
200 if value.is_sign_negative() {
201 return Err(CpusError::NotPositive);
202 }
203 let text = value.to_string();
207 let (whole, fraction) = text.split_once('.').unwrap_or((&text, ""));
208 if fraction.len() > 3 {
209 return Err(CpusError::Precision);
210 }
211 let whole: u32 = whole.parse().map_err(|_| CpusError::TooLarge)?;
212 let mut thousandths = 0u32;
213 for (place, digit) in fraction.bytes().enumerate() {
214 let scale = match place {
215 0 => 100,
216 1 => 10,
217 _ => 1,
218 };
219 thousandths += u32::from(digit - b'0') * scale;
220 }
221 whole
222 .checked_mul(1000)
223 .and_then(|m| m.checked_add(thousandths))
224 .map(Self)
225 .ok_or(CpusError::TooLarge)
226 }
227}
228
229#[derive(Debug, Clone, Copy, PartialEq, Eq)]
231enum CpusError {
232 NotPositive,
234 Precision,
236 TooLarge,
238}
239
240impl Serialize for MilliCpus {
241 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
242 let whole = self.0 / 1000;
243 let thousandths = self.0 % 1000;
244 if thousandths == 0 {
245 return serializer.serialize_u32(whole);
246 }
247 serializer.serialize_f64(f64::from(self.0) / 1000.0)
250 }
251}
252
253impl<'de> Deserialize<'de> for MilliCpus {
254 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
255 let number = Number::deserialize(deserializer)?;
256 Self::from_number(&number).map_err(|e| {
257 serde::de::Error::custom(match e {
258 CpusError::NotPositive => "cpus is negative",
259 CpusError::Precision => "cpus has more than three decimal places",
260 CpusError::TooLarge => "cpus is too large",
261 })
262 })
263 }
264}
265
266#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
280#[serde(rename_all = "lowercase")]
281#[non_exhaustive]
282pub enum ManifestProfile {
283 Job,
286}
287
288#[derive(
305 Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
306)]
307#[serde(rename_all = "lowercase")]
308#[non_exhaustive]
309pub enum WorkspaceMode {
310 #[default]
312 None,
313 Read,
315 Write,
317}
318
319impl WorkspaceMode {
320 pub const ALL: [Self; 3] = [Self::None, Self::Read, Self::Write];
322
323 pub fn as_str(self) -> &'static str {
325 match self {
326 Self::None => "none",
327 Self::Read => "read",
328 Self::Write => "write",
329 }
330 }
331}
332
333impl fmt::Display for WorkspaceMode {
334 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
335 f.write_str(self.as_str())
336 }
337}
338
339impl FromStr for WorkspaceMode {
340 type Err = ParseNameError;
341
342 fn from_str(text: &str) -> Result<Self, Self::Err> {
343 Self::ALL
344 .into_iter()
345 .find(|m| m.as_str() == text)
346 .ok_or(ParseNameError)
347 }
348}
349
350#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
368#[non_exhaustive]
369pub enum AclMode {
370 Read,
372 Write,
374}
375
376impl AclMode {
377 pub fn as_str(self) -> &'static str {
379 match self {
380 Self::Read => "Read",
381 Self::Write => "Write",
382 }
383 }
384
385 pub fn iri(self) -> &'static str {
387 match self {
388 Self::Read => "acl:Read",
389 Self::Write => "acl:Write",
390 }
391 }
392}
393
394impl fmt::Display for AclMode {
395 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
396 f.write_str(self.as_str())
397 }
398}
399
400#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
417#[serde(rename_all = "UPPERCASE")]
418#[non_exhaustive]
419pub enum PodMethod {
420 Get,
422 Head,
424 Put,
426 Delete,
428}
429
430impl PodMethod {
431 pub const ALL: [Self; 4] = [Self::Get, Self::Head, Self::Put, Self::Delete];
433
434 pub fn as_str(self) -> &'static str {
436 match self {
437 Self::Get => "GET",
438 Self::Head => "HEAD",
439 Self::Put => "PUT",
440 Self::Delete => "DELETE",
441 }
442 }
443
444 pub fn needs_write(self) -> bool {
446 matches!(self, Self::Put | Self::Delete)
447 }
448}
449
450impl fmt::Display for PodMethod {
451 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
452 f.write_str(self.as_str())
453 }
454}
455
456impl FromStr for PodMethod {
457 type Err = ParseNameError;
458
459 fn from_str(text: &str) -> Result<Self, Self::Err> {
461 Self::ALL
462 .into_iter()
463 .find(|m| m.as_str() == text)
464 .ok_or(ParseNameError)
465 }
466}
467
468#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
479#[error("not a recognised name")]
480pub struct ParseNameError;
481
482#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
509pub struct ContainerPath(String);
510
511impl ContainerPath {
512 pub fn parse(text: &str) -> Result<Self, ContainerPathError> {
518 if text.is_empty() {
519 return Err(ContainerPathError::Empty);
520 }
521 if text.starts_with('/') {
522 return Err(ContainerPathError::LeadingSlash);
523 }
524 if text.contains('%') {
525 return Err(ContainerPathError::Percent);
526 }
527 if !text.ends_with('/') {
528 return Err(ContainerPathError::NotAContainer);
529 }
530 let full = PodPath::parse(&format!("/pods/{STAND_IN_OWNER}/{text}"))
531 .map_err(ContainerPathError::Shape)?;
532 if !full.is_container() {
533 return Err(ContainerPathError::NotAContainer);
534 }
535 if full.is_acl() {
536 return Err(ContainerPathError::Acl);
537 }
538 if text.split('/').next() == Some("profile") {
539 return Err(ContainerPathError::Profile);
540 }
541 Ok(Self(text.to_owned()))
542 }
543
544 pub fn as_str(&self) -> &str {
546 &self.0
547 }
548
549 pub fn under(&self, owner: &DidNostr) -> PodPath {
556 PodPath::parse(&format!("/pods/{}/{}", owner.to_hex(), self.0))
557 .expect("a checked container path is valid under every owner")
558 }
559}
560
561impl FromStr for ContainerPath {
562 type Err = ContainerPathError;
563
564 fn from_str(text: &str) -> Result<Self, Self::Err> {
565 Self::parse(text)
566 }
567}
568
569impl fmt::Display for ContainerPath {
570 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
571 f.write_str(&self.0)
572 }
573}
574
575impl fmt::Debug for ContainerPath {
576 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
577 write!(f, "ContainerPath({})", self.0)
578 }
579}
580
581impl AsRef<str> for ContainerPath {
582 fn as_ref(&self) -> &str {
583 &self.0
584 }
585}
586
587impl Serialize for ContainerPath {
588 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
589 serializer.serialize_str(&self.0)
590 }
591}
592
593impl<'de> Deserialize<'de> for ContainerPath {
594 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
595 let text = String::deserialize(deserializer)?;
596 text.parse().map_err(serde::de::Error::custom)
597 }
598}
599
600#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
602#[non_exhaustive]
603pub enum ContainerPathError {
604 #[error("container path is empty")]
606 Empty,
607 #[error("container path starts with /")]
609 LeadingSlash,
610 #[error("container path holds %")]
612 Percent,
613 #[error("container path does not name a container")]
615 NotAContainer,
616 #[error("container path breaks the pod path rule: {0}")]
619 Shape(ParsePodPathError),
620 #[error("container path is an ACL")]
622 Acl,
623 #[error("container path is under profile/")]
625 Profile,
626}
627
628#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
646#[serde(deny_unknown_fields)]
647pub struct ContainerGrant {
648 pub path: ContainerPath,
650 pub modes: Vec<AclMode>,
652 pub operations: Vec<PodMethod>,
654}
655
656impl ContainerGrant {
657 pub fn allows(&self, method: PodMethod) -> bool {
659 self.operations.contains(&method)
660 }
661
662 pub fn writes(&self) -> bool {
664 self.modes.contains(&AclMode::Write)
665 }
666}
667
668#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
684#[serde(deny_unknown_fields)]
685pub struct ManifestLimits {
686 #[serde(default, skip_serializing_if = "Option::is_none")]
688 pub cpus: Option<MilliCpus>,
689 #[serde(default, skip_serializing_if = "Option::is_none")]
691 pub memory_bytes: Option<u64>,
692 #[serde(default, skip_serializing_if = "Option::is_none")]
694 pub pids: Option<u64>,
695 #[serde(default, skip_serializing_if = "Option::is_none")]
697 pub tmp_bytes: Option<u64>,
698 #[serde(default, skip_serializing_if = "Option::is_none")]
700 pub timeout_secs: Option<u64>,
701}
702
703#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
717#[serde(deny_unknown_fields)]
718pub struct JobLimits {
719 pub cpus: MilliCpus,
721 pub memory_bytes: u64,
723 pub pids: u64,
725 pub tmp_bytes: u64,
727 pub timeout_secs: u64,
729}
730
731impl JobLimits {
732 pub const DEFAULT: Self = Self {
735 cpus: MilliCpus::new(1000),
736 memory_bytes: 512 * 1024 * 1024,
737 pids: 128,
738 tmp_bytes: 64 * 1024 * 1024,
739 timeout_secs: 600,
740 };
741}
742
743#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
758pub struct JobCeilings {
759 pub cpus: MilliCpus,
761 pub memory_bytes: u64,
763 pub pids: u64,
765 pub tmp_bytes: u64,
767 pub timeout_secs: u64,
769}
770
771impl JobCeilings {
772 pub const DEFAULT: Self = Self {
775 cpus: MilliCpus::new(4000),
776 memory_bytes: 4 * 1024 * 1024 * 1024,
777 pids: 512,
778 tmp_bytes: 1024 * 1024 * 1024,
779 timeout_secs: 3600,
780 };
781}
782
783#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
810#[serde(deny_unknown_fields)]
811pub struct Manifest {
812 pub name: String,
814 pub version: String,
817 pub image_id: ImageId,
819 pub profile: ManifestProfile,
821 pub containers: Vec<ContainerGrant>,
823 pub workspace: WorkspaceMode,
825 pub max_body_bytes: u64,
828 #[serde(default)]
830 pub limits: ManifestLimits,
831}
832
833#[derive(Debug, Clone, PartialEq, Eq, Hash)]
860pub struct ValidManifest {
861 manifest: Manifest,
862 limits: JobLimits,
863}
864
865impl ValidManifest {
866 pub fn parse(json: &[u8], ceilings: &JobCeilings) -> Result<Self, ManifestError> {
874 let value: Value =
875 serde_json::from_slice(json).map_err(|_| ManifestError::new(ManifestRule::Json, ""))?;
876 Self::from_value(&value, ceilings)
877 }
878
879 pub fn from_value(value: &Value, ceilings: &JobCeilings) -> Result<Self, ManifestError> {
886 let manifest = read_manifest(value)?;
887 let limits = effective_limits(&manifest.limits);
888 check_limits(&limits, ceilings)?;
889 Ok(Self { manifest, limits })
890 }
891
892 pub fn check_ceilings(&self, ceilings: &JobCeilings) -> Result<(), ManifestError> {
899 check_limits(&self.limits, ceilings)
900 }
901
902 pub fn manifest(&self) -> &Manifest {
904 &self.manifest
905 }
906
907 pub fn limits(&self) -> JobLimits {
909 self.limits
910 }
911
912 pub fn into_manifest(self) -> Manifest {
914 self.manifest
915 }
916
917 pub fn to_json(&self) -> String {
924 serde_json::to_string(&self.manifest).expect("a manifest always serialises")
925 }
926}
927
928#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
934#[non_exhaustive]
935pub enum ManifestRule {
936 Json,
938 UnknownMember,
940 MissingMember,
942 WrongType,
944 Label,
947 ImageId,
949 Profile,
951 ContainerCount,
953 Path,
955 Mode,
958 ModeSet,
960 Operation,
962 OperationSet,
964 WriteOperationWithoutWrite,
966 DuplicatePath,
968 Workspace,
970 MaxBodyBytes,
972 LimitNotPositive,
975 LimitAboveCeiling,
977 MemoryNotUsable,
980 TmpNotBelowMemory,
982 TimeoutTooShort,
984}
985
986impl ManifestRule {
987 pub fn as_str(self) -> &'static str {
990 match self {
991 Self::Json => "json",
992 Self::UnknownMember => "unknown_member",
993 Self::MissingMember => "missing_member",
994 Self::WrongType => "wrong_type",
995 Self::Label => "label",
996 Self::ImageId => "image_id",
997 Self::Profile => "profile",
998 Self::ContainerCount => "container_count",
999 Self::Path => "path",
1000 Self::Mode => "mode",
1001 Self::ModeSet => "mode_set",
1002 Self::Operation => "operation",
1003 Self::OperationSet => "operation_set",
1004 Self::WriteOperationWithoutWrite => "write_operation_without_write",
1005 Self::DuplicatePath => "duplicate_path",
1006 Self::Workspace => "workspace",
1007 Self::MaxBodyBytes => "max_body_bytes",
1008 Self::LimitNotPositive => "limit_not_positive",
1009 Self::LimitAboveCeiling => "limit_above_ceiling",
1010 Self::MemoryNotUsable => "memory_not_usable",
1011 Self::TmpNotBelowMemory => "tmp_not_below_memory",
1012 Self::TimeoutTooShort => "timeout_too_short",
1013 }
1014 }
1015}
1016
1017impl fmt::Display for ManifestRule {
1018 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1019 f.write_str(self.as_str())
1020 }
1021}
1022
1023#[derive(Debug, Clone, PartialEq, Eq, Hash, thiserror::Error)]
1028#[error("manifest refused at {field}: {rule}")]
1029pub struct ManifestError {
1030 rule: ManifestRule,
1031 field: String,
1032}
1033
1034impl ManifestError {
1035 fn new(rule: ManifestRule, field: impl Into<String>) -> Self {
1036 Self {
1037 rule,
1038 field: field.into(),
1039 }
1040 }
1041
1042 pub fn rule(&self) -> ManifestRule {
1044 self.rule
1045 }
1046
1047 pub fn field(&self) -> &str {
1050 &self.field
1051 }
1052}
1053
1054const MANIFEST_MEMBERS: [&str; 8] = [
1056 "name",
1057 "version",
1058 "image_id",
1059 "profile",
1060 "containers",
1061 "workspace",
1062 "max_body_bytes",
1063 "limits",
1064];
1065
1066const CONTAINER_MEMBERS: [&str; 3] = ["path", "modes", "operations"];
1068
1069const LIMIT_MEMBERS: [&str; 5] = ["cpus", "memory_bytes", "pids", "tmp_bytes", "timeout_secs"];
1071
1072fn object<'v>(value: &'v Value, field: &str) -> Result<&'v Map<String, Value>, ManifestError> {
1073 value
1074 .as_object()
1075 .ok_or_else(|| ManifestError::new(ManifestRule::WrongType, field))
1076}
1077
1078fn no_unknown(map: &Map<String, Value>, known: &[&str], prefix: &str) -> Result<(), ManifestError> {
1079 match map.keys().find(|k| !known.contains(&k.as_str())) {
1080 Some(key) => Err(ManifestError::new(
1081 ManifestRule::UnknownMember,
1082 join_field(prefix, key),
1083 )),
1084 None => Ok(()),
1085 }
1086}
1087
1088fn join_field(prefix: &str, key: &str) -> String {
1089 if prefix.is_empty() {
1090 key.to_owned()
1091 } else {
1092 format!("{prefix}.{key}")
1093 }
1094}
1095
1096fn required<'v>(
1097 map: &'v Map<String, Value>,
1098 key: &str,
1099 field: &str,
1100) -> Result<&'v Value, ManifestError> {
1101 map.get(key)
1102 .ok_or_else(|| ManifestError::new(ManifestRule::MissingMember, field))
1103}
1104
1105fn string<'v>(value: &'v Value, field: &str) -> Result<&'v str, ManifestError> {
1106 value
1107 .as_str()
1108 .ok_or_else(|| ManifestError::new(ManifestRule::WrongType, field))
1109}
1110
1111fn label(value: &Value, field: &str) -> Result<String, ManifestError> {
1112 let text = string(value, field)?;
1113 if text.is_empty()
1114 || text.chars().count() > MAX_LABEL_CHARS
1115 || text.chars().any(char::is_control)
1116 {
1117 return Err(ManifestError::new(ManifestRule::Label, field));
1118 }
1119 Ok(text.to_owned())
1120}
1121
1122fn positive(value: &Value, field: &str, not_positive: ManifestRule) -> Result<u64, ManifestError> {
1125 let number = value
1126 .as_number()
1127 .ok_or_else(|| ManifestError::new(ManifestRule::WrongType, field))?;
1128 number
1129 .as_u64()
1130 .filter(|n| *n > 0)
1131 .ok_or_else(|| ManifestError::new(not_positive, field))
1132}
1133
1134fn read_manifest(value: &Value) -> Result<Manifest, ManifestError> {
1135 let map = value
1136 .as_object()
1137 .ok_or_else(|| ManifestError::new(ManifestRule::Json, ""))?;
1138 no_unknown(map, &MANIFEST_MEMBERS, "")?;
1139 let name = label(required(map, "name", "name")?, "name")?;
1140 let version = label(required(map, "version", "version")?, "version")?;
1141 let image_id = string(required(map, "image_id", "image_id")?, "image_id")?
1142 .parse()
1143 .map_err(|_| ManifestError::new(ManifestRule::ImageId, "image_id"))?;
1144 let profile = match string(required(map, "profile", "profile")?, "profile")? {
1145 "job" => ManifestProfile::Job,
1146 _ => return Err(ManifestError::new(ManifestRule::Profile, "profile")),
1147 };
1148 let containers = read_containers(required(map, "containers", "containers")?)?;
1149 let workspace = string(required(map, "workspace", "workspace")?, "workspace")?
1150 .parse()
1151 .map_err(|_| ManifestError::new(ManifestRule::Workspace, "workspace"))?;
1152 let max_body_bytes = positive(
1153 required(map, "max_body_bytes", "max_body_bytes")?,
1154 "max_body_bytes",
1155 ManifestRule::MaxBodyBytes,
1156 )?;
1157 let limits = match map.get("limits") {
1158 Some(limits) => read_limits(limits)?,
1159 None => ManifestLimits::default(),
1160 };
1161 Ok(Manifest {
1162 name,
1163 version,
1164 image_id,
1165 profile,
1166 containers,
1167 workspace,
1168 max_body_bytes,
1169 limits,
1170 })
1171}
1172
1173fn read_containers(value: &Value) -> Result<Vec<ContainerGrant>, ManifestError> {
1174 let entries = value
1175 .as_array()
1176 .ok_or_else(|| ManifestError::new(ManifestRule::WrongType, "containers"))?;
1177 if entries.is_empty() || entries.len() > MAX_CONTAINERS {
1178 return Err(ManifestError::new(
1179 ManifestRule::ContainerCount,
1180 "containers",
1181 ));
1182 }
1183 let mut grants: Vec<ContainerGrant> = Vec::with_capacity(entries.len());
1184 for (index, entry) in entries.iter().enumerate() {
1185 let prefix = format!("containers[{index}]");
1186 let grant = read_container(entry, &prefix)?;
1187 if grants.iter().any(|g| g.path == grant.path) {
1188 return Err(ManifestError::new(
1189 ManifestRule::DuplicatePath,
1190 format!("{prefix}.path"),
1191 ));
1192 }
1193 grants.push(grant);
1194 }
1195 Ok(grants)
1196}
1197
1198fn read_container(value: &Value, prefix: &str) -> Result<ContainerGrant, ManifestError> {
1199 let map = object(value, prefix)?;
1200 no_unknown(map, &CONTAINER_MEMBERS, prefix)?;
1201 let path_field = format!("{prefix}.path");
1202 let path = string(required(map, "path", &path_field)?, &path_field)?
1203 .parse()
1204 .map_err(|_| ManifestError::new(ManifestRule::Path, path_field.as_str()))?;
1205 let modes = read_modes(map, prefix)?;
1206 let operations = read_operations(map, prefix)?;
1207 if operations.iter().any(|op| op.needs_write()) && !modes.contains(&AclMode::Write) {
1208 return Err(ManifestError::new(
1209 ManifestRule::WriteOperationWithoutWrite,
1210 format!("{prefix}.operations"),
1211 ));
1212 }
1213 Ok(ContainerGrant {
1214 path,
1215 modes,
1216 operations,
1217 })
1218}
1219
1220fn string_list<'v>(
1221 map: &'v Map<String, Value>,
1222 key: &str,
1223 field: &str,
1224) -> Result<Vec<&'v str>, ManifestError> {
1225 let list = required(map, key, field)?
1226 .as_array()
1227 .ok_or_else(|| ManifestError::new(ManifestRule::WrongType, field))?;
1228 list.iter().map(|item| string(item, field)).collect()
1229}
1230
1231fn read_modes(map: &Map<String, Value>, prefix: &str) -> Result<Vec<AclMode>, ManifestError> {
1232 let field = format!("{prefix}.modes");
1233 let names = string_list(map, "modes", &field)?;
1234 let mut modes = Vec::with_capacity(names.len());
1235 for name in names {
1236 modes.push(match name {
1237 "Read" => AclMode::Read,
1238 "Write" => AclMode::Write,
1239 _ => return Err(ManifestError::new(ManifestRule::Mode, field)),
1240 });
1241 }
1242 if modes != [AclMode::Read] && modes != [AclMode::Read, AclMode::Write] {
1243 return Err(ManifestError::new(ManifestRule::ModeSet, field));
1244 }
1245 Ok(modes)
1246}
1247
1248fn read_operations(
1249 map: &Map<String, Value>,
1250 prefix: &str,
1251) -> Result<Vec<PodMethod>, ManifestError> {
1252 let field = format!("{prefix}.operations");
1253 let names = string_list(map, "operations", &field)?;
1254 let mut operations: Vec<PodMethod> = Vec::with_capacity(names.len());
1255 for name in names {
1256 let op: PodMethod = name
1257 .parse()
1258 .map_err(|_| ManifestError::new(ManifestRule::Operation, field.as_str()))?;
1259 if operations.contains(&op) {
1260 return Err(ManifestError::new(ManifestRule::OperationSet, field));
1261 }
1262 operations.push(op);
1263 }
1264 if operations.is_empty() {
1265 return Err(ManifestError::new(ManifestRule::OperationSet, field));
1266 }
1267 Ok(operations)
1268}
1269
1270fn read_limits(value: &Value) -> Result<ManifestLimits, ManifestError> {
1271 let map = object(value, "limits")?;
1272 no_unknown(map, &LIMIT_MEMBERS, "limits")?;
1273 let cpus = match map.get("cpus") {
1274 None => None,
1275 Some(value) => {
1276 let number = value
1277 .as_number()
1278 .ok_or_else(|| ManifestError::new(ManifestRule::WrongType, "limits.cpus"))?;
1279 let cpus = MilliCpus::from_number(number)
1280 .ok()
1281 .filter(|c| c.get() > 0)
1282 .ok_or_else(|| ManifestError::new(ManifestRule::LimitNotPositive, "limits.cpus"))?;
1283 Some(cpus)
1284 }
1285 };
1286 let int = |key: &str| -> Result<Option<u64>, ManifestError> {
1287 let field = format!("limits.{key}");
1288 map.get(key)
1289 .map(|v| positive(v, &field, ManifestRule::LimitNotPositive))
1290 .transpose()
1291 };
1292 Ok(ManifestLimits {
1293 cpus,
1294 memory_bytes: int("memory_bytes")?,
1295 pids: int("pids")?,
1296 tmp_bytes: int("tmp_bytes")?,
1297 timeout_secs: int("timeout_secs")?,
1298 })
1299}
1300
1301fn effective_limits(limits: &ManifestLimits) -> JobLimits {
1302 let d = JobLimits::DEFAULT;
1303 JobLimits {
1304 cpus: limits.cpus.unwrap_or(d.cpus),
1305 memory_bytes: limits.memory_bytes.unwrap_or(d.memory_bytes),
1306 pids: limits.pids.unwrap_or(d.pids),
1307 tmp_bytes: limits.tmp_bytes.unwrap_or(d.tmp_bytes),
1308 timeout_secs: limits.timeout_secs.unwrap_or(d.timeout_secs),
1309 }
1310}
1311
1312fn check_limits(limits: &JobLimits, ceilings: &JobCeilings) -> Result<(), ManifestError> {
1313 let above = |field: &str| ManifestError::new(ManifestRule::LimitAboveCeiling, field);
1314 if limits.cpus > ceilings.cpus {
1315 return Err(above("limits.cpus"));
1316 }
1317 if limits.memory_bytes > ceilings.memory_bytes {
1318 return Err(above("limits.memory_bytes"));
1319 }
1320 if limits.pids > ceilings.pids {
1321 return Err(above("limits.pids"));
1322 }
1323 if limits.tmp_bytes > ceilings.tmp_bytes {
1324 return Err(above("limits.tmp_bytes"));
1325 }
1326 if limits.timeout_secs > ceilings.timeout_secs {
1327 return Err(above("limits.timeout_secs"));
1328 }
1329 if limits.memory_bytes < MIN_MEMORY_BYTES
1330 || !limits.memory_bytes.is_multiple_of(MEMORY_STEP_BYTES)
1331 {
1332 return Err(ManifestError::new(
1333 ManifestRule::MemoryNotUsable,
1334 "limits.memory_bytes",
1335 ));
1336 }
1337 if limits.tmp_bytes >= limits.memory_bytes {
1338 return Err(ManifestError::new(
1339 ManifestRule::TmpNotBelowMemory,
1340 "limits.tmp_bytes",
1341 ));
1342 }
1343 if limits.timeout_secs < MIN_TIMEOUT_SECS {
1344 return Err(ManifestError::new(
1345 ManifestRule::TimeoutTooShort,
1346 "limits.timeout_secs",
1347 ));
1348 }
1349 Ok(())
1350}