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