tablo_core/panel/load.rs
1//! [`Panel::load`]: what a panel reads once for a request, ahead of every handler, for the
2//! policies, queries and conditions that cannot await.
3
4use std::{any::TypeId, future::Future, sync::Arc};
5
6use topcoat::{
7 Result,
8 context::{Cx, try_context},
9};
10
11use super::{Panel, state::current};
12use crate::BoxFuture;
13
14/// A value a panel loads once per request, for what decides without awaiting: a
15/// [`Policy`](crate::Policy), a [`ResourceDef::query_fn`](crate::ResourceDef::query_fn), a
16/// condition on a column or an action. [`Panel::load`] registers it and [`loaded`] reads it.
17///
18/// A policy is asked once per row and once per button, so it reads what the request loaded
19/// instead of querying each time:
20///
21/// ```rust
22/// # use tablo_core::{Ability, Load, Panel, Policy, TenantId, db::db, loaded, tenant_id};
23/// # use topcoat::{Result, context::Cx};
24/// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
25/// # struct Project { #[key] #[auto] id: uuid::Uuid, name: String }
26/// #[derive(Debug, toasty::Model)]
27/// struct Subscription {
28/// #[key]
29/// #[auto]
30/// id: uuid::Uuid,
31/// team: TenantId,
32/// projects: i64,
33/// }
34///
35/// /// How many projects the request's team may hold.
36/// struct Plan {
37/// projects: i64,
38/// }
39///
40/// impl Load for Plan {
41/// async fn load(cx: &Cx) -> Result<Self> {
42/// let Some(team) = tenant_id(cx) else {
43/// return Ok(Self { projects: 0 });
44/// };
45/// let mut db = db(cx)?;
46/// let subscriptions = Subscription::filter(Subscription::fields().team().eq(team))
47/// .exec(&mut db)
48/// .await?;
49/// Ok(Self {
50/// projects: subscriptions.first().map_or(1, |held| held.projects),
51/// })
52/// }
53/// }
54///
55/// fn project_policy() -> impl Policy<Project> {
56/// |cx: &Cx, ability: Ability<'_, Project>| match ability {
57/// Ability::Create => loaded::<Plan>(cx).is_some_and(|plan| plan.projects > 0),
58/// _ => true,
59/// }
60/// }
61///
62/// Panel::new("app").load::<Plan>();
63/// ```
64///
65/// `load` runs after the [auth gate](crate::auth::guard) admitted the request, so it reads the
66/// signed-in user with [`auth::user`](crate::auth::user) and the tenant the request acts for with
67/// [`tenant_id`](crate::tenant_id). On a panel whose authentication is disabled it runs on every
68/// request. It does not run for the pages a signed-out visitor reaches, such as the login page.
69///
70/// It runs on every request the panel answers, the runtime requests of its pages included: keep it
71/// to what the panel's policies read, in one or two statements.
72pub trait Load: Sized + Send + Sync + 'static {
73 /// Reads the value for the request.
74 ///
75 /// # Errors
76 ///
77 /// An `Err` fails the request before any handler runs.
78 fn load(cx: &Cx) -> impl Future<Output = Result<Self>> + Send;
79}
80
81/// The `T` the request's panel [loaded](Panel::load). `None` when the panel does not load `T`,
82/// and where no request loaded it: a signed-out page, a route outside the panel, or a context
83/// built for a job with [`PanelHandle::context`](crate::PanelHandle::context).
84///
85/// A policy reads `None` as a refusal: `loaded::<Plan>(cx).is_some_and(..)`.
86pub fn loaded<T: Load>(cx: &Cx) -> Option<&T> {
87 try_context::<Loaded<T>>(cx).map(|Loaded(value)| &**value)
88}
89
90/// A [`Load`] value as request `Cx` carries it.
91struct Loaded<T>(Arc<T>);
92
93impl<T> Clone for Loaded<T> {
94 fn clone(&self) -> Self {
95 Self(Arc::clone(&self.0))
96 }
97}
98
99/// One [`Load`] of a panel, its type erased: `cx` with the value it loaded.
100#[derive(Clone, Copy)]
101pub(crate) struct LoadFn {
102 loads: TypeId,
103 run: for<'a> fn(&'a Cx) -> BoxFuture<'a, Result<Cx>>,
104}
105
106fn erased<T: Load>(cx: &Cx) -> BoxFuture<'_, Result<Cx>> {
107 Box::pin(async move { Ok(cx.with(Loaded(Arc::new(T::load(cx).await?)))) })
108}
109
110impl Panel {
111 /// Loads the [`Load`] value `T` once for each request the panel admits, ahead of every
112 /// handler, for [`loaded`] to answer. Several values load in the order they are registered,
113 /// so one reads those before it; registering a type twice loads it once.
114 pub fn load<T: Load>(mut self) -> Self {
115 let loads = TypeId::of::<T>();
116 if !self.loads.iter().any(|load| load.loads == loads) {
117 self.loads.push(LoadFn {
118 loads,
119 run: erased::<T>,
120 });
121 }
122 self
123 }
124}
125
126/// `cx` with every value the request's panel loads, in registration order.
127pub(crate) async fn load(cx: Cx) -> Result<Cx> {
128 let Some(panel) = current(&cx).map(Arc::clone) else {
129 return Ok(cx);
130 };
131 let mut cx = cx;
132 for load in &panel.loads {
133 cx = (load.run)(&cx).await?;
134 }
135 Ok(cx)
136}