use std::collections::BTreeMap;
use tilo_actions::{
ActionSpec, Exports, ResourcePresentation, ResourceSemanticIdentity, ResourceSpec,
};
use crate::Effect;
#[derive(Clone, Default)]
pub struct RowBindings {
arguments: BTreeMap<&'static str, Vec<serde_json::Map<String, serde_json::Value>>>,
defaults: BTreeMap<&'static str, Vec<&'static str>>,
choices: BTreeMap<(&'static str, &'static str), Vec<String>>,
specs: Vec<ActionSpec>,
}
impl std::fmt::Debug for RowBindings {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("RowBindings")
.field("arguments", &self.arguments)
.field("defaults", &self.defaults)
.field("choices", &self.choices)
.field(
"specs",
&self
.specs
.iter()
.map(|spec| spec.id.as_str())
.collect::<Vec<_>>(),
)
.finish()
}
}
impl RowBindings {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn bind<R, A, I, K>(self, effect: crate::ActionRef<R, A>, arguments: I) -> Self
where
I: IntoIterator<Item = (K, serde_json::Value)>,
K: Into<String>,
{
self.bind_id(effect.id, arguments)
}
#[must_use]
pub fn bind_id<I, K>(self, effect: &'static str, arguments: I) -> Self
where
I: IntoIterator<Item = (K, serde_json::Value)>,
K: Into<String>,
{
let mut arguments = arguments
.into_iter()
.map(|(name, value)| (name.into(), value));
self.offer_arguments(effect, &mut arguments)
}
#[inline(never)]
fn offer_arguments(
mut self,
effect: &'static str,
arguments: &mut dyn Iterator<Item = (String, serde_json::Value)>,
) -> Self {
self.arguments
.entry(effect)
.or_default()
.push(arguments.collect());
self
}
#[must_use]
pub fn bind_asking<R, A, I, K>(
self,
effect: crate::ActionRef<R, A>,
arguments: I,
asking: &[&'static str],
) -> Self
where
I: IntoIterator<Item = (K, serde_json::Value)>,
K: Into<String>,
{
self.bind_asking_id(effect.id, arguments, asking)
}
#[must_use]
pub fn bind_asking_id<I, K>(
self,
effect: &'static str,
arguments: I,
asking: &[&'static str],
) -> Self
where
I: IntoIterator<Item = (K, serde_json::Value)>,
K: Into<String>,
{
self.bind_id(effect, arguments).ask_defaults(effect, asking)
}
#[inline(never)]
fn ask_defaults(mut self, effect: &'static str, asking: &[&'static str]) -> Self {
let asked = self.defaults.entry(effect).or_default();
for name in asking {
if !asked.contains(name) {
asked.push(name);
}
}
self
}
#[must_use]
pub fn offer<R, A>(self, effect: crate::ActionRef<R, A>) -> Self {
self.offer_id(effect.id)
}
#[must_use]
pub fn offer_id(mut self, effect: &'static str) -> Self {
self.arguments
.entry(effect)
.or_default()
.push(serde_json::Map::default());
self
}
#[must_use]
pub fn extended(mut self, other: &Self) -> Self {
for (effect, arguments) in &other.arguments {
self.arguments
.entry(effect)
.or_default()
.extend(arguments.iter().cloned());
}
for (effect, asking) in &other.defaults {
self = self.ask_defaults(effect, asking);
}
self.choices.extend(other.choices.clone());
self.specs.extend(other.specs.iter().cloned());
self
}
#[must_use]
pub fn choices<R, A>(
self,
effect: crate::ActionRef<R, A>,
param: &'static str,
choices: impl IntoIterator<Item = String>,
) -> Self {
self.chosen_by(effect.id, param, choices.into_iter().collect())
}
#[inline(never)]
fn chosen_by(
mut self,
effect: &'static str,
param: &'static str,
choices: Vec<String>,
) -> Self {
self.choices.insert((effect, param), choices);
self
}
#[must_use]
pub fn spec(mut self, spec: ActionSpec) -> Self {
self.specs.push(spec);
self
}
#[must_use]
pub fn arguments(&self, effect: &str) -> Option<&[serde_json::Map<String, serde_json::Value>]> {
self.arguments.get(effect).map(Vec::as_slice)
}
#[must_use]
pub(crate) fn chosen(&self, effect: &str, param: &str) -> Option<&[String]> {
self.choices
.iter()
.find(|((id, name), _)| *id == effect && *name == param)
.map(|(_, values)| values.as_slice())
}
#[must_use]
pub(crate) fn asks(&self, effect: &str) -> &[&'static str] {
self.defaults.get(effect).map_or(&[], Vec::as_slice)
}
#[must_use]
pub(crate) fn declared(&self) -> &[ActionSpec] {
&self.specs
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.arguments.is_empty() && self.specs.is_empty()
}
}
#[must_use]
pub fn typed_resource<R: crate::words::RowType>(
id: impl Into<String>,
label: impl Into<String>,
) -> ResourceSpec {
ResourceSpec::new(id, R::KIND, label).with_type(R::words())
}
#[derive(Clone)]
pub struct LiveRow {
resource: std::rc::Rc<ResourceSpec>,
}
impl LiveRow {
#[doc(hidden)]
pub fn new(id: impl Into<String>, kind: impl Into<String>, label: impl Into<String>) -> Self {
Self {
resource: std::rc::Rc::new(ResourceSpec::new(id, kind, label)),
}
}
pub fn typed<R: crate::words::RowType>(
id: impl Into<String>,
label: impl Into<String>,
) -> Self {
typed_row(&RowTypeTable::of::<R>(), id.into(), label.into(), None)
}
pub fn typed_with<R: crate::words::RowType>(
id: impl Into<String>,
label: impl Into<String>,
bindings: &RowBindings,
) -> Self {
typed_row(
&RowTypeTable::of::<R>(),
id.into(),
label.into(),
Some(bindings),
)
}
#[must_use]
pub fn semantic_identity(mut self, identity: ResourceSemanticIdentity) -> Self {
std::rc::Rc::make_mut(&mut self.resource).semantic_identity =
identity.is_valid().then_some(identity);
self
}
#[must_use]
pub fn declared(resource: ResourceSpec) -> Self {
assert!(
resource.resource_type.is_some(),
"a row is an entity of a declared type, and `{}` names none",
resource.id.as_str()
);
Self {
resource: std::rc::Rc::new(crate::share::resolved_outside_document(resource)),
}
}
#[must_use]
pub fn vocabulary<E: crate::Effect>(mut self) -> Self {
for spec in E::specs() {
self = self.operation(spec);
}
self
}
#[doc(hidden)]
#[must_use]
pub fn operation(mut self, operation: ActionSpec) -> Self {
if crate::share::admits_outside_document(&operation, self.id()) {
std::rc::Rc::make_mut(&mut self.resource)
.actions
.push(operation);
}
self
}
#[must_use]
pub fn presentation(mut self, presentation: ResourcePresentation) -> Self {
std::rc::Rc::make_mut(&mut self.resource).presentation = Some(presentation);
self
}
#[doc(hidden)]
#[must_use]
pub fn effect<E: Effect>(self, effect: &E) -> Self {
self.operation(effect.bound())
}
#[must_use]
pub fn labelled<E, A>(
mut self,
effect: crate::ActionRef<E, A>,
label: impl Into<String>,
) -> Self {
let label = label.into();
let actions = &mut std::rc::Rc::make_mut(&mut self.resource).actions;
if let Some(spec) = actions.iter_mut().find(|spec| spec.id == effect.id) {
spec.type_mut().label = label;
}
self
}
#[must_use]
pub fn prefilled<R, A, I, K>(mut self, effect: crate::ActionRef<R, A>, values: I) -> Self
where
I: IntoIterator<Item = (K, serde_json::Value)>,
K: Into<String>,
{
let values: Vec<(String, serde_json::Value)> = values
.into_iter()
.map(|(name, value)| (name.into(), value))
.collect();
for spec in std::rc::Rc::make_mut(&mut self.resource)
.actions
.iter_mut()
.filter(|spec| spec.id == effect.id)
{
for (name, value) in &values {
spec.prefilled(name, value.clone());
}
}
self
}
#[must_use]
pub fn view(mut self, view: tilo_actions::ResourceViewSpec) -> Self {
std::rc::Rc::make_mut(&mut self.resource).views.push(view);
self
}
#[must_use]
pub fn unavailable(
self,
effect: &str,
code: impl Into<String>,
reason: impl Into<String>,
) -> Self {
self.amend(effect, move |spec| spec.unavailable(code, reason))
}
#[must_use]
pub fn describe(self, effect: &str, description: impl Into<String>) -> Self {
self.amend(effect, move |spec| spec.with_description(description))
}
fn amend(mut self, effect: &str, change: impl FnOnce(ActionSpec) -> ActionSpec) -> Self {
let actions = &mut std::rc::Rc::make_mut(&mut self.resource).actions;
if let Some(at) = actions.iter().position(|action| action.id == effect) {
let spec = actions.remove(at);
actions.insert(at, change(spec));
}
self
}
#[must_use]
pub fn row(mut self, row: LiveRow) -> Self {
std::rc::Rc::make_mut(&mut self.resource)
.children
.push(std::rc::Rc::unwrap_or_clone(row.resource));
self
}
pub fn id(&self) -> &str {
self.resource.id.as_str()
}
#[must_use]
pub fn find(&self, id: &str) -> Option<Self> {
fn walk<'a>(resource: &'a ResourceSpec, id: &str) -> Option<&'a ResourceSpec> {
if resource.id.0 == id {
return Some(resource);
}
resource.children.iter().find_map(|child| walk(child, id))
}
if self.resource.id.0 == id {
return Some(self.clone());
}
walk(&self.resource, id).map(|found| Self {
resource: std::rc::Rc::new(found.clone()),
})
}
#[must_use]
pub fn operations(&self) -> &[ActionSpec] {
&self.resource.actions
}
pub fn into_resource(self) -> ResourceSpec {
let mut resource = std::rc::Rc::unwrap_or_clone(self.resource);
crate::share::offer_tree(&mut resource);
resource
}
pub fn same_row(&self, other: &Self) -> bool {
std::rc::Rc::ptr_eq(&self.resource, &other.resource)
}
}
struct RowTypeTable {
kind: &'static str,
words: fn() -> tilo_actions::ResourceType,
effects: fn(&crate::Id) -> Vec<ActionSpec>,
effects_with: fn(&crate::Id, &RowBindings) -> Vec<ActionSpec>,
}
impl RowTypeTable {
fn of<R: crate::words::RowType>() -> Self {
Self {
kind: R::KIND,
words: R::words,
effects: R::effects,
effects_with: R::effects_with,
}
}
}
#[inline(never)]
fn typed_row(
kind: &RowTypeTable,
id: String,
label: String,
bindings: Option<&RowBindings>,
) -> LiveRow {
let named = crate::Id::from_raw(id.clone());
let operations = match bindings {
Some(bindings) => {
let mut operations = (kind.effects_with)(&named, bindings);
operations.extend(bindings.declared().iter().cloned());
operations
}
None => (kind.effects)(&named),
};
let resource = ResourceSpec::new(id, kind.kind, label).with_type((kind.words)());
let mut row = LiveRow {
resource: std::rc::Rc::new(resource),
};
for operation in operations {
row = row.operation(operation);
}
row
}
impl Exports for LiveRow {
fn exported(&self) -> &ResourceSpec {
&self.resource
}
}
pub struct Handle<R> {
address: String,
row: std::marker::PhantomData<fn() -> R>,
}
impl<R: crate::words::RowType> Handle<R> {
#[must_use]
pub fn new(address: impl Into<String>) -> Self {
Self {
address: address.into(),
row: std::marker::PhantomData,
}
}
#[must_use]
pub fn address(&self) -> &str {
&self.address
}
#[must_use]
pub fn action(&self, action: &str) -> tilo_actions::ActionAddress {
tilo_actions::ActionAddress::new(self.address.clone(), action)
}
}
impl<R> Clone for Handle<R> {
fn clone(&self) -> Self {
Self {
address: self.address.clone(),
row: std::marker::PhantomData,
}
}
}
impl<R> Default for Handle<R> {
fn default() -> Self {
Self {
address: String::new(),
row: std::marker::PhantomData,
}
}
}
impl<R> PartialEq for Handle<R> {
fn eq(&self, other: &Self) -> bool {
self.address == other.address
}
}
impl<R> Eq for Handle<R> {}
impl<R> std::fmt::Debug for Handle<R> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("Handle").field(&self.address).finish()
}
}
impl<R> serde::Serialize for Handle<R> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&self.address)
}
}
impl<'de, R> serde::Deserialize<'de> for Handle<R> {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Ok(Self {
address: String::deserialize(deserializer)?,
row: std::marker::PhantomData,
})
}
}
impl<R: crate::words::RowType> crate::JsonSchema for Handle<R> {
fn json_schema() -> serde_json::Value {
tilo_actions::params::picked_address_schema(R::KIND)
}
fn field_type(_: &mut crate::TypeSet) -> crate::FieldType {
crate::FieldType::Resource(R::KIND.to_owned())
}
}