use super::send;
use onetaskgraph_linear::live_artifact::{
HolderStamp, Lease, LeaseHolder, LeaseLane, POOL_SIZE, Scope, classify_lease, lease_title,
lease_title_prefix,
};
fn generation(value: u32) -> Result<std::num::NonZeroU32, String> {
std::num::NonZeroU32::new(value).ok_or_else(|| "a Linear lease generation starts at 1".into())
}
use serde_json::{Value, json};
use std::collections::BTreeMap;
use std::time::Duration;
pub const STALE_AFTER: Duration = Duration::from_secs(6 * 60 * 60 + 30 * 60);
const ROUNDS: u32 = 3;
const LEASES: &str = "query($after:String,$filter:IssueFilter!){issues(first:100,after:$after,filter:$filter){nodes{id title createdAt} pageInfo{hasNextPage endCursor}}}";
const LEASE: &str = "query($id:String!){issue(id:$id){id title createdAt}}";
const LEASE_CREATE: &str =
"mutation($input:IssueCreateInput!){issueCreate(input:$input){success issue{id}}}";
const LEASE_UPDATE: &str = "mutation($id:String!,$input:IssueUpdateInput!){issueUpdate(id:$id,input:$input){success issue{id}}}";
const LEASE_DELETE: &str = "mutation($id:String!){issueDelete(id:$id){success}}";
#[must_use]
pub fn first_member(holder: &str) -> u8 {
digest(holder)[0] % POOL_SIZE + 1
}
fn digest(text: &str) -> [u8; 32] {
let hex = onetaskgraph_plugin_api::asset_sha256(text.as_bytes());
let mut bytes = [0u8; 32];
for (index, byte) in bytes.iter_mut().enumerate() {
*byte = u8::from_str_radix(&hex[index * 2..index * 2 + 2], 16)
.expect("asset_sha256 answers 64 hexadecimal digits");
}
bytes
}
#[must_use]
pub fn lease_id(team: &str, lane: LeaseLane, index: u8, generation: u32) -> String {
let lane = match lane {
LeaseLane::Plugin => "plugin",
LeaseLane::Assets => "assets",
};
let digest = digest(&format!(
"onetaskgraph-live-lease-v1\0{team}\0{lane}\0{index}\0{generation}"
));
let mut bytes = [0u8; 16];
bytes.copy_from_slice(&digest[..16]);
bytes[6] = (bytes[6] & 0x0f) | 0x40;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
let hex: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
format!(
"{}-{}-{}-{}-{}",
&hex[..8],
&hex[8..12],
&hex[12..16],
&hex[16..20],
&hex[20..]
)
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Held {
pub team: String,
pub lane: LeaseLane,
pub index: u8,
pub generation: u32,
pub id: String,
pub title: String,
}
impl Held {
pub fn scope(&self) -> Scope<'_> {
Scope::pooled(&self.team, self.index).expect("a held lease names a valid pool member")
}
pub async fn release(&self, endpoint: &str, key: &str) -> Result<(), String> {
let title = lease_title(Lease::new(
self.scope(),
self.lane,
generation(self.generation)?,
LeaseHolder::Released,
)?);
let data = send(
endpoint,
key,
LEASE_UPDATE,
json!({"id":self.id,"input":{"title":title}}),
)
.await
.map_err(|error| format!("pool member {} lease was not released: {error}", self.index))?;
if data["issueUpdate"]["success"] != true {
return Err(format!(
"Linear did not confirm releasing pool member {}'s lease",
self.index
));
}
if let Some(path) = self.record_path() {
let _ = std::fs::remove_file(path);
}
Ok(())
}
fn record_path(&self) -> Option<std::path::PathBuf> {
let directory = std::env::var_os(RECORD_VARIABLE)?;
Some(std::path::Path::new(&directory).join(format!("{}.json", self.id)))
}
fn record(&self) -> Result<(), String> {
let Some(path) = self.record_path() else {
return Ok(());
};
if let Some(directory) = path.parent() {
std::fs::create_dir_all(directory).map_err(|error| {
format!(
"the lease could not be recorded at {}: {error}",
path.display()
)
})?;
}
let record = onetaskgraph_linear::live_artifact::LeaseRecord::new(&self.id, &self.title)?;
std::fs::write(&path, record.to_json()).map_err(|error| {
format!(
"the lease could not be recorded at {}: {error}",
path.display()
)
})
}
}
pub const RECORD_VARIABLE: &str = "ONETASKGRAPH_LINEAR_LEASE_DIR";
struct Leases {
newest: BTreeMap<u8, (u32, String, LeaseState)>,
superseded: Vec<(u8, String)>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum LeaseState {
Free,
Held,
}
fn created_micros(node: &Value) -> Result<u64, String> {
let created = node["createdAt"]
.as_str()
.ok_or("a lease issue answered no createdAt")?;
onetaskgraph_linear::live_artifact::lease_created_micros(created)
.ok_or_else(|| format!("a lease issue answered an unreadable createdAt {created:?}"))
}
fn state_of(lease: &Lease<'_>, created: u64, now: u64) -> LeaseState {
match lease.holder() {
LeaseHolder::Released => LeaseState::Free,
LeaseHolder::Held(_) if now.saturating_sub(created) > STALE_AFTER.as_micros() as u64 => {
LeaseState::Free
}
LeaseHolder::Held(_) => LeaseState::Held,
}
}
async fn read_leases(
endpoint: &str,
key: &str,
team: &str,
lane: LeaseLane,
now: u64,
) -> Result<Leases, String> {
let prefix = lease_title_prefix(team, lane);
let filter = json!({"title":{"startsWith":prefix},"team":{"key":{"eq":team}}});
let mut after = Value::Null;
let mut newest: BTreeMap<u8, (u32, String, LeaseState)> = BTreeMap::new();
let mut superseded = Vec::new();
for _ in 0..20 {
let data = send(
endpoint,
key,
LEASES,
json!({"after":after,"filter":filter}),
)
.await?;
let page = &data["issues"];
for node in page["nodes"]
.as_array()
.ok_or("the lease listing answered no nodes")?
{
let title = node["title"]
.as_str()
.ok_or("a lease issue answered no title")?;
let id = node["id"]
.as_str()
.filter(|id| !id.is_empty())
.ok_or("a lease issue answered no id")?;
let Some(lease) = classify_lease(title).filter(|lease| lease.lane() == lane) else {
continue;
};
if !lease.team().eq_ignore_ascii_case(team)
|| id != lease_id(team, lane, lease.index(), lease.generation())
{
continue;
}
let state = state_of(&lease, created_micros(node)?, now);
match newest.get(&lease.index()) {
Some((generation, _, _)) if *generation >= lease.generation() => {
superseded.push((lease.index(), id.to_owned()));
}
_ => {
if let Some((_, older, _)) =
newest.insert(lease.index(), (lease.generation(), id.to_owned(), state))
{
superseded.push((lease.index(), older));
}
}
}
}
match page
.pointer("/pageInfo/hasNextPage")
.and_then(Value::as_bool)
{
Some(false) => return Ok(Leases { newest, superseded }),
Some(true) => {
let next = page
.pointer("/pageInfo/endCursor")
.and_then(Value::as_str)
.ok_or("the lease listing answered no cursor")?;
if after.as_str() == Some(next) {
return Err("the lease listing cursor did not advance".into());
}
after = json!(next);
}
None => return Err("the lease listing answered no pagination".into()),
}
}
Err("the lease listing did not terminate".into())
}
async fn reads_as(endpoint: &str, key: &str, id: &str, title: &str) -> bool {
send(endpoint, key, LEASE, json!({"id":id}))
.await
.is_ok_and(|data| {
data.pointer("/issue/id").and_then(Value::as_str) == Some(id)
&& data.pointer("/issue/title").and_then(Value::as_str) == Some(title)
})
}
pub async fn claim(
endpoint: &str,
key: &str,
team: &str,
team_id: &str,
lane: LeaseLane,
holder: &str,
now: impl Fn() -> u64,
) -> Result<Held, String> {
let start = first_member(holder) - 1;
let order: Vec<u8> = (0..POOL_SIZE)
.map(|offset| (start + offset) % POOL_SIZE + 1)
.collect();
for round in 0..ROUNDS {
if round > 0 {
tokio::time::sleep(Duration::from_secs(5)).await;
}
if let Some(held) =
claim_among(endpoint, key, team, team_id, lane, holder, &now, &order).await?
{
return Ok(held);
}
}
Err(format!(
"every one of the {POOL_SIZE} standing Linear slot sets for this lane is leased by a \
run still going; no document was touched. A lease frees when its run releases it, or \
{} hours after it was claimed",
STALE_AFTER.as_secs_f64() / 3600.0
))
}
pub async fn verify_exclusive(
endpoint: &str,
key: &str,
team_id: &str,
held: &Held,
) -> Result<(), String> {
let held_title = lease_title(Lease::new(
held.scope(),
held.lane,
generation(held.generation)?,
LeaseHolder::Released,
)?);
let decoy = format!("{held_title} duplicate-probe");
let answered: Value = reqwest::Client::new()
.post(endpoint)
.header("Authorization", key)
.json(&json!({"query":LEASE_CREATE,"variables":{"input":{"id":held.id,"title":decoy,"teamId":team_id}}}))
.send()
.await
.map_err(|error| format!("the lease exclusivity probe got no answer: {error}"))?
.json()
.await
.map_err(|error| format!("the lease exclusivity probe got no readable answer: {error}"))?;
let refusal = duplicate_id_refusal(&held.id);
let errors = answered
.get("errors")
.and_then(Value::as_array)
.cloned()
.unwrap_or_default();
let accepted = answered.pointer("/data/issueCreate/success") == Some(&json!(true));
if !accepted
&& !errors
.iter()
.any(|error| refuses_the_duplicate(error, &refusal))
{
return Err(format!(
"the lease exclusivity probe was not answered with Linear's duplicate-id refusal, so \
it proves nothing and the member is not used: {answered}"
));
}
let refused = !accepted;
let still = send(endpoint, key, LEASE, json!({"id":held.id})).await?;
let title = still.pointer("/issue/title").and_then(Value::as_str);
if !refused || title == Some(decoy.as_str()) {
return Err(format!(
"Linear did not refuse a second create under pool member {}'s lease id {}, so a lease is \
not exclusive and no run may lease a member; the pool's leases rest on that refusal",
held.index, held.id
));
}
if still.pointer("/issue/id").and_then(Value::as_str) != Some(held.id.as_str())
|| title != Some(held.title.as_str())
{
return Err(format!(
"pool member {}'s lease {} no longer reads as this run's ({title:?}); nothing is done \
over a member whose lease cannot be read back",
held.index, held.id
));
}
Ok(())
}
pub struct DuplicateIdRefusal {
pub code: &'static str,
pub message: &'static str,
pub presented: String,
}
#[must_use]
pub fn duplicate_id_refusal(id: &str) -> DuplicateIdRefusal {
DuplicateIdRefusal {
code: "INPUT_ERROR",
message: "conflict on insert of Issue",
presented: format!("Entity Issue with id {id} already exists."),
}
}
fn refuses_the_duplicate(error: &Value, refusal: &DuplicateIdRefusal) -> bool {
error.pointer("/extensions/code").and_then(Value::as_str) == Some(refusal.code)
&& error.get("message").and_then(Value::as_str) == Some(refusal.message)
&& error
.pointer("/extensions/userPresentableMessage")
.and_then(Value::as_str)
== Some(refusal.presented.as_str())
}
#[allow(
clippy::too_many_arguments,
reason = "claim's lane identities plus the one member asked for"
)]
pub async fn claim_member(
endpoint: &str,
key: &str,
team: &str,
team_id: &str,
lane: LeaseLane,
holder: &str,
now: impl Fn() -> u64,
index: u8,
) -> Result<Option<Held>, String> {
claim_among(endpoint, key, team, team_id, lane, holder, &now, &[index]).await
}
#[allow(
clippy::too_many_arguments,
reason = "claim's lane identities plus the members to try, each forwarded unchanged"
)]
async fn claim_among(
endpoint: &str,
key: &str,
team: &str,
team_id: &str,
lane: LeaseLane,
holder: &str,
now: &impl Fn() -> u64,
order: &[u8],
) -> Result<Option<Held>, String> {
{
let leases = read_leases(endpoint, key, team, lane, now()).await?;
for &index in order {
let generation = match leases.newest.get(&index) {
Some((_, _, LeaseState::Held)) => continue,
Some((generation, _, LeaseState::Free)) => generation
.checked_add(1)
.ok_or_else(|| format!("pool member {index}'s lease generations ran out"))?,
None => 1,
};
let lease = Lease::new(
Scope::pooled(team, index)?,
lane,
self::generation(generation)?,
LeaseHolder::Held(HolderStamp::new(holder)?),
)?;
let title = lease_title(lease);
let id = lease_id(team, lane, index, generation);
let _ = send(
endpoint,
key,
LEASE_CREATE,
json!({"input":{"id":id,"title":title,"teamId":team_id}}),
)
.await;
if !reads_as(endpoint, key, &id, &title).await {
continue;
}
let mut stale: Vec<String> = leases
.superseded
.iter()
.filter(|(member, _)| *member == index)
.map(|(_, id)| id.clone())
.collect();
if let Some((_, older, _)) = leases.newest.get(&index) {
stale.push(older.clone());
}
for older in stale {
if let Err(error) = send(endpoint, key, LEASE_DELETE, json!({"id":older})).await {
eprintln!("a superseded lease of pool member {index} was left: {error}");
}
}
let held = Held {
team: team.to_owned(),
lane,
index,
generation,
id,
title,
};
if let Err(error) = held.record() {
let released = held.release(endpoint, key).await;
return Err(match released {
Ok(()) => error,
Err(also) => format!("{error}; additionally, {also}"),
});
}
return Ok(Some(held));
}
}
Ok(None)
}
#[allow(
dead_code,
reason = "this module is compiled into both lanes' test binaries, and the asset lane blocks on its runtime by hand instead"
)]
pub async fn holding<F: std::future::Future>(
lease: Option<&Held>,
endpoint: &str,
key: &str,
body: F,
) -> F::Output {
let outcome = super::unwinding(body).await;
if let Some(lease) = lease
&& let Err(error) = lease.release(endpoint, key).await
{
eprintln!("{error}");
}
outcome.unwrap_or_else(|panic| std::panic::resume_unwind(panic))
}
#[allow(
dead_code,
reason = "this module is compiled into both lanes' test binaries, and only the asset lane blocks on its runtime by hand"
)]
pub fn holding_blocking<T>(
runtime: &tokio::runtime::Runtime,
lease: Option<&Held>,
endpoint: &str,
key: &str,
body: impl FnOnce() -> T,
) -> T {
let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(body));
if let Some(lease) = lease
&& let Err(error) = runtime.block_on(lease.release(endpoint, key))
{
eprintln!("{error}");
}
outcome.unwrap_or_else(|panic| std::panic::resume_unwind(panic))
}