Skip to main content

server/
script_run.rs

1//! Running one stored script over every transaction of an account.
2
3use scripting::ScriptExecutor;
4use sqlx::types::Uuid;
5
6use crate::db::DBError;
7use crate::error::ServerError;
8use crate::script::{ScriptFailure, ScriptRunReport, TransactionState, load_transaction_state};
9use crate::script_tags::{BatchError, Item, write_tags};
10use crate::telemetry::recorder::SCRIPT_BATCH_ITEMS;
11use crate::user::User;
12
13/// The script failure that stopped a run, on the transaction it met it.
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct TransactionFailure {
16    pub transaction_id: Uuid,
17    pub script_id: Uuid,
18    pub code: String,
19    pub message: String,
20}
21
22/// A script failure stops the run at the first transaction it meets it and
23/// writes nothing: `failures` then holds that one failure, `ran` the
24/// transactions before it, and `committed` is empty.
25#[derive(Debug, Clone, Default, PartialEq, Eq)]
26pub struct ScriptRun {
27    pub ran: Vec<Uuid>,
28    pub committed: Vec<Uuid>,
29    pub failures: Vec<TransactionFailure>,
30}
31
32impl std::fmt::Display for ScriptRun {
33    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34        write!(
35            f,
36            "ran {}, committed {}, failed {}",
37            self.ran.len(),
38            self.committed.len(),
39            self.failures.len()
40        )
41    }
42}
43
44#[derive(Debug, thiserror::Error)]
45pub enum RunError {
46    /// The write-back was refused (a stale or unstored split): the script
47    /// user's to fix. `item` names the transaction, or the whole batch.
48    #[error("{item}: refused: {message} (nothing was written)")]
49    Refused { item: String, message: String },
50    /// The write-back failed for a reason that is not the script user's.
51    #[error("{item}: failed: {source} (nothing was written)")]
52    Failed { item: String, source: ServerError },
53    #[error("Script not found")]
54    ScriptNotFound,
55    #[error(transparent)]
56    Server(#[from] ServerError),
57}
58
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60enum Outcome {
61    Committed,
62    Refused,
63    Failed,
64}
65
66impl Outcome {
67    const fn as_str(self) -> &'static str {
68        match self {
69            Self::Committed => "committed",
70            Self::Refused => "refused",
71            Self::Failed => "failed",
72        }
73    }
74}
75
76/// Counted once the batch has committed or rolled back: a failed batch counts
77/// only the item that stopped it.
78fn record(outcome: Outcome, items: usize) {
79    metrics::counter!(SCRIPT_BATCH_ITEMS, "outcome" => outcome.as_str())
80        .increment(u64::try_from(items).unwrap_or(u64::MAX));
81}
82
83/// Runs the stored script on each transaction of the account, then writes
84/// every script tag effect in one all-or-nothing batch. A disabled script
85/// runs too: only the stored row decides.
86///
87/// # Errors
88/// A missing script (`RowNotFound`), a failing load or run, or a refused or
89/// failing write-back; nothing is written then.
90pub async fn run_on_account(
91    user: &User,
92    script_id: Uuid,
93    account_id: Uuid,
94) -> Result<ScriptRun, RunError> {
95    let script = user.get_script(script_id).await.map_err(|err| match err {
96        ServerError::DB(DBError::Sqlx(sqlx::Error::RowNotFound)) => RunError::ScriptNotFound,
97        other => RunError::Server(other),
98    })?;
99    let transaction_ids = user.list_transaction_ids_by_account(account_id).await?;
100    let mut executor = ScriptExecutor::try_new()
101        .map_err(|e| ServerError::Script(format!("failed to build the script executor: {e}")))?;
102    let scripts = vec![(script.id, script.bytecode)];
103    let mut computed = Vec::new();
104
105    for tx_id in transaction_ids {
106        let state = load_transaction_state(user.id, tx_id)
107            .await
108            .inspect_err(|_| record(Outcome::Failed, 1))?;
109        let Some(state) = state else { continue };
110        let (returned, report) = run_blocking(executor, state, scripts.clone())
111            .await
112            .inspect_err(|_| record(Outcome::Failed, 1))?;
113        executor = returned;
114        if let Some(failure) = report.failures.first() {
115            return Ok(stopped(&computed, failure, tx_id));
116        }
117        computed.push((tx_id, report.state));
118    }
119
120    let items: Vec<Item<'_>> = computed.iter().map(|(id, state)| (*id, state)).collect();
121    let committed = write_tags(user, &items).await.map_err(write_failure)?;
122    record(Outcome::Committed, committed.len());
123    let ran = items.iter().map(|(id, _)| *id).collect();
124    Ok(ScriptRun {
125        ran,
126        committed,
127        failures: Vec::new(),
128    })
129}
130
131/// Runs the scripts on a blocking thread and hands the executor back.
132async fn run_blocking(
133    executor: ScriptExecutor,
134    state: TransactionState,
135    scripts: Vec<(Uuid, Vec<u8>)>,
136) -> Result<(ScriptExecutor, ScriptRunReport), ServerError> {
137    let (executor, report) = tokio::task::spawn_blocking(move || {
138        let report = state.run_scripts(&executor, &scripts);
139        (executor, report)
140    })
141    .await
142    .map_err(|e| ServerError::Script(format!("script task failed: {e}")))?;
143    Ok((executor, report?))
144}
145
146fn stopped(
147    computed: &[(Uuid, TransactionState)],
148    failure: &ScriptFailure,
149    transaction_id: Uuid,
150) -> ScriptRun {
151    tracing::error!(
152        "Script {sid} failed on tx {transaction_id}: {code}: {message}",
153        sid = failure.script_id,
154        code = failure.code,
155        message = failure.message
156    );
157    record(Outcome::Failed, 1);
158    ScriptRun {
159        ran: computed.iter().map(|(id, _)| *id).collect(),
160        committed: Vec::new(),
161        failures: vec![TransactionFailure {
162            transaction_id,
163            script_id: failure.script_id,
164            code: failure.code.clone(),
165            message: failure.message.clone(),
166        }],
167    }
168}
169
170/// A write-back refusal is the script user's to fix; any other failure is ours.
171fn write_failure(err: BatchError) -> RunError {
172    let item = err
173        .tx_id
174        .map_or_else(|| "batch".to_string(), |tx_id| tx_id.to_string());
175    match err.error {
176        ServerError::Script(message) => {
177            record(Outcome::Refused, 1);
178            RunError::Refused { item, message }
179        }
180        other => {
181            record(Outcome::Failed, 1);
182            tracing::error!("Script write-back failed on {item}: {other}");
183            RunError::Failed {
184                item,
185                source: other,
186            }
187        }
188    }
189}
190
191#[cfg(test)]
192mod tests;
193#[cfg(test)]
194mod write_tests;