Skip to main content

postproject_core/
job.rs

1//! Persisted work requests without scheduling or execution policy.
2
3use crate::{
4    ActivityId, AgentIdentity, AssetId, Error, ErrorKind, JobId, MediaRoot, MetadataAssertion,
5    RepresentationId, RepresentationKind, Result, Timestamp, ToolIdentity,
6};
7
8/// Maximum encoded length of a namespaced job-kind identifier.
9pub const MAX_JOB_KIND_BYTES: usize = 128;
10/// Maximum number of input representations on one job.
11pub const MAX_JOB_INPUTS: usize = 100_000;
12/// Maximum UTF-8 byte length of a failure diagnostic.
13pub const MAX_JOB_DIAGNOSTIC_BYTES: usize = 4_096;
14/// Maximum artifacts accepted by one regeneration-planning call.
15pub const MAX_REGENERATION_PLANS: usize = 100_000;
16
17/// An open-world, namespaced kind of requested work.
18#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
19pub struct JobKind(String);
20
21impl JobKind {
22    /// Creates a kind such as `org.postproject:generate-proxy`.
23    ///
24    /// # Errors
25    ///
26    /// Returns an invalid-argument error when the value is not a bounded,
27    /// namespaced ASCII identifier.
28    pub fn new(value: impl Into<String>) -> Result<Self> {
29        let value = value.into();
30        let valid_bytes = value
31            .bytes()
32            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b':'));
33        let valid_namespace = value
34            .split_once(':')
35            .is_some_and(|(namespace, local)| !namespace.is_empty() && !local.is_empty());
36        if value.len() > MAX_JOB_KIND_BYTES || !valid_bytes || !valid_namespace {
37            return Err(Error::new(
38                ErrorKind::InvalidArgument,
39                format!(
40                    "job kind must be a namespaced identifier of at most {MAX_JOB_KIND_BYTES} ASCII bytes"
41                ),
42            ));
43        }
44        Ok(Self(value))
45    }
46
47    /// Returns the exact kind identifier.
48    #[must_use]
49    pub fn as_str(&self) -> &str {
50        &self.0
51    }
52}
53
54/// The representation a successful job is expected to add.
55#[derive(Clone, Debug, Eq, PartialEq)]
56pub struct RequestedJobOutput {
57    asset_id: AssetId,
58    representation_kind: RepresentationKind,
59    target_root: Option<String>,
60}
61
62impl RequestedJobOutput {
63    /// Creates a requested output with an optional logical media-root name.
64    ///
65    /// # Errors
66    ///
67    /// Returns an invalid-argument error when `target_root` is not a portable
68    /// logical root name.
69    pub fn new(
70        asset_id: AssetId,
71        representation_kind: RepresentationKind,
72        target_root: Option<String>,
73    ) -> Result<Self> {
74        if let Some(name) = target_root.as_deref() {
75            MediaRoot::validate_name(name)?;
76        }
77        Ok(Self {
78            asset_id,
79            representation_kind,
80            target_root,
81        })
82    }
83
84    /// Returns the asset that will own the output representation.
85    #[must_use]
86    pub const fn asset_id(&self) -> AssetId {
87        self.asset_id
88    }
89
90    /// Returns the semantic representation kind to create.
91    #[must_use]
92    pub const fn representation_kind(&self) -> RepresentationKind {
93        self.representation_kind
94    }
95
96    /// Returns the optional logical output-root name.
97    #[must_use]
98    pub fn target_root(&self) -> Option<&str> {
99        self.target_root.as_deref()
100    }
101}
102
103/// Attribution and lease data for one active claim.
104#[derive(Clone, Debug, Eq, PartialEq)]
105pub struct JobClaim {
106    tool: ToolIdentity,
107    agent: Option<AgentIdentity>,
108    expires_at: Timestamp,
109}
110
111impl JobClaim {
112    /// Creates observed attribution and authority-selected expiry data.
113    /// This value grants no worker ownership.
114    #[must_use]
115    pub const fn new(
116        tool: ToolIdentity,
117        agent: Option<AgentIdentity>,
118        expires_at: Timestamp,
119    ) -> Self {
120        Self {
121            tool,
122            agent,
123            expires_at,
124        }
125    }
126
127    /// Returns the claiming tool identity.
128    #[must_use]
129    pub const fn tool(&self) -> &ToolIdentity {
130        &self.tool
131    }
132
133    /// Returns optional agent attribution for the worker.
134    #[must_use]
135    pub const fn agent(&self) -> Option<&AgentIdentity> {
136        self.agent.as_ref()
137    }
138
139    /// Returns the authority-selected lease expiry.
140    #[must_use]
141    pub const fn expires_at(&self) -> Timestamp {
142        self.expires_at
143    }
144}
145
146/// Durable result of successfully completing a job.
147#[derive(Clone, Copy, Debug, Eq, PartialEq)]
148pub struct JobCompletion {
149    activity_id: ActivityId,
150    representation_id: RepresentationId,
151}
152
153impl JobCompletion {
154    /// Creates a link to the atomically committed activity and output.
155    #[must_use]
156    pub const fn new(activity_id: ActivityId, representation_id: RepresentationId) -> Self {
157        Self {
158            activity_id,
159            representation_id,
160        }
161    }
162
163    /// Returns the activity that completed the requested work.
164    #[must_use]
165    pub const fn activity_id(self) -> ActivityId {
166        self.activity_id
167    }
168
169    /// Returns the output representation produced by the activity.
170    #[must_use]
171    pub const fn representation_id(self) -> RepresentationId {
172        self.representation_id
173    }
174}
175
176/// Bounded diagnostic recorded for failed work.
177#[derive(Clone, Debug, Eq, PartialEq)]
178pub struct JobFailure {
179    diagnostic: String,
180}
181
182impl JobFailure {
183    /// Creates a non-empty, bounded diagnostic.
184    ///
185    /// # Errors
186    ///
187    /// Returns an invalid-argument error for empty, oversized, or NUL-bearing
188    /// text.
189    pub fn new(diagnostic: impl Into<String>) -> Result<Self> {
190        let diagnostic = diagnostic.into();
191        if diagnostic.is_empty()
192            || diagnostic.len() > MAX_JOB_DIAGNOSTIC_BYTES
193            || diagnostic.contains('\0')
194        {
195            return Err(Error::new(
196                ErrorKind::InvalidArgument,
197                format!(
198                    "job failure diagnostic must contain 1-{MAX_JOB_DIAGNOSTIC_BYTES} UTF-8 bytes without NUL"
199                ),
200            ));
201        }
202        Ok(Self { diagnostic })
203    }
204
205    /// Returns the exact recorded diagnostic.
206    #[must_use]
207    pub fn diagnostic(&self) -> &str {
208        &self.diagnostic
209    }
210}
211
212/// Lifecycle state category for filtering and foreign interfaces.
213#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
214#[non_exhaustive]
215pub enum JobStateKind {
216    /// Waiting for a worker.
217    Requested,
218    /// Held by a worker until its lease expires.
219    Claimed,
220    /// Completed with an activity and representation.
221    Succeeded,
222    /// Ended with a diagnostic and no output.
223    Failed,
224    /// Explicitly cancelled before completion.
225    Cancelled,
226}
227
228/// Optional exact predicates for durable job enumeration.
229#[derive(Clone, Debug, Default, Eq, PartialEq)]
230pub struct JobQuery {
231    state: Option<JobStateKind>,
232    kind: Option<JobKind>,
233}
234
235impl JobQuery {
236    /// Creates a query from optional state and open-world kind predicates.
237    #[must_use]
238    pub const fn new(state: Option<JobStateKind>, kind: Option<JobKind>) -> Self {
239        Self { state, kind }
240    }
241
242    /// Returns the exact state predicate, when present.
243    #[must_use]
244    pub const fn state(&self) -> Option<JobStateKind> {
245        self.state
246    }
247
248    /// Returns the exact job-kind predicate, when present.
249    #[must_use]
250    pub const fn kind(&self) -> Option<&JobKind> {
251        self.kind.as_ref()
252    }
253}
254
255/// Validated lifecycle state and its state-specific detail.
256#[derive(Clone, Debug, Eq, PartialEq)]
257#[non_exhaustive]
258pub enum JobState {
259    /// Waiting for a worker.
260    Requested,
261    /// Held by a worker until its lease expires.
262    Claimed(JobClaim),
263    /// Completed with an activity and output representation.
264    Succeeded(JobCompletion),
265    /// Ended with a bounded diagnostic.
266    Failed(JobFailure),
267    /// Explicitly cancelled.
268    Cancelled,
269}
270
271impl JobState {
272    /// Returns the state category without its detail.
273    #[must_use]
274    pub const fn kind(&self) -> JobStateKind {
275        match self {
276            Self::Requested => JobStateKind::Requested,
277            Self::Claimed(_) => JobStateKind::Claimed,
278            Self::Succeeded(_) => JobStateKind::Succeeded,
279            Self::Failed(_) => JobStateKind::Failed,
280            Self::Cancelled => JobStateKind::Cancelled,
281        }
282    }
283}
284
285/// One persisted request for production work.
286#[derive(Clone, Debug, Eq, PartialEq)]
287pub struct Job {
288    id: JobId,
289    kind: JobKind,
290    inputs: Vec<RepresentationId>,
291    requested_output: RequestedJobOutput,
292    state: JobState,
293}
294
295/// A non-persisted job request and copied parameters for one artifact.
296#[derive(Clone, Debug, Eq, PartialEq)]
297pub struct RegenerationJobPlan {
298    artifact_representation_id: RepresentationId,
299    job: Job,
300    parameters: Vec<MetadataAssertion>,
301}
302
303impl RegenerationJobPlan {
304    /// Creates a backend-derived regeneration plan without enqueuing it.
305    #[doc(hidden)]
306    #[must_use]
307    pub fn new(
308        artifact_representation_id: RepresentationId,
309        job: Job,
310        parameters: Vec<MetadataAssertion>,
311    ) -> Self {
312        Self {
313            artifact_representation_id,
314            job,
315            parameters,
316        }
317    }
318
319    /// Returns the existing artifact this request would regenerate.
320    #[must_use]
321    pub const fn artifact_representation_id(&self) -> RepresentationId {
322        self.artifact_representation_id
323    }
324
325    /// Returns the requested job, which has not been persisted.
326    #[must_use]
327    pub const fn job(&self) -> &Job {
328        &self.job
329    }
330
331    /// Returns activity parameter assertions copied for the future job target.
332    #[must_use]
333    pub fn parameters(&self) -> &[MetadataAssertion] {
334        &self.parameters
335    }
336}
337
338impl Job {
339    /// Creates a requested job with canonical, distinct inputs.
340    ///
341    /// # Errors
342    ///
343    /// Returns an invalid-argument error for duplicate or excessive inputs.
344    pub fn new(
345        id: JobId,
346        kind: JobKind,
347        mut inputs: Vec<RepresentationId>,
348        requested_output: RequestedJobOutput,
349    ) -> Result<Self> {
350        if inputs.len() > MAX_JOB_INPUTS {
351            return Err(Error::new(
352                ErrorKind::InvalidArgument,
353                format!("job must have at most {MAX_JOB_INPUTS} inputs"),
354            ));
355        }
356        let supplied_count = inputs.len();
357        inputs.sort_unstable();
358        inputs.dedup();
359        if inputs.len() != supplied_count {
360            return Err(Error::new(
361                ErrorKind::InvalidArgument,
362                "job input representations must be distinct",
363            ));
364        }
365        Ok(Self {
366            id,
367            kind,
368            inputs,
369            requested_output,
370            state: JobState::Requested,
371        })
372    }
373
374    /// Returns the stable job identity.
375    #[must_use]
376    pub const fn id(&self) -> JobId {
377        self.id
378    }
379
380    /// Returns the exact open-world job kind.
381    #[must_use]
382    pub const fn kind(&self) -> &JobKind {
383        &self.kind
384    }
385
386    /// Returns canonical input representation identities.
387    #[must_use]
388    pub fn inputs(&self) -> &[RepresentationId] {
389        &self.inputs
390    }
391
392    /// Returns the requested output description.
393    #[must_use]
394    pub const fn requested_output(&self) -> &RequestedJobOutput {
395        &self.requested_output
396    }
397
398    /// Returns the lifecycle state and its state-specific detail.
399    #[must_use]
400    pub const fn state(&self) -> &JobState {
401        &self.state
402    }
403
404    /// Replaces lifecycle state when reconstructing a storage-owned job.
405    #[doc(hidden)]
406    #[must_use]
407    pub fn with_state(mut self, state: JobState) -> Self {
408        self.state = state;
409        self
410    }
411}
412
413#[cfg(test)]
414mod tests {
415    use super::*;
416
417    fn output() -> RequestedJobOutput {
418        RequestedJobOutput::new(
419            AssetId::from_bytes([1; 16]),
420            RepresentationKind::Proxy,
421            Some("proxies".to_owned()),
422        )
423        .expect("valid output")
424    }
425
426    #[test]
427    fn job_kind_is_open_world_namespaced_text() {
428        assert!(JobKind::new("org.postproject:generate-proxy").is_ok());
429        assert!(JobKind::new("studio.example:custom_work").is_ok());
430        assert!(JobKind::new("not-namespaced").is_err());
431    }
432
433    #[test]
434    fn requested_jobs_canonicalize_and_reject_duplicate_inputs() {
435        let first = RepresentationId::from_bytes([1; 16]);
436        let second = RepresentationId::from_bytes([2; 16]);
437        let job = Job::new(
438            JobId::from_bytes([3; 16]),
439            JobKind::new("org.postproject:render").expect("valid kind"),
440            vec![second, first],
441            output(),
442        )
443        .expect("valid job");
444        assert_eq!(job.inputs(), [first, second]);
445        assert_eq!(job.state().kind(), JobStateKind::Requested);
446        assert!(
447            Job::new(
448                JobId::new(),
449                JobKind::new("org.postproject:render").expect("valid kind"),
450                vec![first, first],
451                output(),
452            )
453            .is_err()
454        );
455    }
456
457    #[test]
458    fn diagnostics_and_output_roots_are_bounded() {
459        assert!(JobFailure::new("").is_err());
460        assert!(JobFailure::new("failed to encode").is_ok());
461        assert!(
462            RequestedJobOutput::new(
463                AssetId::new(),
464                RepresentationKind::Proxy,
465                Some("../machine-path".to_owned()),
466            )
467            .is_err()
468        );
469    }
470}