Skip to main content

tilo_resource/
kind.rs

1//! Resource types by kind, for a host that links no resource type's code at
2//! the call site.
3//!
4//! Every record names the kind of resource it holds (`ResourceType`, the
5//! `resource_type` of an app's definition, [`Resource::KIND`]). A host that
6//! works with whatever a workspace holds — an agent, a service, a script
7//! runner — looks the kind up here and gets everything the typed [`Resource`]
8//! offers, with the type erased: read a document's state, publish the tree
9//! the palette and agents see, register the decoders replay needs, and build a
10//! typed action from its JSON form. Each type registers once, as
11//! [`ResourceKind::of`]; an app framework adds who hosts it
12//! ([`ResourceKind::hosted_by`]) and what an open resource is called
13//! ([`ResourceKind::named`]).
14//!
15//! ```
16//! use tilo_resource::{Kinds, Model, ResourceKind, resource};
17//!
18//! #[derive(Model, Default)]
19//! pub struct Note { pub body: String }
20//!
21//! #[resource(kind = "example.note")]
22//! impl Note {
23//!     /// Edit the note.
24//!     #[action]
25//!     pub fn edit(&mut self, text: String) { self.body = text; }
26//! }
27//!
28//! fn main() {
29//!     let kinds = Kinds::new().with(ResourceKind::of::<Note>());
30//!     let note = kinds.get("example.note").unwrap();
31//!     let doc = tilo_resource::Doc::new();
32//!     let tree = note.publish("example.note", &doc).unwrap();
33//!     assert!(tree.actions.iter().any(|action| action.id == "edit"));
34//! }
35//! ```
36
37use std::any::Any;
38
39use tilo_actions::{ActionRegistry, EncodedAction};
40
41use crate::model::{Doc, ModelError};
42use crate::reader::Demand;
43use crate::resource::{self, Place, Resource, SearchEntry};
44
45/// One resource type with its type erased: what [`Resource`] offers, reached
46/// by the kind a record names. See the [module docs](self).
47#[derive(Clone, Copy)]
48pub struct ResourceKind {
49    kind: &'static str,
50    label: &'static str,
51    action_type: &'static str,
52    app: Option<(&'static str, &'static str)>,
53    version: u32,
54    read: fn(&Doc) -> Result<Box<dyn Any>, ModelError>,
55    /// [`Self::read`] with what the resource's search entries quote read too
56    /// ([`Resource::search_demand`]).
57    read_for_search: fn(&Doc) -> Result<Box<dyn Any>, ModelError>,
58    name: fn(&dyn Any) -> Option<String>,
59    publish: fn(&str, &str, &dyn Any) -> Option<tilo_actions::ResourceSpec>,
60    search: fn(&dyn Any) -> Option<Vec<SearchEntry>>,
61    to_json: fn(&dyn Any) -> Option<serde_json::Value>,
62    child: fn(&dyn Any, &Doc, &str) -> Option<tilo_actions::ResourceSpec>,
63    content: fn(&dyn Any, &Doc, Option<&str>) -> Result<serde_json::Value, String>,
64    reads_item: fn(&str) -> bool,
65    opens_as_item: fn(&str) -> bool,
66    register: fn(&mut ActionRegistry),
67    initialize: fn(&mut Doc) -> Result<(), ModelError>,
68    rewrite: fn(&mut Doc, u32) -> Result<(), ModelError>,
69    needs_migrate: fn(&Doc) -> bool,
70    encode: fn(serde_json::Value) -> Result<EncodedAction, String>,
71    lands: fn(&Doc, &EncodedAction) -> Option<Place>,
72}
73
74impl std::fmt::Debug for ResourceKind {
75    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76        f.debug_struct("ResourceKind")
77            .field("kind", &self.kind)
78            .field("app", &self.app)
79            .finish_non_exhaustive()
80    }
81}
82
83/// The app a resource kind names when the type declares no app of its own: a
84/// test's, a tool's, a host's.
85pub const DEFAULT_APP: &str = "so.tilo.app";
86
87// What a kind declared from a type's name alone answers: it publishes no
88// state of its own, since the record it names is published where it lives.
89
90fn unavailable(_doc: &Doc) -> Result<Box<dyn Any>, ModelError> {
91    Err(ModelError::Refused(
92        "a kind declared by name alone holds no record".to_owned(),
93    ))
94}
95
96fn no_name(_state: &dyn Any) -> Option<String> {
97    None
98}
99
100fn no_publish(_id: &str, _label: &str, _state: &dyn Any) -> Option<tilo_actions::ResourceSpec> {
101    None
102}
103
104fn no_search(_state: &dyn Any) -> Option<Vec<SearchEntry>> {
105    None
106}
107
108fn no_to_json(_state: &dyn Any) -> Option<serde_json::Value> {
109    None
110}
111
112fn no_child(_state: &dyn Any, _doc: &Doc, _id: &str) -> Option<tilo_actions::ResourceSpec> {
113    None
114}
115
116fn no_content(
117    _state: &dyn Any,
118    _doc: &Doc,
119    _item: Option<&str>,
120) -> Result<serde_json::Value, String> {
121    Err("a kind declared by name alone holds no record".to_owned())
122}
123
124fn no_item(_id: &str) -> bool {
125    false
126}
127
128fn no_register(_registry: &mut ActionRegistry) {}
129
130fn no_initialize(_doc: &mut Doc) -> Result<(), ModelError> {
131    Err(ModelError::Refused(
132        "a kind declared by name alone initialises no record".to_owned(),
133    ))
134}
135
136#[allow(
137    clippy::unnecessary_wraps,
138    reason = "a kind's rewrite answers as a type's migration does, whether or not it changes anything"
139)]
140fn no_rewrite(_doc: &mut Doc, _from: u32) -> Result<(), ModelError> {
141    Ok(())
142}
143
144fn no_needs_migrate(_doc: &Doc) -> bool {
145    false
146}
147
148fn no_encode(_action: serde_json::Value) -> Result<EncodedAction, String> {
149    Err("a kind declared by name alone has no action type of its own".to_owned())
150}
151
152fn no_lands(_doc: &Doc, _action: &EncodedAction) -> Option<Place> {
153    None
154}
155
156/// `a == b` as a `const fn`, which `str` comparison is not.
157#[allow(
158    clippy::indexing_slicing,
159    reason = "both sides are walked to the shorter one's length"
160)]
161const fn app_eq(a: &str, b: &str) -> bool {
162    let (a, b) = (a.as_bytes(), b.as_bytes());
163    if a.len() != b.len() {
164        return false;
165    }
166    let mut i = 0;
167    while i < a.len() {
168        if a[i] != b[i] {
169            return false;
170        }
171        i = i.saturating_add(1);
172    }
173    true
174}
175
176/// [`Resource::label`], for a kind declared from a type's name alone.
177#[allow(
178    clippy::unnecessary_wraps,
179    reason = "a kind names its records through a `Resource` method, whatever its state"
180)]
181fn naming<R: Resource>(_state: &dyn Any) -> Option<String> {
182    Some(R::label())
183}
184
185fn read<R: Resource>(doc: &Doc) -> Result<Box<dyn Any>, ModelError> {
186    R::read(doc).map(|state| Box::new(state) as Box<dyn Any>)
187}
188
189/// [`read`] as a reader of the resource reads it when it reads nothing of it yet: its state, and
190/// the parts [`Resource::load`] reads for a demand that asks for none. What search derives says
191/// what a record holds, so it reads the record the way a window's reader does.
192fn read_for_search<R: Resource>(doc: &Doc) -> Result<Box<dyn Any>, ModelError> {
193    let mut state = R::read(doc)?;
194    R::load(&mut state, doc, &Demand::none())?;
195    Ok(Box::new(state) as Box<dyn Any>)
196}
197
198fn resource_label<R: Resource>(state: &dyn Any) -> Option<String> {
199    state.downcast_ref::<R::State>().map(|_| R::label())
200}
201
202fn publish<R: Resource>(
203    id: &str,
204    label: &str,
205    state: &dyn Any,
206) -> Option<tilo_actions::ResourceSpec> {
207    state
208        .downcast_ref::<R::State>()
209        .map(|state| resource::publish::<R>(id, label, state))
210}
211
212fn child<R: Resource>(state: &dyn Any, doc: &Doc, id: &str) -> Option<tilo_actions::ResourceSpec> {
213    resource::child_by_id::<R>(state.downcast_ref::<R::State>()?, doc, id)
214}
215
216fn search<R: Resource>(state: &dyn Any) -> Option<Vec<SearchEntry>> {
217    state.downcast_ref::<R::State>().map(R::search)
218}
219
220/// A record's state as JSON, through its own model table
221/// ([`Model::to_json`](crate::Model::to_json)): what a view of it is offered.
222fn to_json<R: Resource>(state: &dyn Any) -> Option<serde_json::Value> {
223    let table = R::RESOURCE_TABLE?;
224    state
225        .downcast_ref::<R::State>()
226        .map(|state| crate::table::Run(table).to_json(state))
227}
228
229/// [`crate::read::content`] of a state this type reads.
230fn content<R: Resource>(
231    state: &dyn Any,
232    doc: &Doc,
233    item: Option<&str>,
234) -> Result<serde_json::Value, String> {
235    let state = state
236        .downcast_ref::<R::State>()
237        .ok_or_else(|| format!("{} state is another type", R::KIND))?;
238    crate::read::content::<R>(state, doc, item)
239}
240
241fn reads_item<R: Resource>(item: &str) -> bool {
242    R::RESOURCE_TABLE.is_some_and(|table| crate::table::reads_item(table, R::KIND, item))
243}
244
245/// Whether the published resource `id` is an item a window of `R` shows
246/// with an `open` of its own: an item of one of the record's collections, an
247/// item inside an item included, never a part beneath one (an issue's body,
248/// a channel's call) nor a derived place (`<kind>/derived/...`). The
249/// record's table says which; a resource without one counts
250/// `<kind>/<field>/<item>`.
251pub fn opens_as_item<R: Resource>(id: &str) -> bool {
252    match R::RESOURCE_TABLE {
253        Some(table) => crate::table::names_item(table, R::KIND, id),
254        None => crate::items::item_of_resource::<R>(id)
255            .is_some_and(|(_, item)| !item.as_str().contains('/')),
256    }
257}
258
259fn lands<R: Resource>(doc: &Doc, action: &EncodedAction) -> Option<Place> {
260    let action: R::Action = if action.type_id == R::ACTION_TYPE {
261        tilo_actions::decode_json(&action.payload).ok()?
262    } else if action.type_id == crate::group::group_type::<R>() {
263        tilo_actions::decode_payload::<crate::group::ActionGroup<R::Action>>(
264            &action.type_id,
265            &action.payload,
266        )
267        .ok()?
268        .actions
269        .pop()?
270    } else {
271        return None;
272    };
273    if !R::lands_on_state(&action) {
274        return None;
275    }
276    R::lands(&R::read(doc).ok()?, &action)
277}
278
279fn encode<R: Resource>(action: serde_json::Value) -> Result<EncodedAction, String> {
280    encode_in(crate::vocabulary::<R>(), action)
281}
282
283/// [`ResourceKind::encode`] of the resource `vocabulary`.
284fn encode_in(
285    vocabulary: &crate::Vocabulary,
286    action: serde_json::Value,
287) -> Result<EncodedAction, String> {
288    let mut arguments = serde_json::Map::new();
289    arguments.insert(resource::APPLY_PARAM.to_owned(), action);
290    let action = resource::build_action_of(
291        vocabulary,
292        resource::APPLY,
293        &arguments,
294        resource::origin_now_ms(),
295    )?;
296    action.encode().map_err(|error| error.to_string())
297}
298
299impl ResourceKind {
300    /// `R`, by its kind, published by the app it declares
301    /// ([`Resource::APP_ID`]) unless the caller hosts it for another
302    /// ([`Self::hosted_by`]).
303    #[must_use]
304    pub const fn of<R: Resource>() -> Self {
305        Self {
306            kind: R::KIND,
307            label: R::LABEL,
308            action_type: R::ACTION_TYPE,
309            app: Some((R::APP_ID, R::LABEL)),
310            version: R::VERSION,
311            read: read::<R>,
312            read_for_search: read_for_search::<R>,
313            name: resource_label::<R>,
314            publish: publish::<R>,
315            search: search::<R>,
316            to_json: to_json::<R>,
317            child: child::<R>,
318            content: content::<R>,
319            reads_item: reads_item::<R>,
320            opens_as_item: opens_as_item::<R>,
321            register: crate::group::register::<R>,
322            initialize: R::initialize,
323            rewrite: R::migrate,
324            needs_migrate: crate::evolution::needs_migrate::<R>,
325            encode: encode::<R>,
326            lands: lands::<R>,
327        }
328    }
329
330    /// The app that hosts records of this kind: its id, which permissions
331    /// name, and its title.
332    #[must_use]
333    pub const fn hosted_by(mut self, app_id: &'static str, title: &'static str) -> Self {
334        self.app = Some((app_id, title));
335        self
336    }
337
338    /// A kind for an effect vocabulary, which publishes no record of its own
339    /// and reaches state through the record an effect addresses: `kind` is the
340    /// operation its effects travel under and `app` the app that offers them.
341    /// What an effect's [`ActionRef`](crate::ActionRef) carries.
342    #[must_use]
343    pub const fn of_effect<V: crate::Effect>(
344        kind: &'static str,
345        label: &'static str,
346        app: &'static str,
347    ) -> Self {
348        Self {
349            kind,
350            label,
351            action_type: kind,
352            app: Some((app, label)),
353            version: 0,
354            read: unavailable,
355            read_for_search: unavailable,
356            name: no_name,
357            publish: no_publish,
358            search: no_search,
359            to_json: no_to_json,
360            child: no_child,
361            content: no_content,
362            reads_item: no_item,
363            opens_as_item: no_item,
364            register: no_register,
365            initialize: no_initialize,
366            rewrite: no_rewrite,
367            needs_migrate: no_needs_migrate,
368            encode: no_encode,
369            lands: no_lands,
370        }
371    }
372
373    /// `R`'s kind as the app `app` declares it: hosted by it, naming its
374    /// records as the resource itself does, and built from the type's name
375    /// alone — so a typed [`ActionRef`](crate::ActionRef) carries it as a
376    /// constant and [`ActionRef::key`](crate::ActionRef::key) names the app,
377    /// kind and action a control is bound against. Nothing is registered,
378    /// so it costs an app no initialisation.
379    #[must_use]
380    pub const fn declaring<R>(app: &'static str, title: &'static str) -> Self
381    where
382        R: Resource,
383    {
384        Self::of::<R>().hosted_by(app, title).named(naming::<R>)
385    }
386
387    /// [`Self::declaring`] for a kind built where `R` may still be defined:
388    /// the `kind`, `label` and `app` the declaration wrote. A resource
389    /// publishes its own kind from [`Self::of`], so a control bound by key
390    /// reads the same kind either way.
391    #[must_use]
392    pub const fn declared<R>(kind: &'static str, label: &'static str, app: &'static str) -> Self
393    where
394        R: Resource,
395    {
396        let mut declared = Self::of::<R>().hosted_by(app, label);
397        declared.kind = kind;
398        declared
399    }
400
401    /// The app this kind names its actions by: the one hosting it, else
402    /// [`DEFAULT_APP`] for a resource type that declares no app of its own.
403    #[must_use]
404    pub fn declaring_app(&self) -> &'static str {
405        self.app.map_or(DEFAULT_APP, |(id, _)| id)
406    }
407
408    /// Whether `app` is the app `declared` names, or the type declared none
409    /// and `app` is the [default](DEFAULT_APP). What a generated
410    /// [`ActionRef`](crate::ActionRef) asks at compile time before it carries
411    /// `app`, so a constant naming another app than its type's fails where it
412    /// is written rather than at the control that binds it.
413    #[must_use]
414    pub const fn declares(app: &str, declared: &str) -> bool {
415        if app_eq(declared, DEFAULT_APP) {
416            app_eq(app, DEFAULT_APP)
417        } else {
418            app_eq(app, declared)
419        }
420    }
421
422    /// What an open resource of this kind is called, read from its state
423    /// (a document's first heading). `name` answers `None` for a state of
424    /// another type. Defaults to the resource's [`Resource::LABEL`].
425    #[must_use]
426    pub const fn named(mut self, name: fn(&dyn Any) -> Option<String>) -> Self {
427        self.name = name;
428        self
429    }
430
431    /// The kind records of this type name, e.g. `"notes.notebook"`.
432    pub fn kind(&self) -> &'static str {
433        self.kind
434    }
435
436    /// The human name of one resource of this kind.
437    pub fn label(&self) -> &'static str {
438        self.label
439    }
440
441    /// The registry type id its actions replay under.
442    pub fn action_type(&self) -> &'static str {
443        self.action_type
444    }
445
446    /// Where `action` of this kind, just applied to `doc`, leaves the
447    /// member who took it ([`Resource::lands`]); `None` for an action
448    /// of another type or one that lands nowhere in particular. A group
449    /// lands where its last member does.
450    pub fn lands(&self, doc: &Doc, action: &EncodedAction) -> Option<Place> {
451        (self.lands)(doc, action)
452    }
453
454    /// The id of the app hosting it, when one registered it.
455    pub fn app_id(&self) -> Option<&'static str> {
456        self.app.map(|(id, _)| id)
457    }
458
459    /// The title of the app hosting it, when one registered it.
460    pub fn app_title(&self) -> Option<&'static str> {
461        self.app.map(|(_, title)| title)
462    }
463
464    /// The storage version the resource reads; an older record is brought
465    /// up to it when it opens ([`crate::evolution`]).
466    #[must_use]
467    pub fn version(&self) -> u32 {
468        self.version
469    }
470
471    /// The state views render, read from `doc`; downcast it to the
472    /// resource's `State` where the type is known.
473    ///
474    /// # Errors
475    /// Returns [`ModelError`] when the document does not hold this resource.
476    pub fn read(&self, doc: &Doc) -> Result<Box<dyn Any>, ModelError> {
477        (self.read)(doc)
478    }
479
480    /// [`Self::read`] as the state type the caller expects.
481    ///
482    /// # Errors
483    /// Returns [`ModelError`] when the document does not hold this resource
484    /// or its state is not an `S`.
485    pub fn read_as<S: 'static>(&self, doc: &Doc) -> Result<S, ModelError> {
486        self.read(doc)?
487            .downcast::<S>()
488            .map(|state| *state)
489            .map_err(|_| ModelError::invalid(format!("{} state is another type", self.kind)))
490    }
491
492    /// Whether `doc` holds a resource of this kind: its own `read` accepts
493    /// it.
494    pub fn holds(&self, doc: &Doc) -> bool {
495        self.read(doc).is_ok()
496    }
497
498    /// Whether `doc` holds a resource of this kind, or was kept before the
499    /// app changed its storage and is brought up to it when it opens: a
500    /// workspace still keeps the older document after a replica migrated its
501    /// own.
502    pub fn holds_or_older(&self, doc: &Doc) -> bool {
503        crate::evolution::stored_version(doc) < self.version || self.holds(doc)
504    }
505
506    /// What the open resource is called, from a state [`Self::read`]
507    /// returned.
508    pub fn name(&self, state: &dyn Any) -> String {
509        (self.name)(state).unwrap_or_else(|| self.label.to_owned())
510    }
511
512    /// The tree published for the resource `doc` holds, under `id`: every
513    /// declared and state-bound action, the generic `apply` and `group`
514    /// actions, its views and its nested resources — what
515    /// [`publish`](crate::publish) builds for the typed resource.
516    ///
517    /// # Errors
518    /// Returns [`ModelError`] when the document does not hold this resource.
519    pub fn publish(&self, id: &str, doc: &Doc) -> Result<tilo_actions::ResourceSpec, ModelError> {
520        let state = self.read(doc)?;
521        self.publish_state(id, state.as_ref())
522    }
523
524    /// Read one existing lazy child from the publishing resource's own resolver.
525    /// This returns metadata only and never creates or invokes the child.
526    pub fn child(
527        &self,
528        doc: &Doc,
529        id: &str,
530    ) -> Result<Option<tilo_actions::ResourceSpec>, ModelError> {
531        let state = self.read(doc)?;
532        Ok((self.child)(state.as_ref(), doc, id))
533    }
534
535    /// What `doc` holds, as JSON a caller can act on: the resource itself, or
536    /// with `item`, the part of it that id names — the reading a document
537    /// host offers a view (`docs/architecture/apps.md` §2). Read through the
538    /// type's own [`Resource::read_content`] where it answers reads, else
539    /// from the record's model tables, so a host that links no model type
540    /// still reads exactly what the app's process did.
541    ///
542    /// # Errors
543    /// Returns [`ModelError`] when the document does not hold this resource,
544    /// or a refusal naming why the part cannot be read.
545    pub fn content(&self, doc: &Doc, item: Option<&str>) -> Result<serde_json::Value, ModelError> {
546        let state = self.read(doc)?;
547        (self.content)(state.as_ref(), doc, item).map_err(ModelError::Refused)
548    }
549
550    /// Whether [`Self::content`] answers with `item`: the record publishes a
551    /// read of that part.
552    #[must_use]
553    pub fn reads_item(&self, item: &str) -> bool {
554        (self.reads_item)(item)
555    }
556
557    /// Whether the resource `id` is an item this kind's window shows with an
558    /// `open` of its own ([`opens_as_item`]).
559    #[must_use]
560    pub fn opens_as_item(&self, id: &str) -> bool {
561        (self.opens_as_item)(id)
562    }
563
564    /// [`Self::publish`] from a state [`Self::read`] returned.
565    ///
566    /// # Errors
567    /// Returns [`ModelError`] when `state` is not this resource's state.
568    pub fn publish_state(
569        &self,
570        id: &str,
571        state: &dyn Any,
572    ) -> Result<tilo_actions::ResourceSpec, ModelError> {
573        let name = self.name(state);
574        (self.publish)(id, &name, state)
575            .ok_or_else(|| ModelError::invalid(format!("{} state is another type", self.kind)))
576    }
577
578    /// What the state a [`Self::read`] returned is, as JSON: the reading a
579    /// view of the resource is offered, where no better adapter answers.
580    ///
581    /// # Errors
582    /// Returns [`ModelError`] when `state` is not this resource's state.
583    pub fn to_json(&self, state: &dyn Any) -> Result<serde_json::Value, ModelError> {
584        (self.to_json)(state)
585            .ok_or_else(|| ModelError::invalid(format!("{} state is another type", self.kind)))
586    }
587
588    /// Entries for the system search index.
589    ///
590    /// # Errors
591    /// Returns [`ModelError`] when the document does not hold this resource.
592    pub fn search(&self, doc: &Doc) -> Result<Vec<SearchEntry>, ModelError> {
593        let state = (self.read_for_search)(doc)?;
594        (self.search)(state.as_ref())
595            .ok_or_else(|| ModelError::invalid(format!("{} state is another type", self.kind)))
596    }
597
598    /// Register what a replica of this kind replays: the resource's actions
599    /// and groups of them.
600    pub fn register(&self, registry: &mut ActionRegistry) {
601        (self.register)(registry);
602    }
603
604    /// Write a brand-new record's genesis ([`Resource::initialize`]).
605    pub fn initialize(&self, doc: &mut Doc) -> Result<(), ModelError> {
606        (self.initialize)(doc)
607    }
608
609    /// The app's own rewrite of a record of this kind from the version it stood at
610    /// ([`crate::evolution::rewrite`]), which follows its derived steps.
611    ///
612    /// # Errors
613    /// Returns the migration's error.
614    pub fn rewrite(&self, doc: &mut Doc, from: u32) -> Result<(), ModelError> {
615        (self.rewrite)(doc, from)
616    }
617
618    /// Whether `doc` is older than this kind: its chain of steps stops short of
619    /// this kind's version.
620    #[must_use]
621    pub fn needs_migrate(&self, doc: &Doc) -> bool {
622        (self.needs_migrate)(doc)
623    }
624
625    /// One typed action from its JSON form, encoded for replay — read as
626    /// the generic `apply` action reads it, so a value naming a declared
627    /// action is checked against that declaration.
628    pub fn encode(&self, action: serde_json::Value) -> Result<EncodedAction, String> {
629        (self.encode)(action)
630    }
631}
632
633/// The resource types a host knows, by kind. See the [module docs](self).
634#[derive(Clone, Debug, Default)]
635pub struct Kinds {
636    kinds: Vec<ResourceKind>,
637}
638
639impl Kinds {
640    /// No types.
641    #[must_use]
642    pub const fn new() -> Self {
643        Self { kinds: Vec::new() }
644    }
645
646    /// These and `kind`. A kind registered again replaces the earlier entry.
647    #[must_use]
648    pub fn with(mut self, kind: ResourceKind) -> Self {
649        self.insert(kind);
650        self
651    }
652
653    /// Add `kind`, replacing an earlier entry of the same kind.
654    pub fn insert(&mut self, kind: ResourceKind) {
655        match self.kinds.iter_mut().find(|known| known.kind == kind.kind) {
656            Some(known) => *known = kind,
657            None => self.kinds.push(kind),
658        }
659    }
660
661    /// The type records of `kind` hold.
662    pub fn get(&self, kind: &str) -> Option<&ResourceKind> {
663        self.kinds.iter().find(|known| known.kind == kind)
664    }
665
666    /// The type the app `app_id` hosts.
667    pub fn hosted_by(&self, app_id: &str) -> Option<&ResourceKind> {
668        self.kinds
669            .iter()
670            .find(|known| known.app_id() == Some(app_id))
671    }
672
673    /// Every type, in registration order.
674    pub fn iter(&self) -> impl Iterator<Item = &ResourceKind> {
675        self.kinds.iter()
676    }
677
678    /// The decoders of every type, in one registry: what a host replaying
679    /// any of their records needs.
680    pub fn registry(&self) -> ActionRegistry {
681        let mut registry = ActionRegistry::new();
682        for kind in &self.kinds {
683            kind.register(&mut registry);
684        }
685        registry
686    }
687}