foundationdb/database.rs
1// Copyright 2018 foundationdb-rs developers, https://github.com/Clikengo/foundationdb-rs/graphs/contributors
2// Copyright 2013-2018 Apple, Inc and the FoundationDB project authors.
3//
4// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
5// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
6// http://opensource.org/licenses/MIT>, at your option. This file may not be
7// copied, modified, or distributed except according to those terms.
8
9//! Implementations of the FDBDatabase C API
10//!
11//! <https://apple.github.io/foundationdb/api-c.html#database>
12
13use std::convert::TryInto;
14use std::marker::PhantomData;
15use std::pin::Pin;
16use std::ptr::NonNull;
17use std::time::{Duration, Instant};
18
19use fdb_sys::if_cfg_api_versions;
20use foundationdb_macros::cfg_api_versions;
21use foundationdb_sys as fdb_sys;
22
23use crate::metrics::{MetricsReport, TransactionMetrics};
24use crate::options;
25use crate::runner::{MetricsHooks, RunnerHooks, TransactionRunner};
26use crate::transaction::*;
27use crate::{FdbError, FdbResult, error};
28
29use crate::error::RetryableError;
30use futures::prelude::*;
31
32/// Whether any earlier attempt in this run may have committed.
33///
34/// Once true, this remains true for every subsequent attempt, even if later
35/// attempts fail with errors that are known not to have committed.
36/// Convert it to a boolean with `bool::from` when checking the flag.
37pub struct MaybeCommitted(bool);
38
39impl MaybeCommitted {
40 pub(crate) fn new(maybe_committed: bool) -> Self {
41 Self(maybe_committed)
42 }
43}
44
45impl From<MaybeCommitted> for bool {
46 fn from(value: MaybeCommitted) -> Self {
47 value.0
48 }
49}
50
51/// Represents a FoundationDB database
52///
53/// A mutable, lexicographically ordered mapping from binary keys to binary values.
54///
55/// Modifications to a database are performed via transactions.
56pub struct Database {
57 pub(crate) inner: NonNull<fdb_sys::FDBDatabase>,
58}
59unsafe impl Send for Database {}
60unsafe impl Sync for Database {}
61impl Drop for Database {
62 fn drop(&mut self) {
63 unsafe {
64 fdb_sys::fdb_database_destroy(self.inner.as_ptr());
65 }
66 }
67}
68
69#[cfg_api_versions(min = 610)]
70impl Database {
71 /// Create a database for the given configuration path if any, or the default one.
72 ///
73 /// If the client was not initialized yet, the network is started with the
74 /// default API version, like [`crate::boot`] would.
75 pub fn new(path: Option<&str>) -> FdbResult<Database> {
76 crate::api::ensure_network_started()?;
77 let path_str =
78 path.map(|path| std::ffi::CString::new(path).expect("path to be convertible to CStr"));
79 let path_ptr = path_str
80 .as_ref()
81 .map(|path| path.as_ptr())
82 .unwrap_or(std::ptr::null());
83 let mut v: *mut fdb_sys::FDBDatabase = std::ptr::null_mut();
84 let err = unsafe { fdb_sys::fdb_create_database(path_ptr, &mut v) };
85 drop(path_str); // path_str own the CString that we are getting the ptr from
86 error::eval(err)?;
87 let ptr =
88 NonNull::new(v).expect("fdb_create_database to not return null if there is no error");
89 // Safe because the database is constructed in this scope and we know it's
90 // a valid pointer.
91 Ok(unsafe { Self::new_from_pointer(ptr) })
92 }
93
94 /// Create a new FDBDatabase from a raw pointer. Users are expected to use the `new` method.
95 ///
96 /// # Safety
97 ///
98 /// The caller must ensure that `ptr` is a valid pointer to an `FDBDatabase` object
99 /// obtained from the FoundationDB C API, and that the pointer is not aliased or used
100 /// after being passed to this function.
101 pub unsafe fn new_from_pointer(ptr: NonNull<fdb_sys::FDBDatabase>) -> Self {
102 Self { inner: ptr }
103 }
104
105 /// Create a database for the given configuration path
106 pub fn from_path(path: &str) -> FdbResult<Database> {
107 Self::new(Some(path))
108 }
109
110 /// Create a database for the default configuration path
111 #[allow(clippy::should_implement_trait)]
112 pub fn default() -> FdbResult<Database> {
113 Self::new(None)
114 }
115}
116
117#[cfg_api_versions(min = 730)]
118impl Database {
119 /// Retrieve a client-side status information in a JSON format.
120 pub fn get_client_status(
121 &self,
122 ) -> impl Future<Output = FdbResult<crate::future::FdbSlice>> + Send + Sync + Unpin + use<>
123 {
124 crate::future::FdbFuture::new(unsafe {
125 fdb_sys::fdb_database_get_client_status(self.inner.as_ptr())
126 })
127 }
128}
129
130impl Database {
131 /// Create a database for the given configuration path
132 ///
133 /// This is a compatibility api. If you only use API version ≥ 610 you should
134 /// use `Database::new`, `Database::from_path` or `Database::default`.
135 pub async fn new_compat(path: Option<&str>) -> FdbResult<Database> {
136 crate::api::ensure_network_started()?;
137 if_cfg_api_versions!(min = 510, max = 600 => {
138 let cluster = crate::cluster::Cluster::new(path).await?;
139 let database = cluster.create_database().await?;
140 Ok(database)
141 } else {
142 Database::new(path)
143 })
144 }
145
146 /// Called to set an option an on `Database`.
147 pub fn set_option(&self, opt: options::DatabaseOption) -> FdbResult<()> {
148 unsafe { opt.apply(self.inner.as_ptr()) }
149 }
150
151 /// Creates a new transaction on the given database.
152 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
153 pub fn create_trx(&self) -> FdbResult<Transaction> {
154 let mut trx: *mut fdb_sys::FDBTransaction = std::ptr::null_mut();
155 let err =
156 unsafe { fdb_sys::fdb_database_create_transaction(self.inner.as_ptr(), &mut trx) };
157 error::eval(err)?;
158 Ok(Transaction::new(NonNull::new(trx).expect(
159 "fdb_database_create_transaction to not return null if there is no error",
160 )))
161 }
162
163 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
164 pub(crate) fn create_retryable_trx(&self) -> FdbResult<RetryableTransaction> {
165 Ok(RetryableTransaction::new(self.create_trx()?))
166 }
167
168 /// `transact` returns a future which retries on error. It tries to resolve a future created by
169 /// caller-provided function `f` inside a retry loop, providing it with a newly created
170 /// transaction. After caller-provided future resolves, the transaction will be committed
171 /// automatically.
172 ///
173 /// # Warning: Hanging on Network/DNS failures
174 ///
175 /// By default, the FoundationDB C API will retry indefinitely if it cannot reach the cluster
176 /// or if DNS resolution fails. This can cause `transact` to hang forever.
177 /// To prevent this, you should set [`options::DatabaseOption::TransactionTimeout`] or
178 /// [`options::DatabaseOption::TransactionRetryLimit`] on the [`Database`] object, or
179 /// [`options::TransactionOption::Timeout`] or [`options::TransactionOption::RetryLimit`] on the transaction
180 /// itself.
181 ///
182 /// Note that `TransactOption` also provides `retry_limit` and `time_out`, but these are
183 /// Rust-side budgets that are only checked *between* retries. If the C API hangs during a call
184 /// like `commit()` or `on_error()`, these budgets will not be reached.
185 ///
186 /// Once [Generic Associated Types](https://github.com/rust-lang/rfcs/blob/master/text/1598-generic_associated_types.md)
187 /// lands in stable rust, the returned future of f won't need to be boxed anymore, also the
188 /// lifetime limitations around f might be lowered.
189 pub async fn transact<F>(&self, mut f: F, options: TransactOption) -> Result<F::Item, F::Error>
190 where
191 F: DatabaseTransact,
192 {
193 let is_idempotent = options.is_idempotent;
194 let time_out = options.time_out.map(|d| Instant::now() + d);
195 let retry_limit = options.retry_limit;
196 let mut tries: u32 = 0;
197 let mut trx = self.create_trx()?;
198 let mut can_retry = move || {
199 tries += 1;
200 retry_limit.map(|limit| tries < limit).unwrap_or(true)
201 && time_out.map(|t| Instant::now() < t).unwrap_or(true)
202 };
203 loop {
204 let r = f.transact(trx).await;
205 f = r.0;
206 trx = r.1;
207 trx = match r.2 {
208 Ok(item) => match trx.commit().await {
209 Ok(_) => break Ok(item),
210 Err(e) => {
211 if (is_idempotent || !e.is_maybe_committed()) && can_retry() {
212 e.on_error().await?
213 } else {
214 break Err(F::Error::from(e.into()));
215 }
216 }
217 },
218 Err(user_err) => match user_err.try_into_fdb_error() {
219 Ok(e) => {
220 if (is_idempotent || !e.is_maybe_committed()) && can_retry() {
221 trx.on_error(e).await?
222 } else {
223 break Err(F::Error::from(e));
224 }
225 }
226 Err(user_err) => break Err(user_err),
227 },
228 };
229 }
230 }
231
232 /// `transact_boxed` is a version of [`Database::transact`] that accepts a closure returning a
233 /// pinned, boxed future.
234 ///
235 /// # Warning: Hanging on Network/DNS failures
236 ///
237 /// By default, the FoundationDB C API will retry indefinitely if it cannot reach the cluster
238 /// or if DNS resolution fails. This can cause `transact_boxed` to hang forever.
239 /// To prevent this, you should set [`options::DatabaseOption::TransactionTimeout`] or
240 /// [`options::DatabaseOption::TransactionRetryLimit`] on the [`Database`] object, or
241 /// [`options::TransactionOption::Timeout`] or [`options::TransactionOption::RetryLimit`] on the transaction
242 /// itself.
243 ///
244 /// Note that `TransactOption` also provides `retry_limit` and `time_out`, but these are
245 /// Rust-side budgets that are only checked *between* retries. If the C API hangs during a call
246 /// like `commit()` or `on_error()`, these budgets will not be reached.
247 pub fn transact_boxed<'trx, F, D, T, E>(
248 &'trx self,
249 data: D,
250 f: F,
251 options: TransactOption,
252 ) -> impl Future<Output = Result<T, E>> + Send + 'trx
253 where
254 for<'a> F: FnMut(
255 &'a Transaction,
256 &'a mut D,
257 ) -> Pin<Box<dyn Future<Output = Result<T, E>> + Send + 'a>>,
258 E: TransactError,
259 F: Send + 'trx,
260 T: Send + 'trx,
261 E: Send + 'trx,
262 D: Send + 'trx,
263 {
264 self.transact(
265 boxed::FnMutBoxed {
266 f,
267 d: data,
268 m: PhantomData,
269 },
270 options,
271 )
272 }
273
274 /// `transact_boxed_local` is a version of [`Database::transact`] that accepts a closure returning a
275 /// pinned, boxed future that is not `Send`.
276 ///
277 /// # Warning: Hanging on Network/DNS failures
278 ///
279 /// By default, the FoundationDB C API will retry indefinitely if it cannot reach the cluster
280 /// or if DNS resolution fails. This can cause `transact_boxed_local` to hang forever.
281 /// To prevent this, you should set [`options::DatabaseOption::TransactionTimeout`] or
282 /// [`options::DatabaseOption::TransactionRetryLimit`] on the [`Database`] object, or
283 /// [`options::TransactionOption::Timeout`] or [`options::TransactionOption::RetryLimit`] on the transaction
284 /// itself.
285 ///
286 /// Note that `TransactOption` also provides `retry_limit` and `time_out`, but these are
287 /// Rust-side budgets that are only checked *between* retries. If the C API hangs during a call
288 /// like `commit()` or `on_error()`, these budgets will not be reached.
289 pub fn transact_boxed_local<'trx, F, D, T, E>(
290 &'trx self,
291 data: D,
292 f: F,
293 options: TransactOption,
294 ) -> impl Future<Output = Result<T, E>> + 'trx
295 where
296 for<'a> F:
297 FnMut(&'a Transaction, &'a mut D) -> Pin<Box<dyn Future<Output = Result<T, E>> + 'a>>,
298 E: TransactError,
299 F: 'trx,
300 T: 'trx,
301 E: 'trx,
302 D: 'trx,
303 {
304 self.transact(
305 boxed_local::FnMutBoxedLocal {
306 f,
307 d: data,
308 m: PhantomData,
309 },
310 options,
311 )
312 }
313
314 /// Runs a transactional function against this Database with retry logic.
315 /// The associated closure will be called until a non-retryable FDBError
316 /// is thrown or commit(), returns success.
317 ///
318 /// Users are **not** expected to keep reference to the `RetryableTransaction`. If a weak or strong
319 /// reference is kept by the user, the binding will throw an error.
320 ///
321 /// # Warning: retry
322 ///
323 /// It might retry indefinitely if the transaction is highly contentious. It is recommended to
324 /// set [`options::TransactionOption::RetryLimit`] or [`options::TransactionOption::Timeout`] on the transaction
325 /// if the task needs to be guaranteed to finish. These options can be safely set on every iteration of the closure.
326 ///
327 /// # Warning: Hanging on Network/DNS failures
328 ///
329 /// By default, the FoundationDB C API will retry indefinitely if it cannot reach the cluster
330 /// or if DNS resolution fails. This can cause `run` to hang forever.
331 /// To prevent this, you should set [`options::DatabaseOption::TransactionTimeout`] or
332 /// [`options::DatabaseOption::TransactionRetryLimit`] on the [`Database`] object, or
333 /// [`options::TransactionOption::Timeout`] or [`options::TransactionOption::RetryLimit`] on the transaction
334 /// itself.
335 ///
336 /// # Warning: Maybe committed transactions
337 ///
338 /// As with other client/server databases, in some failure scenarios a client may be unable to determine
339 /// whether a transaction succeeded. You should make sure your closure is idempotent.
340 ///
341 /// The closure receives a [`MaybeCommitted`] flag indicating whether any earlier attempt
342 /// in this run may have committed. Once true, it stays true for all subsequent attempts.
343 ///
344 /// This one can be used as boolean with
345 /// ```ignore
346 /// db.run(|trx, maybe_committed| async {
347 /// if maybe_committed.into() {
348 /// // Handle the problem if needed
349 /// }
350 /// Ok::<_, FdbBindingError>(())
351 /// }).await;
352 ///```
353 ///
354 /// # Typed closure errors
355 ///
356 /// The closure error type `E` is generic: any type implementing
357 /// [`RetryableError`](crate::RetryableError) works, and the caller gets it
358 /// back typed. Errors are classified through
359 /// [`RetryableError::retry_decision`](crate::RetryableError::retry_decision):
360 /// by default any error that is, or wraps (through `source()`), an
361 /// [`FdbError`] is handed to `on_error`, which judges retryability and
362 /// applies backoff; [`RetryDecision::Retry`](crate::RetryDecision::Retry)
363 /// is routed through `on_error` with code 1020 (not_committed), so backoff
364 /// and [`options::TransactionOption::RetryLimit`] apply uniformly and
365 /// `MaybeCommitted` is left untouched. When retries are exhausted or the
366 /// error is not retryable, the original closure error is returned as-is.
367 ///
368 /// A closure that never names an error type is ambiguous; pin it on the
369 /// tail expression, for example `Ok::<_, FdbBindingError>(value)`.
370 ///
371 /// # Hooks and retry policy
372 ///
373 /// This is [`runner()`](Self::runner) with its defaults: no hooks and the
374 /// native retry policy. Use the builder to observe the run with
375 /// [`RunnerHooks`] or to decide the retries with a
376 /// [`RetryPolicy`](crate::runner::RetryPolicy).
377 #[cfg_attr(
378 feature = "trace",
379 tracing::instrument(level = "debug", skip(self, closure))
380 )]
381 pub async fn run<F, Fut, T, E>(&self, closure: F) -> Result<T, E>
382 where
383 F: Fn(RetryableTransaction, MaybeCommitted) -> Fut,
384 Fut: Future<Output = Result<T, E>>,
385 E: RetryableError,
386 {
387 self.runner().run(closure).await
388 }
389
390 /// A builder for a transactional run, to plug [`RunnerHooks`] and a
391 /// [`RetryPolicy`](crate::runner::RetryPolicy) into it.
392 ///
393 /// ```no_run
394 /// # use foundationdb::*;
395 /// # use foundationdb::runner::MetricsHooks;
396 /// # async fn example(db: &Database) -> Result<(), FdbBindingError> {
397 /// let metrics = TransactionMetrics::new();
398 /// db.runner()
399 /// .hooks(&MetricsHooks::new(&metrics))
400 /// .run(|trx, _| async move {
401 /// trx.set(b"key", b"value");
402 /// Ok::<_, FdbBindingError>(())
403 /// })
404 /// .await
405 /// # }
406 /// ```
407 pub fn runner(&self) -> TransactionRunner<'_> {
408 TransactionRunner::new(self)
409 }
410
411 /// Runs a transactional function against this Database with retry logic and custom hooks.
412 ///
413 /// Sugar for `db.runner().hooks(hooks).run(closure)`. Stack several hooks
414 /// with a tuple: `db.run_with_hooks(&(first, second), closure)`.
415 ///
416 /// See [`RunnerHooks`] for what each hook observes and in which order.
417 #[cfg_attr(
418 feature = "trace",
419 tracing::instrument(level = "debug", skip(self, hooks, closure))
420 )]
421 pub async fn run_with_hooks<'a, F, Fut, T, E, H: RunnerHooks>(
422 &'a self,
423 hooks: &'a H,
424 closure: F,
425 ) -> Result<T, E>
426 where
427 F: Fn(RetryableTransaction, MaybeCommitted) -> Fut,
428 Fut: Future<Output = Result<T, E>>,
429 E: RetryableError,
430 {
431 self.runner().hooks(hooks).run(closure).await
432 }
433
434 /// Runs a transactional function against this Database with retry logic and metrics collection.
435 /// The associated closure will be called until a non-retryable FDBError
436 /// is thrown or commit() returns success.
437 ///
438 /// This method is similar to `run()` but additionally collects and returns metrics about
439 /// the transaction execution, including operation counts, bytes read/written, and retry counts.
440 /// It is [`MetricsHooks`] plugged into [`runner()`](Self::runner): stack them
441 /// on your own hooks with `db.run_with_hooks(&(MetricsHooks::new(&metrics), my_hooks), closure)`
442 /// to get the same report out of a run you observe yourself.
443 ///
444 /// # Arguments
445 /// * `closure` - A function that takes a RetryableTransaction and MaybeCommitted flag and returns a Future
446 ///
447 /// # Returns
448 /// * `Result<(T, Metrics), (FdbBindingError, Metrics)>` - On success, returns the result of the transaction and collected metrics.
449 /// On failure, returns the error and the metrics collected up to the point of failure.
450 ///
451 /// # Warning: retry
452 ///
453 /// It might retry indefinitely if the transaction is highly contentious. It is recommended to
454 /// set [`options::TransactionOption::RetryLimit`] or [`options::TransactionOption::Timeout`] on the transaction
455 /// if the task needs to be guaranteed to finish.
456 ///
457 /// # Warning: Maybe committed transactions
458 ///
459 /// As with other client/server databases, in some failure scenarios a client may be unable to determine
460 /// whether a transaction succeeded. The closure receives a [`MaybeCommitted`] flag indicating
461 /// whether any earlier attempt in this run may have committed. Once true, it stays true for
462 /// all subsequent attempts.
463 #[cfg_attr(
464 feature = "trace",
465 tracing::instrument(level = "debug", skip(self, closure))
466 )]
467 pub async fn instrumented_run<F, Fut, T, E>(
468 &self,
469 closure: F,
470 ) -> Result<(T, MetricsReport), (E, MetricsReport)>
471 where
472 F: Fn(RetryableTransaction, MaybeCommitted) -> Fut,
473 Fut: Future<Output = Result<T, E>>,
474 E: RetryableError,
475 {
476 let metrics = TransactionMetrics::new();
477 let hooks = MetricsHooks::new(&metrics);
478
479 match self.runner().hooks(&hooks).run(closure).await {
480 Ok(value) => Ok((value, metrics.get_metrics_data())),
481 Err(err) => Err((err, metrics.get_metrics_data())),
482 }
483 }
484
485 /// Perform a no-op against FDB to check network thread liveness. This operation will not change the underlying data
486 /// in any way, nor will it perform any I/O against the FDB cluster. However, it will schedule some amount of work
487 /// onto the FDB client and wait for it to complete. The FoundationDB client operates by scheduling onto an event
488 /// queue that is then processed by a single thread (the "network thread"). This method can be used to determine if
489 /// the network thread has entered a state where it is no longer processing requests or if its time to process
490 /// requests has increased. If the network thread is busy, this operation may take some amount of time to complete,
491 /// which is why this operation returns a future.
492 pub async fn perform_no_op(&self) -> FdbResult<()> {
493 let trx = self.create_trx()?;
494
495 // Set the read version of the transaction, then read it back. This requires no I/O, but it does
496 // require the network thread be running. The exact value used for the read version is unimportant.
497 trx.set_read_version(42);
498 trx.get_read_version().await?;
499 Ok(())
500 }
501
502 /// Returns a value where 0 indicates that the client is idle and 1 (or larger) indicates that the client is saturated.
503 /// By default, this value is updated every second.
504 #[cfg_api_versions(min = 710)]
505 pub async fn get_main_thread_busyness(&self) -> FdbResult<f64> {
506 let busyness =
507 unsafe { fdb_sys::fdb_database_get_main_thread_busyness(self.inner.as_ptr()) };
508 Ok(busyness)
509 }
510}
511pub trait DatabaseTransact: Sized {
512 type Item;
513 type Error: TransactError;
514 type Future: Future<Output = (Self, Transaction, Result<Self::Item, Self::Error>)>;
515 fn transact(self, trx: Transaction) -> Self::Future;
516}
517
518#[allow(clippy::needless_lifetimes)]
519#[allow(clippy::type_complexity)]
520mod boxed {
521 use super::*;
522
523 async fn boxed_data_fut<'t, F, T, E, D>(
524 mut f: FnMutBoxed<'t, F, D>,
525 trx: Transaction,
526 ) -> (FnMutBoxed<'t, F, D>, Transaction, Result<T, E>)
527 where
528 F: for<'a> FnMut(
529 &'a Transaction,
530 &'a mut D,
531 ) -> Pin<Box<dyn Future<Output = Result<T, E>> + Send + 'a>>,
532 E: TransactError,
533 {
534 let r = (f.f)(&trx, &mut f.d).await;
535 (f, trx, r)
536 }
537
538 pub struct FnMutBoxed<'t, F, D> {
539 pub f: F,
540 pub d: D,
541 pub m: PhantomData<&'t ()>,
542 }
543 impl<'t, F, T, E, D> DatabaseTransact for FnMutBoxed<'t, F, D>
544 where
545 F: for<'a> FnMut(
546 &'a Transaction,
547 &'a mut D,
548 ) -> Pin<Box<dyn Future<Output = Result<T, E>> + Send + 'a>>,
549 F: 't + Send,
550 T: 't,
551 E: 't,
552 D: 't + Send,
553 E: TransactError,
554 {
555 type Item = T;
556 type Error = E;
557 type Future = Pin<
558 Box<
559 dyn Future<Output = (Self, Transaction, Result<Self::Item, Self::Error>)>
560 + Send
561 + 't,
562 >,
563 >;
564
565 fn transact(self, trx: Transaction) -> Self::Future {
566 boxed_data_fut(self, trx).boxed()
567 }
568 }
569}
570
571#[allow(clippy::needless_lifetimes)]
572#[allow(clippy::type_complexity)]
573mod boxed_local {
574 use super::*;
575
576 async fn boxed_local_data_fut<'t, F, T, E, D>(
577 mut f: FnMutBoxedLocal<'t, F, D>,
578 trx: Transaction,
579 ) -> (FnMutBoxedLocal<'t, F, D>, Transaction, Result<T, E>)
580 where
581 F: for<'a> FnMut(
582 &'a Transaction,
583 &'a mut D,
584 ) -> Pin<Box<dyn Future<Output = Result<T, E>> + 'a>>,
585 E: TransactError,
586 {
587 let r = (f.f)(&trx, &mut f.d).await;
588 (f, trx, r)
589 }
590
591 pub struct FnMutBoxedLocal<'t, F, D> {
592 pub f: F,
593 pub d: D,
594 pub m: PhantomData<&'t ()>,
595 }
596 impl<'t, F, T, E, D> DatabaseTransact for FnMutBoxedLocal<'t, F, D>
597 where
598 F: for<'a> FnMut(
599 &'a Transaction,
600 &'a mut D,
601 ) -> Pin<Box<dyn Future<Output = Result<T, E>> + 'a>>,
602 F: 't,
603 T: 't,
604 E: 't,
605 D: 't,
606 E: TransactError,
607 {
608 type Item = T;
609 type Error = E;
610 type Future = Pin<
611 Box<dyn Future<Output = (Self, Transaction, Result<Self::Item, Self::Error>)> + 't>,
612 >;
613
614 fn transact(self, trx: Transaction) -> Self::Future {
615 boxed_local_data_fut(self, trx).boxed_local()
616 }
617 }
618}
619
620/// A trait that must be implemented to use `Database::transact` this application error types.
621pub trait TransactError: From<FdbError> {
622 fn try_into_fdb_error(self) -> Result<FdbError, Self>;
623}
624impl<T> TransactError for T
625where
626 T: From<FdbError> + TryInto<FdbError, Error = T>,
627{
628 fn try_into_fdb_error(self) -> Result<FdbError, Self> {
629 self.try_into()
630 }
631}
632impl TransactError for FdbError {
633 fn try_into_fdb_error(self) -> Result<FdbError, Self> {
634 Ok(self)
635 }
636}
637
638/// A set of options that controls the behavior of `Database::transact`.
639#[derive(Default, Clone)]
640pub struct TransactOption {
641 pub retry_limit: Option<u32>,
642 pub time_out: Option<Duration>,
643 pub is_idempotent: bool,
644}
645
646impl TransactOption {
647 /// An idempotent TransactOption
648 pub fn idempotent() -> Self {
649 Self {
650 is_idempotent: true,
651 ..TransactOption::default()
652 }
653 }
654}