Skip to main content

onetaskgraph_linear/
live_artifact.rs

1//! Retained live-test identities. Recognition establishes ownership syntax only; callers
2//! must independently verify the nominated team before mutating a discovered item.
3use crate::LIVE_ARTIFACT_TITLE_PREFIX;
4
5/// Four document slots and the project that holds filed documents.
6#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7pub enum Slot {
8    /// Project-filed document probe.
9    Filed,
10    /// Team-owned document without a project.
11    Loose,
12    /// Metadata and follow-up update probe.
13    FollowUp,
14    /// Binary copy and recopy destination.
15    Assets,
16    /// Retained project, separate from the four document slots.
17    Parent,
18}
19impl Slot {
20    fn name(self) -> &'static str {
21        match self {
22            Self::Filed => "filed",
23            Self::Loose => "loose",
24            Self::FollowUp => "follow-up",
25            Self::Assets => "assets",
26            Self::Parent => "parent",
27        }
28    }
29    fn read(value: &str) -> Option<Self> {
30        match value {
31            "filed" => Some(Self::Filed),
32            "loose" => Some(Self::Loose),
33            "follow-up" => Some(Self::FollowUp),
34            "assets" => Some(Self::Assets),
35            "parent" => Some(Self::Parent),
36            _ => None,
37        }
38    }
39}
40
41/// How many standing CI slot sets the nominated team holds. A CI run leases one member of
42/// the pool for its whole session, so this many runs can execute the live lanes at once,
43/// each over documents no other run reads, writes or counts; twice the eight concurrent runs
44/// the lanes are sized for, at 4 documents and 1 project per member, 64 of the team's 1000
45/// documents.
46pub const POOL_SIZE: u8 = 16;
47
48/// CI identities are stable; local identities belong to one registered invocation.
49///
50/// A CI identity is one member of the standing pool (`pool` is `Some`), or the single
51/// pre-pool standing set (`pool` is `None`), which no lane uses any more and which is still
52/// recognized so the scheduled janitor can tell it apart and retire it.
53#[derive(Clone, Copy, Debug, PartialEq, Eq)]
54pub struct Scope<'a> {
55    team: &'a str,
56    stamp: Option<&'a str>,
57    pool: Option<u8>,
58}
59impl<'a> Scope<'a> {
60    /// Validate the canonical team key of the pre-pool standing CI set.
61    pub fn ci(team: &'a str) -> Result<Self, String> {
62        if !team_valid(team) {
63            return Err("invalid retained Linear team identity".into());
64        }
65        Ok(Self {
66            team,
67            stamp: None,
68            pool: None,
69        })
70    }
71
72    /// Validate the team key and a member `index` of the standing pool, `1..=POOL_SIZE`.
73    pub fn pooled(team: &'a str, index: u8) -> Result<Self, String> {
74        if !(1..=POOL_SIZE).contains(&index) {
75            return Err(format!(
76                "invalid retained Linear pool member {index}; the pool is 1..={POOL_SIZE}"
77            ));
78        }
79        Ok(Self {
80            pool: Some(index),
81            ..Self::ci(team)?
82        })
83    }
84
85    /// The pool member this standing set is, absent for a local set and the pre-pool one.
86    #[must_use]
87    pub fn pool_index(self) -> Option<u8> {
88        self.pool
89    }
90
91    /// Validate the team key and a canonical, positively vouched local ownership stamp.
92    pub fn local(team: &'a str, stamp: &'a str) -> Result<Self, String> {
93        let scope = Self::ci(team)?;
94        if !stamp_valid(stamp) {
95            return Err("invalid retained Linear local ownership stamp".into());
96        }
97        Ok(Self {
98            stamp: Some(stamp),
99            ..scope
100        })
101    }
102
103    /// The validated canonical nominated team key.
104    #[must_use]
105    pub fn team(self) -> &'a str {
106        self.team
107    }
108
109    /// The validated invocation stamp, absent for the standing CI set.
110    #[must_use]
111    pub fn local_stamp(self) -> Option<&'a str> {
112        self.stamp
113    }
114
115    /// Whether this is the standing CI set.
116    #[must_use]
117    pub fn is_ci(self) -> bool {
118        self.stamp.is_none()
119    }
120}
121
122/// Exact recognized identity; this alone does not verify remote team membership.
123#[derive(Clone, Copy, Debug, PartialEq, Eq)]
124pub struct Retained<'a> {
125    /// Who owns this standing set.
126    pub scope: Scope<'a>,
127    /// Which probe or parent this object represents.
128    pub slot: Slot,
129}
130
131fn team_valid(team: &str) -> bool {
132    !team.is_empty()
133        && team
134            .bytes()
135            .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_' || c == b'-')
136}
137fn stamp_valid(stamp: &str) -> bool {
138    let parts: Vec<_> = stamp.split('-').collect();
139    parts.len() == 3
140        && parts.iter().all(|part| {
141            !part.starts_with('0')
142                && part.bytes().all(|c| c.is_ascii_digit())
143                && part.parse::<u64>().is_ok_and(|value| value > 0)
144        })
145        && parts[..2].iter().all(|part| part.parse::<u32>().is_ok())
146}
147
148/// Format an identity whose team and stamp were validated at scope construction.
149pub fn retained_title(scope: Scope<'_>, slot: Slot) -> Result<String, String> {
150    let suffix = match (scope.local_stamp(), scope.pool_index()) {
151        (None, None) => format!("ci {} {}", scope.team(), slot.name()),
152        (None, Some(index)) => format!("ci {} {} pool-{index}", scope.team(), slot.name()),
153        (Some(stamp), _) => format!("local {} {} {stamp}", scope.team(), slot.name()),
154    };
155    Ok(format!("{LIVE_ARTIFACT_TITLE_PREFIX}retained-v1 {suffix}"))
156}
157
158/// Recognize only exact identities. Unknown versions, extra tokens and malformed markers
159/// confer no authority, including authority to clean up an item.
160#[must_use]
161pub fn classify_retained(title: &str) -> Option<Retained<'_>> {
162    let suffix = title
163        .strip_prefix(LIVE_ARTIFACT_TITLE_PREFIX)?
164        .strip_prefix("retained-v1 ")?;
165    let parts: Vec<_> = suffix.split(' ').collect();
166    let (scope, slot) = match parts.as_slice() {
167        ["ci", team, slot] => (Scope::ci(team).ok()?, Slot::read(slot)?),
168        ["ci", team, slot, pool] => (
169            Scope::pooled(team, pool_index_read(pool)?).ok()?,
170            Slot::read(slot)?,
171        ),
172        ["local", team, slot, stamp] => (Scope::local(team, stamp).ok()?, Slot::read(slot)?),
173        _ => return None,
174    };
175    Some(Retained { scope, slot })
176}
177
178fn pool_index_read(token: &str) -> Option<u8> {
179    let digits = token.strip_prefix("pool-")?;
180    if digits.starts_with('0') || !digits.bytes().all(|c| c.is_ascii_digit()) {
181        return None;
182    }
183    digits.parse().ok()
184}
185
186/// Which lane holds a pool member's lease: the plugin lane's three document slots and the
187/// parent project, or the asset lane's one destination.
188#[derive(Clone, Copy, Debug, PartialEq, Eq)]
189pub enum LeaseLane {
190    /// `onetaskgraph-linear`'s capability journey.
191    Plugin,
192    /// `onetaskgraph-linear-e2e`'s asset journey.
193    Assets,
194}
195impl LeaseLane {
196    fn name(self) -> &'static str {
197        match self {
198            Self::Plugin => "plugin",
199            Self::Assets => "assets",
200        }
201    }
202    fn read(value: &str) -> Option<Self> {
203        match value {
204            "plugin" => Some(Self::Plugin),
205            "assets" => Some(Self::Assets),
206            _ => None,
207        }
208    }
209}
210
211/// A lease holder's canonical machine stamp, validated where it is made.
212#[derive(Clone, Copy, Debug, PartialEq, Eq)]
213pub struct HolderStamp<'a>(&'a str);
214impl<'a> HolderStamp<'a> {
215    /// Validate `stamp` as a holder's machine stamp (see [`lease_stamp_valid`]).
216    pub fn new(stamp: &'a str) -> Result<Self, String> {
217        if lease_stamp_valid(stamp) {
218            Ok(Self(stamp))
219        } else {
220            Err(format!(
221                "{stamp:?} is not a Linear lease holder's machine stamp"
222            ))
223        }
224    }
225
226    /// The stamp as written.
227    #[must_use]
228    pub fn as_str(self) -> &'a str {
229        self.0
230    }
231}
232
233/// Who a lease names: a live holder, or nobody once it was released.
234#[derive(Clone, Copy, Debug, PartialEq, Eq)]
235pub enum LeaseHolder<'a> {
236    /// Held by the invocation carrying this stamp.
237    Held(HolderStamp<'a>),
238    /// Released by its holder; the next generation may be claimed.
239    Released,
240}
241
242/// One generation of the lease over one pool member, read off a lease issue's title.
243///
244/// A generation is claimed by creating the issue whose id a lane derives from it, which
245/// Linear refuses when that id already exists, so at most one invocation ever holds a
246/// generation; the newest generation of a member is its current lease. Every part is
247/// validated where the lease is made: a pool member's scope, a generation from 1, a holder's
248/// canonical stamp.
249#[derive(Clone, Copy, Debug, PartialEq, Eq)]
250pub struct Lease<'a> {
251    scope: Scope<'a>,
252    lane: LeaseLane,
253    generation: std::num::NonZeroU32,
254    holder: LeaseHolder<'a>,
255}
256
257impl<'a> Lease<'a> {
258    /// A lease of the pool member `scope` names, which must be one.
259    pub fn new(
260        scope: Scope<'a>,
261        lane: LeaseLane,
262        generation: std::num::NonZeroU32,
263        holder: LeaseHolder<'a>,
264    ) -> Result<Self, String> {
265        if scope.pool_index().is_none() {
266            return Err("a Linear lease names a pool member's scope".into());
267        }
268        Ok(Self {
269            scope,
270            lane,
271            generation,
272            holder,
273        })
274    }
275
276    /// The nominated team the pool belongs to.
277    #[must_use]
278    pub fn team(self) -> &'a str {
279        self.scope.team()
280    }
281
282    /// The lane whose slots this member's lease covers.
283    #[must_use]
284    pub fn lane(self) -> LeaseLane {
285        self.lane
286    }
287
288    /// The pool member, `1..=POOL_SIZE`.
289    #[must_use]
290    pub fn index(self) -> u8 {
291        self.scope
292            .pool_index()
293            .expect("a lease is made of a pooled scope")
294    }
295
296    /// The generation, from 1.
297    #[must_use]
298    pub fn generation(self) -> u32 {
299        self.generation.get()
300    }
301
302    /// Who holds it.
303    #[must_use]
304    pub fn holder(self) -> LeaseHolder<'a> {
305        self.holder
306    }
307
308    /// The pool member's standing scope.
309    #[must_use]
310    pub fn scope(self) -> Scope<'a> {
311        self.scope
312    }
313}
314
315/// The title of a lease issue.
316#[must_use]
317pub fn lease_title(lease: Lease<'_>) -> String {
318    let holder = match lease.holder {
319        LeaseHolder::Held(stamp) => stamp.as_str(),
320        LeaseHolder::Released => "released",
321    };
322    format!(
323        "{LIVE_ARTIFACT_TITLE_PREFIX}lease-v1 {} {} pool-{} gen-{} {holder}",
324        lease.team(),
325        lease.lane.name(),
326        lease.index(),
327        lease.generation
328    )
329}
330
331/// The title prefix every lease of `team`'s `lane` begins with, for a listing filter.
332#[must_use]
333pub fn lease_title_prefix(team: &str, lane: LeaseLane) -> String {
334    format!(
335        "{LIVE_ARTIFACT_TITLE_PREFIX}lease-v1 {team} {} ",
336        lane.name()
337    )
338}
339
340/// Recognize only exact lease titles; anything else confers no lease and no authority.
341#[must_use]
342pub fn classify_lease(title: &str) -> Option<Lease<'_>> {
343    let suffix = title
344        .strip_prefix(LIVE_ARTIFACT_TITLE_PREFIX)?
345        .strip_prefix("lease-v1 ")?;
346    let parts: Vec<_> = suffix.split(' ').collect();
347    let [team, lane, pool, generation, holder] = parts.as_slice() else {
348        return None;
349    };
350    let scope = Scope::pooled(team, pool_index_read(pool)?).ok()?;
351    let digits = generation.strip_prefix("gen-")?;
352    if digits.starts_with('0') || !digits.bytes().all(|c| c.is_ascii_digit()) {
353        return None;
354    }
355    let holder = match *holder {
356        "released" => LeaseHolder::Released,
357        stamp => LeaseHolder::Held(HolderStamp::new(stamp).ok()?),
358    };
359    Lease::new(scope, LeaseLane::read(lane)?, digits.parse().ok()?, holder).ok()
360}
361
362/// A lease is held under the holder's machine stamp, `<host>-<process>-<micros>`: a local
363/// set's canonical grammar, except that a host of `0` — a run no registry vouches for, as on
364/// a runner with none — still names a holder, because what a lease needs of its holder is
365/// only that no other claimant spells the same stamp.
366fn lease_stamp_valid(stamp: &str) -> bool {
367    stamp_valid(stamp)
368        || stamp
369            .strip_prefix("0-")
370            .is_some_and(|rest| stamp_valid(&format!("1-{rest}")))
371}
372
373/// When a lease issue was created, in microseconds since the epoch, read from the RFC 3339
374/// `createdAt` Linear answers with; `None` for one that does not parse or predates the epoch.
375/// A claimant decides a lease is stale by it, so an unreadable time is never read as old.
376#[must_use]
377pub fn lease_created_micros(created_at: &str) -> Option<u64> {
378    let at = chrono::DateTime::parse_from_rfc3339(created_at).ok()?;
379    u64::try_from(at.timestamp_micros()).ok()
380}
381
382/// The current time as Linear spells a `createdAt`, for the replay doubles both Linear lanes
383/// share: they stamp what they create the way Linear does, and `lease_created_micros` reads it.
384#[must_use]
385pub fn now_rfc3339() -> String {
386    chrono::Utc::now().to_rfc3339()
387}
388
389/// Whether `title` is any live-test identity that only its own lifecycle may remove: a
390/// standing slot, a lease, or a malformed or future version of either, which confers no
391/// authority to anyone.
392#[must_use]
393pub fn is_reserved_title(title: &str) -> bool {
394    title
395        .strip_prefix(LIVE_ARTIFACT_TITLE_PREFIX)
396        .is_some_and(|suffix| suffix.starts_with("retained-") || suffix.starts_with("lease-"))
397}
398
399/// What a CI lane writes down of each lease it holds, for its job's cancellation step to hand
400/// back (`onetaskgraph-live-janitor --linear --release-leases`): the lease issue's id and the
401/// title it carries while held. One definition, written by the lane and read by the janitor.
402#[derive(Clone, Debug, PartialEq, Eq)]
403pub struct LeaseRecord {
404    id: String,
405    title: String,
406}
407
408impl LeaseRecord {
409    /// A record of the held lease titled `title`, under issue `id`.
410    pub fn new(id: &str, title: &str) -> Result<Self, String> {
411        let record = Self {
412            id: id.to_owned(),
413            title: title.to_owned(),
414        };
415        record.lease()?;
416        if id.is_empty() || id.chars().any(char::is_control) {
417            return Err("a lease record names an unusable issue id".into());
418        }
419        Ok(record)
420    }
421
422    /// The record as written to its file.
423    #[must_use]
424    pub fn to_json(&self) -> String {
425        serde_json::json!({"id":self.id,"title":self.title}).to_string()
426    }
427
428    /// The record a file holds, refused unless it names a held lease and its issue.
429    pub fn read(bytes: &[u8]) -> Result<Self, String> {
430        let value: serde_json::Value = serde_json::from_slice(bytes)
431            .map_err(|error| format!("not a lease record: {error}"))?;
432        let (Some(id), Some(title)) = (value["id"].as_str(), value["title"].as_str()) else {
433            return Err("a lease record names no issue id and title".into());
434        };
435        Self::new(id, title)
436    }
437
438    /// The lease issue's id.
439    #[must_use]
440    pub fn id(&self) -> &str {
441        &self.id
442    }
443
444    /// The title the issue carries while the recorded holder holds it.
445    #[must_use]
446    pub fn title(&self) -> &str {
447        &self.title
448    }
449
450    /// The held lease the record names.
451    pub fn lease(&self) -> Result<Lease<'_>, String> {
452        classify_lease(&self.title)
453            .filter(|lease| matches!(lease.holder(), LeaseHolder::Held(_)))
454            .ok_or_else(|| format!("a lease record names no held lease: {:?}", self.title))
455    }
456}