Skip to main content

oxide_batch_plan/
nested_job.rs

1use std::collections::BTreeSet;
2
3use oxide_batch_core::{
4    ComponentRevision, DefinitionIdentity, JobName, NodeId, ParameterName, ParameterRole,
5    ParameterValueKind, StateSchemaId, StateSchemaVersion, selector_path_is_valid,
6};
7use serde_json::{Value, json};
8
9use super::PlanError;
10
11/// Maximum number of typed child parameters one nested-job node may declare.
12pub const MAX_NESTED_JOB_PARAMETERS: usize = 64;
13pub use oxide_batch_core::{MAX_SELECTOR_PATH_BYTES, MAX_SELECTOR_PATH_SEGMENTS};
14
15/// A bounded structured path into committed execution-context state.
16///
17/// The path is represented as validated segments rather than an expression
18/// language. It therefore cannot invoke functions, mutate state, perform I/O,
19/// or consult ambient process state.
20#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
21pub struct SelectorPath(Vec<String>);
22
23impl SelectorPath {
24    /// Validates one structured path.
25    ///
26    /// # Errors
27    ///
28    /// Rejects an empty path, more than 32 segments, empty/whitespace-padded
29    /// segments, control characters, or a path larger than 1,024 UTF-8 bytes.
30    pub fn new(segments: impl IntoIterator<Item = String>) -> Result<Self, PlanError> {
31        let segments = segments.into_iter().collect::<Vec<_>>();
32        if !selector_path_is_valid(&segments) {
33            return Err(PlanError::InvalidSelectorPath {
34                max_bytes: MAX_SELECTOR_PATH_BYTES,
35                max_segments: MAX_SELECTOR_PATH_SEGMENTS,
36            });
37        }
38        Ok(Self(segments))
39    }
40
41    /// Borrows the path segments in declaration order.
42    #[must_use]
43    pub fn segments(&self) -> &[String] {
44        &self.0
45    }
46
47    pub(crate) fn manifest_value(&self) -> Value {
48        Value::Array(self.0.iter().cloned().map(Value::String).collect())
49    }
50}
51
52/// Closed framework metadata that a nested-job mapping may read.
53#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
54#[non_exhaustive]
55pub enum FrameworkParameterSource {
56    /// Opaque parent job-instance identifier.
57    ParentJobInstanceId,
58    /// Opaque parent job-execution identifier.
59    ParentJobExecutionId,
60    /// One-based parent execution attempt ordinal.
61    ParentAttempt,
62    /// Parent definition revision.
63    ParentDefinitionRevision,
64    /// Parent definition fingerprint encoded as lower-case hexadecimal.
65    ParentDefinitionFingerprint,
66    /// Logical nested-job node identifier.
67    NestedJobNodeId,
68}
69
70impl FrameworkParameterSource {
71    /// Returns the stable manifest code.
72    #[must_use]
73    pub const fn as_str(self) -> &'static str {
74        match self {
75            Self::ParentJobInstanceId => "parent_job_instance_id",
76            Self::ParentJobExecutionId => "parent_job_execution_id",
77            Self::ParentAttempt => "parent_attempt",
78            Self::ParentDefinitionRevision => "parent_definition_revision",
79            Self::ParentDefinitionFingerprint => "parent_definition_fingerprint",
80            Self::NestedJobNodeId => "nested_job_node_id",
81        }
82    }
83
84    /// Returns the value kind produced before any declared coercion.
85    #[must_use]
86    pub const fn value_kind(self) -> ParameterValueKind {
87        match self {
88            Self::ParentJobInstanceId | Self::ParentJobExecutionId | Self::ParentAttempt => {
89                ParameterValueKind::U64
90            }
91            Self::ParentDefinitionRevision
92            | Self::ParentDefinitionFingerprint
93            | Self::NestedJobNodeId => ParameterValueKind::String,
94        }
95    }
96}
97
98/// One accepted source family for a nested-job child parameter.
99#[derive(Clone, Debug, Eq, PartialEq)]
100#[non_exhaustive]
101pub enum NestedJobParameterSource {
102    /// An immutable parent launch parameter.
103    ParentParameter(ParameterName),
104    /// A value from the committed parent job-execution context snapshot.
105    ParentJobContext {
106        /// Required context schema identity.
107        schema: StateSchemaId,
108        /// Required committed schema version.
109        schema_version: StateSchemaVersion,
110        /// Structured object path.
111        path: SelectorPath,
112    },
113    /// A value from the latest committed context of one logical parent step.
114    ParentStepContext {
115        /// Logical parent step whose committed context is selected.
116        node: NodeId,
117        /// Required context schema identity.
118        schema: StateSchemaId,
119        /// Required committed schema version.
120        schema_version: StateSchemaVersion,
121        /// Structured object path.
122        path: SelectorPath,
123    },
124    /// Closed framework metadata with no ambient source access.
125    Framework(FrameworkParameterSource),
126}
127
128impl NestedJobParameterSource {
129    pub(crate) fn manifest_value(&self) -> Value {
130        match self {
131            Self::ParentParameter(name) => json!({
132                "kind": "parent_parameter",
133                "name": name.as_str()
134            }),
135            Self::ParentJobContext {
136                schema,
137                schema_version,
138                path,
139            } => json!({
140                "kind": "parent_job_context",
141                "path": path.manifest_value(),
142                "schema": schema.as_str(),
143                "schema_version": schema_version.get()
144            }),
145            Self::ParentStepContext {
146                node,
147                schema,
148                schema_version,
149                path,
150            } => json!({
151                "kind": "parent_step_context",
152                "node": node.as_str(),
153                "path": path.manifest_value(),
154                "schema": schema.as_str(),
155                "schema_version": schema_version.get()
156            }),
157            Self::Framework(source) => json!({
158                "field": source.as_str(),
159                "kind": "framework"
160            }),
161        }
162    }
163}
164
165/// Explicit deterministic coercion applied after source selection.
166#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
167#[non_exhaustive]
168pub enum ParameterCoercion {
169    /// Source and target kinds must match exactly.
170    #[default]
171    Exact,
172    /// Parse a UTF-8 string as a signed integer.
173    StringToI64,
174    /// Parse a UTF-8 string as an unsigned integer.
175    StringToU64,
176    /// Parse exactly `true` or `false` as a boolean.
177    StringToBool,
178    /// Convert a non-negative signed integer to unsigned.
179    I64ToU64,
180    /// Convert an unsigned integer that fits into `i64`.
181    U64ToI64,
182}
183
184impl ParameterCoercion {
185    /// Returns the stable manifest code.
186    #[must_use]
187    pub const fn as_str(self) -> &'static str {
188        match self {
189            Self::Exact => "exact",
190            Self::StringToI64 => "string_to_i64",
191            Self::StringToU64 => "string_to_u64",
192            Self::StringToBool => "string_to_bool",
193            Self::I64ToU64 => "i64_to_u64",
194            Self::U64ToI64 => "u64_to_i64",
195        }
196    }
197}
198
199/// Closed behavior when a mapping source is absent.
200#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
201#[non_exhaustive]
202pub enum MissingParameterPolicy {
203    /// Missing data rejects the complete mapping.
204    #[default]
205    Fail,
206    /// Use the non-sensitive zero/empty value of the declared target kind.
207    ///
208    /// This is deliberately not an arbitrary literal default: user values stay
209    /// out of manifests and fingerprints.
210    TypeDefault,
211}
212
213impl MissingParameterPolicy {
214    /// Returns the stable manifest code.
215    #[must_use]
216    pub const fn as_str(self) -> &'static str {
217        match self {
218            Self::Fail => "fail",
219            Self::TypeDefault => "type_default",
220        }
221    }
222}
223
224/// One deterministic typed child-parameter mapping.
225#[derive(Clone, Debug, Eq, PartialEq)]
226pub struct NestedJobParameterMapping {
227    target: ParameterName,
228    role: ParameterRole,
229    source: NestedJobParameterSource,
230    expected: ParameterValueKind,
231    coercion: ParameterCoercion,
232    missing: MissingParameterPolicy,
233}
234
235impl NestedJobParameterMapping {
236    /// Declares one child-parameter mapping.
237    #[must_use]
238    pub const fn new(
239        target: ParameterName,
240        role: ParameterRole,
241        source: NestedJobParameterSource,
242        expected: ParameterValueKind,
243        coercion: ParameterCoercion,
244        missing: MissingParameterPolicy,
245    ) -> Self {
246        Self {
247            target,
248            role,
249            source,
250            expected,
251            coercion,
252            missing,
253        }
254    }
255
256    /// Borrows the child parameter name.
257    #[must_use]
258    pub const fn target(&self) -> &ParameterName {
259        &self.target
260    }
261
262    /// Returns whether the mapped child parameter selects child instance identity.
263    #[must_use]
264    pub const fn role(&self) -> ParameterRole {
265        self.role
266    }
267
268    /// Borrows the structured source declaration.
269    #[must_use]
270    pub const fn source(&self) -> &NestedJobParameterSource {
271        &self.source
272    }
273
274    /// Returns the required child parameter type.
275    #[must_use]
276    pub const fn expected_kind(&self) -> ParameterValueKind {
277        self.expected
278    }
279
280    /// Returns the deterministic coercion policy.
281    #[must_use]
282    pub const fn coercion(&self) -> ParameterCoercion {
283        self.coercion
284    }
285
286    /// Returns missing-source behavior.
287    #[must_use]
288    pub const fn missing_policy(&self) -> MissingParameterPolicy {
289        self.missing
290    }
291
292    pub(crate) fn manifest_value(&self) -> Value {
293        json!({
294            "coercion": self.coercion.as_str(),
295            "expected": self.expected.as_str(),
296            "missing": self.missing.as_str(),
297            "role": match self.role {
298                ParameterRole::Identifying => "identifying",
299                ParameterRole::NonIdentifying => "non_identifying",
300            },
301            "source": self.source.manifest_value(),
302            "target": self.target.as_str()
303        })
304    }
305}
306
307/// A format-4 nested-job lifecycle boundary.
308#[derive(Clone, Debug, Eq, PartialEq)]
309pub struct NestedJobNode {
310    id: NodeId,
311    child_definition: DefinitionIdentity,
312    mapping_revision: ComponentRevision,
313    mappings: Vec<NestedJobParameterMapping>,
314}
315
316impl NestedJobNode {
317    /// Declares a child definition and its complete deterministic parameter map.
318    ///
319    /// Mappings are canonicalized by child parameter name so builder declaration
320    /// order cannot change the definition fingerprint.
321    ///
322    /// # Errors
323    ///
324    /// Rejects a legacy/unbound child identity, more than 64 mappings, or a
325    /// duplicate child parameter name.
326    pub fn new(
327        id: NodeId,
328        child_definition: DefinitionIdentity,
329        mapping_revision: ComponentRevision,
330        mut mappings: Vec<NestedJobParameterMapping>,
331    ) -> Result<Self, PlanError> {
332        if child_definition.job_name().is_none() {
333            return Err(PlanError::NestedJobMissingChildIdentity { node: id });
334        }
335        if mappings.len() > MAX_NESTED_JOB_PARAMETERS {
336            return Err(PlanError::TooManyNestedJobParameters {
337                node: id,
338                max: MAX_NESTED_JOB_PARAMETERS,
339            });
340        }
341        mappings.sort_by(|left, right| left.target.cmp(&right.target));
342        let mut targets = BTreeSet::new();
343        for mapping in &mappings {
344            if !targets.insert(mapping.target.clone()) {
345                return Err(PlanError::DuplicateNestedJobParameter {
346                    node: id,
347                    parameter: mapping.target.clone(),
348                });
349            }
350        }
351        Ok(Self {
352            id,
353            child_definition,
354            mapping_revision,
355            mappings,
356        })
357    }
358
359    /// Borrows the stable parent logical node identifier.
360    #[must_use]
361    pub const fn id(&self) -> &NodeId {
362        &self.id
363    }
364
365    /// Borrows the exact child definition identity required by the node.
366    #[must_use]
367    pub const fn child_definition(&self) -> &DefinitionIdentity {
368        &self.child_definition
369    }
370
371    /// Borrows the mapping implementation revision.
372    #[must_use]
373    pub const fn mapping_revision(&self) -> &ComponentRevision {
374        &self.mapping_revision
375    }
376
377    /// Borrows mappings in canonical target-name order.
378    #[must_use]
379    pub fn mappings(&self) -> &[NestedJobParameterMapping] {
380        &self.mappings
381    }
382
383    pub(crate) fn manifest_value(&self) -> Value {
384        let child_name = self.child_definition.job_name().map_or("", JobName::as_str);
385        json!({
386            "child": {
387                "fingerprint": digest_hex(self.child_definition.manifest_digest()),
388                "format": self.child_definition.manifest_format(),
389                "job": child_name,
390                "revision": self.child_definition.revision().as_str()
391            },
392            "id": self.id.as_str(),
393            "kind": "nested_job",
394            "mapping_revision": self.mapping_revision.as_str(),
395            "parameters": self
396                .mappings
397                .iter()
398                .map(NestedJobParameterMapping::manifest_value)
399                .collect::<Vec<_>>()
400        })
401    }
402}
403
404fn digest_hex(digest: &[u8; 32]) -> String {
405    const HEX: &[u8; 16] = b"0123456789abcdef";
406    let mut encoded = String::with_capacity(64);
407    for byte in digest {
408        encoded.push(char::from(HEX[usize::from(byte >> 4)]));
409        encoded.push(char::from(HEX[usize::from(byte & 0x0f)]));
410    }
411    encoded
412}