Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Resources

A resource declares the panel’s pages for one Toasty model: which rows it lists, how its table and form look, who may see and change a record, and how a write runs. You implement the Resource trait on a unit struct, return what it declares from declare() as one ResourceDef value, and register it with Panel::resource.

The smallest resource lists rows and shows each one, and writes nothing:

#![allow(unused)]
fn main() {
pub struct AuditResource;

impl Resource for AuditResource {
    type Model = Audit;
    type Form = NoForm<Audit>; // list-only: no create or edit pages

    fn declare() -> ResourceDef<Self> {
        ResourceDef::new()
            .policy(ReadOnly)
            .table(Table::new(Audit::columns().action))
    }
}
}

The model derives PanelModel, which reads what a person sees: a table column and a detail page column per field a column can show, whoever writes it. A resource with create and edit pages names a record form as its Form, which writes: the one #[derive(ModelForm)] writes for the model, or a #[derive(RecordForm)] struct, with one form control per field. Set the def’s table, form or detail to arrange or extend one; see Tables, Forms and Detail pages.

The definition

declare() returns a ResourceDef, and every setting has a default:

ResourceDef methodDefaultPurpose
table(..)the model’s PanelModel::table()the list’s columns, filters and options: Tables
form(..)every control, in declaration orderhow the create and edit forms arrange the record form’s controls: Forms
detail(..)the declared table’s columns, else the model’s PanelModel::detail()the detail page’s columns: Detail pages
without_page(ResourcePage::..)the list, the view page, and the create and edit pages of a resource with a record formturns the create or the view page off; the policy decides who may open a page, never whether it exists
record_title(lens!(..))the label and the record’s keythe detail page’s heading, each relationship option over the resource, which also searches the column, each global search result, and a RelationColumn::of cell
global_search(..), without_global_search()searched, each result titled alonethe details under each result in the panel’s global search, or the resource left out of it
public_link(..)nonethe record’s public page, linked from its detail and edit pages
relation(..)nonea related resource shown as a table on the detail and edit pages
action::<A>()nonea record action, on rows, the detail and edit pages and the bulk bar: Actions
header_action::<A>()nonean action on no record, in the list’s header: Actions
policy(..)Denywhat the user may do: Policy, auth, tenancy
tenancy(..)none: served to every tenant, which mounting refuses over tenant-owned rowshow rows belong to a tenant: Policy, auth, tenancy
create_column(..)nonea column an overridden create_record sets itself, once per column
slug(..), label(..), plural_label(..)from the type namesURLs and titles: Naming
icon(..), navigation_order(..), navigation_group(..), navigation(..), without_navigation()the default entrythe sidebar entry; without_navigation() leaves it out: Sidebar

The panel builds the def once when it mounts and serves that copy to every request. Panel::resource_with adjusts it for one panel, so the same resource can mount read-only in a second panel:

#![allow(unused)]
fn main() {
Panel::new("portal").resource_with::<PostResource>(|def| def.policy(ReadOnly))
}

Trait methods

Model and Form are required. The methods, each with a default, receive the request:

MethodDefaultPurpose
validate_record(cx, form)no errorsrules that need the whole parsed form
create_record, update_recordthe derived writethe create and update writes: Writes
delete_record, bulk_delete_recordsdelete by primary keythe delete writes
before_commit(cx, change, ex)nothingrows that commit with the write, such as an audit log: Hooks
after_commit(cx, change)nothingside effects once the write commits: Hooks

Naming

The names default from the type names, following Filament’s conventions: BlogPostResource over BlogPost serves blog-posts, titles a record “Blog post” and its list “Blog posts”. The plural rules are the pluralizer crate’s, which Toasty names its tables with. Set label to rename a record, and plural_label only when the rules guess wrong; ResourceDef::slug and its siblings have the defaults.

Scoping the query

ResourceDef::query narrows the rows every loader reads to the ones a predicate matches: the list, the export, the edit and delete handlers, relationship options and the detail page. Use it for the resource’s own row scoping. Each panel mounts its own def, so one panel can narrow a resource that another serves whole, such as a blog that serves the published posts only:

#![allow(unused)]
fn main() {
pub fn blog() -> Panel {
    Panel::new("blog").resource_with::<PostResource>(|def| {
        def.query(Post::fields().status().eq(PostStatus::Published))
    })
}
}

ResourceDef::query_fn builds the predicate from the request, to narrow the rows to the signed-in user’s own, and answers None for a request that reads them all:

#![allow(unused)]
fn main() {
pub fn desk() -> Panel {
    Panel::new("desk").resource_with::<PostResource>(|def| {
        def.query_fn(|cx| {
            // An editor reads every post, an author their own.
            (!editors_only(cx)).then(|| Post::fields().author_id().eq(signed_in_author(cx)))
        })
    })
}
}

