Skip to main content

fastauth_sqlx/
tx.rs

1//! Sharing an app's sqlx transaction with fastauth server API calls.
2//! See `docs/04-sessions.md`.
3
4use std::sync::Arc;
5
6use fastauth_core::Api;
7use fastauth_core::adapter::{DbError, DbResult};
8use fastauth_core::events::DeferredEvents;
9use sqlx_core::transaction::TransactionManager;
10use tokio::sync::{Mutex, MutexGuard};
11
12use crate::{Dialect, SharedConn, Sqlx};
13
14/// An app's sqlx transaction that fastauth server API calls can join with [`InTx::in_tx`].
15/// The rows those calls write commit or roll back with the app's own, and their events
16/// fire after [`commit`](Self::commit), never on rollback.
17///
18/// ```no_run
19/// # async fn run(auth: fastauth_core::Auth<fastauth_sqlx::Sqlx<fastauth_sqlx::Sqlite>>, pool: fastauth_sqlx::SqlitePool) -> Result<(), Box<dyn std::error::Error>> {
20/// use fastauth_core::routes::CreateUserInput;
21/// use fastauth_sqlx::{InTx, SharedTx};
22///
23/// let tx = SharedTx::new(pool.begin().await?);
24/// let user = auth
25///     .api()
26///     .in_tx(&tx)
27///     .create_user(CreateUserInput {
28///         email: "lasse@acme.dk".into(),
29///         name: "Lasse".into(),
30///         ..Default::default()
31///     })
32///     .await?;
33/// fastauth_sqlx::sqlx::query("insert into team_member (team_id, user_id) values (?, ?)")
34///     .bind(1)
35///     .bind(user.id.as_str())
36///     .execute(&mut **tx.lock().await)
37///     .await?;
38/// tx.commit().await?; // UserCreated fires here
39/// # Ok(())
40/// # }
41/// ```
42pub struct SharedTx<DB: Dialect> {
43    tx: SharedConn<DB>,
44    events: DeferredEvents,
45}
46
47impl<DB: Dialect> std::fmt::Debug for SharedTx<DB> {
48    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49        f.debug_struct("SharedTx")
50            .field("events", &self.events)
51            .finish_non_exhaustive()
52    }
53}
54
55impl<DB: Dialect> SharedTx<DB> {
56    pub fn new(tx: sqlx::Transaction<'static, DB>) -> Self {
57        Self {
58            tx: Arc::new(Mutex::new(tx)),
59            events: DeferredEvents::default(),
60        }
61    }
62
63    /// The transaction, for the app's own queries: `.execute(&mut **tx.lock().await)`.
64    /// Don't hold the guard across a fastauth call; the call waits for it.
65    pub async fn lock(&self) -> MutexGuard<'_, sqlx::Transaction<'static, DB>> {
66        self.tx.lock().await
67    }
68
69    /// Commits, then fires the events of the fastauth calls made in it.
70    pub async fn commit(self) -> DbResult<()> {
71        let tx = unwrap(self.tx)?;
72        if DB::TransactionManager::get_transaction_depth(&*tx) > 1 {
73            return Err(DbError::Other(
74                "a fastauth savepoint is still open in the transaction".into(),
75            ));
76        }
77        tx.commit().await.map_err(DbError::other)?;
78        self.events.fire().await;
79        Ok(())
80    }
81
82    /// Rolls back and discards the events. Dropping it does the same.
83    pub async fn rollback(self) -> DbResult<()> {
84        unwrap(self.tx)?.rollback().await.map_err(DbError::other)
85    }
86}
87
88fn unwrap<DB: Dialect>(tx: SharedConn<DB>) -> DbResult<sqlx::Transaction<'static, DB>> {
89    Arc::try_unwrap(tx)
90        .map(Mutex::into_inner)
91        .map_err(|_| DbError::Other("a fastauth call still holds the transaction".into()))
92}
93
94/// `auth.api().in_tx(&tx)`: server API calls on an app's [`SharedTx`].
95pub trait InTx<'a, DB: Dialect> {
96    /// Runs every call of this `Api` on `tx`, each inside its own savepoint: a call that
97    /// fails rolls back its own writes and leaves `tx` as it was. Events wait for
98    /// [`SharedTx::commit`].
99    fn in_tx(self, tx: &'a SharedTx<DB>) -> Self;
100}
101
102impl<'a, DB: Dialect> InTx<'a, DB> for Api<'a, Sqlx<DB>> {
103    fn in_tx(self, tx: &'a SharedTx<DB>) -> Self {
104        let db = self.adapter().bind(tx.tx.clone());
105        self.within(db, &tx.events)
106    }
107}