Skip to main content

arcadedb_protocol/client/
transaction.rs

1//! Explicit transactions — raw begin/commit/rollback, the [`Transaction`]
2//! drop-guard, the [`TxCommands`] attempt handle, and the retrying
3//! [`ArcadeDbClient::run_transaction`] runner.
4
5use super::*;
6
7impl ArcadeDbClient {
8    /// Begin an explicit server-side transaction.
9    ///
10    /// Returns a transaction id; pass it to [`execute_in_transaction`](Self::execute_in_transaction)
11    /// and [`query_in_transaction`](Self::query_in_transaction), then finish with
12    /// [`commit_transaction`](Self::commit_transaction) or [`rollback_transaction`](Self::rollback_transaction).
13    ///
14    /// NOTE: ArcadeDB keeps schema changes (DDL) outside transaction scope —
15    /// they commit immediately in their own sub-transaction. Use the explicit
16    /// transaction for *record* operations (the copy phase of an override
17    /// rebuild) and verify the copy before committing; do not rely on it to
18    /// make batch DDL atomic.
19    pub async fn begin_transaction(
20        &self,
21        database: &str,
22        isolation: TransactionIsolation,
23    ) -> Result<String> {
24        let req = tonic::Request::new(BeginTransactionRequest {
25            database: database.into(),
26            credentials: Some(self.auth.creds.clone()),
27            isolation: isolation as i32,
28        });
29
30        let resp = self
31            .data
32            .clone()
33            .begin_transaction(self.add_auth_headers(req))
34            .await
35            .map_err(|e| map_rpc_error("begin transaction", "", e))?
36            .into_inner();
37
38        tracing::info!(tx = %resp.transaction_id, "transaction begun");
39        Ok(resp.transaction_id)
40    }
41
42    /// Execute a command inside an explicitly-begun transaction.
43    ///
44    /// The command runs with the transaction attached; it is only durable when
45    /// the transaction is later committed. (Schema statements still commit
46    /// immediately — see [`begin_transaction`](Self::begin_transaction).)
47    pub async fn execute_in_transaction(
48        &self,
49        database: &str,
50        language: &str,
51        command: &str,
52        transaction_id: &str,
53    ) -> Result<ExecuteCommandResponse> {
54        let req = tonic::Request::new(ExecuteCommandRequest {
55            database: database.into(),
56            command: command.into(),
57            credentials: Some(self.auth.creds.clone()),
58            language: language.into(),
59            return_rows: true,
60            transaction: Some(TransactionContext {
61                transaction_id: transaction_id.into(),
62                ..Default::default()
63            }),
64            ..Default::default()
65        });
66
67        let resp = self
68            .data
69            .clone()
70            .execute_command(self.add_auth_headers(req))
71            .await
72            .map_err(|e| map_rpc_error("execute command (in tx)", command, e))?
73            .into_inner();
74
75        if !resp.success {
76            return Err(command_failed(
77                "execute command (in tx)",
78                resp.message,
79                resp.affected_records,
80            ));
81        }
82
83        Ok(resp)
84    }
85
86    /// Run a read query *inside* an explicitly-begun transaction, so the
87    /// caller can verify what the transaction has written before committing.
88    pub async fn query_in_transaction(
89        &self,
90        database: &str,
91        query: &str,
92        transaction_id: &str,
93    ) -> Result<QueryResult> {
94        let req = tonic::Request::new(ExecuteQueryRequest {
95            database: database.into(),
96            query: query.into(),
97            credentials: Some(self.auth.creds.clone()),
98            language: "sql".into(),
99            transaction: Some(TransactionContext {
100                transaction_id: transaction_id.into(),
101                ..Default::default()
102            }),
103            ..Default::default()
104        });
105
106        let resp = self
107            .data
108            .clone()
109            .execute_query(self.add_auth_headers(req))
110            .await
111            .map_err(|e| map_rpc_error("query (in tx)", query, e))?
112            .into_inner();
113
114        let mut records = Vec::with_capacity(resp.results.iter().map(|qr| qr.records.len()).sum());
115        records.extend(resp.results.into_iter().flat_map(|qr| qr.records));
116
117        Ok(QueryResult {
118            records,
119            execution_time_ms: resp.execution_time_ms,
120        })
121    }
122
123    /// Commit an explicitly-begun transaction, making its record operations durable.
124    pub async fn commit_transaction(&self, database: &str, transaction_id: &str) -> Result<()> {
125        let req = tonic::Request::new(CommitTransactionRequest {
126            transaction: Some(TransactionContext {
127                transaction_id: transaction_id.into(),
128                database: database.into(),
129                ..Default::default()
130            }),
131            credentials: Some(self.auth.creds.clone()),
132        });
133
134        let resp = self
135            .data
136            .clone()
137            .commit_transaction(self.add_auth_headers(req))
138            .await
139            .map_err(|e| map_rpc_error("commit transaction", transaction_id, e))?
140            .into_inner();
141
142        tracing::info!(tx = %transaction_id, ok = resp.success, committed = resp.committed, "transaction committed");
143        if !resp.success {
144            return Err(ArcadeDbError::CommandFailed {
145                operation: "commit transaction".into(),
146                message: resp.message,
147                affected: None,
148            });
149        }
150        Ok(())
151    }
152
153    /// Roll back an explicitly-begun transaction, discarding its record operations.
154    pub async fn rollback_transaction(&self, database: &str, transaction_id: &str) -> Result<()> {
155        let req = tonic::Request::new(RollbackTransactionRequest {
156            transaction: Some(TransactionContext {
157                transaction_id: transaction_id.into(),
158                database: database.into(),
159                ..Default::default()
160            }),
161            credentials: Some(self.auth.creds.clone()),
162        });
163
164        let resp = self
165            .data
166            .clone()
167            .rollback_transaction(self.add_auth_headers(req))
168            .await
169            .map_err(|e| map_rpc_error("rollback transaction", transaction_id, e))?
170            .into_inner();
171
172        tracing::info!(tx = %transaction_id, ok = resp.success, rolled_back = resp.rolled_back, "transaction rolled back");
173        if !resp.success {
174            return Err(ArcadeDbError::CommandFailed {
175                operation: "rollback transaction".into(),
176                message: resp.message,
177                affected: None,
178            });
179        }
180        Ok(())
181    }
182
183    /// Begin an explicit server-side transaction as a guard ([`Transaction`]).
184    ///
185    /// The guard owns the transaction lifecycle: run commands with
186    /// [`Transaction::execute`] / [`Transaction::query`], then finish with
187    /// [`Transaction::commit`] or [`Transaction::rollback`]. Dropping the
188    /// guard without finishing fires a best-effort background rollback (the
189    /// server's idle-reaper is the backstop), so forgotten transactions
190    /// cannot leak.
191    pub async fn transaction(
192        &self,
193        database: &str,
194        isolation: TransactionIsolation,
195    ) -> Result<Transaction<'_>> {
196        let id = self.begin_transaction(database, isolation).await?;
197        Ok(Transaction {
198            client: self,
199            database: database.into(),
200            id,
201            finished: false,
202        })
203    }
204
205    /// Run `body` inside an explicit transaction, retrying the whole block
206    /// up to `retries` extra times when the server reports an MVCC conflict
207    /// (concurrent modification) — the Java API's
208    /// `transaction(txBlock, retries)`. A fresh transaction is begun per
209    /// attempt; every failed attempt is rolled back before retrying.
210    ///
211    /// Conflict detection is best-effort message matching (the gRPC surface
212    /// exposes no structured conflict code yet): `concurrent`, `mvcc`, or
213    /// `needretry` in the server message. Non-conflict errors and exhausted
214    /// retries return the last error, transaction rolled back.
215    ///
216    /// DDL is outside transaction scope (see
217    /// [`begin_transaction`](Self::begin_transaction)) — record operations
218    /// only. Pairs with the [`Transaction`](crate::Transaction) drop-guard:
219    /// the guard makes multi-statement units atomic, this makes them
220    /// self-healing under concurrent writers.
221    pub async fn run_transaction<T, F, Fut>(
222        &self,
223        database: &str,
224        isolation: TransactionIsolation,
225        retries: u32,
226        body: F,
227    ) -> Result<T>
228    where
229        F: Fn(TxCommands) -> Fut,
230        Fut: std::future::Future<Output = Result<T>>,
231    {
232        let attempts = retries.saturating_add(1);
233        let mut last_err: Option<ArcadeDbError> = None;
234        for attempt in 0..attempts {
235            let tx_id = self.begin_transaction(database, isolation).await?;
236            let commands = TxCommands::new(self, database, &tx_id);
237            match body(commands).await {
238                Ok(value) => match self.commit_transaction(database, &tx_id).await {
239                    Ok(()) => return Ok(value),
240                    Err(e) => {
241                        let _ = self.rollback_transaction(database, &tx_id).await;
242                        if is_retryable_conflict(&e) && attempt + 1 < attempts {
243                            tracing::warn!(attempt, "transaction commit conflict — retrying");
244                            last_err = Some(e);
245                            continue;
246                        }
247                        return Err(e);
248                    }
249                },
250                Err(e) => {
251                    let _ = self.rollback_transaction(database, &tx_id).await;
252                    if is_retryable_conflict(&e) && attempt + 1 < attempts {
253                        tracing::warn!(attempt, "transaction body conflict — retrying");
254                        last_err = Some(e);
255                        continue;
256                    }
257                    return Err(e);
258                }
259            }
260        }
261        Err(last_err.unwrap_or_else(|| ArcadeDbError::InvalidInput {
262            message: "run_transaction: retries exhausted without an error".into(),
263        }))
264    }
265}
266
267/// Commands issued inside [`ArcadeDbClient::run_transaction`]'s current
268/// attempt — the [`Transaction`] guard's operations without the lifecycle
269/// (begin/commit/rollback are the runner's job).
270///
271/// Owns its data (client handle is a cheap `Arc` clone, plus two small
272/// `String`s) so the [`run_transaction`](ArcadeDbClient::run_transaction)
273/// body can be a plain `|tx| async move { … }` closure — a borrowed
274/// `TxCommands<'_>` would make the closure's future tie to the argument's
275/// lifetime, which stable Rust's closure generics cannot express (no HRTB
276/// over futures). Owned state also means every retry attempt gets a fresh
277/// set of commands, which is exactly the retry semantics.
278pub struct TxCommands {
279    client: ArcadeDbClient,
280    database: String,
281    tx_id: String,
282}
283
284impl TxCommands {
285    pub(crate) fn new(client: &ArcadeDbClient, database: &str, tx_id: &str) -> Self {
286        Self {
287            client: client.clone(),
288            database: database.to_string(),
289            tx_id: tx_id.to_string(),
290        }
291    }
292
293    /// Run a command in the current transaction attempt.
294    pub async fn execute(&self, language: &str, command: &str) -> Result<ExecuteCommandResponse> {
295        self.client
296            .execute_in_transaction(&self.database, language, command, &self.tx_id)
297            .await
298    }
299
300    /// Run a parameterized SQL command in the current transaction attempt.
301    pub async fn execute_with_values(
302        &self,
303        command: &str,
304        parameters: impl Into<crate::encode::Params>,
305    ) -> Result<ExecuteCommandResponse> {
306        // `execute_in_transaction` has no parameter path — inline its request.
307        let parameters = parameters.into();
308        let req = tonic::Request::new(ExecuteCommandRequest {
309            database: self.database.clone(),
310            command: command.into(),
311            parameters: parameters.0,
312            credentials: Some(self.client.creds()),
313            language: "sql".into(),
314            return_rows: true,
315            transaction: Some(TransactionContext {
316                transaction_id: self.tx_id.clone(),
317                ..Default::default()
318            }),
319            ..Default::default()
320        });
321        let resp = self
322            .client
323            .data
324            .clone()
325            .execute_command(self.client.add_auth_headers(req))
326            .await
327            .map_err(|e| map_rpc_error("execute command (in tx)", command, e))?
328            .into_inner();
329        if !resp.success {
330            return Err(command_failed(
331                "execute command (in tx)",
332                resp.message,
333                resp.affected_records,
334            ));
335        }
336        Ok(resp)
337    }
338
339    /// Run a SQL read in the current transaction attempt.
340    pub async fn query(&self, query: &str) -> Result<QueryResult> {
341        self.client
342            .query_in_transaction(&self.database, query, &self.tx_id)
343            .await
344    }
345}
346
347/// Best-effort MVCC-conflict detection from the server message (no
348/// structured gRPC code yet — see
349/// [`run_transaction`](ArcadeDbClient::run_transaction)).
350pub(crate) fn is_retryable_conflict(err: &ArcadeDbError) -> bool {
351    err.server_message()
352        .map(|m| {
353            let m = m.to_ascii_lowercase();
354            m.contains("concurrent") || m.contains("mvcc") || m.contains("needretry")
355        })
356        .unwrap_or(false)
357}
358
359/// A drop-safe explicit transaction: the guard returned by
360/// [`ArcadeDbClient::transaction`]. Commands run through the guard; finishing
361/// is explicit (`commit`/`rollback` both consume `self`), and a guard dropped
362/// unfinished rolls back in a background task — the server's idle-reaper is
363/// the last line of defense.
364///
365/// NOTE (mirrors [`ArcadeDbClient::begin_transaction`]): ArcadeDB keeps DDL
366/// outside transaction scope — use the guard for *record* operations only.
367pub struct Transaction<'a> {
368    client: &'a ArcadeDbClient,
369    database: String,
370    id: String,
371    finished: bool,
372}
373
374impl Transaction<'_> {
375    /// The server-assigned transaction id.
376    pub fn id(&self) -> &str {
377        &self.id
378    }
379
380    /// Run a command inside the transaction.
381    pub async fn execute(&self, language: &str, command: &str) -> Result<ExecuteCommandResponse> {
382        self.client
383            .execute_in_transaction(&self.database, language, command, &self.id)
384            .await
385    }
386
387    /// Run a SQL read inside the transaction.
388    pub async fn query(&self, query: &str) -> Result<QueryResult> {
389        self.client
390            .query_in_transaction(&self.database, query, &self.id)
391            .await
392    }
393
394    /// Commit, making every record operation durable. Consumes the guard.
395    pub async fn commit(mut self) -> Result<()> {
396        self.finished = true;
397        self.client
398            .commit_transaction(&self.database, &self.id)
399            .await
400    }
401
402    /// Roll back, discarding every record operation. Consumes the guard.
403    pub async fn rollback(mut self) -> Result<()> {
404        self.finished = true;
405        self.client
406            .rollback_transaction(&self.database, &self.id)
407            .await
408    }
409}
410
411impl Drop for Transaction<'_> {
412    fn drop(&mut self) {
413        if self.finished {
414            return;
415        }
416        tracing::warn!(tx = %self.id, db = %self.database, "transaction dropped unfinished — rolling back");
417        // Best-effort async rollback: requires a live runtime (the caller is
418        // async by construction); outside one, the server reaper reclaims it.
419        let client = self.client.clone();
420        let database = std::mem::take(&mut self.database);
421        let id = std::mem::take(&mut self.id);
422        let _ = tokio::runtime::Handle::try_current().map(|rt| {
423            rt.spawn(async move {
424                if let Err(e) = client.rollback_transaction(&database, &id).await {
425                    tracing::error!(tx = %id, "drop rollback failed: {e}");
426                }
427            });
428        });
429    }
430}