A narrowing says which rows, and nothing else:

  • The tenant filter. For a tenant-owned resource the framework adds it beside the narrowings at every loader. See Tenancy.
  • Soft deletes. Declare the column instead; see Soft deletes.
  • Relations. The list, the export and the detail page load the relations their columns declare: a RelationColumn declares its own, and a ComputedColumn declares one with include_unscoped. A CountColumn loads nothing and counts each row in the database. ResourceDef::include_unscoped loads a relation with every row, for one every loader reads, for example because the policy does.

In your own code, load a resource’s rows with scoped_query::<R>(cx)?, not Query::all(): it applies the panel’s narrowings, adds the tenant filter and leaves out the trashed records, and returns an error rather than an unscoped query. A background job builds its context from the mounted panel’s PanelHandle; see Outside a request.

The unique-value check on forms reads each narrowing: one that names a field of the #[unique] index stays in its probe, and one that names none is left out, so a value held by a row the narrowing hides is refused under its field. The query rustdoc has the rule.

Soft deletes

A resource that keeps deleted records names the column a delete stamps, a nullable timestamp:

#![allow(unused)]
fn main() {
            .soft_delete(lens!(Post.deleted_at))
}

A delete then sets the column to the current time instead of removing the row, and every loader leaves the stamped records out. The list’s filter menu gains a Trashed control, and a trashed record offers Restore and Delete permanently, which the policy allows through Ability::Restore and Ability::ForceDelete. In your own code, scoped_query_in::<R>(cx, Trashed::Only) loads the trashed records. ResourceDef::soft_delete has the rules, and the hooks receive the writes as Change::Restore and Change::ForceDelete.

Field access

A field only some users may see, or only some may change, declares who:

#![allow(unused)]
fn main() {
            .field_access(lens!(User.age), FieldAccess::new().view(is_admin))
            .field_access(lens!(User.role), FieldAccess::new().edit(is_admin))
}

Each rule asks about the request, not the record, and it binds the field of its model: every resource the panel mounts over that model obeys it. A user view refuses sees the field nowhere the panel shows its records, and one edit refuses sees its control disabled. ResourceDef::field_access lists every place the rule reaches.

The panel cannot see inside a closure, so a ComputedColumn and a TextColumn with a description say which fields they read, and on a panel that restricts a field the mount refuses one that does not. A QueryFilter, a tab and a summary need not: the panel reads the fields off their predicates.

ComputedColumn::new("Pay", |_, e: &Employee| e.salary.to_string())
    .reading(Reads::of(lens!(Employee.salary)))

A related record shows through the resource it names, which applies the restriction: RelationColumn::new::<R> names the fields its closure reads, and RelationColumn::of::<R> shows the record’s title. A declaration that would show a restricted record the panel cannot mask, such as RelationColumn::unscoped, fails to mount. So does a closure over the row beside a column loading such a record, unless it declares it reads only the row’s own fields: it then reads a copy of the row without its relations, which the derived PanelModel builds; FieldAccessFault lists each case.

Writes

Every create, update and delete runs in a transaction the framework opens. For an update or a delete, the handler first loads the target record through the scoped query inside that transaction and checks policy on it. It then calls the resource’s record function with the open transaction as ex.

create_record and update_record default to writing the record form’s fields (write_create and write_update), so most resources declare neither. To check something inside the transaction, override the function and delegate. This one refuses to move a comment onto a post that is not published:

#![allow(unused)]
fn main() {
impl Resource for CommentResource {
    type Model = Comment;
    // …
    async fn update_record(
        cx: &Cx,
        record: Comment,
        posted: Posted<CommentForm>,
        ex: &mut dyn toasty::Executor,
    ) -> Result<Comment, WriteError<CommentForm>> {
        if !posted.named(|f| f.post_id) || posted.post_id == record.post_id {
            return tablo::write_update::<Self>(cx, record, posted, ex).await;
        }
        let post = Post::filter_by_id(posted.post_id)
            .first()
            .exec(&mut *ex)
            .await?;
        if !post.is_some_and(|post| post.status == PostStatus::Published) {
            return Err(WriteError::<CommentForm>::field(
                |f| f.post_id,
                "Comments go on published posts",
            ));
        }
        tablo::write_update::<Self>(cx, record, posted, ex).await
    }
}
}

Run every statement through ex, and use the record you are given rather than loading it again: it is the row the policy check passed. Both functions return the written row, or a WriteError, which rolls the transaction back: Refused renders the form again with each error under its field, Declined renders it again with a message that names no field above the fields, and Failed answers as a failed write does. Return the derived write as it is: write_create and write_update answer a WriteError too.

