1
//! Running one stored script over every transaction of an account.
2

            
3
use scripting::ScriptExecutor;
4
use sqlx::types::Uuid;
5

            
6
use crate::db::DBError;
7
use crate::error::ServerError;
8
use crate::script::{ScriptFailure, ScriptRunReport, TransactionState, load_transaction_state};
9
use crate::script_tags::{BatchError, Item, write_tags};
10
use crate::telemetry::recorder::SCRIPT_BATCH_ITEMS;
11
use crate::user::User;
12

            
13
/// The script failure that stopped a run, on the transaction it met it.
14
#[derive(Debug, Clone, PartialEq, Eq)]
15
pub 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)]
26
pub struct ScriptRun {
27
    pub ran: Vec<Uuid>,
28
    pub committed: Vec<Uuid>,
29
    pub failures: Vec<TransactionFailure>,
30
}
31

            
32
impl 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)]
45
pub 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)]
60
enum Outcome {
61
    Committed,
62
    Refused,
63
    Failed,
64
}
65

            
66
impl Outcome {
67
1632
    const fn as_str(self) -> &'static str {
68
1632
        match self {
69
904
            Self::Committed => "committed",
70
3
            Self::Refused => "refused",
71
725
            Self::Failed => "failed",
72
        }
73
1632
    }
74
}
75

            
76
/// Counted once the batch has committed or rolled back: a failed batch counts
77
/// only the item that stopped it.
78
1632
fn record(outcome: Outcome, items: usize) {
79
1632
    metrics::counter!(SCRIPT_BATCH_ITEMS, "outcome" => outcome.as_str())
80
1632
        .increment(u64::try_from(items).unwrap_or(u64::MAX));
81
1632
}
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.
90
1986
pub async fn run_on_account(
91
1986
    user: &User,
92
1986
    script_id: Uuid,
93
1986
    account_id: Uuid,
94
1986
) -> Result<ScriptRun, RunError> {
95
1986
    let script = user.get_script(script_id).await.map_err(|err| match err {
96
361
        ServerError::DB(DBError::Sqlx(sqlx::Error::RowNotFound)) => RunError::ScriptNotFound,
97
        other => RunError::Server(other),
98
361
    })?;
99
1625
    let transaction_ids = user.list_transaction_ids_by_account(account_id).await?;
100
1625
    let mut executor = ScriptExecutor::try_new()
101
        .map_err(|e| ServerError::Script(format!("failed to build the script executor: {e}")))?;
102
1625
    let scripts = vec![(script.id, script.bytecode)];
103
1625
    let mut computed = Vec::new();
104

            
105
1625
    for tx_id in transaction_ids {
106
2530
        let state = load_transaction_state(user.id, tx_id)
107
2530
            .await
108
180
            .inspect_err(|_| record(Outcome::Failed, 1))?;
109
2350
        let Some(state) = state else { continue };
110
2350
        let (returned, report) = run_blocking(executor, state, scripts.clone())
111
2350
            .await
112
            .inspect_err(|_| record(Outcome::Failed, 1))?;
113
2350
        executor = returned;
114
2350
        if let Some(failure) = report.failures.first() {
115
541
            return Ok(stopped(&computed, failure, tx_id));
116
1809
        }
117
1809
        computed.push((tx_id, report.state));
118
    }
119

            
120
1448
    let items: Vec<Item<'_>> = computed.iter().map(|(id, state)| (*id, state)).collect();
121
904
    let committed = write_tags(user, &items).await.map_err(write_failure)?;
122
904
    record(Outcome::Committed, committed.len());
123
1448
    let ran = items.iter().map(|(id, _)| *id).collect();
124
904
    Ok(ScriptRun {
125
904
        ran,
126
904
        committed,
127
904
        failures: Vec::new(),
128
904
    })
129
1986
}
130

            
131
/// Runs the scripts on a blocking thread and hands the executor back.
132
2350
async fn run_blocking(
133
2350
    executor: ScriptExecutor,
134
2350
    state: TransactionState,
135
2350
    scripts: Vec<(Uuid, Vec<u8>)>,
136
2350
) -> Result<(ScriptExecutor, ScriptRunReport), ServerError> {
137
2350
    let (executor, report) = tokio::task::spawn_blocking(move || {
138
2350
        let report = state.run_scripts(&executor, &scripts);
139
2350
        (executor, report)
140
2350
    })
141
2350
    .await
142
    .map_err(|e| ServerError::Script(format!("script task failed: {e}")))?;
143
2350
    Ok((executor, report?))
144
2350
}
145

            
146
541
fn stopped(
147
541
    computed: &[(Uuid, TransactionState)],
148
541
    failure: &ScriptFailure,
149
541
    transaction_id: Uuid,
150
541
) -> ScriptRun {
151
541
    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
541
    record(Outcome::Failed, 1);
158
    ScriptRun {
159
541
        ran: computed.iter().map(|(id, _)| *id).collect(),
160
541
        committed: Vec::new(),
161
541
        failures: vec![TransactionFailure {
162
541
            transaction_id,
163
541
            script_id: failure.script_id,
164
541
            code: failure.code.clone(),
165
541
            message: failure.message.clone(),
166
541
        }],
167
    }
168
541
}
169

            
170
/// A write-back refusal is the script user's to fix; any other failure is ours.
171
7
fn write_failure(err: BatchError) -> RunError {
172
7
    let item = err
173
7
        .tx_id
174
5
        .map_or_else(|| "batch".to_string(), |tx_id| tx_id.to_string());
175
7
    match err.error {
176
        ServerError::Script(message) => {
177
3
            record(Outcome::Refused, 1);
178
3
            RunError::Refused { item, message }
179
        }
180
        other => {
181
4
            record(Outcome::Failed, 1);
182
4
            tracing::error!("Script write-back failed on {item}: {other}");
183
4
            RunError::Failed {
184
4
                item,
185
4
                source: other,
186
4
            }
187
        }
188
    }
189
7
}
190

            
191
#[cfg(test)]
192
mod tests;
193
#[cfg(test)]
194
mod write_tests;