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
11pub const MAX_NESTED_JOB_PARAMETERS: usize = 64;
13pub use oxide_batch_core::{MAX_SELECTOR_PATH_BYTES, MAX_SELECTOR_PATH_SEGMENTS};
14
15#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
21pub struct SelectorPath(Vec<String>);
22
23impl SelectorPath {
24 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 #[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#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
54#[non_exhaustive]
55pub enum FrameworkParameterSource {
56 ParentJobInstanceId,
58 ParentJobExecutionId,
60 ParentAttempt,
62 ParentDefinitionRevision,
64 ParentDefinitionFingerprint,
66 NestedJobNodeId,
68}
69
70impl FrameworkParameterSource {
71 #[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 #[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#[derive(Clone, Debug, Eq, PartialEq)]
100#[non_exhaustive]
101pub enum NestedJobParameterSource {
102 ParentParameter(ParameterName),
104 ParentJobContext {
106 schema: StateSchemaId,
108 schema_version: StateSchemaVersion,
110 path: SelectorPath,
112 },
113 ParentStepContext {
115 node: NodeId,
117 schema: StateSchemaId,
119 schema_version: StateSchemaVersion,
121 path: SelectorPath,
123 },
124 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#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
167#[non_exhaustive]
168pub enum ParameterCoercion {
169 #[default]
171 Exact,
172 StringToI64,
174 StringToU64,
176 StringToBool,
178 I64ToU64,
180 U64ToI64,
182}
183
184impl ParameterCoercion {
185 #[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#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
201#[non_exhaustive]
202pub enum MissingParameterPolicy {
203 #[default]
205 Fail,
206 TypeDefault,
211}
212
213impl MissingParameterPolicy {
214 #[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#[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 #[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 #[must_use]
258 pub const fn target(&self) -> &ParameterName {
259 &self.target
260 }
261
262 #[must_use]
264 pub const fn role(&self) -> ParameterRole {
265 self.role
266 }
267
268 #[must_use]
270 pub const fn source(&self) -> &NestedJobParameterSource {
271 &self.source
272 }
273
274 #[must_use]
276 pub const fn expected_kind(&self) -> ParameterValueKind {
277 self.expected
278 }
279
280 #[must_use]
282 pub const fn coercion(&self) -> ParameterCoercion {
283 self.coercion
284 }
285
286 #[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#[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 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 #[must_use]
361 pub const fn id(&self) -> &NodeId {
362 &self.id
363 }
364
365 #[must_use]
367 pub const fn child_definition(&self) -> &DefinitionIdentity {
368 &self.child_definition
369 }
370
371 #[must_use]
373 pub const fn mapping_revision(&self) -> &ComponentRevision {
374 &self.mapping_revision
375 }
376
377 #[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}