use super::context::{Context, Fiber, FiberState};
#[cfg(any(feature = "native", feature = "db"))]
use crate::domain::InvariantPhase;
use crate::domain::{BailVerdict, BooleanPCard};
#[cfg(any(feature = "native", feature = "db"))]
use crate::error::{ClmError, EvaluatorErrorCode, Result};
use serde_json::Value;
use std::sync::Arc;
#[cfg(any(feature = "native", feature = "db"))]
use std::time::Instant;
#[cfg(any(feature = "native", feature = "db"))]
use super::savepoint_guard::SavepointGuard;
#[cfg(any(feature = "native", feature = "db"))]
use rusqlite::Connection;
#[cfg(any(feature = "native", feature = "db"))]
use std::sync::Mutex;
pub type PreconditionFn = Arc<dyn Fn(&Context) -> BailVerdict + Send + Sync + 'static>;
pub type TransitionFn =
Arc<dyn Fn(&Context, &Fiber) -> std::result::Result<Value, String> + Send + Sync + 'static>;
pub type PostconditionFn = Arc<dyn Fn(&Context, &Value) -> BailVerdict + Send + Sync + 'static>;
#[derive(Clone)]
pub struct HoareTriple {
pub name: String,
pub precondition: Option<PreconditionFn>,
pub transition: TransitionFn,
pub postcondition: Option<PostconditionFn>,
pub boolean_pcard: Option<BooleanPCard>,
}
impl HoareTriple {
pub fn new<F>(name: impl Into<String>, transition: F) -> Self
where
F: Fn(&Context, &Fiber) -> std::result::Result<Value, String> + Send + Sync + 'static,
{
Self {
name: name.into(),
precondition: None,
transition: Arc::new(transition),
postcondition: None,
boolean_pcard: None,
}
}
pub fn with_precondition<P>(mut self, pred: P) -> Self
where
P: Fn(&Context) -> BailVerdict + Send + Sync + 'static,
{
self.precondition = Some(Arc::new(pred));
self
}
pub fn with_postcondition<Q>(mut self, post: Q) -> Self
where
Q: Fn(&Context, &Value) -> BailVerdict + Send + Sync + 'static,
{
self.postcondition = Some(Arc::new(post));
self
}
pub fn with_boolean_pcard(mut self, pcard: BooleanPCard) -> Self {
self.boolean_pcard = Some(pcard);
self
}
}
#[derive(Debug, Clone)]
pub struct HoareExecutionReport {
pub fiber_id: String,
pub success: bool,
pub rollback_triggered: bool,
pub rollback_duration_nanos: u128,
pub final_state: FiberState,
pub value: Option<Value>,
}
pub struct HoareFiberExecutor;
#[cfg(any(feature = "native", feature = "db"))]
fn advance(fiber: &Fiber, to: FiberState) -> Result<()> {
fiber
.transition_to(to)
.map_err(|refused| ClmError::evaluator(EvaluatorErrorCode::FiberFailure, refused))
}
impl HoareFiberExecutor {
#[cfg(any(feature = "native", feature = "db"))]
pub fn execute(
context: &Context,
fiber: &Fiber,
triple: &HoareTriple,
conn: Option<Arc<Mutex<Connection>>>,
) -> Result<HoareExecutionReport> {
Self::execute_with_clock(context, fiber, triple, conn, crate::layer0::gtime::monotonic_now)
}
#[cfg(any(feature = "native", feature = "db"))]
pub fn execute_with_clock(
context: &Context,
fiber: &Fiber,
triple: &HoareTriple,
conn: Option<Arc<Mutex<Connection>>>,
clock: impl Fn() -> Instant,
) -> Result<HoareExecutionReport> {
advance(fiber, FiberState::Loading)?;
if let Some(ref pre) = triple.precondition {
match pre(context) {
BailVerdict::Pass => {}
BailVerdict::Bail {
reason,
invariant_code,
..
} => {
advance(
fiber,
FiberState::Failed(format!("Precondition [{}] bail: {}", invariant_code, reason)),
)?;
return Err(ClmError::evaluator(
EvaluatorErrorCode::PreconditionFailed,
format!("{}: {}", invariant_code, reason),
));
}
}
}
if let Some(ref pcard) = triple.boolean_pcard
&& pcard.phase == InvariantPhase::Precondition
{
let guard_ctx = context
.get_service::<Value>(crate::layer0::vocabulary::GUARD_SERVICE_CONTEXT)
.map(|v| (*v).clone())
.or_else(|| fiber.get_ast())
.unwrap_or_else(|| serde_json::json!({}));
match crate::layer1::guard_semantics::evaluate_guard(&pcard.expression, &guard_ctx) {
crate::layer1::guard_semantics::GuardVerdict::Pass => {}
crate::layer1::guard_semantics::GuardVerdict::Fail(reason) => {
let msg = format!("Precondition [{}] bail: {}", pcard.id, reason);
advance(fiber, FiberState::Failed(msg.clone()))?;
return Err(ClmError::evaluator(
EvaluatorErrorCode::PreconditionFailed,
msg,
));
}
crate::layer1::guard_semantics::GuardVerdict::Unmatched(expr) => {
let msg = format!("Precondition [{}] unmatched guard: {}", pcard.id, expr);
advance(fiber, FiberState::Failed(msg.clone()))?;
return Err(ClmError::evaluator(
EvaluatorErrorCode::PreconditionFailed,
msg,
));
}
}
}
let savepoint: Option<SavepointGuard> = if let Some(ref c) = conn {
Some(
SavepointGuard::new(c.clone(), format!("hoare_{}", fiber.id))
.map_err(|e| ClmError::evaluator(EvaluatorErrorCode::FiberFailure, e))?,
)
} else {
None
};
advance(fiber, FiberState::Active)?;
let exec_result = (triple.transition)(context, fiber);
match exec_result {
Err(transition_err) => {
let rollback_start = clock();
let _ = fiber.unwind_disposables();
if let Some(mut sp) = savepoint {
let _ = sp.rollback();
}
let rollback_duration_nanos = rollback_start.elapsed().as_nanos();
advance(fiber, FiberState::Failed(transition_err.clone()))?;
Ok(HoareExecutionReport {
fiber_id: fiber.id.clone(),
success: false,
rollback_triggered: true,
rollback_duration_nanos,
final_state: FiberState::Failed(transition_err.clone()),
value: None,
})
}
Ok(output_val) => {
let mut post_failed = None;
if let Some(ref post) = triple.postcondition
&& let BailVerdict::Bail {
reason,
invariant_code,
..
} = post(context, &output_val)
{
post_failed = Some((reason, invariant_code));
}
if post_failed.is_none()
&& let Some(ref pcard) = triple.boolean_pcard
&& pcard.phase == InvariantPhase::Postcondition
{
let mut guard_ctx = context
.get_service::<Value>(crate::layer0::vocabulary::GUARD_SERVICE_CONTEXT)
.map(|v| (*v).clone())
.or_else(|| fiber.get_ast())
.unwrap_or_else(|| serde_json::json!({}));
if let Some(obj) = guard_ctx.as_object_mut() {
obj.entry(crate::layer0::vocabulary::GUARD_VAR_OUTPUT.to_string())
.or_insert_with(|| output_val.clone());
}
match crate::layer1::guard_semantics::evaluate_guard(
&pcard.expression,
&guard_ctx,
) {
crate::layer1::guard_semantics::GuardVerdict::Pass => {}
crate::layer1::guard_semantics::GuardVerdict::Fail(reason) => {
post_failed = Some((reason, pcard.expression.clone()));
}
crate::layer1::guard_semantics::GuardVerdict::Unmatched(expr) => {
post_failed = Some((
format!("unmatched guard: {}", expr),
pcard.expression.clone(),
));
}
}
}
if let Some((reason, invariant_code)) = post_failed {
let _ = fiber.unwind_disposables();
if let Some(mut sp) = savepoint {
let _ = sp.rollback();
}
let fail_msg = format!("Postcondition [{}] bail: {}", invariant_code, reason);
advance(fiber, FiberState::Failed(fail_msg))?;
return Err(ClmError::evaluator(
EvaluatorErrorCode::PostconditionFailed,
format!("{}: {}", invariant_code, reason),
));
}
if let Some(mut sp) = savepoint {
let _ = sp.commit();
}
let final_state = fiber.get_state();
Ok(HoareExecutionReport {
fiber_id: fiber.id.clone(),
success: true,
rollback_triggered: false,
rollback_duration_nanos: 0,
final_state,
value: Some(output_val),
})
}
}
}
}