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::Registry,
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::Registry,
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 snapshot(&self) -> Result<Snapshot, store::Error> {
self.lease.transcript_snapshot()
}
#[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> {
let transaction = self.lease.begin_transaction();
let previous = transaction.version().map_err(ControllerError::Lease)?;
if items.is_empty() {
return Ok(previous);
}
let delta = items.len() as u64;
self.transact(
&transaction,
Shape::Append,
previous,
delta,
items,
cancellation,
)
}
pub(crate) fn replace(
&self,
items: Vec<Item>,
expected: Version,
cancellation: &Token,
) -> Result<Version, ControllerError> {
let transaction = self.lease.begin_transaction();
self.transact(
&transaction,
Shape::Replace,
expected,
1,
items,
cancellation,
)
}
fn transact(
&self,
transaction: &Transaction<'_>,
shape: Shape,
previous: Version,
delta: u64,
items: Vec<Item>,
cancellation: &Token,
) -> Result<Version, ControllerError> {
let version = previous
.as_u64()
.checked_add(delta)
.map(Version::from_u64)
.ok_or(ControllerError::InvalidTransition { previous, delta })?;
let mutation = shape.fact(previous, version, items.clone());
let mut held: Vec<Box<dyn TranscriptReservation>> = Vec::new();
let pre_commit = self
.reserve_all(&mutation, cancellation, &mut held)
.and_then(|()| {
if cancellation.is_cancelled() {
return Err(Reserve::Failed(ControllerError::Dispatch(
DispatchError::Cancelled,
)));
}
shape
.commit(transaction, items, previous)
.map_err(|error| Reserve::Failed(ControllerError::Lease(error)))
});
match pre_commit {
Ok(version) => {
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,
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, 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(())
}
}
#[derive(Clone, Copy)]
enum Shape {
Append,
Replace,
}
impl Shape {
const fn fact(
self,
previous: Version,
version: Version,
items: Vec<Item>,
) -> TranscriptMutation {
match self {
Self::Append => TranscriptMutation::Append {
previous,
version,
items,
},
Self::Replace => TranscriptMutation::Replace {
previous,
version,
items,
},
}
}
fn commit(
self,
transaction: &Transaction<'_>,
items: Vec<Item>,
previous: Version,
) -> Result<Version, LeaseError> {
match self {
Self::Append => transaction.append_batch_if_version(items, previous),
Self::Replace => transaction.replace_if_version(items, previous),
}
}
}
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);
}
}