Lines
98.59 %
Functions
100 %
Branches
use finance::price::Price;
use finance::split::Split;
use finance::tag::Tag;
use finance::transaction::Transaction;
use scripting::ScriptExecutor;
use scripting::error::HookError;
use scripting::runtime::{classify_runtime_error, err_code_and_message};
use sqlx::types::Uuid;
use std::collections::{HashMap, HashSet};
use crate::command::FinanceEntity;
use crate::error::ServerError;
mod load;
mod wire;
pub use load::load_transaction_state;
/// One per-script failure observation from a batch `run_scripts` invocation.
/// `code` is a kebab-case symbol mirroring the wire envelope of catch-each
/// result cells (so emacs / cli / web clients render script failures the
/// same shape regardless of whether the script raised inside catch-each
/// or surfaced at the outer batch boundary). `message` is the engine's
/// diagnostic.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScriptFailure {
pub script_id: Uuid,
pub code: String,
pub message: String,
}
/// Aggregate output of a batch `run_scripts` call. `state` is the final
/// `TransactionState` after every script that succeeded was applied;
/// `failures` lists every script that errored (in execution order).
/// Failures don't abort the run — successive scripts still see the
/// state mutations from previous successful ones.
pub struct ScriptRunReport {
pub state: TransactionState,
pub failures: Vec<ScriptFailure>,
const DEFAULT_OUTPUT_SIZE: u32 = 64 * 1024;
pub struct TransactionState {
pub transaction: Transaction,
pub splits: Vec<Split>,
pub transaction_tags: Vec<Tag>,
pub split_tags: Vec<(Uuid, Tag)>,
pub prices: Vec<Price>,
/// Display name per posting account id, so the serializer can expose
/// `SPLIT-ACCOUNT-NAME` to trigger scripts without an in-script account
/// lookup. Empty for an account whose name is unknown at build time.
pub account_names: HashMap<Uuid, String>,
/// Ids of the tags scripts created, as opposed to the loaded ones.
pub created_tags: HashSet<Uuid>,
/// Loaded tag ids scripts deleted from the transaction.
pub deleted_transaction_tags: HashSet<Uuid>,
/// Loaded (split id, tag id) links scripts deleted.
pub deleted_split_tags: HashSet<(Uuid, Uuid)>,
/// Revision of the stored transaction this state was loaded from; the
/// tag write-back is refused once the stored one differs.
pub loaded_revision: Option<String>,
impl TransactionState {
#[must_use]
pub fn new(transaction: Transaction) -> Self {
Self {
transaction,
splits: Vec::new(),
transaction_tags: Vec::new(),
split_tags: Vec::new(),
prices: Vec::new(),
account_names: HashMap::new(),
created_tags: HashSet::new(),
deleted_transaction_tags: HashSet::new(),
deleted_split_tags: HashSet::new(),
loaded_revision: None,
pub fn with_account_names(mut self, names: HashMap<Uuid, String>) -> Self {
self.account_names = names;
self
pub fn with(mut self, entities: Vec<FinanceEntity>) -> Self {
for entity in entities {
match entity {
FinanceEntity::Split(s) => self.splits.push(s),
FinanceEntity::Price(p) => self.prices.push(p),
FinanceEntity::Tag(t) => self.transaction_tags.push(t),
_ => {}
pub fn with_split_tags(mut self, tags: Vec<(Uuid, Tag)>) -> Self {
self.split_tags = tags;
pub fn with_note(mut self, note: Option<String>) -> Self {
if let Some(note) = note {
self.transaction_tags.push(Tag {
id: Uuid::new_v4(),
tag_name: "note".to_string(),
tag_value: note,
description: None,
});
/// Runs each script against the current state, accumulating
/// per-script failures into a structured `ScriptRunReport` rather
/// than swallowing them silently. The `state` field reflects every
/// script that successfully produced entities; failed scripts are
/// recorded in `failures` and don't abort the batch — subsequent
/// scripts still observe state mutations from earlier successes.
///
/// The outer `Result` reserves `ServerError` for genuine
/// orchestration failures (entity-apply errors), keeping
/// script-side failures structurally separate. Callers that want
/// the previous "first-failure-aborts" semantics can chain with
/// `ScriptRunReport::into_state_or_first_failure`.
pub fn run_scripts(
mut self,
executor: &ScriptExecutor,
scripts: &[(Uuid, Vec<u8>)],
) -> Result<ScriptRunReport, ServerError> {
let mut failures: Vec<ScriptFailure> = Vec::new();
for (script_id, bytecode) in scripts {
let (input, mut index_table, tag_links) = wire::serialize_state(&self);
match executor.execute(bytecode, &input, Some(DEFAULT_OUTPUT_SIZE)) {
Ok(entities) if !entities.is_empty() => {
wire::apply_parsed_entities(&mut self, entities, &mut index_table, &tag_links)?;
Ok(_) => {}
Err(e) => {
failures.push(classify_script_failure(*script_id, &e));
Ok(ScriptRunReport {
state: self,
failures,
})
/// Maps a `HookError` from a single batch-script run into a structured
/// `ScriptFailure`. Wasm-engine errors classify through the same
/// `EngineError` pipeline catch-each uses (`OutOfFuel`, `ScriptRaised`,
/// `HostCondition`, ...) so client renderers see one shape no matter where
/// in the stack the failure originated. A commodity mismatch arrives as a
/// `ScriptRaised{code:"commodity-mismatch"}` (it `throw`s `$nomi_error`
/// in-guest; ADR-0026). Non-engine variants (Parse, Lock, ...) get a
/// `runtime` code with the engine's own message.
fn classify_script_failure(script_id: Uuid, err: &HookError) -> ScriptFailure {
let (code, message) = match err {
HookError::WASM(wasm_err) => err_code_and_message(&classify_runtime_error(wasm_err)),
HookError::Engine(engine_err) => err_code_and_message(engine_err),
other => ("runtime".to_string(), format!("{other}")),
};
ScriptFailure {
script_id,
code,
message,
#[cfg(test)]
mod tests;