A rule that reads the database refuses here rather than in validate_record, which runs before the transaction opens and gets no executor: a stock level, a quota, or a uniqueness no index models. A rule the write itself enforces, such as an update filtered on the stock it needs that matches no row, holds against a concurrent write. The CSV import lists a row its record fn refuses or declines with the other refused rows, and rolls that row back to a savepoint, so the rows after it are checked without its writes.

delete_record deletes the row by its primary key, or stamps it on a resource that soft-deletes, and bulk_delete_records calls it once per record, so overriding delete_record covers both. A bulk delete skips the records the policy refuses, as a bulk action does. A delete, a restore or a force delete that must not happen, such as a paid invoice’s, returns Err(WriteError::declined("..")): the transaction rolls back and the message flashes.

Hooks

Every write the panel makes for a resource reaches two hooks with a Change that says what it wrote: a create, an update, a delete or bulk delete, a restore or force delete, an action, or an attach or detach on a many-to-many relation. Neither runs when the write was refused or failed.

before_commit runs inside the transaction, after the record function or the action wrote, with the transaction as ex. A row written through ex commits with the write or not at all, so an audit log belongs here:

#![allow(unused)]
fn main() {
pub async fn before_commit(
    _cx: &Cx,
    change: &Change<Post>,
    ex: &mut dyn toasty::Executor,
) -> Result<()> {
    let action = match change {
        Change::Create(post) => format!("created {}", post.title),
        Change::Update { before, after } => {
            format!("updated {} (was {})", after.title, before.title)
        }
        Change::Delete(posts) => format!("deleted {} posts", posts.len()),
        Change::Restore(posts) => format!("restored {} posts", posts.len()),
        Change::ForceDelete(posts) => format!("deleted {} posts for good", posts.len()),
        Change::Action { name, records } => format!("ran {name} on {} posts", records.len()),
        Change::HeaderAction { name } => format!("ran {name}"),
        Change::Export { rows } => format!("exported {rows} posts"),
        Change::Attach {
            owner,
            relation,
            key,
        } => {
            format!("linked {} to {relation} {key}", owner.title)
        }
        Change::Detach {
            owner,
            relation,
            keys,
        } => {
            format!(
                "unlinked {} from {relation} {}",
                owner.title,
                keys.join(", ")
            )
        }
    };
    toasty::create!(Audit {
        action,
        created_at: jiff::Timestamp::now().to_string(),
    })
    .exec(ex)
    .await?;
    Ok(())
}
}

An error rolls back the write and every row the hook wrote, and the request fails with the write’s failure toast. Run every statement through ex: db(cx) or Notifications::send opens a second connection, which writes outside the transaction and, on a pool of one, waits forever.

after_commit runs once the transaction commits, before the response. Put work outside the database there, such as email, webhooks and cache invalidation, so a rolled-back write never triggers it:

#![allow(unused)]
fn main() {
pub async fn after_commit(cx: &Cx, change: Change<Post>) -> Result<()> {
    if let Change::Create(post) = &change {
        notify_subscribers(cx, post).await?;
    }
    Ok(())
}
}

An error it returns is logged and the write stays committed, and a crash between the commit and the hook skips it, so a row that must exist whenever the write does is written in before_commit.

An audit trail over every resource of a panel registers one CommitHook on the panel instead of a before_commit on each resource, so a resource added later cannot be left out. It runs inside the same transaction, after the resource’s own hook, and receives a PanelChange: the resource’s slug and label, and the Change with each record named by its key, its URL and the fields the write changed, each spelled before and after it as the model’s default table spells it. Its foreign keys and TenantId fields, which that table leaves out, are spelled as stored, so moving a record to another owner or tenant shows:

impl CommitHook for Audit {
    async fn before_commit(cx: &Cx, change: &PanelChange, ex: &mut dyn Executor) -> Result<()> {
        for record in change.change().records() {
            // record.url(), and for each field: field.name(), field.before(), field.after()
        }
    }
}

Panel::new("admin").before_commit::<Audit>()

Change lists what each variant carries, and what a change does not say, such as the links a form wrote. The audit example’s match lists every variant without a _ arm, so a kind of write a later Tablo adds breaks the build instead of going unaudited.

A Change carries every column, including fields the user’s field access hides, and so do a PanelChange’s fields, but for those the model marks #[columns(skip)]. An audit table that lower-privilege users can read should store only what they may see.

The profile and tenant-settings pages save their own rows and reach neither hook.

The audit log

A panel that needs an audit trail without writing one turns on the shipped log, from the tablo-audit crate, which the facade’s audit feature re-exports as tablo::audit:

tablo = { version = "0.11.1", features = ["sqlite", "audit"] }
use tablo::audit::PanelAuditExt;

