use crate::LIVE_ARTIFACT_TITLE_PREFIX;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Slot {
Filed,
Loose,
FollowUp,
Assets,
Parent,
}
impl Slot {
fn name(self) -> &'static str {
match self {
Self::Filed => "filed",
Self::Loose => "loose",
Self::FollowUp => "follow-up",
Self::Assets => "assets",
Self::Parent => "parent",
}
}
fn read(value: &str) -> Option<Self> {
match value {
"filed" => Some(Self::Filed),
"loose" => Some(Self::Loose),
"follow-up" => Some(Self::FollowUp),
"assets" => Some(Self::Assets),
"parent" => Some(Self::Parent),
_ => None,
}
}
}
pub const POOL_SIZE: u8 = 16;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Scope<'a> {
team: &'a str,
stamp: Option<&'a str>,
pool: Option<u8>,
}
impl<'a> Scope<'a> {
pub fn ci(team: &'a str) -> Result<Self, String> {
if !team_valid(team) {
return Err("invalid retained Linear team identity".into());
}
Ok(Self {
team,
stamp: None,
pool: None,
})
}
pub fn pooled(team: &'a str, index: u8) -> Result<Self, String> {
if !(1..=POOL_SIZE).contains(&index) {
return Err(format!(
"invalid retained Linear pool member {index}; the pool is 1..={POOL_SIZE}"
));
}
Ok(Self {
pool: Some(index),
..Self::ci(team)?
})
}
#[must_use]
pub fn pool_index(self) -> Option<u8> {
self.pool
}
pub fn local(team: &'a str, stamp: &'a str) -> Result<Self, String> {
let scope = Self::ci(team)?;
if !stamp_valid(stamp) {
return Err("invalid retained Linear local ownership stamp".into());
}
Ok(Self {
stamp: Some(stamp),
..scope
})
}
#[must_use]
pub fn team(self) -> &'a str {
self.team
}
#[must_use]
pub fn local_stamp(self) -> Option<&'a str> {
self.stamp
}
#[must_use]
pub fn is_ci(self) -> bool {
self.stamp.is_none()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Retained<'a> {
pub scope: Scope<'a>,
pub slot: Slot,
}
fn team_valid(team: &str) -> bool {
!team.is_empty()
&& team
.bytes()
.all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_' || c == b'-')
}
fn stamp_valid(stamp: &str) -> bool {
let parts: Vec<_> = stamp.split('-').collect();
parts.len() == 3
&& parts.iter().all(|part| {
!part.starts_with('0')
&& part.bytes().all(|c| c.is_ascii_digit())
&& part.parse::<u64>().is_ok_and(|value| value > 0)
})
&& parts[..2].iter().all(|part| part.parse::<u32>().is_ok())
}
pub fn retained_title(scope: Scope<'_>, slot: Slot) -> Result<String, String> {
let suffix = match (scope.local_stamp(), scope.pool_index()) {
(None, None) => format!("ci {} {}", scope.team(), slot.name()),
(None, Some(index)) => format!("ci {} {} pool-{index}", scope.team(), slot.name()),
(Some(stamp), _) => format!("local {} {} {stamp}", scope.team(), slot.name()),
};
Ok(format!("{LIVE_ARTIFACT_TITLE_PREFIX}retained-v1 {suffix}"))
}
#[must_use]
pub fn classify_retained(title: &str) -> Option<Retained<'_>> {
let suffix = title
.strip_prefix(LIVE_ARTIFACT_TITLE_PREFIX)?
.strip_prefix("retained-v1 ")?;
let parts: Vec<_> = suffix.split(' ').collect();
let (scope, slot) = match parts.as_slice() {
["ci", team, slot] => (Scope::ci(team).ok()?, Slot::read(slot)?),
["ci", team, slot, pool] => (
Scope::pooled(team, pool_index_read(pool)?).ok()?,
Slot::read(slot)?,
),
["local", team, slot, stamp] => (Scope::local(team, stamp).ok()?, Slot::read(slot)?),
_ => return None,
};
Some(Retained { scope, slot })
}
fn pool_index_read(token: &str) -> Option<u8> {
let digits = token.strip_prefix("pool-")?;
if digits.starts_with('0') || !digits.bytes().all(|c| c.is_ascii_digit()) {
return None;
}
digits.parse().ok()
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LeaseLane {
Plugin,
Assets,
}
impl LeaseLane {
fn name(self) -> &'static str {
match self {
Self::Plugin => "plugin",
Self::Assets => "assets",
}
}
fn read(value: &str) -> Option<Self> {
match value {
"plugin" => Some(Self::Plugin),
"assets" => Some(Self::Assets),
_ => None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct HolderStamp<'a>(&'a str);
impl<'a> HolderStamp<'a> {
pub fn new(stamp: &'a str) -> Result<Self, String> {
if lease_stamp_valid(stamp) {
Ok(Self(stamp))
} else {
Err(format!(
"{stamp:?} is not a Linear lease holder's machine stamp"
))
}
}
#[must_use]
pub fn as_str(self) -> &'a str {
self.0
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LeaseHolder<'a> {
Held(HolderStamp<'a>),
Released,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Lease<'a> {
scope: Scope<'a>,
lane: LeaseLane,
generation: std::num::NonZeroU32,
holder: LeaseHolder<'a>,
}
impl<'a> Lease<'a> {
pub fn new(
scope: Scope<'a>,
lane: LeaseLane,
generation: std::num::NonZeroU32,
holder: LeaseHolder<'a>,
) -> Result<Self, String> {
if scope.pool_index().is_none() {
return Err("a Linear lease names a pool member's scope".into());
}
Ok(Self {
scope,
lane,
generation,
holder,
})
}
#[must_use]
pub fn team(self) -> &'a str {
self.scope.team()
}
#[must_use]
pub fn lane(self) -> LeaseLane {
self.lane
}
#[must_use]
pub fn index(self) -> u8 {
self.scope
.pool_index()
.expect("a lease is made of a pooled scope")
}
#[must_use]
pub fn generation(self) -> u32 {
self.generation.get()
}
#[must_use]
pub fn holder(self) -> LeaseHolder<'a> {
self.holder
}
#[must_use]
pub fn scope(self) -> Scope<'a> {
self.scope
}
}
#[must_use]
pub fn lease_title(lease: Lease<'_>) -> String {
let holder = match lease.holder {
LeaseHolder::Held(stamp) => stamp.as_str(),
LeaseHolder::Released => "released",
};
format!(
"{LIVE_ARTIFACT_TITLE_PREFIX}lease-v1 {} {} pool-{} gen-{} {holder}",
lease.team(),
lease.lane.name(),
lease.index(),
lease.generation
)
}
#[must_use]
pub fn lease_title_prefix(team: &str, lane: LeaseLane) -> String {
format!(
"{LIVE_ARTIFACT_TITLE_PREFIX}lease-v1 {team} {} ",
lane.name()
)
}
#[must_use]
pub fn classify_lease(title: &str) -> Option<Lease<'_>> {
let suffix = title
.strip_prefix(LIVE_ARTIFACT_TITLE_PREFIX)?
.strip_prefix("lease-v1 ")?;
let parts: Vec<_> = suffix.split(' ').collect();
let [team, lane, pool, generation, holder] = parts.as_slice() else {
return None;
};
let scope = Scope::pooled(team, pool_index_read(pool)?).ok()?;
let digits = generation.strip_prefix("gen-")?;
if digits.starts_with('0') || !digits.bytes().all(|c| c.is_ascii_digit()) {
return None;
}
let holder = match *holder {
"released" => LeaseHolder::Released,
stamp => LeaseHolder::Held(HolderStamp::new(stamp).ok()?),
};
Lease::new(scope, LeaseLane::read(lane)?, digits.parse().ok()?, holder).ok()
}
fn lease_stamp_valid(stamp: &str) -> bool {
stamp_valid(stamp)
|| stamp
.strip_prefix("0-")
.is_some_and(|rest| stamp_valid(&format!("1-{rest}")))
}
#[must_use]
pub fn lease_created_micros(created_at: &str) -> Option<u64> {
let at = chrono::DateTime::parse_from_rfc3339(created_at).ok()?;
u64::try_from(at.timestamp_micros()).ok()
}
#[must_use]
pub fn now_rfc3339() -> String {
chrono::Utc::now().to_rfc3339()
}
#[must_use]
pub fn is_reserved_title(title: &str) -> bool {
title
.strip_prefix(LIVE_ARTIFACT_TITLE_PREFIX)
.is_some_and(|suffix| suffix.starts_with("retained-") || suffix.starts_with("lease-"))
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LeaseRecord {
id: String,
title: String,
}
impl LeaseRecord {
pub fn new(id: &str, title: &str) -> Result<Self, String> {
let record = Self {
id: id.to_owned(),
title: title.to_owned(),
};
record.lease()?;
if id.is_empty() || id.chars().any(char::is_control) {
return Err("a lease record names an unusable issue id".into());
}
Ok(record)
}
#[must_use]
pub fn to_json(&self) -> String {
serde_json::json!({"id":self.id,"title":self.title}).to_string()
}
pub fn read(bytes: &[u8]) -> Result<Self, String> {
let value: serde_json::Value = serde_json::from_slice(bytes)
.map_err(|error| format!("not a lease record: {error}"))?;
let (Some(id), Some(title)) = (value["id"].as_str(), value["title"].as_str()) else {
return Err("a lease record names no issue id and title".into());
};
Self::new(id, title)
}
#[must_use]
pub fn id(&self) -> &str {
&self.id
}
#[must_use]
pub fn title(&self) -> &str {
&self.title
}
pub fn lease(&self) -> Result<Lease<'_>, String> {
classify_lease(&self.title)
.filter(|lease| matches!(lease.holder(), LeaseHolder::Held(_)))
.ok_or_else(|| format!("a lease record names no held lease: {:?}", self.title))
}
}