1
use finance::price::Price;
2
use finance::split::Split;
3
use finance::tag::Tag;
4
use finance::transaction::Transaction;
5
use scripting::ScriptExecutor;
6
use scripting::error::HookError;
7
use scripting::runtime::{classify_runtime_error, err_code_and_message};
8
use sqlx::types::Uuid;
9
use std::collections::{HashMap, HashSet};
10

            
11
use crate::command::FinanceEntity;
12
use crate::error::ServerError;
13

            
14
mod load;
15
mod wire;
16

            
17
pub 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)]
26
pub 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.
37
pub struct ScriptRunReport {
38
    pub state: TransactionState,
39
    pub failures: Vec<ScriptFailure>,
40
}
41

            
42
const DEFAULT_OUTPUT_SIZE: u32 = 64 * 1024;
43

            
44
pub 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

            
65
impl TransactionState {
66
    #[must_use]
67
165215
    pub fn new(transaction: Transaction) -> Self {
68
165215
        Self {
69
165215
            transaction,
70
165215
            splits: Vec::new(),
71
165215
            transaction_tags: Vec::new(),
72
165215
            split_tags: Vec::new(),
73
165215
            prices: Vec::new(),
74
165215
            account_names: HashMap::new(),
75
165215
            created_tags: HashSet::new(),
76
165215
            deleted_transaction_tags: HashSet::new(),
77
165215
            deleted_split_tags: HashSet::new(),
78
165215
            loaded_revision: None,
79
165215
        }
80
165215
    }
81

            
82
    #[must_use]
83
2399
    pub fn with_account_names(mut self, names: HashMap<Uuid, String>) -> Self {
84
2399
        self.account_names = names;
85
2399
        self
86
2399
    }
87

            
88
    #[must_use]
89
489375
    pub fn with(mut self, entities: Vec<FinanceEntity>) -> Self {
90
489375
        for entity in entities {
91
385465
            match entity {
92
346019
                FinanceEntity::Split(s) => self.splits.push(s),
93
11737
                FinanceEntity::Price(p) => self.prices.push(p),
94
27709
                FinanceEntity::Tag(t) => self.transaction_tags.push(t),
95
                _ => {}
96
            }
97
        }
98
489375
        self
99
489375
    }
100

            
101
    #[must_use]
102
165208
    pub fn with_split_tags(mut self, tags: Vec<(Uuid, Tag)>) -> Self {
103
165208
        self.split_tags = tags;
104
165208
        self
105
165208
    }
106

            
107
    #[must_use]
108
162086
    pub fn with_note(mut self, note: Option<String>) -> Self {
109
162086
        if let Some(note) = note {
110
66859
            self.transaction_tags.push(Tag {
111
66859
                id: Uuid::new_v4(),
112
66859
                tag_name: "note".to_string(),
113
66859
                tag_value: note,
114
66859
                description: None,
115
66859
            });
116
95227
        }
117
162086
        self
118
162086
    }
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
3086
    pub fn run_scripts(
133
3086
        mut self,
134
3086
        executor: &ScriptExecutor,
135
3086
        scripts: &[(Uuid, Vec<u8>)],
136
3086
    ) -> Result<ScriptRunReport, ServerError> {
137
3086
        let mut failures: Vec<ScriptFailure> = Vec::new();
138
3086
        for (script_id, bytecode) in scripts {
139
3088
            let (input, mut index_table, tag_links) = wire::serialize_state(&self);
140
3088
            match executor.execute(bytecode, &input, Some(DEFAULT_OUTPUT_SIZE)) {
141
2544
                Ok(entities) if !entities.is_empty() => {
142
2176
                    wire::apply_parsed_entities(&mut self, entities, &mut index_table, &tag_links)?;
143
                }
144
368
                Ok(_) => {}
145
                Err(e) => {
146
544
                    failures.push(classify_script_failure(*script_id, &e));
147
                }
148
            }
149
        }
150
3086
        Ok(ScriptRunReport {
151
3086
            state: self,
152
3086
            failures,
153
3086
        })
154
3086
    }
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.
165
546
fn classify_script_failure(script_id: Uuid, err: &HookError) -> ScriptFailure {
166
546
    let (code, message) = match err {
167
542
        HookError::WASM(wasm_err) => err_code_and_message(&classify_runtime_error(wasm_err)),
168
3
        HookError::Engine(engine_err) => err_code_and_message(engine_err),
169
1
        other => ("runtime".to_string(), format!("{other}")),
170
    };
171
546
    ScriptFailure {
172
546
        script_id,
173
546
        code,
174
546
        message,
175
546
    }
176
546
}
177

            
178
#[cfg(test)]
179
mod tests;