1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
//! `Resource` — maps one Toasty [`Model`](toasty::schema::Model) to its admin UI.
use toasty::{
Executor,
stmt::{List, Query},
};
use topcoat::{Result, context::Cx};
use crate::form::{FieldErrors, Posted, RecordForm};
mod action;
mod check;
mod commit;
mod def;
mod editable;
mod field_access;
mod global_search;
mod header_action;
mod mounted;
mod pages;
mod query;
mod record_page;
mod record_title;
mod relation;
mod soft_delete;
mod write;
mod write_error;
pub use action::{Action, Places, filter_keys};
pub(crate) use action::{
ActionEntry, Actions, ErasedInput, InputResult, InputSpec, RESERVED_KEYS, parse_validated,
};
pub(crate) use check::{ResourceCheck, ServesTenants, check_inputs, check_resource};
pub use commit::Change;
pub(crate) use commit::{acted, run_after_commit};
pub use def::{PublicLink, ResourceDef};
pub use field_access::FieldAccess;
pub(crate) use field_access::{FieldMask, FieldRule};
pub use global_search::GlobalSearch;
pub(crate) use global_search::{Opens, SearchHit, search, searchable};
pub(crate) use header_action::HeaderEntry;
pub use header_action::{HeaderAction, HeaderActions};
pub(crate) use mounted::{
MountScope, Mounted, Mounts, is_mounted, is_restricted_model, is_tenant_model, model_rules,
mounted, require_mounted, restricts_any,
};
pub(crate) use pages::Pages;
pub use pages::ResourcePage;
pub(crate) use query::QueryFn;
pub(crate) use record_page::{
RESERVED_SEGMENTS as RESERVED_RECORD_SEGMENTS, RecordPageEntry, check as check_record_pages,
};
pub use record_page::{RecordPage, RecordPageDef};
use record_title::RecordTitle;
pub use relation::{ForeignKey, Relation};
pub(crate) use relation::{Links, RelationKind};
pub use soft_delete::Trashed;
pub(crate) use soft_delete::{SoftDelete, TRASH_FILTER, TrashFilter};
pub use write::{write_create, write_delete, write_force_delete, write_restore, write_update};
pub use write_error::WriteError;
/// Maps one Toasty `Model` to its admin UI.
///
/// # Contract
///
/// Requires [`Model`](Self::Model) and [`Form`](Self::Form); every other item has a default.
/// [`declare`](Self::declare) returns what the resource declares, as one [`ResourceDef`] value;
/// the methods scope, validate and write records for a request.
///
/// The panel builds the def once when it mounts, binding the paths it names to the database
/// schema, and serves the result to every request. Record fns run inside the handler transaction
/// and fail without partial writes.
pub trait Resource: Sized + Send + Sync + 'static {
/// The persisted model this resource administers. Its [`ModelColumns`](crate::ModelColumns)
/// give the table and detail page the resource declares none of.
type Model: crate::ModelColumns
+ toasty::stmt::IntoExpr<Self::Model>
+ Send
+ Sync
+ Clone
+ 'static;
/// The typed value the create and edit forms parse into.
///
/// A resource with create and edit pages names its
/// [`#[derive(RecordForm)]`](crate::RecordForm) struct; a list-only resource
/// names [`NoForm<Self::Model>`](crate::NoForm), and
/// [`Panel::resource`](crate::Panel::resource) registers no form route for
/// it ([`RecordForm::HAS_FORM`]).
type Form: RecordForm<Model = Self::Model>;
/// What the resource declares: names, navigation, policy, tenancy, table, form, detail page,
/// relations and actions. Defaults to [`ResourceDef::new`], whose policy denies all.
///
/// ```rust
/// # #[derive(Debug, Clone, toasty::Model, tablo_core::ModelColumns)]
/// # struct Post {
/// # #[key] #[auto] id: uuid::Uuid,
/// # title: String,
/// # body: String,
/// # }
/// # #[derive(Debug, Clone, tablo_core::RecordForm)]
/// # #[form(model = Post)]
/// # struct PostForm { title: String, body: String }
/// # struct PostResource;
/// # use tablo_core::{ReadOnly, RecordForm, Resource, ResourceDef, Schema, Section};
/// impl Resource for PostResource {
/// type Model = Post;
/// type Form = PostForm;
///
/// fn declare() -> ResourceDef<Self> {
/// let c = PostForm::controls();
/// ResourceDef::new().policy(ReadOnly).form(Schema::new(
/// Section::new("Content").schema((c.title, c.body.multiline(6))),
/// ))
/// }
/// }
/// ```
///
/// The panel builds the def once when it mounts and serves that copy to every request, so
/// `declare` takes no user, tenant or query string: a request-dependent decision belongs to
/// the policy or to a trait method, which receives `cx`.
fn declare() -> ResourceDef<Self> {
ResourceDef::new()
}
/// App-level rules on the parsed form. The errors render inline with a
/// 200 and nothing is written, so a range or cross-field rule belongs here. A rule that
/// reads the database belongs in [`create_record`](Self::create_record) or
/// [`update_record`](Self::update_record), which refuse through the transaction they write
/// in.
///
/// Each error names a field of the record form (`UserFormField::Age`) and renders under its
/// control, or under an embedded value's first control.
fn validate_record(
_cx: &Cx,
_form: &Self::Form,
) -> FieldErrors<<Self::Form as RecordForm>::Field> {
FieldErrors::new()
}
/// Create a record from the parsed form, inside the handler's transaction.
///
/// Defaults to the derived write, [`write_create`]; override to check
/// something inside the transaction, then delegate. An override on a
/// [`Tenancy::column`](crate::Tenancy::column) resource stamps the tenant
/// only by delegating to [`write_create`]: the handler re-reads the returned row through the
/// request's tenant scope before it commits, and a row outside it fails the write closed.
/// `ex` is the open transaction: run every statement through it. Return the created row; the
/// hooks receive it as [`Change::Create`].
///
/// A rule that reads the database refuses the submission with [`WriteError::Refused`]: the
/// transaction rolls back and the form renders again with the errors under their fields. A
/// reason that names no field declines it with [`WriteError::declined`], which the form
/// renders above its fields.
fn create_record(
cx: &Cx,
form: Self::Form,
ex: &mut dyn Executor,
) -> impl Future<Output = Result<Self::Model, WriteError<<Self::Form as RecordForm>::Field>>> + Send
{
write_create::<Self>(cx, form, ex)
}
/// Update the already-authorized `record` from the posted form, inside the
/// handler's transaction.
///
/// Defaults to the derived write, [`write_update`]. `record` is the
/// snapshot the handler loaded and policy-checked inside the transaction:
/// use it, never re-query. Return the row as it now stands: a row the request's tenant scope
/// no longer holds fails the write closed, as in [`create_record`](Self::create_record).
///
/// Refuses or declines the submission as [`create_record`](Self::create_record) does.
fn update_record(
cx: &Cx,
record: Self::Model,
posted: Posted<Self::Form>,
ex: &mut dyn Executor,
) -> impl Future<Output = Result<Self::Model, WriteError<<Self::Form as RecordForm>::Field>>> + Send
{
write_update::<Self>(cx, record, posted, ex)
}
/// Delete the already-authorized `record`.
///
/// The handler loads `record` through the tenancy-scoped query inside the
/// framework transaction and checks the policy on that snapshot, then
/// calls this with the same transaction as `ex`. The hooks receive the
/// snapshot as [`Change::Delete`].
///
/// The default is [`write_delete`]: it deletes the row through [`scoped_query`], filtered to
/// the record's primary key, or stamps its [`soft_delete`](ResourceDef::soft_delete) column
/// with the time when the resource declares one. Override to delete another way, or to refuse
/// with [`WriteError::declined`] and delegate the rest to [`write_delete`]: the transaction
/// rolls back and the message flashes, as it does for the restore, the force delete and the
/// bulk delete.
fn delete_record(
cx: &Cx,
record: &Self::Model,
ex: &mut dyn toasty::Executor,
) -> impl std::future::Future<Output = Result<(), WriteError>> + Send {
write_delete::<Self>(cx, record, ex)
}
/// Restore the already-authorized trashed `record` of a resource that
/// [soft-deletes](ResourceDef::soft_delete), inside the handler's transaction.
///
/// The handler loads `record` through [`scoped_query_in`] with [`Trashed::Only`] and checks
/// [`Ability::Restore`](crate::Ability::Restore) on it. The default, [`write_restore`], empties
/// the soft-delete column.
fn restore_record(
cx: &Cx,
record: &Self::Model,
ex: &mut dyn toasty::Executor,
) -> impl std::future::Future<Output = Result<(), WriteError>> + Send {
write_restore::<Self>(cx, record, ex)
}
/// Delete the already-authorized trashed `record` for good, inside the handler's
/// transaction.
///
/// The handler loads `record` through [`scoped_query_in`] with [`Trashed::Only`] and checks
/// [`Ability::ForceDelete`](crate::Ability::ForceDelete) on it. The default,
/// [`write_force_delete`], removes the row.
fn force_delete_record(
cx: &Cx,
record: &Self::Model,
ex: &mut dyn toasty::Executor,
) -> impl std::future::Future<Output = Result<(), WriteError>> + Send {
write_force_delete::<Self>(cx, record, ex)
}
/// Bulk-delete the already-authorized `records`: the handler
/// fetches through the tenancy-scoped `IN` query inside the framework
/// transaction, checks `View` on every row, and passes the rows
/// [`Ability::Delete`](crate::Ability::Delete) allows, skipping the rest
/// as a bulk custom action does. The default deletes each record through
/// [`Self::delete_record`] in order, through the same `ex` — any error rolls the whole
/// batch back, so mid-loop failures delete zero rows. An override of `delete_record`,
/// such as a soft delete, therefore covers bulk delete too. Override this
/// for a single-statement batch.
fn bulk_delete_records(
cx: &Cx,
records: &[Self::Model],
ex: &mut dyn toasty::Executor,
) -> impl std::future::Future<Output = Result<(), WriteError>> + Send {
async move {
for record in records {
Self::delete_record(cx, record, &mut *ex).await?;
}
Ok(())
}
}
/// Work inside the write's transaction, after the record fn or action wrote: an audit row,
/// a counter, a row in another table that must commit with the write or not at all.
/// Work every resource of a panel does, such as an audit trail, belongs in a
/// [`CommitHook`](crate::CommitHook), which the panel runs right after this one.
///
/// Called once per write, with the [`Change`] it made, through `ex`, the open transaction:
/// run every statement through it, and notify through
/// [`Notifications::send_in`](crate::Notifications::send_in), which stores the
/// notification only if the write commits. A second connection, through
/// [`db`](crate::db::db) or [`Notifications::send`](crate::Notifications::send),
/// would write outside the transaction, and on a pool of one wait forever for the connection
/// the transaction holds; either refuses instead, and the write rolls back.
///
/// Every write this resource's panel routes make comes here: a create, once per row of a CSV
/// import, an update, a delete or bulk delete, a restore or force delete, a custom or header
/// action, and a many-to-many attach or detach. The profile and tenant-settings pages save
/// their user and tenant rows themselves and do not. A validation error, a policy denial or
/// a failed or refused record fn returns before it. An `Err` rolls the whole write back and
/// fails the request with the write's failure toast.
///
/// ```rust
/// # use tablo_core::{Change, NoForm, Resource};
/// # use topcoat::{Result, context::Cx};
/// # #[derive(Debug, Clone, toasty::Model, tablo_core::ModelColumns)]
/// # struct Post { #[key] #[auto] id: uuid::Uuid, title: String }
/// # #[derive(Debug, toasty::Model)]
/// # struct Audit { #[key] #[auto] id: uuid::Uuid, post_id: uuid::Uuid, change: String }
/// # struct PostResource;
/// # impl Resource for PostResource {
/// # type Model = Post;
/// # type Form = NoForm<Post>;
/// async fn before_commit(
/// _cx: &Cx,
/// change: &Change<Post>,
/// ex: &mut dyn toasty::Executor,
/// ) -> Result<()> {
/// let kind = match change {
/// Change::Create(_) => "create",
/// Change::Update { .. } => "update",
/// Change::Delete(_) => "delete",
/// Change::Restore(_) => "restore",
/// Change::ForceDelete(_) => "force delete",
/// Change::Action { name, .. } | Change::HeaderAction { name } => name,
/// Change::Attach { .. } => "attach",
/// Change::Detach { .. } => "detach",
/// };
/// for post in change.records() {
/// toasty::create!(Audit {
/// post_id: post.id,
/// change: kind.to_string()
/// })
/// .exec(&mut *ex)
/// .await?;
/// }
/// Ok(())
/// }
/// # }
/// ```
fn before_commit(
_cx: &Cx,
_change: &Change<Self::Model>,
_ex: &mut dyn Executor,
) -> impl Future<Output = Result<()>> + Send {
async move { Ok(()) }
}
/// Work after the write commits, outside the database: an email, a webhook, cache
/// invalidation.
///
/// Called once per committed write, after `tx.commit()` and before the response, with the
/// [`Change`] [`Self::before_commit`] received. It is never called when nothing committed, so
/// a rollback cannot produce the effect. Nothing guarantees it runs either: an error it
/// returns is logged and ignored, since the write is committed, and a crash between the
/// commit and the hook skips it. A row that must exist whenever the write does belongs in
/// [`Self::before_commit`]; retries are the app's to build. A panic surfaces as Topcoat's
/// panic-isolated 500.
///
/// ```rust
/// # use tablo_core::{Change, NoForm, Resource};
/// # use topcoat::{Result, context::Cx};
/// # #[derive(Debug, Clone, toasty::Model, tablo_core::ModelColumns)]
/// # struct Post { #[key] #[auto] id: uuid::Uuid, title: String }
/// # async fn notify(_cx: &Cx, _post: &Post) -> Result<()> { Ok(()) }
/// # struct PostResource;
/// # impl Resource for PostResource {
/// # type Model = Post;
/// # type Form = NoForm<Post>;
/// async fn after_commit(cx: &Cx, change: Change<Post>) -> Result<()> {
/// if let Change::Create(post) = &change {
/// notify(cx, post).await?;
/// }
/// Ok(())
/// }
/// # }
/// ```
fn after_commit(
_cx: &Cx,
_change: Change<Self::Model>,
) -> impl Future<Output = Result<()>> + Send {
async move { Ok(()) }
}
}
/// The tenant-scoped base query.
///
/// The resource's rows as the context's panel narrows them with [`ResourceDef::query`], with the
/// [`tenancy`](ResourceDef::tenancy) filter ANDed onto them, so no narrowing can drop the tenant
/// scope, and with the trashed records of a resource that [soft-deletes](ResourceDef::soft_delete)
/// left out.
/// Every framework loader and app code start here; [`scoped_query_in`] admits the trashed
/// records too.
///
/// # Errors
///
/// A tenant-scoped resource and no tenant in `cx`: 403, the same answer the
/// panel's handlers give. A declaration error when the context's panel does not mount `R`; a
/// background job builds its context with [`PanelHandle::context`](crate::PanelHandle::context).
///
/// App code that loads rows itself must call this: `Query::all()` reads every tenant's rows and
/// skips the panel's narrowings.
pub fn scoped_query<R: Resource>(cx: &Cx) -> Result<Query<List<R::Model>>> {
scoped_query_in::<R>(cx, Trashed::Without)
}
/// [`scoped_query`] admitting the records `trashed` names, as a restore or a trash list loads
/// them, under the same tenant filter.
///
/// On a resource that declares no [`soft_delete`](ResourceDef::soft_delete) column every record
/// is live: [`Trashed::Only`] admits none, and the other scopes admit all.
///
/// # Errors
///
/// As [`scoped_query`].
pub fn scoped_query_in<R: Resource>(cx: &Cx, trashed: Trashed) -> Result<Query<List<R::Model>>> {
require_mounted::<R>(cx)?.scoped_query_in(cx, trashed)
}
impl<R: Resource> Mounted<R> {
/// [`scoped_query`] for this mount.
pub(crate) fn scoped_query(&self, cx: &Cx) -> Result<Query<List<R::Model>>> {
self.scoped_query_in(cx, Trashed::Without)
}
/// [`scoped_query_in`] for this mount.
pub(crate) fn scoped_query_in(
&self,
cx: &Cx,
trashed: Trashed,
) -> Result<Query<List<R::Model>>> {
let query = self
.queries
.iter()
.fold(Query::<List<R::Model>>::all(), |query, narrow| {
narrow(cx, query)
});
let query = self.tenant_scope(cx, query)?;
Ok(match &self.soft_delete {
Some(soft_delete) => match soft_delete.filter(trashed) {
Some(filter) => query.filter(filter),
None => query,
},
None if trashed == Trashed::Only => query.filter(crate::toasty_compat::never()),
None => query,
})
}
/// The records a list in `state` admits: the ones its trash control selects, else the live
/// ones.
pub(crate) fn list_trashed(&self, state: &crate::TableState) -> Trashed {
if self.soft_delete.is_none() {
return Trashed::Without;
}
Trashed::from_filter(state.filters.get(TRASH_FILTER)).unwrap_or_default()
}
/// [`scoped_query_in`] for the list in `state`.
pub(crate) fn list_query(
&self,
cx: &Cx,
state: &crate::TableState,
) -> Result<Query<List<R::Model>>> {
self.scoped_query_in(cx, self.list_trashed(state))
}
/// Whether `record` is trashed: never on a resource that does not soft-delete.
pub(crate) fn is_trashed(&self, record: &R::Model) -> bool {
self.soft_delete
.as_ref()
.is_some_and(|soft_delete| soft_delete.is_trashed(record))
}
/// AND the resource's tenant filter onto `query`.
fn tenant_scope(&self, cx: &Cx, query: Query<List<R::Model>>) -> Result<Query<List<R::Model>>> {
if !self.tenancy.is_scoped() {
return Ok(query);
}
if let Some(Err(error)) = self.tenancy.column_field() {
return Err(crate::error::declaration(
crate::DeclarationError::of::<R>(crate::Site::Tenancy, error).to_string(),
));
}
let tenant = crate::tenancy::require_tenant(cx)?;
Ok(match self.tenancy.filter(tenant) {
Some(filter) => query.filter(filter),
None => query,
})
}
}
/// Whether `R`'s policy, as the context's panel mounted it, allows `ability`; `false` when the
/// panel does not mount `R`. Does not check sign-in or tenant scope.
pub fn can<R: Resource>(cx: &Cx, ability: crate::Ability<'_, R::Model>) -> bool {
mounted::<R>(cx).is_some_and(|resource| resource.can(cx, ability))
}
/// Every `Resource` is an [`OptionSource`](crate::extend::OptionSource), answering from its def
/// as the context's panel mounted it.
///
/// [`scoped_query`](crate::extend::OptionSource::scoped_query) forwards to
/// [`scoped_query`], so an option load inherits the tenant check and filter
/// exactly as every other loader does. The search expression and default ordering come from the
/// resource's [`table`](ResourceDef::table), whose searchable columns the option search searches
/// with the [`record_title`](ResourceDef::record_title) column, and each record's label is its
/// title.
impl<R: Resource> crate::schema::OptionSource for R {
type Model = R::Model;
fn scoped_query(cx: &Cx) -> Result<Query<List<R::Model>>> {
scoped_query::<R>(cx)
}
fn lists(cx: &Cx) -> bool {
can::<R>(cx, crate::Ability::ViewAny)
}
fn requires_tenant(cx: &Cx) -> bool {
mounted::<R>(cx).is_some_and(|mounted| mounted.tenancy.is_scoped())
}
fn search_expr(cx: &Cx, term: &str) -> Option<toasty::stmt::Expr<bool>> {
mounted::<R>(cx)?.option_search_expr(cx, term)
}
fn order_by(cx: &Cx) -> Option<toasty::stmt::OrderByExpr> {
mounted::<R>(cx)?.table_for(cx).first_order_by()
}
/// The record's title, as its detail page shows it.
fn label(cx: &Cx, record: &R::Model) -> String {
let key = crate::toasty_compat::pk::pk_text(record);
match mounted::<R>(cx) {
Some(mounted) => mounted.record_title(cx, record, &key),
None => key,
}
}
fn available(cx: &Cx) -> bool {
mounted::<R>(cx).is_some()
}
fn hidden_fields(cx: &Cx) -> Vec<String> {
mounted::<R>(cx).map_or_else(Vec::new, |mounted| mounted.field_mask(cx).hidden().to_vec())
}
fn creates() -> bool {
true
}
fn create_page(cx: &Cx) -> Option<String> {
let mounted = mounted::<R>(cx)?;
// The page a save lands on offers the record only to a user who may list the resource.
(mounted.pages.create && mounted.can_create(cx) && mounted.can(cx, crate::Ability::ViewAny))
.then(|| crate::naming::create_page_url(&mounted.url))
}
}
#[cfg(test)]
mod tests;