use std::collections::HashMap;
use std::fmt::Write as _;
use std::io::{self, Read as _};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use tokio::sync::watch;
use crate::api::{ActionResult, ActionTarget, JobAction, RunSeen, Superseded};
use crate::sync::lock;
const ISSUED_MAX: usize = 256;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct RunKey {
repository: String,
run: u64,
}
#[derive(Debug, Clone)]
pub(super) struct Issued {
pub(super) target: ActionTarget,
pub(super) revision: u64,
pub(super) origin: Origin,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Origin {
Owner,
Automatic,
}
#[derive(Debug, Clone, Copy)]
pub(super) enum Withheld {
NotFailed,
Unread(crate::github::ActionFailure),
}
#[derive(Debug, Clone)]
pub(super) enum Landed {
Done(ActionResult),
Repreview {
run: RunSeen,
why: Superseded,
},
Withheld(Withheld),
}
struct Confirmation {
issued: Issued,
at: Instant,
used: Use,
}
#[derive(Clone, Copy)]
enum Use {
Open,
Boarded(u64),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Asked {
action: JobAction,
job: u64,
}
struct Flight {
id: u64,
asked: Asked,
origin: Origin,
answer: watch::Sender<Option<Landed>>,
}
struct Book {
issued: HashMap<String, Confirmation>,
runs: HashMap<RunKey, Flight>,
next_flight: u64,
}
pub(super) struct Flights {
lasts: Duration,
book: Mutex<Book>,
}
pub(super) enum Redeemed {
Board {
boarding: Boarding,
issued: Issued,
},
Stale(Superseded),
}
pub(super) enum Boarding {
Lead {
landing: Landing,
answer: watch::Receiver<Option<Landed>>,
},
Follow(watch::Receiver<Option<Landed>>),
Busy(JobAction),
}
pub(super) struct Landing {
flights: Arc<Flights>,
key: RunKey,
id: u64,
}
impl Flights {
pub(super) fn new(lasts: Duration) -> Flights {
Flights {
lasts,
book: Mutex::new(Book {
issued: HashMap::new(),
runs: HashMap::new(),
next_flight: 0,
}),
}
}
pub(super) fn issue(&self, issued: Issued, now: Instant) -> io::Result<String> {
let token = token()?;
lock(&self.book).issue(token.clone(), issued, now, self.lasts);
Ok(token)
}
pub(super) fn redeem(
self: &Arc<Flights>,
token: &str,
action: JobAction,
job: u64,
revision: u64,
now: Instant,
) -> Redeemed {
let mut book = lock(&self.book);
book.forget(now, self.lasts);
match book.redeem(token, Asked { action, job }, revision) {
Taken::Stale(why) => Redeemed::Stale(why),
Taken::Follow { answer, issued } => Redeemed::Board {
boarding: Boarding::Follow(answer),
issued,
},
Taken::Busy { other, issued } => Redeemed::Board {
boarding: Boarding::Busy(other),
issued,
},
Taken::Lead {
key,
id,
answer,
issued,
} => Redeemed::Board {
boarding: Boarding::Lead {
landing: Landing {
flights: self.clone(),
key,
id,
},
answer,
},
issued,
},
}
}
pub(super) fn board(self: &Arc<Flights>, issued: &Issued) -> Boarding {
let target = &issued.target;
let key = RunKey {
repository: target.repository.clone(),
run: target.run,
};
let asked = Asked {
action: target.action,
job: target.job,
};
match lock(&self.book).board(key.clone(), asked) {
Joined::Follow(answer) => Boarding::Follow(answer),
Joined::Busy(other) => Boarding::Busy(other),
Joined::Lead { id, answer } => Boarding::Lead {
landing: Landing {
flights: self.clone(),
key,
id,
},
answer,
},
}
}
#[cfg(test)]
pub(super) fn len(&self) -> usize {
lock(&self.book).runs.len()
}
#[cfg(test)]
pub(super) fn waiting(&self) -> usize {
lock(&self.book)
.runs
.values()
.map(|flight| flight.answer.receiver_count())
.sum()
}
}
enum Taken {
Stale(Superseded),
Follow {
answer: watch::Receiver<Option<Landed>>,
issued: Issued,
},
Busy {
other: JobAction,
issued: Issued,
},
Lead {
key: RunKey,
id: u64,
answer: watch::Receiver<Option<Landed>>,
issued: Issued,
},
}
enum Joined {
Follow(watch::Receiver<Option<Landed>>),
Busy(JobAction),
Lead {
id: u64,
answer: watch::Receiver<Option<Landed>>,
},
}
impl Book {
fn board(&mut self, key: RunKey, asked: Asked) -> Joined {
match self.runs.get(&key) {
Some(flight) if flight.asked == asked && flight.origin == Origin::Automatic => {
Joined::Follow(flight.answer.subscribe())
}
Some(flight) => Joined::Busy(flight.asked.action),
None => {
let id = self.next_flight;
self.next_flight += 1;
let (answer, receiver) = watch::channel(None);
self.runs.insert(
key,
Flight {
id,
asked,
origin: Origin::Automatic,
answer,
},
);
Joined::Lead {
id,
answer: receiver,
}
}
}
}
fn issue(&mut self, token: String, issued: Issued, now: Instant, lasts: Duration) {
self.forget(now, lasts);
while self.issued.len() >= ISSUED_MAX {
let oldest = self
.issued
.iter()
.min_by_key(|(_, confirmation)| confirmation.at)
.map(|(token, _)| token.clone());
match oldest {
Some(oldest) => self.issued.remove(&oldest),
None => break,
};
}
self.issued.insert(
token,
Confirmation {
issued,
at: now,
used: Use::Open,
},
);
}
fn forget(&mut self, now: Instant, lasts: Duration) {
self.issued
.retain(|_, confirmation| now.saturating_duration_since(confirmation.at) < lasts);
}
fn redeem(&mut self, token: &str, asked: Asked, revision: u64) -> Taken {
let Some(confirmation) = self.issued.get(token) else {
return Taken::Stale(Superseded::Unknown);
};
let issued = confirmation.issued.clone();
let target = &issued.target;
if target.action != asked.action || target.job != asked.job {
return Taken::Stale(Superseded::OtherRequest);
}
let key = RunKey {
repository: target.repository.clone(),
run: target.run,
};
let flight = self.runs.get(&key);
if let Use::Boarded(boarded) = confirmation.used {
return match flight {
Some(flight) if flight.id == boarded => Taken::Follow {
answer: flight.answer.subscribe(),
issued,
},
_ => Taken::Stale(Superseded::Used),
};
}
if issued.revision != revision {
self.issued.remove(token);
return Taken::Stale(Superseded::ConfigChanged);
}
let joined = match flight {
Some(flight) if flight.asked == asked => (flight.id, flight.answer.subscribe()),
Some(flight) => {
return Taken::Busy {
other: flight.asked.action,
issued,
};
}
None => {
let id = self.next_flight;
self.next_flight += 1;
let (answer, receiver) = watch::channel(None);
self.runs.insert(
key.clone(),
Flight {
id,
asked,
origin: Origin::Owner,
answer,
},
);
if let Some(confirmation) = self.issued.get_mut(token) {
confirmation.used = Use::Boarded(id);
}
return Taken::Lead {
key,
id,
answer: receiver,
issued,
};
}
};
let (id, answer) = joined;
if let Some(confirmation) = self.issued.get_mut(token) {
confirmation.used = Use::Boarded(id);
}
Taken::Follow { answer, issued }
}
fn answer(&self, key: &RunKey, id: u64, landed: Landed) {
if let Some(flight) = self.runs.get(key).filter(|flight| flight.id == id) {
flight.answer.send_replace(Some(landed));
}
}
fn remove(&mut self, key: &RunKey, id: u64) {
if self.runs.get(key).is_some_and(|flight| flight.id == id) {
self.runs.remove(key);
}
}
}
impl Landing {
pub(super) fn land(self, landed: Landed) {
lock(&self.flights.book).answer(&self.key, self.id, landed);
}
}
impl Drop for Landing {
fn drop(&mut self) {
lock(&self.flights.book).remove(&self.key, self.id);
}
}
fn token() -> io::Result<String> {
let mut bytes = [0u8; 16];
std::fs::File::open("/dev/urandom")?.read_exact(&mut bytes)?;
Ok(bytes
.iter()
.fold(String::with_capacity(32), |mut hex, byte| {
let _ = write!(hex, "{byte:02x}");
hex
}))
}