Skip to main content

stratum_node_core/
manifest.rs

1//! Application manifests: the shape an administrator approves, its
2//! validation, and the limits a job runs under.
3//!
4//! A manifest is JSON with unknown members refused. [`ValidManifest::parse`]
5//! reads it member by member, so that a refusal names the member and the
6//! rule it broke ([`ManifestError::field`], [`ManifestError::rule`]), then
7//! applies the defaults and checks every limit against the node's
8//! [`JobCeilings`]. [`Manifest`] is the accepted shape, with serde for
9//! storage and display.
10
11use 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
21/// The most containers one manifest may grant.
22pub const MAX_CONTAINERS: usize = 8;
23
24/// The shortest timeout a manifest may ask for, in seconds. It gives an
25/// attempt at least 180 s of retry window before the 60 s cut-off.
26pub const MIN_TIMEOUT_SECS: u64 = 240;
27
28/// The smallest `memory_bytes` a manifest may ask for: 6 MiB, the least
29/// the container engine accepts.
30pub const MIN_MEMORY_BYTES: u64 = 6 * 1024 * 1024;
31
32/// `memory_bytes` must be a multiple of this many bytes (one page). The
33/// kernel rounds a memory limit down to a whole page, so any other value
34/// could never be verified as applied.
35pub const MEMORY_STEP_BYTES: u64 = 4096;
36
37/// The longest `name` or `version`, in characters.
38pub const MAX_LABEL_CHARS: usize = 128;
39
40/// The prefix of an [`ImageId`].
41const IMAGE_ID_PREFIX: &str = "sha256:";
42
43/// A key that stands in for the owner when a manifest path is checked
44/// (plan Q18): the path rule does not depend on the owner segment.
45const STAND_IN_OWNER: &str = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798";
46
47/// A container image identifier: `sha256:` and 64 lower-case hex digits.
48///
49/// This is the image ID the tenant daemon reports, never a tag or a
50/// repository digest. "The same image" means the same image ID.
51///
52/// # Examples
53///
54/// ```
55/// use stratum_node_core::ImageId;
56///
57/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
58/// let id: ImageId = format!("sha256:{}", "ab".repeat(32)).parse()?;
59/// assert_eq!(id.hex(), "ab".repeat(32));
60/// assert!("sha256:AB".parse::<ImageId>().is_err());
61/// assert!("ab".repeat(32).parse::<ImageId>().is_err());
62/// # Ok(())
63/// # }
64/// ```
65#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
66pub struct ImageId(String);
67
68impl ImageId {
69    /// Builds an image ID from the 32 bytes of its digest.
70    pub fn from_digest(digest: [u8; 32]) -> Self {
71        Self(format!("{IMAGE_ID_PREFIX}{}", hex::encode(digest)))
72    }
73
74    /// Returns the text form, `sha256:<64 hex>`.
75    pub fn as_str(&self) -> &str {
76        &self.0
77    }
78
79    /// Returns the 64 hex digits after `sha256:`.
80    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    /// Parses exactly `sha256:` followed by 64 lower-case hex digits.
89    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/// The text is not `sha256:` followed by 64 lower-case hex digits.
127///
128/// # Examples
129///
130/// ```
131/// use stratum_node_core::{ImageId, ParseImageIdError};
132///
133/// assert_eq!("latest".parse::<ImageId>(), Err(ParseImageIdError));
134/// ```
135#[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/// A CPU limit in thousandths of a CPU.
140///
141/// In JSON it is a decimal number of CPUs with at most three decimal places
142/// (`1.5` is 1500 millicpus); nothing after parsing uses floating point. The
143/// expected `cpu.max` is `<millicpus × 100> 100000` and Docker's `NanoCpus`
144/// is millicpus × 10⁶.
145///
146/// # Examples
147///
148/// ```
149/// use stratum_node_core::MilliCpus;
150///
151/// # fn main() -> Result<(), serde_json::Error> {
152/// let cpus: MilliCpus = serde_json::from_str("1.5")?;
153/// assert_eq!(cpus.get(), 1500);
154/// assert_eq!(cpus.cpu_max(), "150000 100000");
155/// assert_eq!(cpus.nano_cpus(), 1_500_000_000);
156/// assert_eq!(serde_json::to_string(&cpus)?, "1.5");
157/// assert!(serde_json::from_str::<MilliCpus>("0.0005").is_err());
158/// assert!(serde_json::from_str::<MilliCpus>("-1").is_err());
159/// # Ok(())
160/// # }
161/// ```
162#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
163pub struct MilliCpus(u32);
164
165impl MilliCpus {
166    /// Wraps a count of millicpus.
167    pub const fn new(millicpus: u32) -> Self {
168        Self(millicpus)
169    }
170
171    /// Returns the count of millicpus.
172    pub const fn get(self) -> u32 {
173        self.0
174    }
175
176    /// Returns the cgroup v2 `cpu.max` text the runner expects to read:
177    /// `<millicpus × 100> 100000`.
178    pub fn cpu_max(self) -> String {
179        format!("{} 100000", u64::from(self.0) * 100)
180    }
181
182    /// Returns Docker's `NanoCpus`: millicpus × 10⁶.
183    pub fn nano_cpus(self) -> u64 {
184        u64::from(self.0) * 1_000_000
185    }
186
187    /// Reads a JSON number of CPUs.
188    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        // `Display` for f64 is the shortest text that reads back as the same
204        // value and never uses an exponent, so the decimal places are
205        // counted on the number's value, not on how the sender wrote it.
206        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/// Why a JSON number is not a CPU count.
230#[derive(Debug, Clone, Copy, PartialEq, Eq)]
231enum CpusError {
232    /// Negative.
233    NotPositive,
234    /// More than three decimal places.
235    Precision,
236    /// Beyond `u32::MAX` millicpus.
237    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        // The nearest f64 to a three-place decimal prints back as that
248        // decimal, so this writes `1.5`, never `1.50000000001`.
249        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/// The job profile a manifest asks for. Only `"job"` exists.
267///
268/// # Examples
269///
270/// ```
271/// use stratum_node_core::ManifestProfile;
272///
273/// # fn main() -> Result<(), serde_json::Error> {
274/// assert_eq!(serde_json::to_string(&ManifestProfile::Job)?, "\"job\"");
275/// assert!(serde_json::from_str::<ManifestProfile>("\"service\"").is_err());
276/// # Ok(())
277/// # }
278/// ```
279#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
280#[serde(rename_all = "lowercase")]
281#[non_exhaustive]
282pub enum ManifestProfile {
283    /// A job: started for one period, it runs until it reports a result or
284    /// its timeout.
285    Job,
286}
287
288/// The most workspace an application may be given, or an installation
289/// asks for: `"none"`, `"read"` or `"write"`.
290///
291/// # Examples
292///
293/// ```
294/// use stratum_node_core::WorkspaceMode;
295///
296/// # fn main() -> Result<(), serde_json::Error> {
297/// assert_eq!(WorkspaceMode::default(), WorkspaceMode::None);
298/// assert!(WorkspaceMode::Read <= WorkspaceMode::Write);
299/// assert_eq!(serde_json::from_str::<WorkspaceMode>("\"write\"")?, WorkspaceMode::Write);
300/// assert_eq!(WorkspaceMode::None.as_str(), "none");
301/// # Ok(())
302/// # }
303/// ```
304#[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    /// No workspace.
311    #[default]
312    None,
313    /// The workspace mounted read-only.
314    Read,
315    /// The workspace mounted read-write.
316    Write,
317}
318
319impl WorkspaceMode {
320    /// Every mode, least to most.
321    pub const ALL: [Self; 3] = [Self::None, Self::Read, Self::Write];
322
323    /// Returns the lowercase name.
324    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/// A WAC access mode a manifest may grant: `"Read"` or `"Write"`.
351///
352/// `Append` and `Control` are not grantable: an application key never holds
353/// `Control`, so it can never change an ACL.
354///
355/// # Examples
356///
357/// ```
358/// use stratum_node_core::AclMode;
359///
360/// # fn main() -> Result<(), serde_json::Error> {
361/// assert_eq!(serde_json::to_string(&AclMode::Read)?, "\"Read\"");
362/// assert!(serde_json::from_str::<AclMode>("\"Control\"").is_err());
363/// assert_eq!(AclMode::Write.iri(), "acl:Write");
364/// # Ok(())
365/// # }
366/// ```
367#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
368#[non_exhaustive]
369pub enum AclMode {
370    /// `acl:Read`.
371    Read,
372    /// `acl:Write`.
373    Write,
374}
375
376impl AclMode {
377    /// Returns the name as written in a manifest, `Read` or `Write`.
378    pub fn as_str(self) -> &'static str {
379        match self {
380            Self::Read => "Read",
381            Self::Write => "Write",
382        }
383    }
384
385    /// Returns the prefixed IRI, `acl:Read` or `acl:Write`.
386    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/// A pod operation a manifest may allow: `GET`, `HEAD`, `PUT` or `DELETE`.
401///
402/// # Examples
403///
404/// ```
405/// use stratum_node_core::PodMethod;
406///
407/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
408/// assert_eq!("PUT".parse::<PodMethod>()?, PodMethod::Put);
409/// assert!(PodMethod::Delete.needs_write());
410/// assert!(!PodMethod::Head.needs_write());
411/// assert!("POST".parse::<PodMethod>().is_err());
412/// assert_eq!(serde_json::to_string(&PodMethod::Get)?, "\"GET\"");
413/// # Ok(())
414/// # }
415/// ```
416#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
417#[serde(rename_all = "UPPERCASE")]
418#[non_exhaustive]
419pub enum PodMethod {
420    /// `GET`.
421    Get,
422    /// `HEAD`.
423    Head,
424    /// `PUT`.
425    Put,
426    /// `DELETE`.
427    Delete,
428}
429
430impl PodMethod {
431    /// Every operation.
432    pub const ALL: [Self; 4] = [Self::Get, Self::Head, Self::Put, Self::Delete];
433
434    /// Returns the method name.
435    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    /// Returns `true` for `PUT` and `DELETE`, which need [`AclMode::Write`].
445    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    /// Parses an upper-case method name, exactly.
460    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/// The text is not one of the type's names. The match is exact and
469/// case-sensitive.
470///
471/// # Examples
472///
473/// ```
474/// use stratum_node_core::{ParseNameError, PodMethod};
475///
476/// assert_eq!("get".parse::<PodMethod>(), Err(ParseNameError));
477/// ```
478#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
479#[error("not a recognised name")]
480pub struct ParseNameError;
481
482/// A manifest container path: relative to the owner's pod root, naming a
483/// container.
484///
485/// The path rule: no leading `/`, exactly one terminal `/`, no empty inner
486/// segment, no `.` or `..` segment and no `%`; it is case-sensitive and
487/// never decoded. It is checked by prefixing `/pods/<owner>/` and applying
488/// [`PodPath::parse`] to the result, which must be a container and not an
489/// ACL. Its first segment may not be `profile`.
490///
491/// # Examples
492///
493/// ```
494/// use stratum_node_core::{ContainerPath, DidNostr};
495///
496/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
497/// let path: ContainerPath = "reports/2026/".parse()?;
498/// let owner = DidNostr::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798")?;
499/// assert_eq!(path.under(&owner).as_str(), format!("/pods/{}/reports/2026/", owner.to_hex()));
500///
501/// for bad in ["", "/reports/", "reports", "reports//", "a/../b/", "a%2F/", "profile/", "Reports Ö/"] {
502///     assert!(bad.parse::<ContainerPath>().is_err(), "{bad}");
503/// }
504/// assert!("profiles/".parse::<ContainerPath>().is_ok());
505/// # Ok(())
506/// # }
507/// ```
508#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
509pub struct ContainerPath(String);
510
511impl ContainerPath {
512    /// Checks `text` against the path rule.
513    ///
514    /// # Errors
515    ///
516    /// Returns the first rule the text breaks, as a [`ContainerPathError`].
517    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    /// Returns the relative path, ending in `/`.
545    pub fn as_str(&self) -> &str {
546        &self.0
547    }
548
549    /// Returns the full pod path of this container in `owner`'s pod.
550    ///
551    /// # Panics
552    ///
553    /// Never: the path rule was checked on construction with a stand-in
554    /// owner, and the rule does not depend on the owner.
555    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/// The rule of the manifest path rule that a path breaks.
601#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
602#[non_exhaustive]
603pub enum ContainerPathError {
604    /// The path is empty (the pod root is not grantable).
605    #[error("container path is empty")]
606    Empty,
607    /// The path starts with `/`.
608    #[error("container path starts with /")]
609    LeadingSlash,
610    /// The path holds `%`.
611    #[error("container path holds %")]
612    Percent,
613    /// The path does not end in `/`.
614    #[error("container path does not name a container")]
615    NotAContainer,
616    /// The pod path parser refused the prefixed path: a character outside
617    /// `A–Z a–z 0–9 - . _ ~ /`, a `.` or `..` segment, or an empty segment.
618    #[error("container path breaks the pod path rule: {0}")]
619    Shape(ParsePodPathError),
620    /// The path is an ACL.
621    #[error("container path is an ACL")]
622    Acl,
623    /// The first segment is `profile`.
624    #[error("container path is under profile/")]
625    Profile,
626}
627
628/// One granted container: its path, the modes and the operations.
629///
630/// # Examples
631///
632/// ```
633/// use stratum_node_core::{AclMode, ContainerGrant, PodMethod};
634///
635/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
636/// let grant: ContainerGrant = serde_json::from_str(
637///     r#"{"path":"reports/","modes":["Read","Write"],"operations":["GET","PUT"]}"#,
638/// )?;
639/// assert!(grant.allows(PodMethod::Put));
640/// assert!(!grant.allows(PodMethod::Delete));
641/// assert_eq!(grant.modes, [AclMode::Read, AclMode::Write]);
642/// # Ok(())
643/// # }
644/// ```
645#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
646#[serde(deny_unknown_fields)]
647pub struct ContainerGrant {
648    /// The container, relative to the pod root.
649    pub path: ContainerPath,
650    /// `[Read]` or `[Read, Write]`.
651    pub modes: Vec<AclMode>,
652    /// The operations allowed on the container and below it.
653    pub operations: Vec<PodMethod>,
654}
655
656impl ContainerGrant {
657    /// Returns `true` when `method` is one of this grant's operations.
658    pub fn allows(&self, method: PodMethod) -> bool {
659        self.operations.contains(&method)
660    }
661
662    /// Returns `true` when the grant includes [`AclMode::Write`].
663    pub fn writes(&self) -> bool {
664        self.modes.contains(&AclMode::Write)
665    }
666}
667
668/// The limits a manifest names; an absent limit takes its default.
669///
670/// # Examples
671///
672/// ```
673/// use stratum_node_core::ManifestLimits;
674///
675/// # fn main() -> Result<(), serde_json::Error> {
676/// let limits: ManifestLimits = serde_json::from_str(r#"{"cpus":0.5,"timeout_secs":300}"#)?;
677/// assert_eq!(limits.cpus.map(|c| c.get()), Some(500));
678/// assert_eq!(limits.memory_bytes, None);
679/// assert_eq!(serde_json::to_string(&limits)?, r#"{"cpus":0.5,"timeout_secs":300}"#);
680/// # Ok(())
681/// # }
682/// ```
683#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
684#[serde(deny_unknown_fields)]
685pub struct ManifestLimits {
686    /// CPUs, as millicpus.
687    #[serde(default, skip_serializing_if = "Option::is_none")]
688    pub cpus: Option<MilliCpus>,
689    /// Memory, in bytes.
690    #[serde(default, skip_serializing_if = "Option::is_none")]
691    pub memory_bytes: Option<u64>,
692    /// Processes.
693    #[serde(default, skip_serializing_if = "Option::is_none")]
694    pub pids: Option<u64>,
695    /// The `/tmp` tmpfs size, in bytes; below `memory_bytes`.
696    #[serde(default, skip_serializing_if = "Option::is_none")]
697    pub tmp_bytes: Option<u64>,
698    /// The attempt's timeout, in seconds; at least [`MIN_TIMEOUT_SECS`].
699    #[serde(default, skip_serializing_if = "Option::is_none")]
700    pub timeout_secs: Option<u64>,
701}
702
703/// The limits a job actually runs under: the manifest's, with defaults
704/// applied.
705///
706/// # Examples
707///
708/// ```
709/// use stratum_node_core::JobLimits;
710///
711/// let d = JobLimits::DEFAULT;
712/// assert_eq!(d.cpus.get(), 1000);
713/// assert_eq!(d.memory_bytes, 512 * 1024 * 1024);
714/// assert_eq!((d.pids, d.tmp_bytes, d.timeout_secs), (128, 64 * 1024 * 1024, 600));
715/// ```
716#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
717#[serde(deny_unknown_fields)]
718pub struct JobLimits {
719    /// CPUs, as millicpus.
720    pub cpus: MilliCpus,
721    /// Memory, in bytes; swap is set equal, so `memory.swap.max` is 0.
722    pub memory_bytes: u64,
723    /// Processes.
724    pub pids: u64,
725    /// The `/tmp` tmpfs size, in bytes.
726    pub tmp_bytes: u64,
727    /// The attempt's timeout, in seconds.
728    pub timeout_secs: u64,
729}
730
731impl JobLimits {
732    /// The defaults for a limit a manifest omits: 1 CPU, 512 MiB, 128
733    /// processes, 64 MiB scratch, 600 s.
734    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/// The node's ceilings on job limits, from configuration
744/// (`limits.job_max_*`). Approval refuses a manifest above them, and so does
745/// launch, in case a ceiling was lowered since.
746///
747/// # Examples
748///
749/// ```
750/// use stratum_node_core::JobCeilings;
751///
752/// let c = JobCeilings::DEFAULT;
753/// assert_eq!(c.cpus.get(), 4000);
754/// assert_eq!(c.memory_bytes, 4 * 1024 * 1024 * 1024);
755/// assert_eq!((c.pids, c.tmp_bytes, c.timeout_secs), (512, 1024 * 1024 * 1024, 3600));
756/// ```
757#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
758pub struct JobCeilings {
759    /// CPUs, as millicpus.
760    pub cpus: MilliCpus,
761    /// Memory, in bytes.
762    pub memory_bytes: u64,
763    /// Processes.
764    pub pids: u64,
765    /// The `/tmp` tmpfs size, in bytes.
766    pub tmp_bytes: u64,
767    /// The attempt's timeout, in seconds.
768    pub timeout_secs: u64,
769}
770
771impl JobCeilings {
772    /// The contract's default ceilings: 4 CPUs, 4 GiB, 512 processes, 1 GiB
773    /// scratch, 3600 s.
774    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/// An application manifest, in the shape an administrator approves.
784///
785/// Deserialising refuses unknown members and malformed values, but does not
786/// check the cross-member rules or the ceilings; use [`ValidManifest::parse`]
787/// on anything received. Serialising writes the members in this order.
788///
789/// # Examples
790///
791/// ```
792/// use stratum_node_core::{JobCeilings, ValidManifest};
793///
794/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
795/// let json = format!(
796///     r#"{{"name":"report","version":"1.0.0","image_id":"sha256:{}","profile":"job",
797///        "containers":[{{"path":"reports-input/","modes":["Read"],"operations":["GET"]}},
798///                      {{"path":"reports/","modes":["Read","Write"],"operations":["GET","HEAD","PUT"]}}],
799///        "workspace":"none","max_body_bytes":65536,"limits":{{"timeout_secs":300}}}}"#,
800///     "ab".repeat(32)
801/// );
802/// let valid = ValidManifest::parse(json.as_bytes(), &JobCeilings::DEFAULT)?;
803/// assert_eq!(valid.limits().timeout_secs, 300);
804/// assert_eq!(valid.limits().pids, 128);
805/// assert_eq!(valid.manifest().containers.len(), 2);
806/// # Ok(())
807/// # }
808/// ```
809#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
810#[serde(deny_unknown_fields)]
811pub struct Manifest {
812    /// The application's name; a label only.
813    pub name: String,
814    /// The application's version; a label only. A new version is a new
815    /// application.
816    pub version: String,
817    /// The image the runner starts.
818    pub image_id: ImageId,
819    /// The job profile, always [`ManifestProfile::Job`].
820    pub profile: ManifestProfile,
821    /// One to eight granted containers.
822    pub containers: Vec<ContainerGrant>,
823    /// The most workspace the application may be given.
824    pub workspace: WorkspaceMode,
825    /// The largest request body the application may send, in bytes; the
826    /// proxy applies the smaller of this and `limits.max_pod_body_bytes`.
827    pub max_body_bytes: u64,
828    /// The limits; absent members take their defaults.
829    #[serde(default)]
830    pub limits: ManifestLimits,
831}
832
833/// A manifest that passed validation, with its effective limits.
834///
835/// # Examples
836///
837/// ```
838/// use stratum_node_core::{JobCeilings, ManifestRule, MilliCpus, ValidManifest};
839///
840/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
841/// let json = format!(
842///     r#"{{"name":"n","version":"1","image_id":"sha256:{}","profile":"job",
843///        "containers":[{{"path":"a/","modes":["Read"],"operations":["PUT"]}}],
844///        "workspace":"none","max_body_bytes":1}}"#,
845///     "00".repeat(32)
846/// );
847/// let err = ValidManifest::parse(json.as_bytes(), &JobCeilings::DEFAULT).unwrap_err();
848/// assert_eq!(err.rule(), ManifestRule::WriteOperationWithoutWrite);
849/// assert_eq!(err.field(), "containers[0].operations");
850///
851/// // A lowered ceiling refuses a manifest that was valid before.
852/// let ok = json.replace(r#""operations":["PUT"]"#, r#""operations":["GET"]"#);
853/// let valid = ValidManifest::parse(ok.as_bytes(), &JobCeilings::DEFAULT)?;
854/// let lowered = JobCeilings { cpus: MilliCpus::new(500), ..JobCeilings::DEFAULT };
855/// assert_eq!(valid.check_ceilings(&lowered).unwrap_err().field(), "limits.cpus");
856/// # Ok(())
857/// # }
858/// ```
859#[derive(Debug, Clone, PartialEq, Eq, Hash)]
860pub struct ValidManifest {
861    manifest: Manifest,
862    limits: JobLimits,
863}
864
865impl ValidManifest {
866    /// Parses and validates a manifest's JSON bytes against `ceilings`.
867    ///
868    /// # Errors
869    ///
870    /// Returns a [`ManifestError`] naming the first member that breaks a
871    /// rule, checked in document order of the members listed under
872    /// [`ManifestRule`].
873    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    /// Validates a manifest already parsed as JSON, such as the `manifest`
880    /// member of an approval request.
881    ///
882    /// # Errors
883    ///
884    /// As [`ValidManifest::parse`].
885    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    /// Re-checks the effective limits against `ceilings`, as launch does.
893    ///
894    /// # Errors
895    ///
896    /// [`ManifestRule::LimitAboveCeiling`] naming the first limit above its
897    /// ceiling.
898    pub fn check_ceilings(&self, ceilings: &JobCeilings) -> Result<(), ManifestError> {
899        check_limits(&self.limits, ceilings)
900    }
901
902    /// Returns the manifest.
903    pub fn manifest(&self) -> &Manifest {
904        &self.manifest
905    }
906
907    /// Returns the effective limits.
908    pub fn limits(&self) -> JobLimits {
909        self.limits
910    }
911
912    /// Returns the manifest, consuming the validated wrapper.
913    pub fn into_manifest(self) -> Manifest {
914        self.manifest
915    }
916
917    /// Returns the manifest serialised as compact JSON, the form the store
918    /// keeps and [`ValidManifest::parse`] reads back.
919    ///
920    /// # Panics
921    ///
922    /// Never: every member serialises.
923    pub fn to_json(&self) -> String {
924        serde_json::to_string(&self.manifest).expect("a manifest always serialises")
925    }
926}
927
928/// The validation rule a manifest broke.
929///
930/// Each row of the contract's validation list has one variant, so a refusal
931/// table can name its case; the shape rules (JSON, members, types) have
932/// their own.
933#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
934#[non_exhaustive]
935pub enum ManifestRule {
936    /// The bytes are not a JSON object.
937    Json,
938    /// A member the manifest does not define.
939    UnknownMember,
940    /// A required member is absent.
941    MissingMember,
942    /// A member has the wrong JSON type.
943    WrongType,
944    /// `name` or `version` is empty, longer than [`MAX_LABEL_CHARS`] or
945    /// holds a control character.
946    Label,
947    /// `image_id` is not `sha256:` and 64 lower-case hex digits.
948    ImageId,
949    /// `profile` is not `"job"`.
950    Profile,
951    /// Zero containers, or more than [`MAX_CONTAINERS`].
952    ContainerCount,
953    /// A path that fails the path rule.
954    Path,
955    /// A mode other than `Read` or `Write` (so no `Control` and no
956    /// `Append`).
957    Mode,
958    /// Modes other than exactly `["Read"]` or `["Read","Write"]`.
959    ModeSet,
960    /// An operation not in `GET`, `HEAD`, `PUT`, `DELETE`.
961    Operation,
962    /// No operation, or one listed twice.
963    OperationSet,
964    /// `PUT` or `DELETE` on a container without `Write`.
965    WriteOperationWithoutWrite,
966    /// Two entries for one path.
967    DuplicatePath,
968    /// `workspace` is not `"none"`, `"read"` or `"write"`.
969    Workspace,
970    /// `max_body_bytes` is zero or negative.
971    MaxBodyBytes,
972    /// A limit that is zero or negative, or `cpus` that is not a number of
973    /// CPUs with at most three decimal places.
974    LimitNotPositive,
975    /// A limit above the node's ceiling.
976    LimitAboveCeiling,
977    /// `memory_bytes` below [`MIN_MEMORY_BYTES`], or not a multiple of
978    /// [`MEMORY_STEP_BYTES`].
979    MemoryNotUsable,
980    /// `tmp_bytes` at or above `memory_bytes`.
981    TmpNotBelowMemory,
982    /// `timeout_secs` below [`MIN_TIMEOUT_SECS`].
983    TimeoutTooShort,
984}
985
986impl ManifestRule {
987    /// Returns a short, stable name for the rule, such as
988    /// `duplicate_path`.
989    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/// A manifest refusal: the rule and the member it concerns.
1024///
1025/// The controller answers it as 400 `invalid` with `error.field` set to
1026/// [`field`](Self::field). The message never echoes a member's value.
1027#[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    /// Returns the rule broken.
1043    pub fn rule(&self) -> ManifestRule {
1044        self.rule
1045    }
1046
1047    /// Returns the member, as a path such as `containers[1].modes` or
1048    /// `limits.cpus`; empty for [`ManifestRule::Json`].
1049    pub fn field(&self) -> &str {
1050        &self.field
1051    }
1052}
1053
1054/// The members of a manifest, in order.
1055const 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
1066/// The members of a container entry.
1067const CONTAINER_MEMBERS: [&str; 3] = ["path", "modes", "operations"];
1068
1069/// The members of `limits`.
1070const 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
1122/// A positive integer member. A non-number is [`ManifestRule::WrongType`];
1123/// zero, a negative or a fractional number is `not_positive`.
1124fn 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}