Lines
85.15 %
Functions
70 %
Branches
100 %
//! Running one stored script over every transaction of an account.
use scripting::ScriptExecutor;
use sqlx::types::Uuid;
use crate::db::DBError;
use crate::error::ServerError;
use crate::script::{ScriptFailure, ScriptRunReport, TransactionState, load_transaction_state};
use crate::script_tags::{BatchError, Item, write_tags};
use crate::telemetry::recorder::SCRIPT_BATCH_ITEMS;
use crate::user::User;
/// The script failure that stopped a run, on the transaction it met it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TransactionFailure {
pub transaction_id: Uuid,
pub script_id: Uuid,
pub code: String,
pub message: String,
}
/// A script failure stops the run at the first transaction it meets it and
/// writes nothing: `failures` then holds that one failure, `ran` the
/// transactions before it, and `committed` is empty.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ScriptRun {
pub ran: Vec<Uuid>,
pub committed: Vec<Uuid>,
pub failures: Vec<TransactionFailure>,
impl std::fmt::Display for ScriptRun {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"ran {}, committed {}, failed {}",
self.ran.len(),
self.committed.len(),
self.failures.len()
)
#[derive(Debug, thiserror::Error)]
pub enum RunError {
/// The write-back was refused (a stale or unstored split): the script
/// user's to fix. `item` names the transaction, or the whole batch.
#[error("{item}: refused: {message} (nothing was written)")]
Refused { item: String, message: String },
/// The write-back failed for a reason that is not the script user's.
#[error("{item}: failed: {source} (nothing was written)")]
Failed { item: String, source: ServerError },
#[error("Script not found")]
ScriptNotFound,
#[error(transparent)]
Server(#[from] ServerError),
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Outcome {
Committed,
Refused,
Failed,
impl Outcome {
const fn as_str(self) -> &'static str {
match self {
Self::Committed => "committed",
Self::Refused => "refused",
Self::Failed => "failed",
/// Counted once the batch has committed or rolled back: a failed batch counts
/// only the item that stopped it.
fn record(outcome: Outcome, items: usize) {
metrics::counter!(SCRIPT_BATCH_ITEMS, "outcome" => outcome.as_str())
.increment(u64::try_from(items).unwrap_or(u64::MAX));
/// Runs the stored script on each transaction of the account, then writes
/// every script tag effect in one all-or-nothing batch. A disabled script
/// runs too: only the stored row decides.
///
/// # Errors
/// A missing script (`RowNotFound`), a failing load or run, or a refused or
/// failing write-back; nothing is written then.
pub async fn run_on_account(
user: &User,
script_id: Uuid,
account_id: Uuid,
) -> Result<ScriptRun, RunError> {
let script = user.get_script(script_id).await.map_err(|err| match err {
ServerError::DB(DBError::Sqlx(sqlx::Error::RowNotFound)) => RunError::ScriptNotFound,
other => RunError::Server(other),
})?;
let transaction_ids = user.list_transaction_ids_by_account(account_id).await?;
let mut executor = ScriptExecutor::try_new()
.map_err(|e| ServerError::Script(format!("failed to build the script executor: {e}")))?;
let scripts = vec![(script.id, script.bytecode)];
let mut computed = Vec::new();
for tx_id in transaction_ids {
let state = load_transaction_state(user.id, tx_id)
.await
.inspect_err(|_| record(Outcome::Failed, 1))?;
let Some(state) = state else { continue };
let (returned, report) = run_blocking(executor, state, scripts.clone())
executor = returned;
if let Some(failure) = report.failures.first() {
return Ok(stopped(&computed, failure, tx_id));
computed.push((tx_id, report.state));
let items: Vec<Item<'_>> = computed.iter().map(|(id, state)| (*id, state)).collect();
let committed = write_tags(user, &items).await.map_err(write_failure)?;
record(Outcome::Committed, committed.len());
let ran = items.iter().map(|(id, _)| *id).collect();
Ok(ScriptRun {
ran,
committed,
failures: Vec::new(),
})
/// Runs the scripts on a blocking thread and hands the executor back.
async fn run_blocking(
executor: ScriptExecutor,
state: TransactionState,
scripts: Vec<(Uuid, Vec<u8>)>,
) -> Result<(ScriptExecutor, ScriptRunReport), ServerError> {
let (executor, report) = tokio::task::spawn_blocking(move || {
let report = state.run_scripts(&executor, &scripts);
(executor, report)
.map_err(|e| ServerError::Script(format!("script task failed: {e}")))?;
Ok((executor, report?))
fn stopped(
computed: &[(Uuid, TransactionState)],
failure: &ScriptFailure,
transaction_id: Uuid,
) -> ScriptRun {
tracing::error!(
"Script {sid} failed on tx {transaction_id}: {code}: {message}",
sid = failure.script_id,
code = failure.code,
message = failure.message
);
record(Outcome::Failed, 1);
ScriptRun {
ran: computed.iter().map(|(id, _)| *id).collect(),
committed: Vec::new(),
failures: vec![TransactionFailure {
transaction_id,
script_id: failure.script_id,
code: failure.code.clone(),
message: failure.message.clone(),
}],
/// A write-back refusal is the script user's to fix; any other failure is ours.
fn write_failure(err: BatchError) -> RunError {
let item = err
.tx_id
.map_or_else(|| "batch".to_string(), |tx_id| tx_id.to_string());
match err.error {
ServerError::Script(message) => {
record(Outcome::Refused, 1);
RunError::Refused { item, message }
other => {
tracing::error!("Script write-back failed on {item}: {other}");
RunError::Failed {
item,
source: other,
#[cfg(test)]
mod tests;
mod write_tests;