tablo_core/panel/build/handle.rs
1//! [`PanelHandle`]: a mounted panel kept for a job, a test or a public page.
2
3use std::sync::Arc;
4
5use toasty::Db;
6use topcoat::{
7 Result,
8 context::{BaseUrl, Cx},
9 view::{BoxView, View, ViewExt},
10};
11
12use super::{build_catalog, serves_tenants, unregistered_models, validation_cx};
13use crate::{
14 MountError,
15 bus::NotificationBus,
16 i18n::{Catalog, CatalogSource},
17 notification::Notifications,
18 panel::{
19 Panel,
20 register::Registry,
21 state::{PanelState, current, enter},
22 },
23 resource::Mounts,
24 toasty_compat::model::AppSchema,
25};
26
27/// A panel's mounted resources and its database, which a background job or a test keeps to build
28/// a context per run without declaring the panel again. Mounting a panel on a router with
29/// [`panel`](super::RouterBuilderPanelExt::panel) returns it, and [`Panel::handle`] gives one for
30/// a panel no router mounts. Cloning it is cheap.
31///
32/// ```rust,no_run
33/// # use tablo_core::{NoForm, Panel, Resource, RouterBuilderPanelExt, Tenant, scoped_query};
34/// # use topcoat::router::{Router, RouterBuilderDiscoverExt};
35/// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
36/// # struct Post { #[key] #[auto] id: uuid::Uuid, title: String }
37/// # struct PostResource;
38/// # impl Resource for PostResource { type Model = Post; type Form = NoForm<Post>; }
39/// # async fn run(db: toasty::Db, tenant: tablo_core::TenantId) -> topcoat::Result<()> {
40/// let mut builder = Router::builder().discover().with(db);
41/// let admin = builder.panel(Panel::new("admin").resource::<PostResource>())?;
42/// let router = builder.build();
43///
44/// // In the job, once per run:
45/// let cx = admin.context().with(Tenant(tenant));
46/// let posts = scoped_query::<PostResource>(&cx)?;
47/// # let _ = (router, posts);
48/// # Ok(())
49/// # }
50/// ```
51#[derive(Clone)]
52pub struct PanelHandle {
53 pub(super) db: Db,
54 pub(super) mounts: Arc<Mounts>,
55 /// The panel's messages, which [`context`](Self::context) renders its words from.
56 pub(super) catalog: Arc<Catalog>,
57 /// The mounted panel, for a handle a router gives; `None` for [`Panel::handle`]'s.
58 pub(super) panel: Option<Arc<PanelState>>,
59 pub(super) id: crate::PanelId,
60 pub(super) prefix: String,
61 /// The router's bus, or one no bell listens on for [`Panel::handle`]'s.
62 pub(super) bus: NotificationBus,
63 /// The router's base URL when it declared one before mounting the panel.
64 pub(super) base_url: Option<BaseUrl>,
65}
66
67impl PanelHandle {
68 /// A context outside any request in which the panel's resources answer as the panel mounted
69 /// them: what a job or a test passes to [`scoped_query`](crate::scoped_query),
70 /// [`can`](crate::can), [`write_create`](crate::write_create) and the other entry points that
71 /// answer from a mounted def. It holds the database and the resources, and no request,
72 /// session or tenant. Add a tenant with `cx.with(Tenant(id))`. It carries no signed-in user,
73 /// so a policy that reads one answers as for a signed-out request.
74 ///
75 /// Its words, [`t!`](crate::t) and a [`Text`](crate::Text)'s
76 /// [`localize`](crate::Text::localize), read the panel's catalogs in its default locale. A
77 /// job writing to someone in another language adds theirs, `cx.with(locale)`, which reads the
78 /// panel's best match for it.
79 ///
80 /// For a handle a router gives, the [`url`](crate::url) helpers answer with the panel's URLs,
81 /// and the context carries the router's [`BaseUrl`] when the router declared one before
82 /// mounting the panel, so a job mails an absolute link:
83 ///
84 /// ```rust,no_run
85 /// # use tablo_core::{Page, PanelHandle, url};
86 /// # struct BillingPage;
87 /// # impl Page for BillingPage {}
88 /// # fn link(app: &PanelHandle) -> Option<String> {
89 /// let cx = app.context();
90 /// // "/app/settings/billing", then "https://example.com/app/settings/billing"
91 /// let billing = url::page::<BillingPage>(&cx)?;
92 /// Some(topcoat::context::try_base_url(&cx)?.join(&billing))
93 /// # }
94 /// ```
95 ///
96 /// The context is one unit of work, as a request is: loads it memoizes stay cached for its
97 /// lifetime, so a job builds one per run. A context built with no panel at all knows no
98 /// resource: every entry point that reads a mounted def answers as for a resource the panel
99 /// does not mount.
100 pub fn context(&self) -> Cx {
101 let mut cx = validation_cx(&self.db, &self.mounts).with_many((
102 HeldCatalog(Arc::clone(&self.catalog)),
103 CatalogSource(held_catalog),
104 ));
105 if let Some(panel) = &self.panel {
106 cx = cx.with(HandlePanel(Arc::clone(panel)));
107 }
108 if let Some(base_url) = &self.base_url {
109 cx = cx.with(base_url.clone());
110 }
111 cx
112 }
113
114 /// `cx` answering as this panel, for a request outside every panel's prefix, such as a
115 /// public page: [`scoped_query`](crate::scoped_query), [`can`](crate::can) and the other
116 /// entry points that answer from a mounted def answer as this panel mounted its resources,
117 /// and, for a handle a router gives, the [`url`](crate::url) helpers answer with its URLs.
118 /// A request outside every prefix answers as no panel until it enters one, however many
119 /// panels the router mounts. It runs no auth gate and signs no one in, so a public page's
120 /// context knows no user. Enter only outside every prefix: under a panel's prefix, a handle
121 /// [`Panel::handle`] gives leaves the request answering as its own panel.
122 ///
123 /// ```rust,no_run
124 /// # use tablo_core::{NoForm, PanelHandle, Resource, scoped_query};
125 /// # use topcoat::{Result, context::Cx};
126 /// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
127 /// # struct Post { #[key] #[auto] id: uuid::Uuid, title: String }
128 /// # struct PostResource;
129 /// # impl Resource for PostResource { type Model = Post; type Form = NoForm<Post>; }
130 /// async fn public_posts(cx: &Cx, admin: &PanelHandle) -> Result<Vec<Post>> {
131 /// let cx = admin.enter(cx);
132 /// Ok(scoped_query::<PostResource>(&cx)?
133 /// .exec(&mut tablo_core::db::db(&cx)?)
134 /// .await?)
135 /// }
136 /// ```
137 pub fn enter(&self, cx: &Cx) -> Cx {
138 match &self.panel {
139 Some(panel) => enter(cx, panel),
140 None => cx.with(EnteredPanel(Arc::clone(&self.mounts))),
141 }
142 }
143
144 /// Which panel this is: the id
145 /// [`PanelUser::can_access_panel`](crate::PanelUser::can_access_panel) receives for it, to
146 /// compare with rather than spelling its prefix again.
147 pub fn id(&self) -> &crate::PanelId {
148 &self.id
149 }
150
151 /// The panel's prefix, e.g. `/admin`, for a public page's link to it; `None` for
152 /// [`Panel::handle`]'s, which no router mounts.
153 pub fn url(&self) -> Option<String> {
154 self.panel.as_ref().map(|panel| panel.realm.prefix.clone())
155 }
156
157 /// Sends stored notifications to this panel's users from outside a request, such as from a
158 /// job, for no tenant until [`Notifications::tenant`] names one. The bells they have open
159 /// update when the handle is a router's.
160 ///
161 /// ```rust,no_run
162 /// # use tablo_core::{Notification, PanelHandle};
163 /// # async fn nightly(admin: &PanelHandle, owner_id: &str, tenant: tablo_core::TenantId) -> topcoat::Result<()> {
164 /// admin
165 /// .notifications()
166 /// .tenant(tenant)
167 /// .send(owner_id, Notification::info("The nightly import finished"))
168 /// .await?;
169 /// # Ok(())
170 /// # }
171 /// ```
172 pub fn notifications(&self) -> Notifications {
173 Notifications::new(self.db.clone(), self.bus.clone(), self.prefix.clone(), None)
174 }
175
176 /// Renders a complete HTML document around a page outside every prefix with this panel's
177 /// shell settings: its stylesheet, font, scripts, favicon and dark-mode default. A handle
178 /// [`Panel::handle`] gives renders the document without them.
179 ///
180 /// ```rust,no_run
181 /// # use tablo_core::PanelHandle;
182 /// # use topcoat::{Result, context::{Cx, context}, router::{Slot, layout}, view::{View, view}};
183 /// /// The handle mounting the admin panel returned, kept on the router.
184 /// struct Admin(PanelHandle);
185 ///
186 /// #[layout("/blog")]
187 /// async fn blog_layout(cx: &Cx, slot: Slot<'_>) -> Result<impl View> {
188 /// let Admin(admin) = context::<Admin>(cx);
189 /// admin.document(cx, "Blog", view! { <main>(slot)</main> }).await
190 /// }
191 /// ```
192 pub async fn document<'a>(
193 &'a self,
194 cx: &'a Cx,
195 title: impl Into<String>,
196 body: impl View + 'a,
197 ) -> Result<BoxView<'a>> {
198 Panel::render_document(cx, self.panel.as_deref(), title.into(), body.boxed()).await
199 }
200}
201
202/// The resources [`PanelHandle::enter`] put in scope for a request outside every panel.
203pub(super) struct EnteredPanel(Arc<Mounts>);
204
205/// The resources the request answers from: its own panel's, or the ones
206/// [`PanelHandle::enter`] put in scope.
207pub(super) fn request_mounts(cx: &Cx) -> Option<&Mounts> {
208 match current(cx) {
209 Some(panel) => Some(&*panel.mounts),
210 None => {
211 topcoat::context::try_context::<EnteredPanel>(cx).map(|EnteredPanel(mounts)| &**mounts)
212 }
213 }
214}
215
216/// The mounted panel whose URLs the [`url`](crate::url) helpers answer in a
217/// [`PanelHandle::context`].
218pub(crate) struct HandlePanel(pub(crate) Arc<PanelState>);
219
220/// The catalog [`PanelHandle::context`] renders words from, outside every request.
221struct HeldCatalog(Arc<Catalog>);
222
223/// The [`CatalogSource`] of a handle's context.
224fn held_catalog(cx: &Cx) -> Option<&Catalog> {
225 topcoat::context::try_context::<HeldCatalog>(cx).map(|HeldCatalog(catalog)| &**catalog)
226}
227
228impl Panel {
229 /// The panel's resources declared and checked against `db` without a router: what a test, or
230 /// a job that runs with no router, builds its contexts from with [`PanelHandle::context`].
231 /// A job that runs beside a router keeps the handle that mounting the panel with
232 /// [`panel`](super::RouterBuilderPanelExt::panel) returned instead.
233 ///
234 /// # Errors
235 ///
236 /// The declaration errors [`panel`](super::RouterBuilderPanelExt::panel) refuses the resources
237 /// with.
238 pub fn handle(self, db: &Db) -> Result<PanelHandle> {
239 let Panel {
240 prefix,
241 registrations,
242 configuration_errors,
243 uploads,
244 auth,
245 limits,
246 locales,
247 translations,
248 default_translations,
249 required_models,
250 commit_hooks,
251 ..
252 } = self;
253 let mut registry = Registry::new(prefix.clone(), Some(AppSchema::of_db(db)));
254 let (mounts, mut errors) = registry.register_all(registrations, configuration_errors);
255 errors.extend(unregistered_models(db, &required_models));
256 errors.extend(super::super::commit_hook::missing_commit_hooks(
257 ®istry.resources,
258 &commit_hooks,
259 ));
260 let serves_tenants = serves_tenants(&auth, &mounts);
261 registry.check_all(
262 db,
263 &mounts,
264 serves_tenants,
265 uploads.is_some(),
266 &limits,
267 &mut errors,
268 );
269 let catalog = build_catalog(&locales, &default_translations, &translations, &mut errors);
270 if !errors.is_empty() {
271 return Err(MountError::new(&prefix, errors).into());
272 }
273 Ok(PanelHandle {
274 db: db.clone(),
275 mounts,
276 panel: None,
277 catalog: Arc::new(catalog.expect("a catalog that failed to build fails the handle")),
278 id: crate::PanelId::new(&prefix),
279 prefix,
280 bus: NotificationBus::new(),
281 base_url: None,
282 })
283 }
284}