From cdd4078772c8a164d70f88774bbae6d4ff695fbb Mon Sep 17 00:00:00 2001 From: broisnees Date: Fri, 20 Nov 2026 09:42:12 +0000 Subject: [PATCH 1/7] Roll back abandoned transactions instead of leaking them into the pool A console transaction starts with a plain BEGIN, so sqlx does not know the connection is in one. The idle sweep and a failed COMMIT dropped the session, sqlx handed the connection back to the pool still inside the transaction, and the next grid edit or console run joined it: writes never committed, locks held. A live test reproduces it. - Every session ends through release(): ROLLBACK, or close the socket if that fails. - The idle sweep runs on a one-minute timer, not only on begin and status. - Sessions carry the connection epoch. Switching, parking or closing the connection rolls them back, so a tab's statements can't run on a database the window has left. - Postgres sessions set idle_in_transaction_session_timeout as a server backstop. - The badge shows how long the transaction has been held and how many sessions wait on its locks (pg_blocking_pids, performance_schema). - Quit and window close ask before rolling back open transactions, and the quit path stops its 6 second fallback while a question is on screen. --- src-tauri/src/db/connection.rs | 3 + src-tauri/src/db/parked.rs | 2 + src-tauri/src/db/tx.rs | 393 ++++++++++++++++++++++---- src-tauri/src/lib.rs | 11 + src/lib/api.js | 6 + src/lib/components/SqlConsole.svelte | 21 ++ src/lib/components/StudioShell.svelte | 89 +++++- 7 files changed, 460 insertions(+), 65 deletions(-) diff --git a/src-tauri/src/db/connection.rs b/src-tauri/src/db/connection.rs index 2ce51837..7f251602 100644 --- a/src-tauri/src/db/connection.rs +++ b/src-tauri/src/db/connection.rs @@ -544,6 +544,8 @@ pub fn update_d1_token(token: &str) { } fn set_conn(state: &Db<'_>, conn: Option) -> Result<(), String> { + // Open transactions belong to the connection being replaced. + super::tx::connection_changed(); *state.conn.lock().map_err(|e| e.to_string())? = conn; // A fresh pool: the page names its key once it knows it (set_active_conn_key). *state.active_key.lock().map_err(|e| e.to_string())? = None; @@ -551,6 +553,7 @@ fn set_conn(state: &Db<'_>, conn: Option) -> Result<(), String } async fn close_existing(state: &Db<'_>) { + super::tx::connection_changed(); let old = state.conn.lock().ok().and_then(|mut g| g.take()); let Some(conn) = old else { return }; close_in_background(conn); diff --git a/src-tauri/src/db/parked.rs b/src-tauri/src/db/parked.rs index 6c84f0ff..52d2643e 100644 --- a/src-tauri/src/db/parked.rs +++ b/src-tauri/src/db/parked.rs @@ -11,6 +11,7 @@ const MAX_PARKED: usize = 8; /// Set the open connection aside under `key`. Nothing open: nothing to do. #[tauri::command] pub fn park_connection(state: Db<'_>, key: String) -> Result<(), String> { + super::tx::connection_changed(); let Some(conn) = state.conn.lock().map_err(|e| e.to_string())?.take() else { return Ok(()); }; @@ -34,6 +35,7 @@ pub fn resume_connection(state: Db<'_>, key: String) -> Result { parked.iter().position(|(k, _)| k == &key).map(|i| parked.remove(i).1) }; let Some(conn) = found else { return Ok(false) }; + super::tx::connection_changed(); let previous = state.conn.lock().map_err(|e| e.to_string())?.replace(conn); *state.active_key.lock().map_err(|e| e.to_string())? = Some(key); if let Some(prev) = previous { diff --git a/src-tauri/src/db/tx.rs b/src-tauri/src/db/tx.rs index b03fab1d..cd56fca9 100644 --- a/src-tauri/src/db/tx.rs +++ b/src-tauri/src/db/tx.rs @@ -7,20 +7,29 @@ the user can run a few statements, look at what they did, and then decide whether to keep them. A transaction holds a real connection (and, on most engines, locks) for as long -as it stays open, so a session that is left behind is closed automatically after -`IDLE_TIMEOUT` - see `sweep_idle`. +as it stays open, so a session that is left behind is rolled back after +`IDLE_TIMEOUT` by a timer (`sweep_idle`), and every session is rolled back when +the active connection changes (`connection_changed`). + +A session ends through `release` and nowhere else. Its `BEGIN` was a plain +statement, so sqlx does not know the connection is in a transaction: dropping +the `PoolConnection` hands it back to the pool still inside it (sqlx only pings +on release), and the next grid edit or console run that picks it up joins the +abandoned transaction. Its writes are never committed and the locks stay held. +`release` rolls back first and closes the socket if the rollback fails. */ use crate::db::connection::Db; use std::collections::HashMap; -use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{LazyLock, Mutex, OnceLock}; use std::time::{Duration, Instant}; use futures::TryStreamExt; use serde::Serialize; use serde_json::Value; use sqlx::{Column, Row, TypeInfo}; -use tauri::State; +use tauri::Emitter; use super::connection::{require_conn, ActiveConnection}; use super::query::{ @@ -33,6 +42,16 @@ use super::query::{ /// idle this long is rolled back and released on the next transaction command. const IDLE_TIMEOUT: Duration = Duration::from_secs(30 * 60); +/// How often the timer looks for sessions past `IDLE_TIMEOUT`. +pub const SWEEP_EVERY: Duration = Duration::from_secs(60); + +/// Postgres's own backstop, a little past ours: if this process dies or hangs +/// with a transaction open, the server ends the session itself. +const SERVER_IDLE_TIMEOUT: &str = "35min"; + +/// A ROLLBACK that takes longer than this is talking to a dead socket. +const RELEASE_TIMEOUT: Duration = Duration::from_secs(5); + /// The checked-out connection, per engine. enum TxConn { Postgres(sqlx::pool::PoolConnection), @@ -41,6 +60,16 @@ enum TxConn { } impl TxConn { + /// Take the connection out of the pool for good. Dropping the raw + /// connection closes its socket, which makes the server roll back. + fn close_hard(self) { + match self { + TxConn::Postgres(c) => drop(c.detach()), + TxConn::Mysql(c) => drop(c.detach()), + TxConn::Sqlite(c) => drop(c.detach()), + } + } + fn engine(&self) -> &'static str { match self { TxConn::Postgres(_) => "postgres", @@ -50,8 +79,18 @@ impl TxConn { } } +/// Where to ask who this transaction is holding up: a second pooled +/// connection and this session's server-side id. +enum Blocker { + Postgres(sqlx::PgPool, i32), + Mysql(sqlx::MySqlPool, u64), +} + struct TxSession { conn: TxConn, + /// The connection epoch at BEGIN (see `connection_changed`). + epoch: u64, + blocker: Option, /// Statements run since BEGIN, for the status line. statements: usize, /// Rows reported changed by those statements. @@ -60,9 +99,101 @@ struct TxSession { last_used: Instant, } +/// Open sessions by id. Module state rather than Tauri state so a connection +/// switch (`connection_changed`, called from `db::connection`) can reach them. +static SESSIONS: LazyLock>> = LazyLock::new(Default::default); + +/// Bumped every time the active connection is replaced, parked or closed. A +/// session from an older epoch belongs to a database the window has left. +static EPOCH: AtomicU64 = AtomicU64::new(0); + +/// For the `tx-ended` event the window listens to. +static APP: OnceLock = OnceLock::new(); + +pub fn init(app: tauri::AppHandle) { + let _ = APP.set(app); +} + +/// Kept so `lib.rs` can still `.manage()` it; the sessions live in `SESSIONS`. #[derive(Default)] -pub struct TxState { - sessions: Mutex>, +pub struct TxState; + +/// Why a session ended without the user pressing Commit or Rollback. +#[derive(Debug, Clone, Copy, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub enum EndReason { + Idle, + ConnectionChanged, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +struct TxEnded { + session_id: String, + reason: EndReason, + /// False when the rollback failed and the socket was closed instead (the + /// server rolls back on its own when it sees the socket go). + rolled_back: bool, +} + +/// Roll the session back and give its connection back to the pool, or close +/// it if the rollback does not come back clean. True when it rolled back. +async fn release(mut session: TxSession) -> bool { + let ok = matches!( + tokio::time::timeout(RELEASE_TIMEOUT, run_statement(&mut session.conn, "ROLLBACK")).await, + Ok(Ok(_)) + ); + if !ok { + log::info!("tx: rollback failed, closing the {} connection", session.conn.engine()); + session.conn.close_hard(); + } + ok +} + +/// End sessions taken out of the map, tell the window, and report how many. +async fn end_sessions(ended: Vec<(String, TxSession)>, reason: EndReason) -> usize { + let n = ended.len(); + for (id, session) in ended { + let rolled_back = release(session).await; + if let Some(app) = APP.get() { + let _ = app.emit("tx-ended", TxEnded { session_id: id, reason, rolled_back }); + } + } + n +} + +/// The active connection is about to be replaced, parked or closed. Every open +/// session belongs to the old one: roll them all back. Without this, a tab's +/// session kept a live connection to the database just left, and its next +/// statement ran there while the window showed the new one. +pub fn connection_changed() { + EPOCH.fetch_add(1, Ordering::SeqCst); + let ended: Vec<(String, TxSession)> = SESSIONS.lock().unwrap().drain().collect(); + if ended.is_empty() { + return; + } + tauri::async_runtime::spawn(end_sessions(ended, EndReason::ConnectionChanged)); +} + +/// Roll back sessions idle past `IDLE_TIMEOUT`. Runs on a timer (lib.rs) as well +/// as on every begin and status call. +pub async fn sweep_idle() -> usize { + let ended: Vec<(String, TxSession)> = { + let mut sessions = SESSIONS.lock().unwrap(); + let stale: Vec = sessions + .iter() + .filter(|(_, s)| s.last_used.elapsed() >= IDLE_TIMEOUT) + .map(|(id, _)| id.clone()) + .collect(); + stale.into_iter().filter_map(|id| sessions.remove(&id).map(|s| (id, s))).collect() + }; + end_sessions(ended, EndReason::Idle).await +} + +/// Ids of the open sessions, for the quit guard. +#[tauri::command] +pub fn tx_open_sessions() -> Vec { + SESSIONS.lock().unwrap().keys().cloned().collect() } #[derive(Debug, Clone, Serialize)] @@ -74,11 +205,14 @@ pub struct TxStatus { /// Milliseconds since BEGIN, so the UI can warn about a long-held lock. pub open_ms: u64, pub engine: Option, + /// Other sessions waiting on a lock this transaction holds. None when the + /// engine can't say (SQLite) or the server would not tell us. + pub blocking: Option, } impl TxStatus { fn closed() -> Self { - Self { open: false, statements: 0, rows_affected: 0, open_ms: 0, engine: None } + Self { open: false, statements: 0, rows_affected: 0, open_ms: 0, engine: None, blocking: None } } fn of(session: &TxSession) -> Self { @@ -88,6 +222,7 @@ impl TxStatus { rows_affected: session.rows_affected, open_ms: session.started.elapsed().as_millis() as u64, engine: Some(session.conn.engine().to_string()), + blocking: None, } } } @@ -99,40 +234,84 @@ impl TxStatus { // uncontended across awaits, and makes a second concurrent command for the same // session fail fast instead of interleaving statements on one connection. -/// Remove sessions idle past the timeout. Their connections are dropped, which -/// returns them to the pool; the server rolls back the abandoned transaction. -fn sweep_idle(state: &State<'_, TxState>) { - let mut sessions = state.sessions.lock().unwrap(); - sessions.retain(|_, s| s.last_used.elapsed() < IDLE_TIMEOUT); +fn take(id: &str) -> Option { + SESSIONS.lock().unwrap().remove(id) } -fn take(state: &State<'_, TxState>, id: &str) -> Option { - state.sessions.lock().unwrap().remove(id) +/// Put a session back after a command. If the connection changed while the +/// command ran, `connection_changed` has already drained the map, so the +/// session comes back to a world that has moved on: end it instead. +async fn put(id: &str, session: TxSession) -> Result<(), String> { + if session.epoch != EPOCH.load(Ordering::SeqCst) { + let id = id.to_string(); + end_sessions(vec![(id, session)], EndReason::ConnectionChanged).await; + return Err(LEFT_CONNECTION.into()); + } + SESSIONS.lock().unwrap().insert(id.to_string(), session); + Ok(()) } -fn put(state: &State<'_, TxState>, id: &str, session: TxSession) { - state.sessions.lock().unwrap().insert(id.to_string(), session); -} +const LEFT_CONNECTION: &str = + "This transaction was on a connection you have since left, so it was rolled back. Nothing it did was saved."; fn no_session(id: &str) -> String { format!("No open transaction for {id}. Start one before running statements in it.") } +/// This session's server-side id, so `tx_status` can ask who it is blocking. +async fn blocker_for(conn: &mut TxConn, db: &ActiveConnection) -> Option { + match (conn, db) { + (TxConn::Postgres(c), ActiveConnection::Postgres(pool)) => { + let pid = sqlx::query_scalar::<_, i32>("SELECT pg_backend_pid()").fetch_one(&mut **c).await.ok()?; + Some(Blocker::Postgres(pool.clone(), pid)) + } + (TxConn::Mysql(c), ActiveConnection::Mysql(pool)) => { + let id = sqlx::query_scalar::<_, u64>("SELECT CONNECTION_ID()").fetch_one(&mut **c).await.ok()?; + Some(Blocker::Mysql(pool.clone(), id)) + } + _ => None, + } +} + +/// Sessions waiting on a lock this one holds, asked on a second connection. +/// None when the server won't say (MySQL needs performance_schema access). +async fn blocking_count(blocker: &Blocker) -> Option { + let ask = async { + match blocker { + Blocker::Postgres(pool, pid) => sqlx::query_scalar::<_, i64>( + "SELECT count(*)::bigint FROM pg_stat_activity WHERE $1 = ANY(pg_blocking_pids(pid))", + ) + .bind(pid) + .fetch_one(pool) + .await + .ok(), + Blocker::Mysql(pool, id) => sqlx::query_scalar::<_, i64>( + "SELECT COUNT(*) FROM performance_schema.data_lock_waits w \ + JOIN performance_schema.threads t ON t.THREAD_ID = w.BLOCKING_THREAD_ID \ + WHERE t.PROCESSLIST_ID = ?", + ) + .bind(id) + .fetch_one(pool) + .await + .ok(), + } + }; + tokio::time::timeout(Duration::from_secs(2), ask).await.ok().flatten() +} + // ── Commands ────────────────────────────────────────────────────────────────── /// Open a transaction and hold its connection until commit or rollback. #[tauri::command] -pub async fn tx_begin( - db: Db<'_>, - tx: State<'_, TxState>, - session_id: String, -) -> Result { - sweep_idle(&tx); - if tx.sessions.lock().unwrap().contains_key(&session_id) { +pub async fn tx_begin(db: Db<'_>, session_id: String) -> Result { + sweep_idle().await; + if SESSIONS.lock().unwrap().contains_key(&session_id) { return Err("A transaction is already open here. Commit or roll it back first.".into()); } + let epoch = EPOCH.load(Ordering::SeqCst); + let active = require_conn(&db)?; - let mut conn = match require_conn(&db)? { + let mut conn = match &active { ActiveConnection::Postgres(pool) => TxConn::Postgres( pool.acquire().await.map_err(|e| format!("Could not open a transaction: {e}"))?, ), @@ -157,37 +336,39 @@ pub async fn tx_begin( }; run_statement(&mut conn, "BEGIN").await.map_err(|e| format!("Could not begin: {e}"))?; - // A statement that hangs inside a transaction holds its locks for as long as - // it runs, so cap it the same way the autocommit path does. if let TxConn::Postgres(_) = conn { + // A statement that hangs inside a transaction holds its locks for as + // long as it runs, so cap it the same way the autocommit path does. + let _ = run_statement(&mut conn, &format!("SET LOCAL statement_timeout = {EXECUTE_SQL_TIMEOUT_MS}")).await; + // The server's own backstop for a session this process never comes + // back to. Postgres 9.6+; older servers refuse it, which is harmless. let _ = run_statement( &mut conn, - &format!("SET LOCAL statement_timeout = {EXECUTE_SQL_TIMEOUT_MS}"), + &format!("SET LOCAL idle_in_transaction_session_timeout = '{SERVER_IDLE_TIMEOUT}'"), ) .await; } + let blocker = blocker_for(&mut conn, &active).await; let now = Instant::now(); let session = TxSession { conn, + epoch, + blocker, statements: 0, rows_affected: 0, started: now, last_used: now, }; let status = TxStatus::of(&session); - put(&tx, &session_id, session); + put(&session_id, session).await?; Ok(status) } /// Run SQL inside the open transaction. Nothing is visible to anyone else until /// the transaction commits. #[tauri::command] -pub async fn tx_execute( - tx: State<'_, TxState>, - session_id: String, - sql: String, -) -> Result { +pub async fn tx_execute(session_id: String, sql: String) -> Result { let trimmed = sql.trim().to_string(); if trimmed.is_empty() { return Err("Query is empty".into()); @@ -204,7 +385,11 @@ pub async fn tx_execute( } } - let mut session = take(&tx, &session_id).ok_or_else(|| no_session(&session_id))?; + let mut session = take(&session_id).ok_or_else(|| no_session(&session_id))?; + if session.epoch != EPOCH.load(Ordering::SeqCst) { + end_sessions(vec![(session_id, session)], EndReason::ConnectionChanged).await; + return Err(LEFT_CONNECTION.into()); + } let started = Instant::now(); let result = execute_in(&mut session.conn, &trimmed).await; @@ -221,7 +406,7 @@ pub async fn tx_execute( session.statements += 1; } } - put(&tx, &session_id, session); + put(&session_id, session).await?; result.map(|mut r| { r.query_ms = started.elapsed().as_millis() as u64; @@ -232,40 +417,60 @@ pub async fn tx_execute( /// Commit the open transaction and give the connection back. #[tauri::command] -pub async fn tx_commit(tx: State<'_, TxState>, session_id: String) -> Result { - let mut session = take(&tx, &session_id).ok_or_else(|| no_session(&session_id))?; +pub async fn tx_commit(session_id: String) -> Result { + let mut session = take(&session_id).ok_or_else(|| no_session(&session_id))?; + if session.epoch != EPOCH.load(Ordering::SeqCst) { + end_sessions(vec![(session_id, session)], EndReason::ConnectionChanged).await; + return Err(LEFT_CONNECTION.into()); + } match run_statement(&mut session.conn, "COMMIT").await { - // The connection is dropped with `session`, returning it to the pool. + // Clean: the connection is out of its transaction, back to the pool. Ok(_) => Ok(TxStatus::closed()), Err(e) => { // The commit failed, so the transaction is neither applied nor - // cleanly closed. Drop the connection rather than hand back a - // session whose state nobody can describe. - Err(format!("Could not commit: {e}")) + // cleanly closed. Roll back what is left, or close the socket. + release(session).await; + Err(format!("Could not commit: {e}. Nothing was saved.")) } } } /// Roll the open transaction back and give the connection back. #[tauri::command] -pub async fn tx_rollback(tx: State<'_, TxState>, session_id: String) -> Result { - let mut session = take(&tx, &session_id).ok_or_else(|| no_session(&session_id))?; - run_statement(&mut session.conn, "ROLLBACK") - .await - .map_err(|e| format!("Could not roll back: {e}"))?; - Ok(TxStatus::closed()) +pub async fn tx_rollback(session_id: String) -> Result { + let session = take(&session_id).ok_or_else(|| no_session(&session_id))?; + // Whatever happens the session is over: a failed ROLLBACK closes the + // socket, and the server rolls back when it sees it go. + if release(session).await { + Ok(TxStatus::closed()) + } else { + Err("The rollback did not complete, so the connection was closed. The server rolls back a closed connection's transaction, so nothing was saved.".into()) + } } /// What the UI needs to render the transaction indicator. #[tauri::command] -pub async fn tx_status(tx: State<'_, TxState>, session_id: String) -> Result { - sweep_idle(&tx); - let sessions = tx.sessions.lock().unwrap(); - Ok(sessions.get(&session_id).map_or_else(TxStatus::closed, TxStatus::of)) +pub async fn tx_status(session_id: String) -> Result { + sweep_idle().await; + let (mut status, blocker) = { + let sessions = SESSIONS.lock().unwrap(); + match sessions.get(&session_id) { + None => return Ok(TxStatus::closed()), + Some(s) => ( + TxStatus::of(s), + s.blocker.as_ref().map(|b| match b { + Blocker::Postgres(p, pid) => Blocker::Postgres(p.clone(), *pid), + Blocker::Mysql(p, id) => Blocker::Mysql(p.clone(), *id), + }), + ), + } + }; + if let Some(b) = blocker { + status.blocking = blocking_count(&b).await; + } + Ok(status) } -// ── Execution ───────────────────────────────────────────────────────────────── - /// The first word of a statement, lowercased, skipping leading comments. fn leading_keyword(sql: &str) -> Option { let mut rest = sql.trim_start(); @@ -403,6 +608,86 @@ async fn fetch_rows(conn: &mut TxConn, stmt: &str) -> Result mod tests { use super::leading_keyword; + // Live: a released session must give back a connection that is out of its + // transaction. Before `release`, the idle sweep dropped the PoolConnection, + // sqlx returned it to the pool still inside the BEGIN, and the next user of + // the pool ran in the abandoned transaction. + // STROKE_TEST_PG_URL=postgres://postgres@127.0.0.1:5433/postgres \ + // cargo test --lib tx::tests::release_ -- --nocapture + #[tokio::test] + async fn release_returns_a_clean_connection() { + use super::*; + let Ok(url) = std::env::var("STROKE_TEST_PG_URL") else { return }; + // One connection, so the next acquire gets the one we released. + let pool = sqlx::postgres::PgPoolOptions::new().max_connections(1).connect(&url).await.unwrap(); + sqlx::query("CREATE TABLE IF NOT EXISTS stroke_tx_release (v int)").execute(&pool).await.unwrap(); + sqlx::query("TRUNCATE stroke_tx_release").execute(&pool).await.unwrap(); + + let session = |conn| TxSession { + conn, + epoch: 0, + blocker: None, + statements: 0, + rows_affected: 0, + started: Instant::now(), + last_used: Instant::now(), + }; + let open = |pool: &sqlx::PgPool| { + let pool = pool.clone(); + async move { + let mut conn = TxConn::Postgres(pool.acquire().await.unwrap()); + run_statement(&mut conn, "BEGIN").await.unwrap(); + run_statement(&mut conn, "INSERT INTO stroke_tx_release VALUES (1)").await.unwrap(); + conn + } + }; + let in_tx = |pool: &sqlx::PgPool| { + let pool = pool.clone(); + async move { + // Assigned only inside a transaction that wrote something. + sqlx::query_scalar::<_, Option>("SELECT txid_current_if_assigned()") + .fetch_one(&pool) + .await + .unwrap() + .is_some() + } + }; + + // What the sweep used to do: drop it. + drop(session(open(&pool).await)); + tokio::time::sleep(Duration::from_millis(200)).await; + assert!(in_tx(&pool).await, "a dropped session leaks its transaction into the pool"); + // Clean up after the demonstration. + sqlx::query("ROLLBACK").execute(&pool).await.unwrap(); + + // What every exit does now. + assert!(release(session(open(&pool).await)).await); + tokio::time::sleep(Duration::from_millis(200)).await; + assert!(!in_tx(&pool).await, "a released session must not leave a transaction open"); + let rows: i64 = sqlx::query_scalar("SELECT count(*) FROM stroke_tx_release").fetch_one(&pool).await.unwrap(); + assert_eq!(rows, 0, "the uncommitted insert must be gone"); + sqlx::query("DROP TABLE stroke_tx_release").execute(&pool).await.unwrap(); + } + + // Live: switching connections ends every open session. + #[tokio::test] + async fn connection_change_ends_sessions() { + use super::*; + let Ok(url) = std::env::var("STROKE_TEST_PG_URL") else { return }; + let pool = sqlx::postgres::PgPoolOptions::new().max_connections(2).connect(&url).await.unwrap(); + let mut conn = TxConn::Postgres(pool.acquire().await.unwrap()); + run_statement(&mut conn, "BEGIN").await.unwrap(); + let epoch = EPOCH.load(Ordering::SeqCst); + let now = Instant::now(); + let s = TxSession { conn, epoch, blocker: None, statements: 0, rows_affected: 0, started: now, last_used: now }; + put("test-switch", s).await.unwrap(); + assert!(tx_open_sessions().contains(&"test-switch".to_string())); + connection_changed(); + assert!(!tx_open_sessions().contains(&"test-switch".to_string())); + let err = tx_execute("test-switch".into(), "SELECT 1".into()).await.unwrap_err(); + assert!(err.contains("No open transaction"), "{err}"); + } + #[test] fn finds_the_first_keyword() { assert_eq!(leading_keyword("SELECT 1").as_deref(), Some("select")); diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 102635e7..c279d793 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -498,6 +498,16 @@ pub fn run() { .manage(launch::LaunchState::default()) .setup(move |app| { display_backend::watch(app.handle().clone()); + // Explicit transactions: roll back the ones left idle, on a timer, + // so a forgotten tab does not hold its locks until someone looks. + db::tx::init(app.handle().clone()); + tauri::async_runtime::spawn(async { + let mut tick = tokio::time::interval(db::tx::SWEEP_EVERY); + loop { + tick.tick().await; + db::tx::sweep_idle().await; + } + }); // Local servers marked "Start with Stroke". local_servers::autostart(app.handle().clone()); // Linux packages renamed the binary from `app` to `stroke` (2.5.6), and @@ -904,6 +914,7 @@ pub fn run() { db::tx::tx_commit, db::tx::tx_rollback, db::tx::tx_status, + db::tx::tx_open_sessions, db::terminal::terminal_client, db::terminal::terminal_open, db::terminal::terminal_install_client, diff --git a/src/lib/api.js b/src/lib/api.js index 7bc335f4..99175a72 100644 --- a/src/lib/api.js +++ b/src/lib/api.js @@ -1966,6 +1966,7 @@ export async function backupCancel() { * @property {number} rowsAffected * @property {number} openMs how long the transaction has been held * @property {string|null} engine + * @property {number|null} [blocking] sessions waiting on a lock it holds (null: the engine can't say) */ /** @@ -2012,6 +2013,11 @@ export async function txStatus(sessionId) { return inv('tx_status', { sessionId }) } +/** Ids of every open transaction session, for the quit guard. @returns {Promise} */ +export async function txOpenSessions() { + return inv('tx_open_sessions', {}) +} + /** * A read for a console write's undo copy (sql-undo.js), outside any * transaction. Not logged as a query of the user's, and stoppable through the diff --git a/src/lib/components/SqlConsole.svelte b/src/lib/components/SqlConsole.svelte index b7ec723e..325051f3 100644 --- a/src/lib/components/SqlConsole.svelte +++ b/src/lib/components/SqlConsole.svelte @@ -240,6 +240,12 @@ }) }) + /** "14m", "1h 5m": how long a transaction has held its locks. @param {number} ms */ + function heldFor(ms) { + const m = Math.floor(ms / 60_000) + return m < 60 ? `${m}m` : `${Math.floor(m / 60)}h ${m % 60}m` + } + /** @param {string} name @param {import('$lib/sql-params.js').SqlParamValue} next */ function setParam(name, next) { paramValues = { ...paramValues, [name]: next } @@ -999,7 +1005,22 @@ {txStatus.statements}{txStatus.statements === 1 ? 'stmt' : 'stmts'} + + {#if txStatus.openMs >= 60_000} + {heldFor(txStatus.openMs)} + {/if} + {#if txStatus.blocking} + + + {txStatus.blocking} + {txStatus.blocking === 1 ? 'session waiting' : 'sessions waiting'} + + {/if}