use std::any::Any;
use tilo_actions::{ActionRegistry, EncodedAction};
use crate::model::{Doc, ModelError};
use crate::reader::Demand;
use crate::resource::{self, Place, Resource, SearchEntry};
#[derive(Clone, Copy)]
pub struct ResourceKind {
kind: &'static str,
label: &'static str,
action_type: &'static str,
app: Option<(&'static str, &'static str)>,
version: u32,
read: fn(&Doc) -> Result<Box<dyn Any>, ModelError>,
read_for_search: fn(&Doc) -> Result<Box<dyn Any>, ModelError>,
name: fn(&dyn Any) -> Option<String>,
publish: fn(&str, &str, &dyn Any) -> Option<tilo_actions::ResourceSpec>,
search: fn(&dyn Any) -> Option<Vec<SearchEntry>>,
to_json: fn(&dyn Any) -> Option<serde_json::Value>,
child: fn(&dyn Any, &Doc, &str) -> Option<tilo_actions::ResourceSpec>,
content: fn(&dyn Any, &Doc, Option<&str>) -> Result<serde_json::Value, String>,
reads_item: fn(&str) -> bool,
opens_as_item: fn(&str) -> bool,
register: fn(&mut ActionRegistry),
initialize: fn(&mut Doc) -> Result<(), ModelError>,
migrate: fn(&mut Doc) -> Result<bool, ModelError>,
needs_migrate: fn(&Doc) -> bool,
encode: fn(serde_json::Value) -> Result<EncodedAction, String>,
lands: fn(&Doc, &EncodedAction) -> Option<Place>,
}
impl std::fmt::Debug for ResourceKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ResourceKind")
.field("kind", &self.kind)
.field("app", &self.app)
.finish_non_exhaustive()
}
}
pub const DEFAULT_APP: &str = "so.tilo.app";
fn unavailable(_doc: &Doc) -> Result<Box<dyn Any>, ModelError> {
Err(ModelError::Refused(
"a kind declared by name alone holds no record".to_owned(),
))
}
fn no_name(_state: &dyn Any) -> Option<String> {
None
}
fn no_publish(_id: &str, _label: &str, _state: &dyn Any) -> Option<tilo_actions::ResourceSpec> {
None
}
fn no_search(_state: &dyn Any) -> Option<Vec<SearchEntry>> {
None
}
fn no_to_json(_state: &dyn Any) -> Option<serde_json::Value> {
None
}
fn no_child(_state: &dyn Any, _doc: &Doc, _id: &str) -> Option<tilo_actions::ResourceSpec> {
None
}
fn no_content(
_state: &dyn Any,
_doc: &Doc,
_item: Option<&str>,
) -> Result<serde_json::Value, String> {
Err("a kind declared by name alone holds no record".to_owned())
}
fn no_item(_id: &str) -> bool {
false
}
fn no_register(_registry: &mut ActionRegistry) {}
fn no_initialize(_doc: &mut Doc) -> Result<(), ModelError> {
Err(ModelError::Refused(
"a kind declared by name alone initialises no record".to_owned(),
))
}
#[allow(
clippy::unnecessary_wraps,
reason = "a kind's migration answers as a type's migration does, whether or not it changes anything"
)]
fn no_migrate(_doc: &mut Doc) -> Result<bool, ModelError> {
Ok(false)
}
fn no_needs_migrate(_doc: &Doc) -> bool {
false
}
fn no_encode(_action: serde_json::Value) -> Result<EncodedAction, String> {
Err("a kind declared by name alone has no action type of its own".to_owned())
}
fn no_lands(_doc: &Doc, _action: &EncodedAction) -> Option<Place> {
None
}
#[allow(
clippy::indexing_slicing,
reason = "both sides are walked to the shorter one's length"
)]
const fn app_eq(a: &str, b: &str) -> bool {
let (a, b) = (a.as_bytes(), b.as_bytes());
if a.len() != b.len() {
return false;
}
let mut i = 0;
while i < a.len() {
if a[i] != b[i] {
return false;
}
i = i.saturating_add(1);
}
true
}
#[allow(
clippy::unnecessary_wraps,
reason = "a kind names its records through a `Resource` method, whatever its state"
)]
fn naming<R: Resource>(_state: &dyn Any) -> Option<String> {
Some(R::label())
}
fn read<R: Resource>(doc: &Doc) -> Result<Box<dyn Any>, ModelError> {
R::read(doc).map(|state| Box::new(state) as Box<dyn Any>)
}
fn read_for_search<R: Resource>(doc: &Doc) -> Result<Box<dyn Any>, ModelError> {
let mut state = R::read(doc)?;
R::load(&mut state, doc, &Demand::none())?;
Ok(Box::new(state) as Box<dyn Any>)
}
fn resource_label<R: Resource>(state: &dyn Any) -> Option<String> {
state.downcast_ref::<R::State>().map(|_| R::label())
}
fn publish<R: Resource>(
id: &str,
label: &str,
state: &dyn Any,
) -> Option<tilo_actions::ResourceSpec> {
state
.downcast_ref::<R::State>()
.map(|state| resource::publish::<R>(id, label, state))
}
fn child<R: Resource>(state: &dyn Any, doc: &Doc, id: &str) -> Option<tilo_actions::ResourceSpec> {
resource::child_by_id::<R>(state.downcast_ref::<R::State>()?, doc, id)
}
fn search<R: Resource>(state: &dyn Any) -> Option<Vec<SearchEntry>> {
state.downcast_ref::<R::State>().map(R::search)
}
fn to_json<R: Resource>(state: &dyn Any) -> Option<serde_json::Value> {
let table = R::RESOURCE_TABLE?;
state
.downcast_ref::<R::State>()
.map(|state| crate::table::Run(table).to_json(state))
}
fn content<R: Resource>(
state: &dyn Any,
doc: &Doc,
item: Option<&str>,
) -> Result<serde_json::Value, String> {
let state = state
.downcast_ref::<R::State>()
.ok_or_else(|| format!("{} state is another type", R::KIND))?;
crate::read::content::<R>(state, doc, item)
}
fn reads_item<R: Resource>(item: &str) -> bool {
R::RESOURCE_TABLE.is_some_and(|table| crate::table::reads_item(table, R::KIND, item))
}
pub fn opens_as_item<R: Resource>(id: &str) -> bool {
match R::RESOURCE_TABLE {
Some(table) => crate::table::names_item(table, R::KIND, id),
None => crate::items::item_of_resource::<R>(id)
.is_some_and(|(_, item)| !item.as_str().contains('/')),
}
}
fn lands<R: Resource>(doc: &Doc, action: &EncodedAction) -> Option<Place> {
let action: R::Action = if action.type_id == R::ACTION_TYPE {
tilo_actions::decode_json(&action.payload).ok()?
} else if action.type_id == crate::group::group_type::<R>() {
tilo_actions::decode_payload::<crate::group::ActionGroup<R::Action>>(
&action.type_id,
&action.payload,
)
.ok()?
.actions
.pop()?
} else {
return None;
};
if !R::lands_on_state(&action) {
return None;
}
R::lands(&R::read(doc).ok()?, &action)
}
fn encode<R: Resource>(action: serde_json::Value) -> Result<EncodedAction, String> {
encode_in(crate::vocabulary::<R>(), action)
}
fn encode_in(
vocabulary: &crate::Vocabulary,
action: serde_json::Value,
) -> Result<EncodedAction, String> {
let mut arguments = serde_json::Map::new();
arguments.insert(resource::APPLY_PARAM.to_owned(), action);
let action = resource::build_action_of(
vocabulary,
resource::APPLY,
&arguments,
resource::origin_now_ms(),
)?;
action.encode().map_err(|error| error.to_string())
}
impl ResourceKind {
#[must_use]
pub const fn of<R: Resource>() -> Self {
Self {
kind: R::KIND,
label: R::LABEL,
action_type: R::ACTION_TYPE,
app: Some((R::APP_ID, R::LABEL)),
version: R::VERSION,
read: read::<R>,
read_for_search: read_for_search::<R>,
name: resource_label::<R>,
publish: publish::<R>,
search: search::<R>,
to_json: to_json::<R>,
child: child::<R>,
content: content::<R>,
reads_item: reads_item::<R>,
opens_as_item: opens_as_item::<R>,
register: crate::group::register::<R>,
initialize: R::initialize,
migrate: crate::evolution::migrate::<R>,
needs_migrate: crate::evolution::needs_migrate::<R>,
encode: encode::<R>,
lands: lands::<R>,
}
}
#[must_use]
pub const fn hosted_by(mut self, app_id: &'static str, title: &'static str) -> Self {
self.app = Some((app_id, title));
self
}
#[must_use]
pub const fn of_effect<V: crate::Effect>(
kind: &'static str,
label: &'static str,
app: &'static str,
) -> Self {
Self {
kind,
label,
action_type: kind,
app: Some((app, label)),
version: 0,
read: unavailable,
read_for_search: unavailable,
name: no_name,
publish: no_publish,
search: no_search,
to_json: no_to_json,
child: no_child,
content: no_content,
reads_item: no_item,
opens_as_item: no_item,
register: no_register,
initialize: no_initialize,
migrate: no_migrate,
needs_migrate: no_needs_migrate,
encode: no_encode,
lands: no_lands,
}
}
#[must_use]
pub const fn declaring<R>(app: &'static str, title: &'static str) -> Self
where
R: Resource,
{
Self::of::<R>().hosted_by(app, title).named(naming::<R>)
}
#[must_use]
pub const fn declared<R>(kind: &'static str, label: &'static str, app: &'static str) -> Self
where
R: Resource,
{
let mut declared = Self::of::<R>().hosted_by(app, label);
declared.kind = kind;
declared
}
#[must_use]
pub fn declaring_app(&self) -> &'static str {
self.app.map_or(DEFAULT_APP, |(id, _)| id)
}
#[must_use]
pub const fn declares(app: &str, declared: &str) -> bool {
if app_eq(declared, DEFAULT_APP) {
app_eq(app, DEFAULT_APP)
} else {
app_eq(app, declared)
}
}
#[must_use]
pub const fn named(mut self, name: fn(&dyn Any) -> Option<String>) -> Self {
self.name = name;
self
}
pub fn kind(&self) -> &'static str {
self.kind
}
pub fn label(&self) -> &'static str {
self.label
}
pub fn action_type(&self) -> &'static str {
self.action_type
}
pub fn lands(&self, doc: &Doc, action: &EncodedAction) -> Option<Place> {
(self.lands)(doc, action)
}
pub fn app_id(&self) -> Option<&'static str> {
self.app.map(|(id, _)| id)
}
pub fn app_title(&self) -> Option<&'static str> {
self.app.map(|(_, title)| title)
}
#[must_use]
pub fn version(&self) -> u32 {
self.version
}
pub fn read(&self, doc: &Doc) -> Result<Box<dyn Any>, ModelError> {
(self.read)(doc)
}
pub fn read_as<S: 'static>(&self, doc: &Doc) -> Result<S, ModelError> {
self.read(doc)?
.downcast::<S>()
.map(|state| *state)
.map_err(|_| ModelError::invalid(format!("{} state is another type", self.kind)))
}
pub fn holds(&self, doc: &Doc) -> bool {
self.read(doc).is_ok()
}
pub fn holds_or_older(&self, doc: &Doc) -> bool {
crate::evolution::stored_version(doc) < self.version || self.holds(doc)
}
pub fn name(&self, state: &dyn Any) -> String {
(self.name)(state).unwrap_or_else(|| self.label.to_owned())
}
pub fn publish(&self, id: &str, doc: &Doc) -> Result<tilo_actions::ResourceSpec, ModelError> {
let state = self.read(doc)?;
self.publish_state(id, state.as_ref())
}
pub fn child(
&self,
doc: &Doc,
id: &str,
) -> Result<Option<tilo_actions::ResourceSpec>, ModelError> {
let state = self.read(doc)?;
Ok((self.child)(state.as_ref(), doc, id))
}
pub fn content(&self, doc: &Doc, item: Option<&str>) -> Result<serde_json::Value, ModelError> {
let state = self.read(doc)?;
(self.content)(state.as_ref(), doc, item).map_err(ModelError::Refused)
}
#[must_use]
pub fn reads_item(&self, item: &str) -> bool {
(self.reads_item)(item)
}
#[must_use]
pub fn opens_as_item(&self, id: &str) -> bool {
(self.opens_as_item)(id)
}
pub fn publish_state(
&self,
id: &str,
state: &dyn Any,
) -> Result<tilo_actions::ResourceSpec, ModelError> {
let name = self.name(state);
(self.publish)(id, &name, state)
.ok_or_else(|| ModelError::invalid(format!("{} state is another type", self.kind)))
}
pub fn to_json(&self, state: &dyn Any) -> Result<serde_json::Value, ModelError> {
(self.to_json)(state)
.ok_or_else(|| ModelError::invalid(format!("{} state is another type", self.kind)))
}
pub fn search(&self, doc: &Doc) -> Result<Vec<SearchEntry>, ModelError> {
let state = (self.read_for_search)(doc)?;
(self.search)(state.as_ref())
.ok_or_else(|| ModelError::invalid(format!("{} state is another type", self.kind)))
}
pub fn register(&self, registry: &mut ActionRegistry) {
(self.register)(registry);
}
pub fn initialize(&self, doc: &mut Doc) -> Result<(), ModelError> {
(self.initialize)(doc)
}
pub fn migrate(&self, doc: &mut Doc) -> Result<bool, ModelError> {
(self.migrate)(doc)
}
#[must_use]
pub fn needs_migrate(&self, doc: &Doc) -> bool {
(self.needs_migrate)(doc)
}
pub fn encode(&self, action: serde_json::Value) -> Result<EncodedAction, String> {
(self.encode)(action)
}
}
#[derive(Clone, Debug, Default)]
pub struct Kinds {
kinds: Vec<ResourceKind>,
}
impl Kinds {
#[must_use]
pub const fn new() -> Self {
Self { kinds: Vec::new() }
}
#[must_use]
pub fn with(mut self, kind: ResourceKind) -> Self {
self.insert(kind);
self
}
pub fn insert(&mut self, kind: ResourceKind) {
match self.kinds.iter_mut().find(|known| known.kind == kind.kind) {
Some(known) => *known = kind,
None => self.kinds.push(kind),
}
}
pub fn get(&self, kind: &str) -> Option<&ResourceKind> {
self.kinds.iter().find(|known| known.kind == kind)
}
pub fn hosted_by(&self, app_id: &str) -> Option<&ResourceKind> {
self.kinds
.iter()
.find(|known| known.app_id() == Some(app_id))
}
pub fn iter(&self) -> impl Iterator<Item = &ResourceKind> {
self.kinds.iter()
}
pub fn registry(&self) -> ActionRegistry {
let mut registry = ActionRegistry::new();
for kind in &self.kinds {
kind.register(&mut registry);
}
registry
}
}