Skip to main content

tablo_core/
db.rs

1//! The `Db` glue: how Tablo code reaches the pooled Toasty database, and the transaction a panel
2//! write runs its record fns and hooks in.
3
4use std::{
5    ops::{Deref, DerefMut},
6    sync::{Mutex, PoisonError},
7};
8
9use toasty::{
10    Db, Transaction,
11    stmt::{IntoStatement, List},
12};
13use topcoat::context::{Cx, CxId, context};
14
15/// Returns the pooled [`Db`] registered on the router.
16///
17/// Never runs statements on another handle while a transaction holds its connection; drains or
18/// drops streaming list bodies before the next query.
19///
20/// # Errors
21///
22/// A declaration failure when called while a panel write's transaction is open for the same
23/// request, such as from [`Resource::before_commit`](crate::Resource::before_commit) or a record
24/// fn: run the statement through the `ex` the hook received instead.
25#[inline]
26pub fn db(cx: &Cx) -> topcoat::Result<Db> {
27    no_write_open(cx.id(), "db(cx)")?;
28    Ok(context::<Db>(cx).clone())
29}
30
31/// How many rows `query` holds, counted on the pooled [`Db`]: a model's query, such as
32/// `Post::filter(..)`, or a [`Query`](toasty::stmt::Query) such as
33/// [`list_query`](crate::list_query)'s.
34///
35/// Reads 0 where Toasty answers no value: a count over a filter Toasty can tell matches nothing,
36/// such as [`list_query`](crate::list_query) narrowed to one status on a list whose tab shows
37/// another, which `Query::count` fails to read.
38///
39/// A record fn or a hook counts through the `ex` it received, with [`count_in`].
40///
41/// # Errors
42///
43/// As [`db`], and the database failing the count.
44pub async fn count<M: toasty::schema::Model>(
45    cx: &Cx,
46    query: impl IntoStatement<Returning = List<M>>,
47) -> topcoat::Result<u64> {
48    count_in(&mut db(cx)?, query).await
49}
50
51/// How many rows `query` holds, counted through `ex`: inside the transaction a record fn or a
52/// hook received, so the count sees the rows the write has made so far and a limit check holds
53/// against concurrent writes the isolation level orders. Reads 0 where Toasty answers no value, as
54/// [`count`] does.
55///
56/// ```rust,no_run
57/// # use tablo_core::{NoForm, Resource, WriteError, db};
58/// # use topcoat::context::Cx;
59/// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
60/// # struct Project { #[key] #[auto] id: uuid::Uuid, team_id: String }
61/// # struct ProjectResource;
62/// # impl Resource for ProjectResource { type Model = Project; type Form = NoForm<Project>; }
63/// # async fn check(cx: &Cx, team: String, ex: &mut dyn toasty::Executor) -> topcoat::Result<bool> {
64/// let projects = db::count_in(ex, Project::filter(Project::fields().team_id().eq(team))).await?;
65/// Ok(projects < 10)
66/// # }
67/// ```
68///
69/// # Errors
70///
71/// The database failing the count, and a declaration failure for a statement that writes, such as
72/// an insert, which has no rows to count.
73pub async fn count_in<M: toasty::schema::Model>(
74    ex: &mut dyn toasty::Executor,
75    query: impl IntoStatement<Returning = List<M>>,
76) -> topcoat::Result<u64> {
77    let Some(query) = query.into_statement().into_query() else {
78        return Err(crate::error::declaration(
79            "db::count counts the rows a query reads, not a statement that writes",
80        ));
81    };
82    crate::toasty_compat::count(query, ex)
83        .await
84        .map_err(crate::error::unavailable)
85}
86
87/// The requests with a panel write's transaction open now, each with the work to run once it
88/// commits. A request opens one at a time, and few run at once, so a list is enough.
89static OPEN: Mutex<Vec<Open>> = Mutex::new(Vec::new());
90
91/// One request's open transaction.
92struct Open {
93    request: CxId,
94    after_commit: Vec<Box<dyn FnOnce() + Send>>,
95}
96
97fn open() -> std::sync::MutexGuard<'static, Vec<Open>> {
98    OPEN.lock().unwrap_or_else(PoisonError::into_inner)
99}
100
101/// Refuses when `request` has a panel write's transaction open: a second connection taken now
102/// writes outside it, and on a pool of one waits forever for the connection the transaction
103/// holds.
104pub(crate) fn no_write_open(request: CxId, what: &str) -> topcoat::Result<()> {
105    if open().iter().any(|open| open.request == request) {
106        return Err(crate::error::declaration(format!(
107            "{what} opens a second connection while this request's write transaction is open: \
108             its statements would run outside the transaction, and on a pool of one it waits \
109             forever. Run them through the `ex` the record fn or hook received."
110        )));
111    }
112    Ok(())
113}
114
115/// Queues `work` to run once `request`'s open panel write commits, and drops it if the write
116/// rolls back. Hands `work` back when no panel write is open for `request`.
117pub(crate) fn after_write_commits<F: FnOnce() + Send + 'static>(
118    request: CxId,
119    work: F,
120) -> Result<(), F> {
121    match open().iter_mut().find(|open| open.request == request) {
122        Some(open) => {
123            open.after_commit.push(Box::new(work));
124            Ok(())
125        }
126        None => Err(work),
127    }
128}
129
130/// The transaction a panel write runs in. While it is open, [`db`] refuses the same request,
131/// and [`Notifications::send_in`](crate::Notifications::send_in)
132/// wakes bells only once it commits.
133pub(crate) struct WriteTx<'a> {
134    /// `None` only inside [`Self::commit`], once the transaction is consumed.
135    tx: Option<Transaction<'a>>,
136    request: CxId,
137}
138
139impl<'a> WriteTx<'a> {
140    /// Opens a transaction on `db` for `cx`'s request.
141    pub(crate) async fn begin(cx: &Cx, db: &'a mut Db) -> toasty::Result<Self> {
142        let tx = db.transaction().await?;
143        let request = cx.id();
144        let mut open = open();
145        debug_assert!(
146            open.iter().all(|open| open.request != request),
147            "a request opens one write transaction at a time"
148        );
149        open.push(Open {
150            request,
151            after_commit: Vec::new(),
152        });
153        Ok(Self {
154            tx: Some(tx),
155            request,
156        })
157    }
158
159    /// Commits, then runs what [`after_write_commits`] queued.
160    pub(crate) async fn commit(mut self) -> toasty::Result<()> {
161        let committed = match self.tx.take() {
162            Some(tx) => tx.commit().await,
163            None => Ok(()),
164        };
165        let after_commit = self.close();
166        if committed.is_ok() {
167            for work in after_commit {
168                work();
169            }
170        }
171        committed
172    }
173
174    /// Unregisters this transaction, answering the work queued for its commit.
175    fn close(&mut self) -> Vec<Box<dyn FnOnce() + Send>> {
176        let mut open = open();
177        match open.iter().position(|open| open.request == self.request) {
178            Some(index) => open.swap_remove(index).after_commit,
179            None => Vec::new(),
180        }
181    }
182}
183
184impl<'a> Deref for WriteTx<'a> {
185    type Target = Transaction<'a>;
186
187    fn deref(&self) -> &Self::Target {
188        self.tx.as_ref().expect("open until commit")
189    }
190}
191
192impl DerefMut for WriteTx<'_> {
193    fn deref_mut(&mut self) -> &mut Self::Target {
194        self.tx.as_mut().expect("open until commit")
195    }
196}
197
198impl Drop for WriteTx<'_> {
199    /// A transaction dropped uncommitted rolls back, and what waited for its commit with it.
200    fn drop(&mut self) {
201        self.close();
202    }
203}
204
205#[cfg(test)]
206mod tests;