use std::{
collections::HashMap,
sync::{Arc, Condvar, Mutex, MutexGuard},
};
pub use kcode_k1_ese_format::{ExternalSubsystem, TxId};
const UNAVAILABLE: &str = "ESE driver state is unavailable";
const LOCK_FAILED: &str = "ESE driver state lock failed";
const CONFLICT: &str = "external subsystem operation conflicts with its pending payload";
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SubmitOutcome {
progress: TxId,
duplicate: bool,
}
impl SubmitOutcome {
pub const fn new(progress: TxId, duplicate: bool) -> Self {
Self {
progress,
duplicate,
}
}
pub const fn progress(self) -> TxId {
self.progress
}
pub const fn duplicate(self) -> bool {
self.duplicate
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
struct Key {
stream: ExternalSubsystem,
operation_id: [u8; 32],
}
struct Slot {
payload: Arc<[u8]>,
result: Mutex<Option<Result<SubmitOutcome, String>>>,
changed: Condvar,
}
impl Slot {
fn new(payload: &[u8]) -> Self {
Self {
payload: Arc::from(payload),
result: Mutex::new(None),
changed: Condvar::new(),
}
}
fn publish(&self, result: Result<SubmitOutcome, String>) -> Result<(), String> {
let mut stored = self.result.lock().map_err(|_| LOCK_FAILED.to_owned())?;
if stored.is_some() {
return Err("ESE pending operation was completed twice".to_owned());
}
*stored = Some(result);
self.changed.notify_all();
Ok(())
}
fn wait(&self) -> Result<SubmitOutcome, String> {
let mut stored = self.result.lock().map_err(|_| LOCK_FAILED.to_owned())?;
while stored.is_none() {
stored = self
.changed
.wait(stored)
.map_err(|_| LOCK_FAILED.to_owned())?;
}
stored.as_ref().expect("result checked").clone()
}
}
pub enum Claim {
Owner(Ticket),
Waiter(Ticket),
}
pub struct Ticket {
key: Key,
slot: Arc<Slot>,
owner: bool,
}
struct State {
available: bool,
pending: HashMap<Key, Arc<Slot>>,
}
pub struct DriverState {
state: Mutex<State>,
}
impl DriverState {
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
Self {
state: Mutex::new(State {
available: true,
pending: HashMap::new(),
}),
}
}
pub fn ensure_available(&self) -> Result<(), String> {
if self.lock()?.available {
Ok(())
} else {
Err(UNAVAILABLE.to_owned())
}
}
pub fn claim(
&self,
stream: ExternalSubsystem,
operation_id: [u8; 32],
payload: &[u8],
) -> Result<Claim, String> {
let key = Key {
stream,
operation_id,
};
let mut state = self.lock()?;
if !state.available {
return Err(UNAVAILABLE.to_owned());
}
if let Some(slot) = state.pending.get(&key) {
if slot.payload.as_ref() != payload {
return Err(CONFLICT.to_owned());
}
return Ok(Claim::Waiter(Ticket {
key,
slot: Arc::clone(slot),
owner: false,
}));
}
let slot = Arc::new(Slot::new(payload));
state.pending.insert(key.clone(), Arc::clone(&slot));
Ok(Claim::Owner(Ticket {
key,
slot,
owner: true,
}))
}
pub fn complete(
&self,
ticket: Ticket,
result: Result<SubmitOutcome, String>,
) -> Result<SubmitOutcome, String> {
if !ticket.owner {
self.fault()?;
return Err("ESE waiter cannot complete an operation".to_owned());
}
if let Err(error) = ticket.slot.publish(result.clone()) {
let _ = self.fault();
return Err(error);
}
let mut state = self.lock()?;
match state.pending.get(&ticket.key) {
Some(slot) if Arc::ptr_eq(slot, &ticket.slot) => {
state.pending.remove(&ticket.key);
}
_ => {
Self::make_unavailable(&mut state);
return Err("ESE pending operation identity changed".to_owned());
}
}
if !state.available {
return Err(UNAVAILABLE.to_owned());
}
result
}
pub fn wait(&self, ticket: Ticket) -> Result<SubmitOutcome, String> {
if ticket.owner {
self.fault()?;
return Err("ESE owner cannot wait as a duplicate".to_owned());
}
ticket.slot.wait()
}
pub fn fault(&self) -> Result<(), String> {
let slots = {
let mut state = self.lock()?;
Self::make_unavailable(&mut state)
};
for slot in slots {
let _ = slot.publish(Err(UNAVAILABLE.to_owned()));
}
Ok(())
}
fn lock(&self) -> Result<MutexGuard<'_, State>, String> {
self.state.lock().map_err(|_| LOCK_FAILED.to_owned())
}
fn make_unavailable(state: &mut State) -> Vec<Arc<Slot>> {
state.available = false;
std::mem::take(&mut state.pending).into_values().collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
use kcode_k1_ese_format::{Authority, UserId};
use std::sync::Arc;
fn tx(byte: u8) -> TxId {
TxId::from_bytes([byte; 12])
}
fn stream() -> ExternalSubsystem {
ExternalSubsystem::new(
Authority::User(UserId::from_tx_id(tx(1))),
"titles".to_owned(),
)
.unwrap()
}
#[test]
fn equal_concurrent_claims_share_one_result() {
let state = Arc::new(DriverState::new());
let owner = match state.claim(stream(), [2; 32], b"same").unwrap() {
Claim::Owner(ticket) => ticket,
Claim::Waiter(_) => panic!("first claim must own"),
};
let waiter = match state.claim(stream(), [2; 32], b"same").unwrap() {
Claim::Waiter(ticket) => ticket,
Claim::Owner(_) => panic!("second claim must wait"),
};
let waiting = {
let state = Arc::clone(&state);
std::thread::spawn(move || state.wait(waiter))
};
let outcome = SubmitOutcome::new(tx(3), false);
assert_eq!(state.complete(owner, Ok(outcome)), Ok(outcome));
assert_eq!(waiting.join().unwrap(), Ok(outcome));
assert!(matches!(
state.claim(stream(), [2; 32], b"same").unwrap(),
Claim::Owner(_)
));
}
#[test]
fn conflicts_and_fault_wakeup_are_exact() {
let state = Arc::new(DriverState::new());
let _owner = match state.claim(stream(), [4; 32], b"first").unwrap() {
Claim::Owner(ticket) => ticket,
Claim::Waiter(_) => unreachable!(),
};
assert_eq!(
state.claim(stream(), [4; 32], b"other").err(),
Some(CONFLICT.to_owned())
);
let waiter = match state.claim(stream(), [4; 32], b"first").unwrap() {
Claim::Waiter(ticket) => ticket,
Claim::Owner(_) => unreachable!(),
};
let waiting = {
let state = Arc::clone(&state);
std::thread::spawn(move || state.wait(waiter))
};
state.fault().unwrap();
assert_eq!(waiting.join().unwrap(), Err(UNAVAILABLE.to_owned()));
assert_eq!(state.ensure_available(), Err(UNAVAILABLE.to_owned()));
}
#[test]
fn complete_error_is_shared_and_package_is_bounded() {
let state = DriverState::new();
let owner = match state.claim(stream(), [5; 32], b"x").unwrap() {
Claim::Owner(ticket) => ticket,
Claim::Waiter(_) => unreachable!(),
};
let waiter = match state.claim(stream(), [5; 32], b"x").unwrap() {
Claim::Waiter(ticket) => ticket,
Claim::Owner(_) => unreachable!(),
};
assert_eq!(
state.complete(owner, Err("submission failed".to_owned())),
Err("submission failed".to_owned())
);
assert_eq!(state.wait(waiter), Err("submission failed".to_owned()));
let files = [
include_str!("../Cargo.toml"),
include_str!("../Documentation.md"),
include_str!("lib.rs"),
];
assert!(
files
.iter()
.flat_map(|file| file.lines())
.filter(|line| !line.trim().is_empty())
.count()
< 500
);
}
}