1use crate::LIVE_ARTIFACT_TITLE_PREFIX;
4
5#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7pub enum Slot {
8 Filed,
10 Loose,
12 FollowUp,
14 Assets,
16 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
41pub const POOL_SIZE: u8 = 16;
47
48#[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 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 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 #[must_use]
87 pub fn pool_index(self) -> Option<u8> {
88 self.pool
89 }
90
91 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 #[must_use]
105 pub fn team(self) -> &'a str {
106 self.team
107 }
108
109 #[must_use]
111 pub fn local_stamp(self) -> Option<&'a str> {
112 self.stamp
113 }
114
115 #[must_use]
117 pub fn is_ci(self) -> bool {
118 self.stamp.is_none()
119 }
120}
121
122#[derive(Clone, Copy, Debug, PartialEq, Eq)]
124pub struct Retained<'a> {
125 pub scope: Scope<'a>,
127 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
148pub 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#[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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
189pub enum LeaseLane {
190 Plugin,
192 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
213pub struct HolderStamp<'a>(&'a str);
214impl<'a> HolderStamp<'a> {
215 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 #[must_use]
228 pub fn as_str(self) -> &'a str {
229 self.0
230 }
231}
232
233#[derive(Clone, Copy, Debug, PartialEq, Eq)]
235pub enum LeaseHolder<'a> {
236 Held(HolderStamp<'a>),
238 Released,
240}
241
242#[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 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 #[must_use]
278 pub fn team(self) -> &'a str {
279 self.scope.team()
280 }
281
282 #[must_use]
284 pub fn lane(self) -> LeaseLane {
285 self.lane
286 }
287
288 #[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 #[must_use]
298 pub fn generation(self) -> u32 {
299 self.generation.get()
300 }
301
302 #[must_use]
304 pub fn holder(self) -> LeaseHolder<'a> {
305 self.holder
306 }
307
308 #[must_use]
310 pub fn scope(self) -> Scope<'a> {
311 self.scope
312 }
313}
314
315#[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#[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#[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
362fn 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#[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#[must_use]
385pub fn now_rfc3339() -> String {
386 chrono::Utc::now().to_rfc3339()
387}
388
389#[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#[derive(Clone, Debug, PartialEq, Eq)]
403pub struct LeaseRecord {
404 id: String,
405 title: String,
406}
407
408impl LeaseRecord {
409 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 #[must_use]
424 pub fn to_json(&self) -> String {
425 serde_json::json!({"id":self.id,"title":self.title}).to_string()
426 }
427
428 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 #[must_use]
440 pub fn id(&self) -> &str {
441 &self.id
442 }
443
444 #[must_use]
446 pub fn title(&self) -> &str {
447 &self.title
448 }
449
450 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}