Skip to main content

server/
script.rs

1use finance::price::Price;
2use finance::split::Split;
3use finance::tag::Tag;
4use finance::transaction::Transaction;
5use scripting::ScriptExecutor;
6use scripting::error::HookError;
7use scripting::runtime::{classify_runtime_error, err_code_and_message};
8use sqlx::types::Uuid;
9use std::collections::{HashMap, HashSet};
10
11use crate::command::FinanceEntity;
12use crate::error::ServerError;
13
14mod load;
15mod wire;
16
17pub use load::load_transaction_state;
18
19/// One per-script failure observation from a batch `run_scripts` invocation.
20/// `code` is a kebab-case symbol mirroring the wire envelope of catch-each
21/// result cells (so emacs / cli / web clients render script failures the
22/// same shape regardless of whether the script raised inside catch-each
23/// or surfaced at the outer batch boundary). `message` is the engine's
24/// diagnostic.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct ScriptFailure {
27    pub script_id: Uuid,
28    pub code: String,
29    pub message: String,
30}
31
32/// Aggregate output of a batch `run_scripts` call. `state` is the final
33/// `TransactionState` after every script that succeeded was applied;
34/// `failures` lists every script that errored (in execution order).
35/// Failures don't abort the run — successive scripts still see the
36/// state mutations from previous successful ones.
37pub struct ScriptRunReport {
38    pub state: TransactionState,
39    pub failures: Vec<ScriptFailure>,
40}
41
42const DEFAULT_OUTPUT_SIZE: u32 = 64 * 1024;
43
44pub struct TransactionState {
45    pub transaction: Transaction,
46    pub splits: Vec<Split>,
47    pub transaction_tags: Vec<Tag>,
48    pub split_tags: Vec<(Uuid, Tag)>,
49    pub prices: Vec<Price>,
50    /// Display name per posting account id, so the serializer can expose
51    /// `SPLIT-ACCOUNT-NAME` to trigger scripts without an in-script account
52    /// lookup. Empty for an account whose name is unknown at build time.
53    pub account_names: HashMap<Uuid, String>,
54    /// Ids of the tags scripts created, as opposed to the loaded ones.
55    pub created_tags: HashSet<Uuid>,
56    /// Loaded tag ids scripts deleted from the transaction.
57    pub deleted_transaction_tags: HashSet<Uuid>,
58    /// Loaded (split id, tag id) links scripts deleted.
59    pub deleted_split_tags: HashSet<(Uuid, Uuid)>,
60    /// Revision of the stored transaction this state was loaded from; the
61    /// tag write-back is refused once the stored one differs.
62    pub loaded_revision: Option<String>,
63}
64
65impl TransactionState {
66    #[must_use]
67    pub fn new(transaction: Transaction) -> Self {
68        Self {
69            transaction,
70            splits: Vec::new(),
71            transaction_tags: Vec::new(),
72            split_tags: Vec::new(),
73            prices: Vec::new(),
74            account_names: HashMap::new(),
75            created_tags: HashSet::new(),
76            deleted_transaction_tags: HashSet::new(),
77            deleted_split_tags: HashSet::new(),
78            loaded_revision: None,
79        }
80    }
81
82    #[must_use]
83    pub fn with_account_names(mut self, names: HashMap<Uuid, String>) -> Self {
84        self.account_names = names;
85        self
86    }
87
88    #[must_use]
89    pub fn with(mut self, entities: Vec<FinanceEntity>) -> Self {
90        for entity in entities {
91            match entity {
92                FinanceEntity::Split(s) => self.splits.push(s),
93                FinanceEntity::Price(p) => self.prices.push(p),
94                FinanceEntity::Tag(t) => self.transaction_tags.push(t),
95                _ => {}
96            }
97        }
98        self
99    }
100
101    #[must_use]
102    pub fn with_split_tags(mut self, tags: Vec<(Uuid, Tag)>) -> Self {
103        self.split_tags = tags;
104        self
105    }
106
107    #[must_use]
108    pub fn with_note(mut self, note: Option<String>) -> Self {
109        if let Some(note) = note {
110            self.transaction_tags.push(Tag {
111                id: Uuid::new_v4(),
112                tag_name: "note".to_string(),
113                tag_value: note,
114                description: None,
115            });
116        }
117        self
118    }
119
120    /// Runs each script against the current state, accumulating
121    /// per-script failures into a structured `ScriptRunReport` rather
122    /// than swallowing them silently. The `state` field reflects every
123    /// script that successfully produced entities; failed scripts are
124    /// recorded in `failures` and don't abort the batch — subsequent
125    /// scripts still observe state mutations from earlier successes.
126    ///
127    /// The outer `Result` reserves `ServerError` for genuine
128    /// orchestration failures (entity-apply errors), keeping
129    /// script-side failures structurally separate. Callers that want
130    /// the previous "first-failure-aborts" semantics can chain with
131    /// `ScriptRunReport::into_state_or_first_failure`.
132    pub fn run_scripts(
133        mut self,
134        executor: &ScriptExecutor,
135        scripts: &[(Uuid, Vec<u8>)],
136    ) -> Result<ScriptRunReport, ServerError> {
137        let mut failures: Vec<ScriptFailure> = Vec::new();
138        for (script_id, bytecode) in scripts {
139            let (input, mut index_table, tag_links) = wire::serialize_state(&self);
140            match executor.execute(bytecode, &input, Some(DEFAULT_OUTPUT_SIZE)) {
141                Ok(entities) if !entities.is_empty() => {
142                    wire::apply_parsed_entities(&mut self, entities, &mut index_table, &tag_links)?;
143                }
144                Ok(_) => {}
145                Err(e) => {
146                    failures.push(classify_script_failure(*script_id, &e));
147                }
148            }
149        }
150        Ok(ScriptRunReport {
151            state: self,
152            failures,
153        })
154    }
155}
156
157/// Maps a `HookError` from a single batch-script run into a structured
158/// `ScriptFailure`. Wasm-engine errors classify through the same
159/// `EngineError` pipeline catch-each uses (`OutOfFuel`, `ScriptRaised`,
160/// `HostCondition`, ...) so client renderers see one shape no matter where
161/// in the stack the failure originated. A commodity mismatch arrives as a
162/// `ScriptRaised{code:"commodity-mismatch"}` (it `throw`s `$nomi_error`
163/// in-guest; ADR-0026). Non-engine variants (Parse, Lock, ...) get a
164/// `runtime` code with the engine's own message.
165fn classify_script_failure(script_id: Uuid, err: &HookError) -> ScriptFailure {
166    let (code, message) = match err {
167        HookError::WASM(wasm_err) => err_code_and_message(&classify_runtime_error(wasm_err)),
168        HookError::Engine(engine_err) => err_code_and_message(engine_err),
169        other => ("runtime".to_string(), format!("{other}")),
170    };
171    ScriptFailure {
172        script_id,
173        code,
174        message,
175    }
176}
177
178#[cfg(test)]
179mod tests;