arcadedb_protocol/client/
transaction.rs1use super::*;
6
7impl ArcadeDbClient {
8 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 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 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 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 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 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 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
267pub 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 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 pub async fn execute_with_values(
302 &self,
303 command: &str,
304 parameters: impl Into<crate::encode::Params>,
305 ) -> Result<ExecuteCommandResponse> {
306 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 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
347pub(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
359pub struct Transaction<'a> {
368 client: &'a ArcadeDbClient,
369 database: String,
370 id: String,
371 finished: bool,
372}
373
374impl Transaction<'_> {
375 pub fn id(&self) -> &str {
377 &self.id
378 }
379
380 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 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 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 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 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}