use std::panic::{AssertUnwindSafe, catch_unwind};
use crate::cancel::Token;
use crate::runtime::hook::{
self, DispatchError, Emitter, TranscriptMutation, TranscriptReservation,
};
use crate::runtime::session::{Lease, LeaseError, Transaction};
use crate::state::run_state::{self};
use crate::state::session_state::{self};
use crate::transcript::item::Item;
use crate::transcript::store::{self, Snapshot, Version};
use crate::value::lifecycle::Coord;
#[derive(Debug)]
pub(crate) enum ControllerError {
Dispatch(DispatchError),
Lease(LeaseError),
InvalidTransition {
previous: Version,
delta: u64,
},
}
impl core::fmt::Display for ControllerError {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Dispatch(DispatchError::Callback(failure)) => write!(
formatter,
"transcript reservation rejected by hook {}: {}",
failure.name(),
failure.error()
),
Self::Dispatch(DispatchError::Cancelled) => {
formatter.write_str("transcript mutation cancelled before commit")
}
Self::Lease(error) => write!(formatter, "transcript mutation rejected: {error}"),
Self::InvalidTransition { previous, delta } => write!(
formatter,
"invalid transcript transition: previous {previous}, increment {delta}"
),
}
}
}
impl std::error::Error for ControllerError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Dispatch(error) => Some(error),
Self::Lease(error) => Some(error),
Self::InvalidTransition { .. } => None,
}
}
}
pub(crate) struct ReservationResources {
run_states: Vec<run_state::Store>,
session_state: session_state::Reader,
}
impl ReservationResources {
#[must_use]
#[cfg_attr(not(test), expect(dead_code, reason = "reached only by tests so far"))]
pub(crate) fn new(registrations: usize, session_state: session_state::Reader) -> Self {
Self {
run_states: (0..registrations)
.map(|_| run_state::Store::new())
.collect(),
session_state,
}
}
#[must_use]
pub(crate) fn shared(
run_states: &[run_state::Store],
session_state: session_state::Reader,
) -> Self {
Self {
run_states: run_states
.iter()
.map(run_state::Store::clone_handle)
.collect(),
session_state,
}
}
}
pub(crate) struct TranscriptController<'a> {
lease: &'a Lease,
registry: &'a hook::RuntimeRegistry,
resources: &'a ReservationResources,
coord: &'a Coord,
emitter: &'a dyn Emitter,
}
impl<'a> TranscriptController<'a> {
#[must_use]
pub(crate) fn new(
lease: &'a Lease,
registry: &'a hook::RuntimeRegistry,
resources: &'a ReservationResources,
coord: &'a Coord,
emitter: &'a dyn Emitter,
) -> Self {
Self {
lease,
registry,
resources,
coord,
emitter,
}
}
#[must_use]
pub(crate) const fn with_coord<'b>(&self, coord: &'b Coord) -> TranscriptController<'b>
where
'a: 'b,
{
TranscriptController {
lease: self.lease,
registry: self.registry,
resources: self.resources,
coord,
emitter: self.emitter,
}
}
pub(crate) fn staging_store(&self) -> Result<store::Store, store::Error> {
self.lease.fork_transcript()
}
pub(crate) fn snapshot_reader(&self) -> store::SnapshotReader {
self.lease.transcript_reader()
}
#[cfg_attr(not(test), expect(dead_code, reason = "reached only by tests so far"))]
pub(crate) fn version(&self) -> Result<Version, ControllerError> {
self.lease
.begin_transaction()
.version()
.map_err(ControllerError::Lease)
}
pub(crate) fn append_batch(
&self,
items: Vec<Item>,
cancellation: &Token,
) -> Result<Version, ControllerError> {
self.append_batch_settling(items, cancellation, &mut || {})
}
pub(crate) fn append_batch_settling(
&self,
items: Vec<Item>,
cancellation: &Token,
on_commit: &mut dyn FnMut(),
) -> Result<Version, ControllerError> {
let transaction = self.lease.begin_transaction();
let transcript = transaction.snapshot().map_err(ControllerError::Lease)?;
let previous = transcript.version();
if items.is_empty() {
return Ok(previous);
}
self.transact(
&transaction,
Candidate::Append(items),
previous,
transcript,
cancellation,
on_commit,
)
}
pub(crate) fn replace_snapshot(
&self,
snapshot: Snapshot,
expected: Version,
cancellation: &Token,
) -> Result<Version, ControllerError> {
let transaction = self.lease.begin_transaction();
let transcript = transaction.snapshot().map_err(ControllerError::Lease)?;
if transcript.version() != expected {
return Err(ControllerError::Lease(LeaseError::Transcript(
store::Error::VersionConflict {
expected,
actual: transcript.version(),
},
)));
}
self.transact(
&transaction,
Candidate::Replace(snapshot),
expected,
transcript,
cancellation,
&mut || {},
)
}
fn transact(
&self,
transaction: &Transaction<'_>,
candidate: Candidate,
previous: Version,
transcript: Snapshot,
cancellation: &Token,
on_commit: &mut dyn FnMut(),
) -> Result<Version, ControllerError> {
let delta = candidate.delta();
let version = previous
.as_u64()
.checked_add(delta)
.map(Version::from_u64)
.ok_or(ControllerError::InvalidTransition { previous, delta })?;
let mutation = candidate.into_mutation(previous, version);
let mut held: Vec<Box<dyn TranscriptReservation>> = Vec::new();
let reserved = self.reserve_all(&transcript, &mutation, cancellation, &mut held);
drop(transcript);
let pre_commit = reserved.and_then(|()| {
if cancellation.is_cancelled() {
return Err(Reserve::Failed(ControllerError::Dispatch(
DispatchError::Cancelled,
)));
}
Ok(Candidate::commit(transaction, mutation, previous))
});
match pre_commit {
Ok(version) => {
on_commit();
publish_all(held);
Ok(version)
}
Err(Reserve::Failed(error)) => {
abort_all(held);
Err(error)
}
Err(Reserve::Panicked(payload)) => {
let _ = catch_unwind(AssertUnwindSafe(|| abort_all(held)));
std::panic::resume_unwind(payload);
}
}
}
fn reserve_all(
&self,
transcript: &Snapshot,
mutation: &TranscriptMutation,
cancellation: &Token,
held: &mut Vec<Box<dyn TranscriptReservation>>,
) -> Result<(), Reserve> {
for adapter in self.registry.transcript_hooks() {
if cancellation.is_cancelled() {
return Err(Reserve::Failed(ControllerError::Dispatch(
DispatchError::Cancelled,
)));
}
let run_state = self
.resources
.run_states
.get(adapter.index())
.expect("reservation resources cover every registry index");
let resources = crate::runtime::hook::CallbackResources::new(
self.coord,
run_state,
&self.resources.session_state,
None,
self.emitter,
);
let reserved = catch_unwind(AssertUnwindSafe(|| {
adapter.invoke_reserve(resources, transcript, mutation)
}))
.map_err(Reserve::Panicked)?;
match reserved {
Ok(reservation) => held.push(reservation),
Err(error) => {
return Err(Reserve::Failed(ControllerError::Dispatch(error)));
}
}
if cancellation.is_cancelled() {
return Err(Reserve::Failed(ControllerError::Dispatch(
DispatchError::Cancelled,
)));
}
}
Ok(())
}
}
enum Candidate {
Append(Vec<Item>),
Replace(Snapshot),
}
impl Candidate {
fn delta(&self) -> u64 {
match self {
Self::Append(items) => items.len() as u64,
Self::Replace(_) => 1,
}
}
fn into_mutation(self, previous: Version, version: Version) -> TranscriptMutation {
match self {
Self::Append(items) => TranscriptMutation::Append {
previous,
version,
items,
},
Self::Replace(snapshot) => TranscriptMutation::Replace {
previous,
snapshot: snapshot.with_version(version),
},
}
}
fn commit(
transaction: &Transaction<'_>,
mutation: TranscriptMutation,
previous: Version,
) -> Version {
match mutation {
TranscriptMutation::Append { items, .. } => transaction
.append_batch_if_version(items, previous)
.expect("validated transaction append remains committable"),
TranscriptMutation::Replace { snapshot, .. } => transaction
.install_snapshot(snapshot, previous)
.expect("validated transaction replacement remains committable"),
}
}
}
enum Reserve {
Failed(ControllerError),
Panicked(Box<dyn core::any::Any + Send>),
}
fn abort_all(held: Vec<Box<dyn TranscriptReservation>>) {
resolve_all(held.into_iter().rev(), TranscriptReservation::abort);
}
fn publish_all(held: Vec<Box<dyn TranscriptReservation>>) {
resolve_all(held, TranscriptReservation::publish);
}
fn resolve_all(
held: impl IntoIterator<Item = Box<dyn TranscriptReservation>>,
resolve: fn(Box<dyn TranscriptReservation>),
) {
let mut first_panic = None;
for reservation in held {
if let Err(payload) = catch_unwind(AssertUnwindSafe(|| resolve(reservation))) {
if first_panic.is_none() {
first_panic = Some(payload);
}
}
}
if let Some(payload) = first_panic {
std::panic::resume_unwind(payload);
}
}