use std::sync::{Condvar, Mutex, MutexGuard};
use uuid::Uuid;
use super::{State, Store, StoreError, Tx, commit, state, version_row};
use crate::audit::{Action, Actor, Entry};
use crate::backend::Packed;
use crate::ids::{KeyId, VersionId};
pub(super) struct Confirm {
pub(super) key: KeyId,
pub(super) action: Action,
pub(super) uuid: Uuid,
pub(super) version: Option<VersionId>,
pub(super) opened: bool,
pub(super) place: Option<Packed>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Confirmed {
Answer,
Again,
Refused(StoreError),
}
#[derive(Default)]
struct Queue {
leading: bool,
waiting: Vec<(u64, Confirm)>,
done: Vec<(u64, Result<Confirmed, StoreError>)>,
next: u64,
}
#[derive(Default)]
pub(super) struct Group {
queue: Mutex<Queue>,
turn: Condvar,
#[cfg(test)]
pub(super) batches: Mutex<Vec<usize>>,
#[cfg(test)]
pub(super) parts: std::sync::atomic::AtomicUsize,
}
impl Group {
fn lock(&self) -> MutexGuard<'_, Queue> {
self.queue
.lock()
.expect("no thread panicked holding the queue")
}
pub(super) fn confirm(&self, store: &Store, read: Confirm) -> Result<Confirmed, StoreError> {
let mut queue = self.lock();
let ticket = queue.next;
queue.next += 1;
queue.waiting.push((ticket, read));
loop {
if let Some(at) = queue.done.iter().position(|(t, _)| *t == ticket) {
return queue.done.swap_remove(at).1;
}
if queue.leading {
queue = self
.turn
.wait(queue)
.expect("no thread panicked holding the queue");
continue;
}
queue.leading = true;
drop(queue);
Lead { group: self }.run(store);
queue = self.lock();
}
}
#[cfg(test)]
pub(super) fn waiting(&self) -> usize {
self.lock().waiting.len()
}
}
struct Lead<'a> {
group: &'a Group,
}
impl Lead<'_> {
fn run(&self, store: &Store) {
let tx = store.catalog.immediate();
let batch = std::mem::take(&mut self.group.lock().waiting);
let outcomes = match tx {
Ok(tx) => batch_in(store, tx, &batch),
Err(e) => vec![Err(e); batch.len()],
};
#[cfg(test)]
self.group
.batches
.lock()
.expect("batches")
.push(batch.len());
let mut queue = self.group.lock();
queue
.done
.extend(batch.iter().map(|(t, _)| *t).zip(outcomes));
}
}
impl Drop for Lead<'_> {
fn drop(&mut self) {
let mut queue = self.group.lock();
queue.leading = false;
drop(queue);
self.group.turn.notify_all();
}
}
fn batch_in(
store: &Store,
mut tx: Tx,
batch: &[(u64, Confirm)],
) -> Vec<Result<Confirmed, StoreError>> {
let lone = batch.len() == 1;
let mut outcomes: Vec<_> = batch
.iter()
.map(|(_, read)| {
if lone {
one(store, &mut tx, read)
} else {
#[cfg(test)]
store
.group
.parts
.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
in_part(&mut tx, |tx| one(store, tx, read))
}
})
.collect();
let recorded = |outcome: &Result<Confirmed, StoreError>| {
matches!(outcome, Ok(Confirmed::Answer | Confirmed::Refused(_)))
};
if !outcomes.iter().any(recorded) {
return outcomes;
}
if let Err(e) = commit(tx) {
for outcome in &mut outcomes {
if recorded(outcome) {
*outcome = Err(e);
}
}
}
outcomes
}
fn in_part(
tx: &mut Tx,
step: impl FnOnce(&mut Tx) -> Result<Confirmed, StoreError>,
) -> Result<Confirmed, StoreError> {
tx.begin_part()?;
match step(tx) {
Ok(outcome) => {
if let Err(e) = tx.release_part() {
let _ = tx.rollback_part();
return Err(e);
}
Ok(outcome)
}
Err(e) => {
tx.rollback_part()?;
Err(e)
}
}
}
fn one(store: &Store, tx: &mut Tx, read: &Confirm) -> Result<Confirmed, StoreError> {
let entry = |status, version| Entry {
actor: Actor::Key(read.key),
action: read.action,
target: Some(read.uuid.to_string()),
version,
status,
};
match state(tx, read.uuid)? {
State::Live(now)
if Some(now) == read.version
&& !read.opened
&& matches!(version_row(tx, now), Ok(r) if r.place != read.place) =>
{
Ok(Confirmed::Again)
}
State::Live(now) if Some(now) == read.version => {
let status = if read.opened { 200 } else { 500 };
store.record(tx, &entry(status, Some(now)))?;
Ok(Confirmed::Answer)
}
State::Live(_) => Ok(Confirmed::Again),
State::Gone => {
store.record(tx, &entry(410, None))?;
Ok(Confirmed::Refused(StoreError::Gone))
}
State::Absent => {
store.record(tx, &entry(404, None))?;
Ok(Confirmed::Refused(StoreError::NotFound))
}
}
}