Skip to main content

ignite_core/
runtime_resource.rs

1//! Resources defined at run time, from data: their slug, fields, columns and queries are
2//! values, not a Rust type, so an app can add and remove them while the panel serves.
3//!
4//! A static resource implements [`IgniteResource`](crate::IgniteResource) and is added with
5//! `Ignite::resource`. A runtime resource is a [`RuntimeResource`] value, whose rows come from
6//! a [`RuntimeData`] the app implements, and is added with [`register_runtime`]. The panel
7//! serves both through the same list, form and delete flows, at the same `/admin/<slug>`
8//! address, and a slug can belong to only one of them.
9//!
10//! ```ignore
11//! register_runtime(
12//!     RuntimeResource::new("books", "Books", "Book", BookData)
13//!         .field(FieldDef { name: "title".into(), label: "Title".into(),
14//!                           kind: FieldKindDef::Text, required: true })
15//!         .column(ColumnDef { key: "title".into(), label: "Title".into(),
16//!                             sortable: true, searchable: true }),
17//! )?;
18//! ```
19
20use std::collections::HashSet;
21use std::fmt;
22use std::future::Future;
23use std::pin::Pin;
24use std::sync::{Arc, PoisonError, RwLock};
25
26use orbit_orm::{Database, Error};
27use serde_json::{Map, Value};
28
29use crate::field::{self as check, Block, Column, Field, FieldKind};
30use crate::form::{FieldErrors, FormInput};
31use crate::policy::ActingUser;
32use crate::query::{ListQuery, Page};
33
34/// One record of a runtime resource: its values by key, as JSON. A row the panel lists or
35/// edits must have a numeric `id`, and a key for each field and column it shows.
36pub type Row = Map<String, Value>;
37
38/// The future a [`RuntimeData`] method returns: boxed, so the trait can be a trait object.
39/// Write the body as `Box::pin(async move { ... })`.
40pub type RuntimeFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T, Error>> + Send + 'a>>;
41
42/// Where the rows of a runtime resource live. The app implements it, so Ignite assumes no
43/// table layout: a custom post type can keep its rows in a shared `posts` table and its
44/// values in a meta table.
45///
46/// The methods mirror the queries of [`IgniteResource`](crate::IgniteResource), with
47/// [`Row`]s for records and for validated input. The panel calls the `*_for` methods, which
48/// are given the signed-in [`ActingUser`]; by default each calls its method without the user,
49/// so a source that does not depend on the user implements only those.
50pub trait RuntimeData: Send + Sync + 'static {
51    /// Returns one page of rows that match `query`. The sort key, when there is one, is a
52    /// sortable column of the resource.
53    fn list<'a>(&'a self, db: &'a Database, query: &'a ListQuery) -> RuntimeFuture<'a, Page<Row>>;
54    /// Returns the row with `id`, or `None` if there is no such row.
55    fn find<'a>(&'a self, db: &'a Database, id: i64) -> RuntimeFuture<'a, Option<Row>>;
56    /// Inserts a row from the validated `input` and returns it. See
57    /// [`RegisteredResource::validate`] for the values `input` holds.
58    ///
59    /// An [`Error::UniqueViolation`] whose index is named `{slug}_{field}_unique` shows on the
60    /// form as `"<label> is already taken."`, as for a static resource. Any other error is a
61    /// server error. A source whose indexes are named otherwise (or that keeps values in a
62    /// meta table without such an index) should return a violation with an index of that
63    /// name, or check the value before it writes.
64    fn create<'a>(&'a self, db: &'a Database, input: Row) -> RuntimeFuture<'a, Row>;
65    /// Updates the row with `id` from the validated `input` and returns it. A key that is
66    /// missing from `input`, such as a password left blank or a field the form did not send,
67    /// keeps its stored value. A key whose value is `null` is an optional field the user cleared: store NULL, so the value
68    /// is cleared, as a static resource does. A unique violation is reported as for
69    /// [`create`](Self::create).
70    fn update<'a>(&'a self, db: &'a Database, id: i64, input: Row) -> RuntimeFuture<'a, Row>;
71    /// Deletes the row with `id` and returns the number of rows deleted.
72    fn delete<'a>(&'a self, db: &'a Database, id: i64) -> RuntimeFuture<'a, u64>;
73    /// The choices of the field `field`, as `(value, label)` pairs in display order, for a
74    /// field whose kind [loads its options](FieldKindDef::loads_options): a lookup, post
75    /// object, relationship, taxonomy or user field. The default is no choices.
76    fn options<'a>(
77        &'a self,
78        db: &'a Database,
79        field: &'a str,
80    ) -> RuntimeFuture<'a, Vec<(String, String)>> {
81        let _ = (db, field);
82        Box::pin(async { Ok(Vec::new()) })
83    }
84
85    /// [`list`](Self::list) for the signed-in `user`: the panel's list calls it. Restrict the
86    /// rows to the user here, as a Filament resource does in `getEloquentQuery()`, such as an
87    /// author who sees only their own posts. The total counts the same rows. The default is
88    /// [`list`](Self::list), for every user.
89    fn list_for<'a>(
90        &'a self,
91        db: &'a Database,
92        user: &'a ActingUser,
93        query: &'a ListQuery,
94    ) -> RuntimeFuture<'a, Page<Row>> {
95        let _ = user;
96        self.list(db, query)
97    }
98
99    /// [`find`](Self::find) for the signed-in `user`: the panel finds the record of the edit
100    /// form, of its save and of the delete action with it. Return `None` for a row the user's
101    /// list leaves out, so the panel answers 404, as Filament resolves a record through
102    /// `getEloquentQuery()`. The default is [`find`](Self::find), for every user.
103    fn find_for<'a>(
104        &'a self,
105        db: &'a Database,
106        user: &'a ActingUser,
107        id: i64,
108    ) -> RuntimeFuture<'a, Option<Row>> {
109        let _ = user;
110        self.find(db, id)
111    }
112
113    /// [`create`](Self::create) for the signed-in `user`, such as to make them the author.
114    /// The default is [`create`](Self::create).
115    fn create_for<'a>(
116        &'a self,
117        db: &'a Database,
118        user: &'a ActingUser,
119        input: Row,
120    ) -> RuntimeFuture<'a, Row> {
121        let _ = user;
122        self.create(db, input)
123    }
124
125    /// [`update`](Self::update) for the signed-in `user`, such as to keep a status the user
126    /// may not set. The panel calls it only after [`find_for`](Self::find_for) found the row
127    /// and the [`Policy`](crate::Policy) allowed the update. The default is
128    /// [`update`](Self::update).
129    fn update_for<'a>(
130        &'a self,
131        db: &'a Database,
132        user: &'a ActingUser,
133        id: i64,
134        input: Row,
135    ) -> RuntimeFuture<'a, Row> {
136        let _ = user;
137        self.update(db, id, input)
138    }
139
140    /// [`delete`](Self::delete) for the signed-in `user`. The panel calls it only after
141    /// [`find_for`](Self::find_for) found the row and the [`Policy`](crate::Policy) allowed
142    /// the delete. The default is [`delete`](Self::delete).
143    fn delete_for<'a>(
144        &'a self,
145        db: &'a Database,
146        user: &'a ActingUser,
147        id: i64,
148    ) -> RuntimeFuture<'a, u64> {
149        let _ = user;
150        self.delete(db, id)
151    }
152
153    /// [`options`](Self::options) for the signed-in `user`: the panel fills the form's
154    /// selects with these choices and checks a submitted value against them, so a choice left
155    /// out cannot be saved, as a Filament select whose options depend on the user. The default
156    /// is [`options`](Self::options).
157    fn options_for<'a>(
158        &'a self,
159        db: &'a Database,
160        user: &'a ActingUser,
161        field: &'a str,
162    ) -> RuntimeFuture<'a, Vec<(String, String)>> {
163        let _ = user;
164        self.options(db, field)
165    }
166}
167
168/// The kind of a [`FieldDef`]: every [`FieldKind`], with owned values so it can be loaded
169/// from a database.
170#[derive(Debug, Clone, PartialEq, Eq, Hash)]
171pub enum FieldKindDef {
172    /// A single line of text. See [`FieldKind::Text`].
173    Text,
174    /// Several lines of text. See [`FieldKind::Textarea`].
175    Textarea,
176    /// A password, hashed on save. See [`FieldKind::Password`].
177    Password,
178    /// A whole number. See [`FieldKind::Number`].
179    Number,
180    /// A decimal number, with the browser's step, such as `"any"` or `"0.01"`. See
181    /// [`FieldKind::Decimal`].
182    Decimal(String),
183    /// A yes/no value. See [`FieldKind::Checkbox`].
184    Checkbox,
185    /// One choice from a list of `(value, label)` pairs. See [`FieldKind::Select`].
186    Select(Vec<(String, String)>),
187    /// One choice from options that [`RuntimeData::options`] loads. See [`FieldKind::Lookup`].
188    Lookup,
189    /// A calendar date. See [`FieldKind::Date`].
190    Date,
191    /// A date and time. See [`FieldKind::DateTime`].
192    DateTime,
193    /// An email address. See [`FieldKind::Email`].
194    Email,
195    /// A URL. See [`FieldKind::Url`].
196    Url,
197    /// One choice from a list of `(value, label)` pairs, as radio buttons. See
198    /// [`FieldKind::Radio`].
199    Radio(Vec<(String, String)>),
200    /// A color, as `#rrggbb`. See [`FieldKind::Color`].
201    Color,
202    /// An image from the media library. See [`FieldKind::Image`].
203    Image,
204    /// A file from the media library. See [`FieldKind::File`].
205    File,
206    /// A link, as JSON text. See [`FieldKind::Link`].
207    Link,
208    /// Rich text, edited with the app's editor. See [`FieldKind::Wysiwyg`].
209    Wysiwyg,
210    /// One post, from options [`RuntimeData::options`] loads. See [`FieldKind::PostObject`].
211    PostObject,
212    /// Several choices, from options [`RuntimeData::options`] loads. See
213    /// [`FieldKind::Relationship`].
214    Relationship,
215    /// One taxonomy term, from loaded options. See [`FieldKind::Taxonomy`].
216    Taxonomy,
217    /// One user, from loaded options. See [`FieldKind::User`].
218    User,
219    /// Rows of the given sub-fields, as JSON text. See [`FieldKind::Repeater`].
220    Repeater(Vec<FieldDef>),
221    /// The given sub-fields, as one JSON object. See [`FieldKind::Group`].
222    Group(Vec<FieldDef>),
223    /// Rows that each take one of the given blocks, as JSON text. See
224    /// [`FieldKind::FlexibleContent`].
225    FlexibleContent(Vec<BlockDef>),
226    /// Several images from the media library, as a JSON array of ids. See
227    /// [`FieldKind::Gallery`].
228    Gallery,
229    /// The fields of another field group, reused. See [`FieldKind::Clone`].
230    Clone(Vec<FieldDef>),
231}
232
233impl FieldKindDef {
234    /// Whether the field's choices come from [`RuntimeData::options`] each time its form is
235    /// shown. See [`FieldKind::loads_options`].
236    pub fn loads_options(&self) -> bool {
237        matches!(
238            self,
239            FieldKindDef::Lookup
240                | FieldKindDef::PostObject
241                | FieldKindDef::Relationship
242                | FieldKindDef::Taxonomy
243                | FieldKindDef::User
244        )
245    }
246
247    /// Whether the field holds media library ids: an image, a file or a gallery.
248    pub fn uses_media(&self) -> bool {
249        matches!(
250            self,
251            FieldKindDef::Image | FieldKindDef::File | FieldKindDef::Gallery
252        )
253    }
254}
255
256/// One block of a [`FieldKindDef::FlexibleContent`] field: the owned twin of [`Block`].
257#[derive(Debug, Clone, PartialEq, Eq, Hash)]
258pub struct BlockDef {
259    /// The block's name, stored as the `type` of each row that uses it.
260    pub name: String,
261    /// The label shown when choosing the block.
262    pub label: String,
263    /// The block's sub-fields, in display order.
264    pub fields: Vec<FieldDef>,
265}
266
267impl From<Block> for BlockDef {
268    fn from(block: Block) -> Self {
269        BlockDef {
270            name: block.name.to_string(),
271            label: block.label.to_string(),
272            fields: owned_fields(block.fields),
273        }
274    }
275}
276
277/// Owned definitions of static sub-fields.
278fn owned_fields(fields: &[Field]) -> Vec<FieldDef> {
279    fields.iter().copied().map(FieldDef::from).collect()
280}
281
282/// Owned `(value, label)` pairs of static choices.
283fn owned_choices(choices: &[(&str, &str)]) -> Vec<(String, String)> {
284    choices
285        .iter()
286        .map(|(value, label)| (value.to_string(), label.to_string()))
287        .collect()
288}
289
290impl From<FieldKind> for FieldKindDef {
291    fn from(kind: FieldKind) -> Self {
292        match kind {
293            FieldKind::Text => FieldKindDef::Text,
294            FieldKind::Textarea => FieldKindDef::Textarea,
295            FieldKind::Password => FieldKindDef::Password,
296            FieldKind::Number => FieldKindDef::Number,
297            FieldKind::Decimal(step) => FieldKindDef::Decimal(step.to_string()),
298            FieldKind::Checkbox => FieldKindDef::Checkbox,
299            FieldKind::Select(choices) => FieldKindDef::Select(owned_choices(choices)),
300            FieldKind::Lookup => FieldKindDef::Lookup,
301            FieldKind::Date => FieldKindDef::Date,
302            FieldKind::DateTime => FieldKindDef::DateTime,
303            FieldKind::Email => FieldKindDef::Email,
304            FieldKind::Url => FieldKindDef::Url,
305            FieldKind::Radio(choices) => FieldKindDef::Radio(owned_choices(choices)),
306            FieldKind::Color => FieldKindDef::Color,
307            FieldKind::Image => FieldKindDef::Image,
308            FieldKind::File => FieldKindDef::File,
309            FieldKind::Link => FieldKindDef::Link,
310            FieldKind::Wysiwyg => FieldKindDef::Wysiwyg,
311            FieldKind::PostObject => FieldKindDef::PostObject,
312            FieldKind::Relationship => FieldKindDef::Relationship,
313            FieldKind::Taxonomy => FieldKindDef::Taxonomy,
314            FieldKind::User => FieldKindDef::User,
315            FieldKind::Repeater(fields) => FieldKindDef::Repeater(owned_fields(fields)),
316            FieldKind::Group(fields) => FieldKindDef::Group(owned_fields(fields)),
317            FieldKind::FlexibleContent(blocks) => {
318                FieldKindDef::FlexibleContent(blocks.iter().copied().map(BlockDef::from).collect())
319            }
320            FieldKind::Gallery => FieldKindDef::Gallery,
321            FieldKind::Clone(fields) => FieldKindDef::Clone(owned_fields(fields)),
322        }
323    }
324}
325
326/// One input on the form of a runtime resource: the owned twin of [`Field`].
327#[derive(Debug, Clone, PartialEq, Eq, Hash)]
328pub struct FieldDef {
329    /// The form field name. It matches a key of the row.
330    pub name: String,
331    /// The label shown next to the input.
332    pub label: String,
333    /// The input type, and how the value is read.
334    pub kind: FieldKindDef,
335    /// Whether the form rejects a blank value.
336    pub required: bool,
337}
338
339impl From<Field> for FieldDef {
340    fn from(field: Field) -> Self {
341        FieldDef {
342            name: field.name.to_string(),
343            label: field.label.to_string(),
344            kind: field.kind.into(),
345            required: field.required,
346        }
347    }
348}
349
350/// One column of the list of a runtime resource: the owned twin of [`Column`].
351#[derive(Debug, Clone, PartialEq, Eq, Hash)]
352pub struct ColumnDef {
353    /// The row key the column shows. It matches a field name.
354    pub key: String,
355    /// The column heading.
356    pub label: String,
357    /// Whether the heading links to a sort by this column.
358    pub sortable: bool,
359    /// Whether the search box matches this column.
360    pub searchable: bool,
361}
362
363impl From<Column> for ColumnDef {
364    fn from(column: Column) -> Self {
365        ColumnDef {
366            key: column.key.to_string(),
367            label: column.label.to_string(),
368            sortable: column.sortable,
369            searchable: column.searchable,
370        }
371    }
372}
373
374/// A resource defined by data. Build it with [`new`](Self::new) and the
375/// [`field`](Self::field) and [`column`](Self::column) methods, then add it to the panel
376/// with [`register_runtime`].
377#[derive(Clone)]
378pub struct RuntimeResource {
379    /// URL segment: `"books"` serves the resource at `/admin/books`. Lowercase letters,
380    /// digits, `-` and `_` only.
381    pub slug: String,
382    /// Heading and navigation label: `"Books"`.
383    pub title: String,
384    /// The name of one record, for headings such as "New Book".
385    pub singular: String,
386    /// Rows per page on the list view. The default is 20, as for a static resource.
387    pub per_page: i64,
388    /// Form fields, in display order.
389    pub fields: Vec<FieldDef>,
390    /// Table columns, in display order. Each column's `key` is a field name.
391    pub columns: Vec<ColumnDef>,
392    /// Where the rows live.
393    pub data: Arc<dyn RuntimeData>,
394    /// The label of the navigation entry, as Filament's `$navigationLabel`. `None`, the
395    /// default, is the [`title`](Self::title).
396    pub navigation_label: Option<String>,
397    /// The navigation group the resource is listed under, as Filament's `$navigationGroup`.
398    /// See [`IgniteResource::NAVIGATION_GROUP`](crate::IgniteResource::NAVIGATION_GROUP).
399    pub navigation_group: Option<String>,
400    /// The resource's place in the navigation, as Filament's `$navigationSort`: lower first.
401    /// See [`IgniteResource::NAVIGATION_SORT`](crate::IgniteResource::NAVIGATION_SORT).
402    pub navigation_sort: Option<i32>,
403    /// The CSS classes of the navigation entry's icon, as Filament's `$navigationIcon`.
404    /// See [`IgniteResource::NAVIGATION_ICON`](crate::IgniteResource::NAVIGATION_ICON).
405    pub navigation_icon: Option<String>,
406}
407
408impl fmt::Debug for RuntimeResource {
409    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
410        f.debug_struct("RuntimeResource")
411            .field("slug", &self.slug)
412            .field("title", &self.title)
413            .field("singular", &self.singular)
414            .field("per_page", &self.per_page)
415            .field("fields", &self.fields)
416            .field("columns", &self.columns)
417            .field("navigation_label", &self.navigation_label)
418            .field("navigation_group", &self.navigation_group)
419            .field("navigation_sort", &self.navigation_sort)
420            .field("navigation_icon", &self.navigation_icon)
421            .finish_non_exhaustive()
422    }
423}
424
425impl RuntimeResource {
426    /// A resource at `slug` with no fields or columns yet, whose rows come from `data`.
427    pub fn new(
428        slug: impl Into<String>,
429        title: impl Into<String>,
430        singular: impl Into<String>,
431        data: impl RuntimeData,
432    ) -> Self {
433        RuntimeResource {
434            slug: slug.into(),
435            title: title.into(),
436            singular: singular.into(),
437            per_page: 20,
438            fields: Vec::new(),
439            columns: Vec::new(),
440            data: Arc::new(data),
441            navigation_label: None,
442            navigation_group: None,
443            navigation_sort: None,
444            navigation_icon: None,
445        }
446    }
447
448    /// Adds a form field after the others.
449    pub fn field(mut self, field: FieldDef) -> Self {
450        self.fields.push(field);
451        self
452    }
453
454    /// Adds a list column after the others.
455    pub fn column(mut self, column: ColumnDef) -> Self {
456        self.columns.push(column);
457        self
458    }
459
460    /// Sets the rows per page of the list view.
461    pub fn per_page(mut self, per_page: i64) -> Self {
462        self.per_page = per_page;
463        self
464    }
465
466    /// Sets the label of the navigation entry, as Filament's `navigationLabel`.
467    pub fn navigation_label(mut self, label: impl Into<String>) -> Self {
468        self.navigation_label = Some(label.into());
469        self
470    }
471
472    /// Lists the resource under the navigation group `group`, as Filament's `navigationGroup`.
473    pub fn navigation_group(mut self, group: impl Into<String>) -> Self {
474        self.navigation_group = Some(group.into());
475        self
476    }
477
478    /// Sets the resource's place in the navigation, as Filament's `navigationSort`: lower first.
479    pub fn navigation_sort(mut self, sort: i32) -> Self {
480        self.navigation_sort = Some(sort);
481        self
482    }
483
484    /// Sets the icon of the navigation entry, as Filament's `navigationIcon`: one or more CSS
485    /// classes from a stylesheet the app loads, such as `"dashicons dashicons-admin-post"`.
486    /// See [`IgniteResource::NAVIGATION_ICON`](crate::IgniteResource::NAVIGATION_ICON).
487    pub fn navigation_icon(mut self, classes: impl Into<String>) -> Self {
488        self.navigation_icon = Some(classes.into());
489        self
490    }
491}
492
493/// The checks of [`RegisteredResource::validate`]. Each error is keyed by its field's name.
494fn validate_fields(
495    fields: &[FieldDef],
496    form: &FormInput,
497    creating: bool,
498) -> Result<Row, FieldErrors> {
499    let mut errors = FieldErrors::new();
500    let mut row = Row::new();
501    for field in fields {
502        let name = field.name.as_str();
503        let label = field.label.as_str();
504        // A checkbox is never blank: an unticked checkbox is false.
505        if field.kind == FieldKindDef::Checkbox {
506            row.insert(name.to_string(), Value::Bool(form.checkbox(name)));
507            continue;
508        }
509        let is_password = field.kind == FieldKindDef::Password;
510        // A password is required only when creating. On an edit a blank one keeps the hash.
511        let present = if field.required && (creating || !is_password) {
512            check::check_required(name, label, form, &mut errors)
513        } else {
514            form.get(name)
515        };
516        let Some(text) = present else {
517            // On an update, a field the form did not send keeps its stored value, and a blank
518            // password keeps its hash. A field sent blank is cleared to NULL.
519            let keep = !creating && (is_password || !form.has(name));
520            if !keep {
521                row.insert(name.to_string(), Value::Null);
522            }
523            continue;
524        };
525        let value = match &field.kind {
526            FieldKindDef::Password => match crate::hash_password(text) {
527                Ok(hash) => Some(Value::String(hash)),
528                Err(_) => {
529                    errors.insert(
530                        name.to_string(),
531                        "Could not save this password.".to_string(),
532                    );
533                    None
534                }
535            },
536            FieldKindDef::Number => {
537                check::check_whole_number::<i64>(name, label, text, &mut errors).map(Value::from)
538            }
539            FieldKindDef::Decimal(_) => {
540                check::check_decimal::<f64>(name, label, text, &mut errors).map(Value::from)
541            }
542            FieldKindDef::Select(choices) => {
543                let text = text.trim();
544                let choices: Vec<(&str, &str)> = choices
545                    .iter()
546                    .map(|(value, label)| (value.as_str(), label.as_str()))
547                    .collect();
548                check::check_choice(name, text, &choices, &mut errors)
549                    .then(|| Value::String(text.to_string()))
550            }
551            FieldKindDef::Lookup => Some(Value::String(text.trim().to_string())),
552            FieldKindDef::Date => check::check_date(name, label, text, &mut errors)
553                .map(|date| Value::String(date.format("%Y-%m-%d").to_string())),
554            FieldKindDef::DateTime => check::check_datetime(name, label, text, &mut errors)
555                .map(|stamp| Value::String(stamp.format("%Y-%m-%d %H:%M:%S").to_string())),
556            FieldKindDef::Text | FieldKindDef::Textarea | FieldKindDef::Checkbox => {
557                Some(Value::String(text.to_string()))
558            }
559            kind => crate::value::check_value(name, label, field.required, kind, text, &mut errors)
560                .map(Value::String),
561        };
562        if let Some(value) = value {
563            row.insert(name.to_string(), value);
564        }
565    }
566    if errors.is_empty() {
567        Ok(row)
568    } else {
569        Err(errors)
570    }
571}
572
573/// Why the registry refused a change.
574#[derive(Debug, Clone, PartialEq, Eq)]
575pub enum RuntimeError {
576    /// The slug is not one URL segment of lowercase letters, digits, `-` and `_`.
577    InvalidSlug(String),
578    /// Another resource, static or runtime, or one of the panel's own pages, has the slug.
579    SlugTaken(String),
580    /// A field name is not a lowercase identifier: lowercase ASCII letters, digits and `_`,
581    /// starting with a letter, at most 64 bytes ([`MAX_FIELD_NAME`]).
582    InvalidFieldName {
583        /// The slug of the resource.
584        slug: String,
585        /// The name that was refused.
586        field: String,
587    },
588    /// Two fields of the resource have the same name.
589    DuplicateField {
590        /// The slug of the resource.
591        slug: String,
592        /// The name used twice.
593        field: String,
594    },
595    /// No runtime resource has the slug.
596    NotRegistered(String),
597}
598
599impl fmt::Display for RuntimeError {
600    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
601        match self {
602            RuntimeError::InvalidSlug(slug) => write!(
603                f,
604                "the slug `{slug}` is not valid: use lowercase letters, digits, `-` and `_`"
605            ),
606            RuntimeError::SlugTaken(slug) => write!(
607                f,
608                "the slug `{slug}` is already used by another Ignite resource"
609            ),
610            RuntimeError::InvalidFieldName { slug, field } => write!(
611                f,
612                "the field `{field}` of the resource `{slug}` is not valid: use lowercase \
613                 letters, digits and `_`, starting with a letter, at most {MAX_FIELD_NAME} bytes"
614            ),
615            RuntimeError::DuplicateField { slug, field } => {
616                write!(f, "the resource `{slug}` has two fields named `{field}`")
617            }
618            RuntimeError::NotRegistered(slug) => {
619                write!(f, "no runtime resource is registered at `{slug}`")
620            }
621        }
622    }
623}
624
625impl std::error::Error for RuntimeError {}
626
627/// A runtime resource as the registry holds it: the definition, ready for the panel.
628pub struct RegisteredResource {
629    resource: RuntimeResource,
630}
631
632impl RegisteredResource {
633    /// The definition that was registered.
634    pub fn resource(&self) -> &RuntimeResource {
635        &self.resource
636    }
637
638    /// The slug, as the panel's routes match it.
639    pub fn slug(&self) -> &str {
640        &self.resource.slug
641    }
642
643    /// The heading and navigation label.
644    pub fn title(&self) -> &str {
645        &self.resource.title
646    }
647
648    /// The name of one record.
649    pub fn singular(&self) -> &str {
650        &self.resource.singular
651    }
652
653    /// The label of the navigation entry: the navigation label, or the title.
654    pub fn navigation_label(&self) -> &str {
655        self.resource
656            .navigation_label
657            .as_deref()
658            .unwrap_or(&self.resource.title)
659    }
660
661    /// The navigation group the resource is listed under, if any.
662    pub fn navigation_group(&self) -> Option<&str> {
663        self.resource.navigation_group.as_deref()
664    }
665
666    /// The resource's place in the navigation, if set.
667    pub fn navigation_sort(&self) -> Option<i32> {
668        self.resource.navigation_sort
669    }
670
671    /// The CSS classes of the navigation entry's icon, if set.
672    pub fn navigation_icon(&self) -> Option<&str> {
673        self.resource.navigation_icon.as_deref()
674    }
675
676    /// The form fields, in display order.
677    pub fn fields(&self) -> &[FieldDef] {
678        &self.resource.fields
679    }
680
681    /// The list columns, in display order.
682    pub fn columns(&self) -> &[ColumnDef] {
683        &self.resource.columns
684    }
685
686    /// Turns the submitted form into a [`Row`] for a create, or returns one message per
687    /// field. It runs the same checks as a static resource, with the same messages:
688    /// required fields ([`Field::check_required`](crate::Field::check_required)), whole
689    /// numbers, decimals, dates, date-times and select choices. The row holds one key per
690    /// field:
691    ///
692    /// - text, textarea, select, lookup: a string. A required value is trimmed.
693    /// - email, URL, radio, color, image, file, link, wysiwyg, post object, relationship,
694    ///   taxonomy, user, repeater, group, flexible content, gallery, clone: the text
695    ///   [`Field::check_value`](crate::Field::check_value) returns. The structured kinds
696    ///   hold JSON text.
697    /// - number: an integer. Decimal: a number.
698    /// - checkbox: `true` or `false`; a checkbox is never blank.
699    /// - date: `"YYYY-MM-DD"`. Date-time: `"YYYY-MM-DD HH:MM:SS"`.
700    /// - password: the hash of the password ([`hash_password`](crate::hash_password)).
701    /// - a blank field that is not required: `null`.
702    ///
703    /// Each error in [`FieldErrors`] is keyed by the field's name, an owned `String`.
704    ///
705    /// A lookup, post object, relationship, taxonomy or user value is checked against
706    /// [`RuntimeData::options`] by the panel, which can read the database, and so is a media
707    /// id against the registered [`MediaLibrary`](crate::MediaLibrary).
708    pub fn validate(&self, form: &FormInput) -> Result<Row, FieldErrors> {
709        validate_fields(&self.resource.fields, form, true)
710    }
711
712    /// Turns the submitted form into a [`Row`] for an update. It is
713    /// [`validate`](Self::validate), except that:
714    ///
715    /// - a blank password is not an error: the row leaves its key out, so the stored
716    ///   password is kept;
717    /// - an optional field the form did not send at all ([`FormInput::has`] is false) is left
718    ///   out of the row, so its stored value is kept;
719    /// - an optional field sent blank is `null`, so clearing it on the edit form clears the
720    ///   stored value, as `#[derive(IgniteResource)]` does since 0.3.0;
721    /// - a checkbox the form did not send is `false`, because an unticked HTML checkbox sends
722    ///   nothing.
723    pub fn validate_update(&self, form: &FormInput) -> Result<Row, FieldErrors> {
724        validate_fields(&self.resource.fields, form, false)
725    }
726}
727
728/// The registry: the runtime resources in registration order, and the slugs reserved for
729/// static resources and for the panel's own pages.
730#[derive(Default)]
731struct Registry {
732    resources: Vec<Arc<RegisteredResource>>,
733    reserved: HashSet<String>,
734}
735
736static REGISTRY: RwLock<Option<Registry>> = RwLock::new(None);
737
738/// Runs `f` on the registry, read-only. The lock is never held across an `.await`: every
739/// caller is synchronous.
740fn read<T>(f: impl FnOnce(&Registry) -> T) -> T {
741    let guard = REGISTRY.read().unwrap_or_else(PoisonError::into_inner);
742    match guard.as_ref() {
743        Some(registry) => f(registry),
744        None => f(&Registry::default()),
745    }
746}
747
748/// Runs `f` on the registry, to change it.
749fn write<T>(f: impl FnOnce(&mut Registry) -> T) -> T {
750    let mut guard = REGISTRY.write().unwrap_or_else(PoisonError::into_inner);
751    f(guard.get_or_insert_with(Registry::default))
752}
753
754/// The longest field name a runtime resource accepts, in bytes, as for a MySQL or MariaDB
755/// column name. The limit is a validation rule: names are owned by their resource and freed
756/// with it.
757pub const MAX_FIELD_NAME: usize = 64;
758
759/// Whether `name` is a field name a runtime resource accepts: lowercase ASCII letters, digits
760/// and `_`, starting with a letter, at most [`MAX_FIELD_NAME`] bytes, as a column name is.
761fn valid_field_name(name: &str) -> bool {
762    name.len() <= MAX_FIELD_NAME
763        && name.bytes().next().is_some_and(|b| b.is_ascii_lowercase())
764        && name
765            .bytes()
766            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
767}
768
769/// Whether `slug` is one URL segment the panel's `/<slug>` routes match: lowercase ASCII
770/// letters, digits, `-` and `_`, as Filament's kebab-case slugs are.
771fn valid_slug(slug: &str) -> bool {
772    !slug.is_empty()
773        && slug
774            .bytes()
775            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_')
776}
777
778/// Adds a runtime resource to the panel. It shows in the navigation and the dashboard, and
779/// its list, forms and delete action answer at `/<mount>/<slug>`, from the next request on.
780/// Create its permissions (`<slug>.viewAny` and the others) in the same request with
781/// `ignite_panel::register_runtime_permissions`; otherwise the panel creates them on the next
782/// signed-in request.
783///
784/// Refuses a slug that is not valid, a slug that a static resource, another runtime resource
785/// or one of the panel's own pages (such as `login`) uses, and two fields with one name.
786pub fn register_runtime(resource: RuntimeResource) -> Result<(), RuntimeError> {
787    if !valid_slug(&resource.slug) {
788        return Err(RuntimeError::InvalidSlug(resource.slug));
789    }
790    if let Some(field) = resource.fields.iter().find(|f| !valid_field_name(&f.name)) {
791        return Err(RuntimeError::InvalidFieldName {
792            slug: resource.slug.clone(),
793            field: field.name.clone(),
794        });
795    }
796    let mut names = HashSet::new();
797    if let Some(field) = resource.fields.iter().find(|f| !names.insert(&f.name)) {
798        return Err(RuntimeError::DuplicateField {
799            slug: resource.slug.clone(),
800            field: field.name.clone(),
801        });
802    }
803    write(|registry| {
804        let slug = resource.slug.as_str();
805        if registry.reserved.contains(slug) || registry.resources.iter().any(|r| r.slug() == slug) {
806            return Err(RuntimeError::SlugTaken(resource.slug.clone()));
807        }
808        registry
809            .resources
810            .push(Arc::new(RegisteredResource { resource }));
811        Ok(())
812    })
813}
814
815/// Removes the runtime resource at `slug`. From the next request on, it is gone from the
816/// navigation and its routes answer 404. Its permission rows stay, so the grants come back
817/// if the resource is registered again.
818pub fn unregister_runtime(slug: &str) -> Result<(), RuntimeError> {
819    write(|registry| {
820        let before = registry.resources.len();
821        registry.resources.retain(|r| r.slug() != slug);
822        if registry.resources.len() == before {
823            Err(RuntimeError::NotRegistered(slug.to_string()))
824        } else {
825            Ok(())
826        }
827    })
828}
829
830/// The runtime resource at `slug`, if one is registered.
831pub fn runtime_resource(slug: &str) -> Option<Arc<RegisteredResource>> {
832    read(|registry| {
833        registry
834            .resources
835            .iter()
836            .find(|r| r.slug() == slug)
837            .cloned()
838    })
839}
840
841/// Every runtime resource, in registration order.
842pub fn runtime_resources() -> Vec<Arc<RegisteredResource>> {
843    read(|registry| registry.resources.clone())
844}
845
846/// Reserves `slugs`, so no runtime resource can take them. The panel reserves the slugs of
847/// its static resources and of its own pages when it is built. Reserving a slug twice is
848/// fine. Refuses, and reserves none, when a runtime resource already has one of them.
849pub fn reserve_slugs(slugs: &[&str]) -> Result<(), RuntimeError> {
850    write(|registry| {
851        if let Some(slug) = slugs
852            .iter()
853            .find(|slug| registry.resources.iter().any(|r| r.slug() == **slug))
854        {
855            return Err(RuntimeError::SlugTaken(slug.to_string()));
856        }
857        registry
858            .reserved
859            .extend(slugs.iter().map(|slug| slug.to_string()));
860        Ok(())
861    })
862}
863
864#[cfg(test)]
865mod tests {
866    use super::*;
867
868    struct NoData;
869
870    impl RuntimeData for NoData {
871        fn list<'a>(&'a self, _: &'a Database, _: &'a ListQuery) -> RuntimeFuture<'a, Page<Row>> {
872            unreachable!()
873        }
874        fn find<'a>(&'a self, _: &'a Database, _: i64) -> RuntimeFuture<'a, Option<Row>> {
875            unreachable!()
876        }
877        fn create<'a>(&'a self, _: &'a Database, _: Row) -> RuntimeFuture<'a, Row> {
878            unreachable!()
879        }
880        fn update<'a>(&'a self, _: &'a Database, _: i64, _: Row) -> RuntimeFuture<'a, Row> {
881            unreachable!()
882        }
883        fn delete<'a>(&'a self, _: &'a Database, _: i64) -> RuntimeFuture<'a, u64> {
884            unreachable!()
885        }
886    }
887
888    /// A resource with the fields `growth_title` and `growth_status`, whose label and
889    /// choices change with `n`.
890    fn edited(slug: &str, n: usize) -> RuntimeResource {
891        RuntimeResource::new(slug, format!("Title {n}"), format!("One {n}"), NoData)
892            .field(FieldDef {
893                name: "growth_title".into(),
894                label: format!("Title {n}"),
895                kind: FieldKindDef::Text,
896                required: n.is_multiple_of(2),
897            })
898            .field(FieldDef {
899                name: "growth_status".into(),
900                label: format!("Status {n}"),
901                kind: FieldKindDef::Select(vec![(format!("v{n}"), format!("Value {n}"))]),
902                required: false,
903            })
904            .column(ColumnDef {
905                key: "growth_title".into(),
906                label: format!("Column {n}"),
907                sortable: false,
908                searchable: false,
909            })
910    }
911
912    // Field names are owned by their resource: editing a definition a thousand times keeps
913    // nothing of the old ones, and an error is keyed by the field's own name.
914    #[test]
915    fn editing_a_definition_a_thousand_times_keeps_owned_names() {
916        register_runtime(edited("growth", 0)).expect("register");
917        for n in 1..=1000 {
918            unregister_runtime("growth").expect("unregister");
919            register_runtime(edited("growth", n)).expect("register again");
920            let registered = runtime_resource("growth").expect("registered");
921            let mut values = std::collections::HashMap::new();
922            values.insert("growth_status".to_string(), "not a choice".to_string());
923            let errors = registered
924                .validate(&FormInput::new(values.clone()))
925                .unwrap_err();
926            assert!(errors.contains_key("growth_status"));
927            let _ = registered.validate_update(&FormInput::new(values));
928        }
929        // The last registration is the only one the registry holds.
930        let registered = runtime_resource("growth").expect("registered");
931        assert_eq!(registered.title(), "Title 1000");
932        assert_eq!(
933            runtime_resources()
934                .iter()
935                .filter(|r| r.slug() == "growth")
936                .count(),
937            1
938        );
939        unregister_runtime("growth").expect("unregister");
940    }
941}