Skip to main content

tablo_core/schema/
relationship.rs

1//! Relationship option loading — bounded, memoized, policy-checked.
2//!
3//! Every relationship choice field over one source shares a single bounded load per `(request,
4//! tenant)` and fails closed instead of leaking labels. A choice offers the rows the source's
5//! list shows: its scoped query's, when its policy allows listing them.
6
7use toasty::stmt::{Expr, List, OrderByExpr, Query};
8use topcoat::{Result, context::Cx};
9
10use crate::BoxFuture;
11
12/// Describes the source a relationship option loader reads.
13///
14/// Every [`Resource`](crate::Resource) is one, answering from its def as the context's panel
15/// mounted it.
16///
17/// Every relationship choice over one source shares a single load per request and tenant,
18/// bounded to [`MAX_RELATIONSHIP_OPTIONS`] rows of its [`scoped_query`](Self::scoped_query). A
19/// load the source refuses fails closed: the choice offers nothing rather than leak a label.
20pub trait OptionSource: Sized + Send + Sync + 'static {
21    /// The model whose rows become options.
22    type Model: toasty::schema::Model + toasty::stmt::IntoExpr<Self::Model> + Send + Sync + 'static;
23
24    /// States the tenant-scoped seed query every option load starts from and reports an unscopable
25    /// source as misdeclared.
26    fn scoped_query(cx: &Cx) -> Result<Query<List<Self::Model>>>;
27
28    /// Whether the current user may list the source's rows; refusing fails every load closed.
29    /// Defaults to refusing. The rows the user may not see belong out of
30    /// [`scoped_query`](Self::scoped_query).
31    fn lists(_cx: &Cx) -> bool {
32        false
33    }
34
35    /// Declares whether the source's rows are tenant-owned and fails a tenantless request closed.
36    ///
37    /// A [`Resource`](crate::Resource) answers from its def's
38    /// [`tenancy`](crate::ResourceDef::tenancy). An implementor that is not one declares no def and
39    /// no tenant lens the framework could read, so it states the boolean and scopes
40    /// [`scoped_query`](Self::scoped_query) itself.
41    fn requires_tenant(_cx: &Cx) -> bool {
42        false
43    }
44
45    /// States the related source's search predicate for `term`, or `None` when it declares no
46    /// searchable column.
47    fn search_expr(_cx: &Cx, _term: &str) -> Option<Expr<bool>> {
48        None
49    }
50
51    /// States the related source's declared default ordering.
52    fn order_by(_cx: &Cx) -> Option<OrderByExpr> {
53        None
54    }
55
56    /// Labels `record` wherever a relationship choice offers it or a
57    /// [`RelationColumn::of`](crate::RelationColumn::of) shows it.
58    ///
59    /// A [`Resource`](crate::Resource) answers with its def's
60    /// [`record_title`](crate::ResourceDef::record_title), else its label and the record's key.
61    /// The record is loaded without its relations.
62    fn label(cx: &Cx, record: &Self::Model) -> String;
63
64    /// Whether the context's panel can load from the source: a resource only when the panel
65    /// mounts it.
66    #[doc(hidden)]
67    fn available(_cx: &Cx) -> bool {
68        true
69    }
70
71    /// The root fields of the source's records the request may not view: for a resource, the
72    /// ones the panel's [`field_access`](crate::ResourceDef::field_access) hides from the request.
73    #[doc(hidden)]
74    fn hidden_fields(_cx: &Cx) -> Vec<String> {
75        Vec::new()
76    }
77
78    /// Whether the source has a create page a choice could open: only a resource does.
79    #[doc(hidden)]
80    fn creates() -> bool {
81        false
82    }
83
84    /// The source's create page, when the context's panel mounts it with one and lets the user
85    /// create.
86    #[doc(hidden)]
87    fn create_page(_cx: &Cx) -> Option<String> {
88        None
89    }
90}
91
92/// Distinguishes a policy denial and an over-cap table from a retryable load failure so validation
93/// answers correctly.
94#[derive(Debug, Clone, PartialEq, Eq)]
95pub(crate) enum OptionLoadError {
96    Denied,
97    LoadFailed,
98    Overflow,
99    Misdeclared,
100}
101
102pub(crate) type RelationshipLoader = std::sync::Arc<
103    dyn Fn(&Cx) -> BoxFuture<'static, Result<Vec<(String, String)>, OptionLoadError>> + Send + Sync,
104>;
105
106pub(crate) type RelationshipSearchLoader = std::sync::Arc<
107    dyn Fn(
108            &Cx,
109            String,
110            Option<Expr<bool>>,
111        ) -> BoxFuture<'static, Result<Vec<(String, String)>, OptionLoadError>>
112        + Send
113        + Sync,
114>;
115
116/// Reads the option of one key: its value and label, or `None` when the source's scoped query
117/// holds no row it names.
118pub(crate) type RelationshipNamer = std::sync::Arc<
119    dyn Fn(&Cx, String) -> BoxFuture<'static, Result<Option<(String, String)>, OptionLoadError>>
120        + Send
121        + Sync,
122>;
123
124pub(crate) type RelationshipChecker = std::sync::Arc<
125    dyn for<'a> Fn(
126            &'a Cx,
127            String,
128            Option<Expr<bool>>,
129            &'a mut dyn toasty::Executor,
130        ) -> BoxFuture<'a, Result<bool, OptionLoadError>>
131        + Send
132        + Sync,
133>;
134
135/// Refuses the option load closed when the source refuses the list or a tenant-owned source gets
136/// a tenantless request.
137pub(crate) fn ensure_option_access<R>(cx: &Cx) -> Result<(), OptionLoadError>
138where
139    R: OptionSource,
140{
141    if !R::lists(cx) {
142        return Err(OptionLoadError::Denied);
143    }
144    if R::requires_tenant(cx) && crate::tenancy::tenant_id(cx).is_none() {
145        return Err(OptionLoadError::Denied);
146    }
147    Ok(())
148}
149
150/// Starts every option loader from the source's tenant-scoped seed query and reports an unscopable
151/// source as misdeclared.
152fn option_query<R>(cx: &Cx) -> Result<Query<List<R::Model>>, OptionLoadError>
153where
154    R: OptionSource,
155{
156    R::scoped_query(cx).map_err(|error| {
157        tracing::error!(
158            resource = std::any::type_name::<R>(),
159            error = %error,
160            "relationship option load cannot scope the related resource"
161        );
162        OptionLoadError::Misdeclared
163    })
164}
165
166/// Caps the options a relationship choice field loads instead of scanning a large table per select.
167pub const MAX_RELATIONSHIP_OPTIONS: usize = 200;
168
169/// Loads option records for one related resource, memoized per request, and checks the cap.
170#[topcoat::context::memoize(as_ref)]
171pub(crate) async fn related_records<R>(
172    cx: &Cx,
173    _tenant: Option<crate::TenantId>,
174) -> Result<Vec<R::Model>, OptionLoadError>
175where
176    R: OptionSource,
177{
178    ensure_option_access::<R>(cx)?;
179    let mut query = option_query::<R>(cx)?;
180    if let Some(ord) = R::order_by(cx) {
181        query = query.order_by(ord);
182    }
183    bounded_options::<R>(
184        cx,
185        query,
186        "relationship option load failed",
187        "relationship option table overflows the cap",
188    )
189    .await
190}
191
192/// Fetches one row past the cap and refuses a set over the cap with `Overflow`.
193async fn bounded_options<R>(
194    cx: &Cx,
195    query: Query<List<R::Model>>,
196    failed: &str,
197    overflow: &str,
198) -> Result<Vec<R::Model>, OptionLoadError>
199where
200    R: OptionSource,
201{
202    let mut db = crate::db::db(cx).map_err(|_| OptionLoadError::Misdeclared)?;
203    let records = query
204        .limit(MAX_RELATIONSHIP_OPTIONS + 1)
205        .exec(&mut db)
206        .await
207        .map_err(|e| {
208            tracing::warn!(
209                resource = std::any::type_name::<R>(),
210                error = %e,
211                "{failed}"
212            );
213            OptionLoadError::LoadFailed
214        })?;
215    if records.len() > MAX_RELATIONSHIP_OPTIONS {
216        tracing::warn!(
217            resource = std::any::type_name::<R>(),
218            max = MAX_RELATIONSHIP_OPTIONS,
219            "{overflow}"
220        );
221        return Err(OptionLoadError::Overflow);
222    }
223    Ok(records)
224}
225
226/// Longest accepted search term, in chars; a relationship's option search and a table's `?q=`
227/// search share it.
228pub(crate) const MAX_QUERY_TERM: usize = 128;
229
230/// Clamps a search term to [`MAX_QUERY_TERM`] chars, so a multibyte term truncates on a char
231/// boundary.
232pub(crate) fn clamp_query_term(term: &str) -> String {
233    term.trim().chars().take(MAX_QUERY_TERM).collect()
234}
235
236/// Searches the related table's declared searchable columns, among the rows `scope` selects, in
237/// one bounded round-trip and fails past the cap with `Overflow`.
238pub(crate) async fn related_records_search<R>(
239    cx: &Cx,
240    q: String,
241    scope: Option<Expr<bool>>,
242) -> Result<Vec<R::Model>, OptionLoadError>
243where
244    R: OptionSource,
245{
246    ensure_option_access::<R>(cx)?;
247    let term = clamp_query_term(&q);
248    let mut query = option_query::<R>(cx)?;
249    if let Some(scope) = scope {
250        query = query.filter(scope);
251    }
252    if !term.is_empty()
253        && let Some(expr) = R::search_expr(cx, &term)
254    {
255        query = query.filter(crate::toasty_compat::case_insensitive_search(
256            &crate::db::db(cx).map_err(|_| OptionLoadError::Misdeclared)?,
257            expr,
258        ));
259    }
260    if let Some(ord) = R::order_by(cx) {
261        query = query.order_by(ord);
262    }
263    bounded_options::<R>(
264        cx,
265        query,
266        "relationship option search failed",
267        "relationship option search overflows the cap",
268    )
269    .await
270}
271
272/// The row of the source's scoped query that `key` names, if any.
273pub(crate) async fn related_record<R>(
274    cx: &Cx,
275    key: &str,
276) -> Result<Option<R::Model>, OptionLoadError>
277where
278    R: OptionSource,
279{
280    ensure_option_access::<R>(cx)?;
281    let Some(expr) = crate::toasty_compat::pk::pk_eq_expr::<R::Model>(key.trim()) else {
282        return Ok(None);
283    };
284    option_query::<R>(cx)?
285        .filter(expr)
286        .first()
287        .exec(&mut crate::db::db(cx).map_err(|_| OptionLoadError::Misdeclared)?)
288        .await
289        .map_err(|e| {
290            tracing::warn!(
291                resource = std::any::type_name::<R>(),
292                error = %e,
293                "relationship option read failed"
294            );
295            OptionLoadError::LoadFailed
296        })
297}
298
299/// Whether one submitted key names a row of the source's scoped query among the rows `scope`
300/// selects, read through the given executor.
301pub(crate) async fn related_record_check<R>(
302    cx: &Cx,
303    value: String,
304    scope: Option<Expr<bool>>,
305    ex: &mut dyn toasty::Executor,
306) -> Result<bool, OptionLoadError>
307where
308    R: OptionSource,
309{
310    ensure_option_access::<R>(cx)?;
311    let trimmed = value.trim();
312    let Some(expr) = crate::toasty_compat::pk::pk_eq_expr::<R::Model>(trimmed) else {
313        return Ok(false);
314    };
315    let mut query = option_query::<R>(cx)?.filter(expr);
316    if let Some(scope) = scope {
317        query = query.filter(scope);
318    }
319    let row = query.first().exec(ex).await.map_err(|e| {
320        tracing::warn!(
321            resource = std::any::type_name::<R>(),
322            error = %e,
323            "relationship option check failed"
324        );
325        OptionLoadError::LoadFailed
326    })?;
327    Ok(row.is_some())
328}
329
330/// The keys among `keys` naming a row `R`'s scoped query holds, read in one query: what a
331/// relationship filter admits past the cap. Memoized per request, so the list and its filter menu
332/// ask once.
333#[topcoat::context::memoize(as_ref)]
334pub(crate) async fn held_keys<R>(
335    cx: &Cx,
336    _tenant: Option<crate::TenantId>,
337    keys: &[String],
338) -> Result<std::collections::HashSet<String>, OptionLoadError>
339where
340    R: OptionSource,
341{
342    ensure_option_access::<R>(cx)?;
343    let Some(any) = keys
344        .iter()
345        .filter_map(|key| crate::toasty_compat::pk::pk_eq_expr::<R::Model>(key))
346        .reduce(|any, one| any.or(one))
347    else {
348        return Ok(std::collections::HashSet::new());
349    };
350    let rows = option_query::<R>(cx)?
351        .filter(any)
352        .exec(&mut crate::db::db(cx).map_err(|_| OptionLoadError::Misdeclared)?)
353        .await
354        .map_err(|e| {
355            tracing::warn!(
356                resource = std::any::type_name::<R>(),
357                error = %e,
358                "relationship filter check failed"
359            );
360            OptionLoadError::LoadFailed
361        })?;
362    Ok(rows.iter().map(crate::toasty_compat::pk::pk_text).collect())
363}
364
365#[cfg(test)]
366mod tests;