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