Panel::new("admin").audit_log(|log| log.policy(when(is_admin)))

Every write of the panel then stores an AuditEntry per record it names, inside the write’s transaction, so a write whose entry fails rolls back with it. An entry keeps the user who did it, the tenant they acted for, the resource’s slug, the record’s key and page, and the fields the write changed, as a PanelChange spells them: a field marked #[columns(skip)] is never stored. The app lists the model in its models!, as tablo::models!(Post, tablo::audit::AuditEntry); mounting refuses a Db without it.

The trail also keeps what auth does on the panel, on no resource:

EntryWhen
sign_ina session opens: by password, by a provider, after the second factor, on sign-up
sign_in_failedthe panel refuses a sign-in; the entry keeps the login as typed
second_factor_failedthe password was right and the code wrong
sign_outthe user signs out
credentials_changedthe profile page saves a new password
password_reseta mailed reset link sets a password
email_changedthe link mailed to a new address is confirmed
two_factor_enabled, two_factor_disabled, recovery_codes_replacedthe two-factor page
impersonate, stop_impersonatingacting as a user

A sign-in, and every change of a credential, commits with its entry or not at all. A refused sign-in, a wrong code and a sign-out go through when the entry cannot be stored, and the failure is logged. A refused sign-in names no user, since a wrong password and an unknown login read alike, and an attempt past the throttle stores nothing. Anyone who reaches the login page can add entries by failing to sign in, and someone who types their password in the login field leaves it in the log: prune on a schedule, and give the log a narrow policy. These entries carry no tenant but for what a signed-in user does, so in a panel with tenants only a reader who acts outside every tenant sees a sign-in. A sign-in the app does itself under Auth::external is recorded when the panel opens its own session for it; the app’s own login page records its failures.

The log is a read-only resource at {prefix}/audit-log, newest first. It is denied until customize gives it a policy, and whatever that policy says, its pages never write. A reader sees the entries of their own panel and tenant, about the resources whose list they may open; a field field access hides from them reads “Hidden”. The resource’s own row scope, such as a query that lists only the user’s own orders, does not narrow the log: give the log a policy no wider than the narrowest scope of the resources it records.

A tenant’s trail belongs with its settings. audit_trail() keeps the entries without listing them, and an area group lists the log as it lists any resource, at {prefix}/{area}/audit-log:

Panel::new("app")
    .audit_trail()
    .area(Area::new("settings").tenant_group(|group| {
        group
            .tenant_profile()
            .resource_with::<AuditLog>(|log| log.policy(when(manages_members)))
    }))

Mounting refuses an AuditLog on a panel without audit_trail(), where it would list nothing.

Values are stored as the writer read them, in their language and time zone, so an entry is a snapshot rather than data to compute on. A delete stores every field the record held, so data an app erases on request also lives in the log until it is pruned; mark such a field #[columns(skip)], or prune on the schedule the app’s retention rules set. Erasing an account, audit::forget_actor keeps its entries without its name, and erasing a tenant, audit::forget_tenant deletes the tenant’s entries but its impersonations. AuditEntry::impersonation() reads a start or a stop back typed, and audit::impersonations() filters a resource of AuditEntry to them.

A CSV export stores an entry too, with how many rows it handed over, before the first byte leaves: an export whose entry cannot be stored is refused. The entry says the file was asked for, not that the download finished.

An app records its own events, a report or a payment, with AuditEvent, through a hook’s executor or the panel’s Db. Nothing deletes entries but tablo::audit::prune(&handle, age), which a job calls on the schedule the app keeps them for.

The log uses nothing an app cannot: a commit hook, an AuthHook for what auth does, ResourceDef::restrict to stay read-only, mounted_resources to mask what its reader may not see, Panel::require_model and Panel::default_translations. A feature of the app’s own that reads across resources builds on the same calls.

Startup checks

Mounting the panel builds each resource’s def once and binds its table, form and detail page to the database schema. It refuses a resource whose declaration cannot work, such as a unique() field with no unique index, a column nothing writes on create, or a relation to a resource the panel does not register, and lists every mistake it found in one MountError: see Mount errors.

An action’s NAME is checked when the app compiles: ResourceDef::action and ResourceDef::header_action do not compile an action whose name is not one URL segment.

A modifier on the wrong kind of field does not compile: each Field constructor returns its control’s builder (TextField, ChoiceField, FileField, CustomField), which offers only that control’s modifiers.

A form control from elsewhere does not compile either: ResourceDef::form takes a Schema<R::Form>, which places only the record form’s own controls(), so a control of another form, or a field built with Field::text, is a type error rather than a refused mount.

The panel serves the checked def to every request, so declare() never reads the request: decisions about the user or the tenant belong to the policy and to the trait methods.