postproject_core/job_lease.rs
1//! Shared lease duration and local ownership states.
2
3use std::time::Duration;
4
5use crate::{Error, ErrorKind, JobId, ProductionId, Result, Timestamp};
6
7/// Backend-owned, production-bound worker capability; never a claim-ID pair.
8///
9/// Implementations keep credentials private and omit them from diagnostics.
10/// Dropping ownership never renews, releases or writes a claim.
11pub trait JobLease {
12 /// Returns the production scope without a credential.
13 fn production_id(&self) -> ProductionId;
14 /// Returns the claimed job without a credential.
15 fn job_id(&self) -> JobId;
16 /// Returns cached local ownership; transitions always recheck the store.
17 ///
18 /// # Errors
19 /// Returns an ownership-state error when local state cannot be read.
20 fn state(&self) -> Result<JobLeaseState>;
21 /// Explicitly exports a bounded versioned credential for file/pipe transport.
22 ///
23 /// # Errors
24 /// Rejects pending or closed ownership. Import revalidates current authority.
25 fn export_token(&self) -> Result<String>;
26}
27
28/// Longest supported job lease: one day.
29pub const MAX_JOB_LEASE_DURATION: Duration = Duration::from_secs(86_400);
30
31/// Converts a positive, bounded lease duration to exact whole microseconds.
32///
33/// # Errors
34///
35/// Rejects zero, fractional microseconds and durations longer than one day.
36pub fn validate_job_lease_duration(duration: Duration) -> Result<u64> {
37 if duration.is_zero()
38 || duration > MAX_JOB_LEASE_DURATION
39 || duration.subsec_nanos() % 1_000 != 0
40 {
41 return Err(Error::new(
42 ErrorKind::InvalidArgument,
43 "job lease duration must be whole microseconds between 1 us and 24 h",
44 ));
45 }
46 u64::try_from(duration.as_micros())
47 .map_err(|_| Error::new(ErrorKind::InvalidArgument, "job lease duration overflow"))
48}
49
50/// Local ownership state; an active handle still needs authoritative validation.
51#[derive(Clone, Copy, Debug, Eq, PartialEq)]
52pub enum JobLeaseState {
53 /// The claim belongs to an edit that has not committed yet.
54 Pending,
55 /// The owning edit committed; the timestamp is the last accepted expiry.
56 Active {
57 /// Unix microseconds, rather than a process-local monotonic instant.
58 expires_at: Timestamp,
59 },
60 /// Ownership ended through a terminal transition or failed claiming edit.
61 Closed,
62}
63
64#[cfg(test)]
65mod tests {
66 use super::*;
67
68 #[test]
69 fn duration_conversion_is_exact_and_bounded() {
70 for duration in [Duration::ZERO, Duration::from_nanos(1), Duration::MAX] {
71 assert_eq!(
72 validate_job_lease_duration(duration).unwrap_err().kind(),
73 ErrorKind::InvalidArgument
74 );
75 }
76 assert_eq!(
77 validate_job_lease_duration(Duration::from_micros(1)).unwrap(),
78 1
79 );
80 assert_eq!(
81 validate_job_lease_duration(MAX_JOB_LEASE_DURATION).unwrap(),
82 86_400_000_000
83 );
84 assert!(
85 validate_job_lease_duration(MAX_JOB_LEASE_DURATION + Duration::from_micros(1)).is_err()
86 );
87 }
88}