use std::any::Any;
use std::marker::PhantomData;
use tilo_sort::CompactSort as _;
use automerge::ROOT;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use tilo_action_policy::MemberId;
use tilo_actions::{ActionError, ExecutionLocus, RiskLevel};
use crate::collection::Id;
use crate::kind::ResourceKind;
use crate::model::{Doc, Fields};
use crate::resource::Resource;
#[derive(Debug)]
pub struct ActionCx {
preview: bool,
seed: [u8; 32],
minted: u64,
ids: Vec<Id>,
now_ms: i64,
author: Option<MemberId>,
invocation: Option<tilo_actions::InvocationId>,
removes_item: bool,
}
fn invoking_author() -> Option<MemberId> {
tilo_actions::reading_invoking_context(|context| {
context
.and_then(|context| context.invoker.as_ref())
.and_then(invoker_member)
})
.or_else(|| RESOURCE_ACTOR.with_borrow(Clone::clone))
}
fn invoker_member(invoker: &tilo_actions::ActionInvoker) -> Option<MemberId> {
invoker
.acting
.members()
.first()
.map(|member| (*member).clone())
}
pub(crate) fn writing_author() -> Option<MemberId> {
tilo_actions::reading_invoking_context(|context| match context {
Some(context) => context.invoker.as_ref().and_then(invoker_member),
None => RESOURCE_ACTOR.with_borrow(Clone::clone),
})
}
thread_local! {
static RESOURCE_ACTOR: std::cell::RefCell<Option<MemberId>> = const { std::cell::RefCell::new(None) };
}
pub struct ResourceActorScope(Option<MemberId>);
impl ResourceActorScope {
#[must_use]
pub fn enter(actor: MemberId) -> Self {
Self(RESOURCE_ACTOR.replace(Some(actor)))
}
}
impl Drop for ResourceActorScope {
fn drop(&mut self) {
RESOURCE_ACTOR.replace(self.0.take());
}
}
fn invoking_invocation() -> Option<tilo_actions::InvocationId> {
tilo_actions::reading_invoking_context(|context| context?.source_invocation)
}
impl ActionCx {
pub fn remove_item(&mut self) {
self.removes_item = true;
}
#[doc(hidden)]
pub fn take_item_removal(&mut self) -> bool {
std::mem::take(&mut self.removes_item)
}
#[must_use]
pub fn for_apply(doc: &Doc, payload: &[u8], now_ms: i64) -> Self {
Self {
preview: tilo_actions::executor::is_replaying(),
seed: seed(doc, b"tilo-resource/action-seed/v1", payload),
minted: 0,
ids: Vec::new(),
now_ms,
author: invoking_author(),
invocation: invoking_invocation(),
removes_item: false,
}
}
#[must_use]
pub fn for_write(doc: &Doc, payload: &[u8]) -> Self {
let mut hasher = blake3::Hasher::new();
hasher.update(b"tilo-resource/write-seed/v1");
if let Some((group, position)) = crate::group::current_member() {
hasher.update(b"member");
hasher.update(&group);
hasher.update(&position.to_le_bytes());
} else {
hasher.update(doc.get_actor().to_bytes());
let mut heads = automerge::transaction::Transactable::base_heads(doc);
heads.compact_sort();
for head in heads {
hasher.update(&head.0);
}
}
hasher.update(payload);
Self {
preview: tilo_actions::executor::is_replaying(),
seed: *hasher.finalize().as_bytes(),
minted: 0,
ids: Vec::new(),
now_ms: 0,
author: invoking_author(),
invocation: invoking_invocation(),
removes_item: false,
}
}
#[must_use]
pub fn is_preview(&self) -> bool {
self.preview
}
pub fn id(&mut self) -> Id {
let id = minted(&self.seed, self.minted);
self.minted = self.minted.saturating_add(1);
self.ids.push(id.clone());
note_minted(id.as_str());
id
}
pub fn uuid(&mut self) -> uuid::Uuid {
let uuid = minted_uuid(&self.seed, self.minted);
self.minted = self.minted.saturating_add(1);
note_minted(&uuid.to_string());
uuid
}
pub fn named(&mut self, id: impl Into<String>, label: impl Into<String>) {
NAMED.with(|named| {
named.borrow_mut().replace(tilo_actions::ActionItem {
id: id.into(),
label: label.into(),
});
});
}
#[must_use]
pub fn acting_name(&self) -> String {
invoking_name()
}
#[must_use]
pub fn appearance(&self) -> Option<tilo_actions::Appearance> {
tilo_actions::reading_invoking_context(|context| {
context?
.invoker
.as_ref()
.filter(|invoker| invoker.acting.is_bot())?
.appearance
.clone()
})
}
#[must_use]
pub fn invoked_by(&self) -> Option<tilo_actions::Acting> {
tilo_actions::reading_invoking_context(|context| {
Some(context?.invoker.as_ref()?.acting.clone())
})
}
pub fn now_ms(&self) -> i64 {
self.now_ms
}
pub fn author(&self) -> Option<&MemberId> {
self.author.as_ref()
}
pub const fn invocation(&self) -> Option<tilo_actions::InvocationId> {
self.invocation
}
}
fn uuid_from(digest: &[u8; 32]) -> uuid::Uuid {
let mut bytes = [0_u8; 16];
bytes.copy_from_slice(digest.get(..16).unwrap_or(&[0; 16]));
uuid::Builder::from_random_bytes(bytes).into_uuid()
}
thread_local! {
static MINTED: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
static ENTRIES: std::cell::RefCell<std::collections::HashMap<String, automerge::ObjId>> =
std::cell::RefCell::new(std::collections::HashMap::new());
static NAMED: std::cell::RefCell<Option<tilo_actions::ActionItem>> =
const { std::cell::RefCell::new(None) };
}
pub(crate) fn start_minting() {
drop(take_minted());
ENTRIES.with(|entries| entries.borrow_mut().clear());
NAMED.with(|named| named.borrow_mut().take());
}
pub(crate) fn note_entry(map: &automerge::ObjId, id: &str) {
ENTRIES.with(|entries| {
entries.borrow_mut().insert(id.to_owned(), map.clone());
});
}
#[must_use]
pub fn minted_entry(id: &str) -> Option<automerge::ObjId> {
ENTRIES.with(|entries| entries.borrow().get(id).cloned())
}
pub(crate) fn named_item() -> Option<tilo_actions::ActionItem> {
NAMED.with_borrow(Clone::clone)
}
pub(crate) fn entries_so_far() -> Vec<String> {
ENTRIES.with_borrow(|entries| entries.keys().cloned().collect())
}
pub(crate) fn minted_so_far() -> Vec<String> {
MINTED.with_borrow(Clone::clone)
}
pub(crate) fn note_minted(id: &str) {
MINTED.with(|minted| minted.borrow_mut().push(id.to_owned()));
}
#[must_use]
pub fn take_minted() -> Vec<String> {
MINTED.with(|minted| std::mem::take(&mut *minted.borrow_mut()))
}
pub fn restore_minted(ids: impl IntoIterator<Item = String>) {
MINTED.with(|minted| minted.borrow_mut().extend(ids));
}
thread_local! {
static MINT: std::cell::Cell<Option<([u8; 32], u64)>> = const { std::cell::Cell::new(None) };
}
struct MintScope(Option<([u8; 32], u64)>);
impl MintScope {
fn enter(cx: &ActionCx) -> Self {
let mut hasher = blake3::Hasher::new();
hasher.update(b"tilo-resource/fresh-uuid/v1");
hasher.update(&cx.seed);
let seed = *hasher.finalize().as_bytes();
Self(MINT.with(|mint| mint.replace(Some((seed, 0)))))
}
}
impl Drop for MintScope {
fn drop(&mut self) {
MINT.with(|mint| mint.set(self.0));
}
}
#[must_use]
pub fn invoking_member() -> Option<MemberId> {
invoking_author()
}
#[must_use]
pub fn invoking_name() -> String {
tilo_actions::reading_invoking_context(|context| {
context
.and_then(|context| context.invoker.as_ref())
.filter(|invoker| !invoker.acting.is_person())
.and_then(|invoker| invoker.name.clone())
.filter(|name| !name.trim().is_empty())
.unwrap_or_default()
})
}
#[must_use]
pub fn fresh_uuid() -> uuid::Uuid {
MINT.with(|mint| match mint.get() {
Some((seed, counter)) => {
mint.set(Some((seed, counter.saturating_add(1))));
let mut hasher = blake3::Hasher::new();
hasher.update(&seed);
hasher.update(&counter.to_le_bytes());
let uuid = uuid_from(hasher.finalize().as_bytes());
note_minted(&uuid.to_string());
uuid
}
None => uuid::Uuid::new_v4(),
})
}
fn minted_uuid(seed: &[u8; 32], counter: u64) -> uuid::Uuid {
let mut hasher = blake3::Hasher::new();
hasher.update(b"uuid");
hasher.update(seed);
hasher.update(&counter.to_le_bytes());
uuid_from(hasher.finalize().as_bytes())
}
fn minted(seed: &[u8; 32], counter: u64) -> Id {
let mut hasher = blake3::Hasher::new();
hasher.update(seed);
hasher.update(&counter.to_le_bytes());
let digest = hasher.finalize();
let hex = digest.to_hex();
Id::from_raw(hex.as_str().get(..20).unwrap_or_default())
}
pub fn minted_ids(envelope: &tilo_actions::ActionEnvelope) -> impl Iterator<Item = Id> {
let seed = envelope_seed(envelope);
(0_u64..).map(move |counter| minted(&seed, counter))
}
pub fn minted_keys(envelope: &tilo_actions::ActionEnvelope) -> impl Iterator<Item = [String; 2]> {
let seed = envelope_seed(envelope);
(0_u64..).map(move |counter| {
[
minted(&seed, counter).as_str().to_owned(),
minted_uuid(&seed, counter).to_string(),
]
})
}
fn envelope_seed(envelope: &tilo_actions::ActionEnvelope) -> [u8; 32] {
let mut hasher = blake3::Hasher::new();
hasher.update(b"tilo-resource/action-seed/v1");
hasher.update(envelope.actor().to_bytes());
let mut heads = envelope.base_heads.clone();
heads.compact_sort();
for head in &heads {
hasher.update(head);
}
hasher.update(&envelope.action.payload);
*hasher.finalize().as_bytes()
}
pub(crate) fn seed(doc: &Doc, domain: &[u8], payload: &[u8]) -> [u8; 32] {
use automerge::transaction::Transactable as _;
let mut hasher = blake3::Hasher::new();
hasher.update(domain);
if let Some((group, position)) = crate::group::current_member() {
hasher.update(b"member");
hasher.update(&group);
hasher.update(&position.to_le_bytes());
} else {
hasher.update(doc.get_actor().to_bytes());
let mut heads = doc.base_heads();
heads.compact_sort();
for head in heads {
hasher.update(&head.0);
}
let pending = doc.pending_ops();
if pending > 0 {
hasher.update(b"pending");
hasher.update(&u64::try_from(pending).unwrap_or(u64::MAX).to_le_bytes());
}
}
hasher.update(payload);
*hasher.finalize().as_bytes()
}
pub trait Outcome {
fn into_result(self) -> Result<(), Refusal>;
}
impl Outcome for () {
fn into_result(self) -> Result<(), Refusal> {
Ok(())
}
}
impl<E: Into<Refusal>> Outcome for Result<(), E> {
fn into_result(self) -> Result<(), Refusal> {
self.map_err(Into::into)
}
}
pub use tilo_action_policy::ActionKind;
pub use tilo_actions::ActionKey;
pub trait Operation: Serialize + DeserializeOwned + Clone + std::fmt::Debug + 'static {
type Record: Fields + 'static;
const KIND: &'static str;
fn edit(&self) -> Option<&crate::Edit<Self::Record>> {
None
}
fn kind(&self) -> ActionKind {
ActionKind::Undoable
}
fn perform(&self, record: &mut Self::Record, cx: &mut ActionCx) -> Result<(), Refusal>;
fn writes(&self) -> crate::footprint::Writes {
crate::footprint::Writes::record()
}
fn snapshot(record: &Self::Record) -> Option<Self::Record> {
let _ = record;
None
}
fn risk(&self) -> RiskLevel {
RiskLevel::Low
}
fn change_kind(&self) -> tilo_actions::ChangeKind {
tilo_actions::ChangeKind::Content
}
fn incoming_message(&self) -> bool {
false
}
fn irreversible(&self) -> bool {
false
}
fn by_app(&self) -> bool {
false
}
fn compensates(&self) -> bool {
false
}
const QUEUES: bool = false;
fn queue(record: &mut Self::Record, before: &Self::Record, cx: &mut ActionCx) {
let _ = (record, before, cx);
}
fn perform_item(&self, doc: &mut Doc, cx: &mut ActionCx) -> Option<Result<(), Refusal>> {
let _ = (doc, cx);
None
}
fn field_edit(edit: crate::Edit<Self::Record>) -> Option<Self> {
let _ = edit;
None
}
fn compensation(
&self,
before: &Self::Record,
after: &Self::Record,
minted: &[Id],
) -> Option<Result<Self, String>> {
let _ = (before, after, minted);
None
}
}
pub struct Undoing<'a, R, P> {
pub before: &'a R,
pub after: &'a R,
pub minted: &'a [Id],
pub params: &'a P,
}
impl<R, P> Clone for Undoing<'_, R, P> {
fn clone(&self) -> Self {
*self
}
}
impl<R, P> Copy for Undoing<'_, R, P> {}
#[allow(
clippy::needless_pass_by_value,
reason = "`map_err` hands it the error by value"
)]
fn model_refused(error: crate::ModelError) -> ActionError {
ActionError::Refused(error.to_string())
}
#[allow(
clippy::needless_pass_by_value,
reason = "`map_err` hands it the error by value"
)]
fn automerge_refused(error: automerge::AutomergeError) -> ActionError {
ActionError::Refused(error.to_string())
}
pub use tilo_actions::Refusal;
fn refusal_refused(refusal: Refusal) -> ActionError {
refusal.into()
}
#[derive(Serialize, Clone)]
pub struct Stamped<O> {
#[serde(rename = "op")]
pub operation: O,
#[serde(rename = "at", default)]
pub now_ms: i64,
}
impl<O: std::fmt::Debug> std::fmt::Debug for Stamped<O> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fmt_stamped(&self.operation, self.now_ms, f)
}
}
fn fmt_stamped(
operation: &dyn std::fmt::Debug,
now_ms: i64,
f: &mut std::fmt::Formatter<'_>,
) -> std::fmt::Result {
f.debug_struct("Stamped")
.field("operation", operation)
.field("now_ms", &now_ms)
.finish()
}
impl<'de, O: DeserializeOwned> Deserialize<'de> for Stamped<O> {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let value = serde_json::Value::deserialize(deserializer)?;
match Self::from_json(value) {
Ok(stamped) => Ok(stamped),
Err(error) => Err(serde::de::Error::custom(error)),
}
}
}
impl<O: DeserializeOwned> Stamped<O> {
pub fn from_json(value: serde_json::Value) -> Result<Self, serde_json::Error> {
let (operation, now_ms) = stamped_parts(value)?;
Ok(Self {
operation: O::deserialize(operation)?,
now_ms,
})
}
}
#[inline(never)]
fn stamped_parts(value: serde_json::Value) -> Result<(serde_json::Value, i64), serde_json::Error> {
use serde::de::Error as _;
let serde_json::Value::Object(mut fields) = value else {
return Err(serde_json::Error::custom(
"a stamped operation is an object",
));
};
let operation = fields
.remove("op")
.ok_or_else(|| serde_json::Error::missing_field("op"))?;
let now_ms = match fields.remove("at") {
None | Some(serde_json::Value::Null) => 0,
Some(at) => i64::deserialize(at)?,
};
Ok((operation, now_ms))
}
fn settles(operation: &impl Operation) -> bool {
matches!(
operation.edit().map(crate::Edit::op),
Some(crate::EditOp::Settle { .. } | crate::EditOp::Forget { .. })
)
}
#[inline(never)]
fn on_copy(doc: &Doc, apply: &mut dyn FnMut(&mut Doc)) {
let mut copy = doc.clone();
apply(&mut copy);
}
impl<O: Operation> Stamped<O> {
fn compensated(&self) -> bool {
if settles(&self.operation)
|| matches!(
self.operation.change_kind(),
tilo_actions::ChangeKind::External | tilo_actions::ChangeKind::Housekeeping
)
{
return false;
}
O::QUEUES || (self.operation.edit().is_none() && self.operation.compensates())
}
fn applied_to_copy(&self, doc: &Doc) -> Option<(O::Record, Vec<Id>)> {
let payload = serde_json::to_vec(self).ok()?;
if let Some(edit) = self.operation.edit() {
let mut cx = ActionCx::for_apply(doc, &payload, self.now_ms);
cx.preview = true;
let mut after = None;
on_copy(doc, &mut |copy| {
after = edit
.apply(copy, &mut cx)
.ok()
.and_then(|()| O::Record::read_fields(copy, &ROOT).ok());
});
return Some((after?, cx.ids));
}
let mut after = O::Record::read_fields(doc, &ROOT).ok()?;
let mut cx = ActionCx::for_apply(doc, &payload, self.now_ms);
cx.preview = true;
let minting = MintScope::enter(&cx);
let performed = self.operation.perform(&mut after, &mut cx);
drop(minting);
performed.ok()?;
Some((after, cx.ids))
}
fn compensation(&self, doc: &Doc) -> Option<tilo_actions::EncodedAction> {
if !self.compensated() {
return None;
}
let before = O::Record::read_fields(doc, &ROOT).ok()?;
let (after, minted) = self.applied_to_copy(doc)?;
if self.operation.edit().is_none() && self.operation.compensates() {
let operation = self
.operation
.compensation(&before, &after, &minted)?
.ok()?;
let undo = Self {
operation,
now_ms: self.now_ms,
};
return tilo_actions::EncodedAction::encode(O::KIND, &undo).ok();
}
let mut restore: Vec<crate::Edit<()>> = Vec::new();
crate::Model::diff(&after, &before, &[], &mut restore);
let mut members = Vec::with_capacity(restore.len());
for edit in restore {
members.push(Self {
operation: O::field_edit(edit.retyped())?,
now_ms: self.now_ms,
});
}
let restore = match members.len() {
0 => return None,
1 => tilo_actions::EncodedAction::encode(O::KIND, &members.pop()?).ok()?,
_ => tilo_actions::EncodedAction::encode(
crate::group::group_type_of(O::KIND),
&crate::ActionGroup { actions: members },
)
.ok()?,
};
if serde_json::to_vec(&restore).ok()?.len() <= tilo_actions::context::COMPENSATION_BUDGET {
return Some(restore);
}
let reverting = Reverting::<O> {
actor: doc.get_actor().to_hex_string(),
deps: doc
.committed_heads()
.iter()
.map(ToString::to_string)
.collect(),
now_ms: self.now_ms,
operation: PhantomData,
};
tilo_actions::EncodedAction::encode(reverting_type(O::KIND), &reverting).ok()
}
}
pub fn reverting_type(kind: &str) -> String {
format!("{kind}+revert")
}
#[derive(Serialize)]
#[serde(bound = "")]
pub struct Reverting<O> {
actor: String,
deps: Vec<String>,
#[serde(rename = "at", default)]
now_ms: i64,
#[serde(skip)]
operation: PhantomData<O>,
}
impl<'de, O> Deserialize<'de> for Reverting<O> {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let value = serde_json::Value::deserialize(deserializer)?;
let (actor, deps, now_ms) = match reverted(value) {
Ok(target) => target,
Err(error) => return Err(serde::de::Error::custom(error)),
};
Ok(Self {
actor,
deps,
now_ms,
operation: PhantomData,
})
}
}
#[inline(never)]
fn reverted(value: serde_json::Value) -> Result<(String, Vec<String>, i64), serde_json::Error> {
#[derive(Deserialize)]
struct Form {
actor: String,
deps: Vec<String>,
#[serde(rename = "at", default)]
now_ms: i64,
}
let form = Form::deserialize(value)?;
Ok((form.actor, form.deps, form.now_ms))
}
impl<O> std::fmt::Debug for Reverting<O> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Reverting")
.field("actor", &self.actor)
.field("deps", &self.deps)
.finish_non_exhaustive()
}
}
impl<O: Operation> Reverting<O> {
fn change(&self, doc: &mut Doc) -> Result<automerge::ChangeHash, ActionError> {
reverted_change(&self.actor, &self.deps, doc)
}
}
#[inline(never)]
fn reverted_change(
actor: &str,
deps: &[String],
doc: &mut Doc,
) -> Result<automerge::ChangeHash, ActionError> {
let refused = |why: &str| ActionError::Refused(why.into());
let mut deps = deps
.iter()
.map(|hash| hash.parse())
.collect::<Result<Vec<automerge::ChangeHash>, _>>()
.map_err(|_| refused("a reverted change names invalid heads"))?;
deps.compact_sort();
doc.get_changes(&deps)
.into_iter()
.find(|change| {
change.actor_id().to_hex_string() == actor && {
let mut of = change.deps().to_vec();
of.compact_sort();
of == deps
}
})
.map(|change| change.hash())
.ok_or_else(|| refused("the change to take back is not in this document"))
}
impl<O: Operation> tilo_actions::Action for Reverting<O> {
fn apply(&self, doc: &mut Doc) -> Result<(), ActionError> {
let change = self.change(doc)?;
let payload = serde_json::to_vec(self).map_err(ActionError::Encode)?;
revert(
&ResourceOf::<O::Record>::OPS,
&|record, before, cx| {
if let (Some(record), Some(before)) = (
record.downcast_mut::<O::Record>(),
before.downcast_ref::<O::Record>(),
) {
O::queue(record, before, cx);
}
},
(change, &payload, self.now_ms),
doc,
)
}
fn locus(&self) -> ExecutionLocus {
ExecutionLocus::ClientLocal
}
}
fn revert(
record: &ResourceOps,
queue: &dyn Fn(&mut dyn Any, &dyn Any, &mut ActionCx),
(change, payload, now_ms): (automerge::ChangeHash, &[u8], i64),
doc: &mut Doc,
) -> Result<(), ActionError> {
let deps: Vec<automerge::ChangeHash> = doc
.get_change_meta_by_hash(&change)
.map(|meta| meta.deps)
.unwrap_or_default();
let before = {
let at = doc.committed_fork_at(&deps).map_err(automerge_refused)?;
(record.read)(&at).map_err(model_refused)?
};
let after = {
let at = doc
.committed_fork_at(&[change])
.map_err(automerge_refused)?;
(record.read)(&at).map_err(model_refused)?
};
let restore = (record.diff)(after.as_ref(), before.as_ref());
let mut cx = ActionCx::for_apply(doc, payload, now_ms);
let current = (record.read)(doc).map_err(model_refused)?;
for edit in &restore {
(record.edit)(edit, doc, &mut cx).map_err(model_refused)?;
}
let mut written = (record.read)(doc).map_err(model_refused)?;
let minting = MintScope::enter(&cx);
queue(written.as_mut(), current.as_ref(), &mut cx);
drop(minting);
(record.write)(written.as_ref(), doc).map_err(model_refused)
}
type WriteChanged =
fn(&dyn Any, &dyn Any, &mut Doc, &crate::Delta) -> Result<(), crate::ModelError>;
pub(crate) struct ResourceOps {
shape: crate::Shape,
name: fn() -> &'static str,
kind: fn() -> std::any::TypeId,
read: fn(&Doc) -> Result<Box<dyn Any>, crate::ModelError>,
write: fn(&dyn Any, &mut Doc) -> Result<(), crate::ModelError>,
write_changed: WriteChanged,
check: fn(&dyn Any) -> Result<(), Refusal>,
refresh: fn(&mut dyn Any, &Doc, &crate::Delta) -> bool,
diff: fn(&dyn Any, &dyn Any) -> Vec<crate::Edit<()>>,
edit: fn(&crate::Edit<()>, &mut Doc, &mut ActionCx) -> Result<(), crate::ModelError>,
}
fn resource_of<R: 'static>(record: &dyn Any) -> Result<&R, crate::ModelError> {
match record.downcast_ref::<R>() {
Some(record) => Ok(record),
None => Err(crate::ModelError::invalid("a record of another type")),
}
}
fn read_resource<R: Fields + 'static>(doc: &Doc) -> Result<Box<dyn Any>, crate::ModelError> {
match R::read_fields(doc, &ROOT) {
Ok(record) => Ok(Box::new(record)),
Err(error) => Err(error),
}
}
fn write_resource<R: Fields + 'static>(
record: &dyn Any,
doc: &mut Doc,
) -> Result<(), crate::ModelError> {
resource_of::<R>(record)?.write_fields(doc, &ROOT)
}
fn write_changed_resource<R: Fields + 'static>(
record: &dyn Any,
kept: &dyn Any,
doc: &mut Doc,
dirty: &crate::Delta,
) -> Result<(), crate::ModelError> {
resource_of::<R>(record)?.write_changed_fields(resource_of::<R>(kept)?, doc, &ROOT, dirty)
}
fn check_resource<R: Fields + 'static>(record: &dyn Any) -> Result<(), Refusal> {
match record.downcast_ref::<R>() {
Some(record) => crate::Model::check(record),
None => Err(Refusal::new("a record of another type")),
}
}
fn refresh_resource<R: Fields + 'static>(
record: &mut dyn Any,
doc: &Doc,
delta: &crate::Delta,
) -> bool {
match record.downcast_mut::<R>() {
Some(record) => record.refresh_fields(doc, &ROOT, delta).is_ok(),
None => false,
}
}
fn diff_resources<R: Fields + 'static>(from: &dyn Any, to: &dyn Any) -> Vec<crate::Edit<()>> {
let mut edits = Vec::new();
if let (Some(from), Some(to)) = (from.downcast_ref::<R>(), to.downcast_ref::<R>()) {
crate::Model::diff(from, to, &[], &mut edits);
}
edits
}
fn edit_resource<R: Fields + 'static>(
edit: &crate::Edit<()>,
doc: &mut Doc,
cx: &mut ActionCx,
) -> Result<(), crate::ModelError> {
R::edit_fields(doc, &ROOT, edit.path(), edit.op(), cx)
}
pub(crate) struct ResourceOf<R>(PhantomData<R>);
impl<R: Fields + 'static> ResourceOf<R> {
pub(crate) const OPS: ResourceOps = ResourceOps {
shape: <R as crate::Model>::SHAPE,
name: std::any::type_name::<R>,
kind: std::any::TypeId::of::<R>,
read: read_resource::<R>,
write: write_resource::<R>,
write_changed: write_changed_resource::<R>,
check: check_resource::<R>,
refresh: refresh_resource::<R>,
diff: diff_resources::<R>,
edit: edit_resource::<R>,
};
}
fn apply_edit(
operation: &dyn Performs,
doc: &mut Doc,
cx: &mut ActionCx,
) -> Result<(), ActionError> {
match operation.apply_edit(doc, cx) {
Some(applied) => applied.map_err(model_refused),
None => Ok(()),
}
}
trait Performs {
fn is_edit(&self) -> bool;
fn apply_edit(&self, doc: &mut Doc, cx: &mut ActionCx)
-> Option<Result<(), crate::ModelError>>;
fn queues(&self) -> bool;
fn perform(&self, record: &mut dyn Any, cx: &mut ActionCx) -> Result<(), Refusal>;
fn queue(&self, record: &mut dyn Any, before: &dyn Any, cx: &mut ActionCx);
fn perform_item(&self, doc: &mut Doc, cx: &mut ActionCx) -> Option<Result<(), Refusal>>;
fn writes(&self) -> crate::footprint::Writes;
fn snapshot(&self, record: &dyn Any) -> Option<Box<dyn Any>>;
}
impl<O: Operation> Performs for O {
fn is_edit(&self) -> bool {
self.edit().is_some()
}
fn apply_edit(
&self,
doc: &mut Doc,
cx: &mut ActionCx,
) -> Option<Result<(), crate::ModelError>> {
let edit = self.edit()?;
Some(O::Record::edit_fields(
doc,
&ROOT,
edit.path(),
edit.op(),
cx,
))
}
fn queues(&self) -> bool {
O::QUEUES && !settles(self)
}
fn perform(&self, record: &mut dyn Any, cx: &mut ActionCx) -> Result<(), Refusal> {
match record.downcast_mut::<O::Record>() {
Some(record) => Operation::perform(self, record, cx),
None => Err(Refusal::new("a record of another type")),
}
}
fn queue(&self, record: &mut dyn Any, before: &dyn Any, cx: &mut ActionCx) {
if let (Some(record), Some(before)) = (
record.downcast_mut::<O::Record>(),
before.downcast_ref::<O::Record>(),
) {
O::queue(record, before, cx);
}
}
fn perform_item(&self, doc: &mut Doc, cx: &mut ActionCx) -> Option<Result<(), Refusal>> {
Operation::perform_item(self, doc, cx)
}
fn writes(&self) -> crate::footprint::Writes {
Operation::writes(self)
}
fn snapshot(&self, record: &dyn Any) -> Option<Box<dyn Any>> {
let record = record.downcast_ref::<O::Record>()?;
O::snapshot(record).map(|record| Box::new(record) as Box<dyn Any>)
}
}
fn apply_edit_queued(
record: &'static ResourceOps,
operation: &dyn Performs,
doc: &mut Doc,
cx: &mut ActionCx,
) -> Result<(), ActionError> {
if !operation.queues() {
return apply_edit(operation, doc, cx);
}
let before = (record.read)(doc).map_err(model_refused)?;
apply_edit(operation, doc, cx)?;
let mut after = (record.read)(doc).map_err(model_refused)?;
let minting = MintScope::enter(cx);
operation.queue(after.as_mut(), before.as_ref(), cx);
drop(minting);
(record.write)(after.as_ref(), doc).map_err(model_refused)
}
fn read_whole(ops: &'static ResourceOps, doc: &Doc) -> Result<Box<dyn Any>, ActionError> {
let _whole = crate::profiling::Phase::start("resource.apply_whole_read");
(ops.read)(doc).map_err(model_refused)
}
fn apply_operation(
record: &'static ResourceOps,
operation: &dyn Performs,
(payload, now_ms): (&[u8], i64),
doc: &mut Doc,
) -> Result<(), ActionError> {
if crate::group::current_member().is_none() {
start_minting();
}
let mut cx = ActionCx::for_apply(doc, payload, now_ms);
let shape = record.shape;
let units = crate::footprint::has_units(shape);
let index = |doc: &mut Doc| {
if units {
crate::footprint::index(doc, shape).map_err(automerge_refused)?;
}
Ok::<(), ActionError>(())
};
let queues = operation.queues();
let grouping = crate::group::grouping();
if grouping {
if !operation.is_edit() && !queues && held::holds(record) {
return held::perform(record, operation, &mut cx);
}
held::flush(record, doc)?;
}
if operation.is_edit() {
apply_edit_queued(record, operation, doc, &mut cx)?;
return index(doc);
}
if !queues {
let minting = MintScope::enter(&cx);
let performed = operation.perform_item(doc, &mut cx);
drop(minting);
if let Some(performed) = performed {
performed.map_err(refusal_refused)?;
return index(doc);
}
}
let committed = automerge::transaction::Transactable::pending_ops(doc) == 0;
let started = automerge::transaction::Transactable::base_heads(doc);
let (mut current, dirty) =
match crate::apply_cache::take_any((record.kind)(), doc, &record.refresh) {
Some((warm, dirty)) => (warm, Some(dirty)),
None => (read_whole(record, doc)?, None),
};
if grouping && !queues {
let base = operation.snapshot(current.as_ref());
held::start(record, current, base, dirty);
return held::perform(record, operation, &mut cx);
}
let kept = if committed || queues || units || dirty.is_some() {
operation.snapshot(current.as_ref())
} else {
None
};
let read_before;
let before: Option<&dyn Any> = match (&kept, queues || units) {
(_, false) => None,
(Some(kept), true) => Some(kept.as_ref()),
(None, true) => {
read_before = (record.read)(doc).map_err(model_refused)?;
Some(read_before.as_ref())
}
};
let minting = MintScope::enter(&cx);
let performed = operation.perform(current.as_mut(), &mut cx);
if let (Ok(()), Some(before), true) = (&performed, before, queues) {
operation.queue(current.as_mut(), before, &mut cx);
}
drop(minting);
performed.map_err(refusal_refused)?;
if grouping {
crate::group::check_or_defer(format!("{}@root", (record.name)()), doc, move |doc| {
match (record.read)(doc) {
Ok(read) => (record.check)(read.as_ref()),
Err(error) => Err(Refusal::new(error.to_string())),
}
})
.map_err(refusal_refused)?;
} else {
(record.check)(current.as_ref()).map_err(refusal_refused)?;
}
if let (Some(before), true) = (before, units) {
let edits = (record.diff)(before, current.as_ref());
crate::footprint::check_edits(shape, &edits, &operation.writes())
.map_err(refusal_refused)?;
}
crate::apply_cache::begin_storing();
match (&kept, &dirty) {
(Some(kept), Some(dirty)) => {
(record.write_changed)(current.as_ref(), kept.as_ref(), doc, dirty)
}
_ => (record.write)(current.as_ref(), doc),
}
.map_err(model_refused)?;
index(doc)?;
crate::apply_cache::seal_stored(doc);
if committed {
if let Some(kept) = kept {
crate::apply_cache::keep_any((record.kind)(), kept, doc, &started);
}
} else {
crate::apply_cache::keep_open((record.kind)(), current, doc);
}
Ok(())
}
mod held {
use std::any::{Any, TypeId};
use std::cell::RefCell;
use tilo_actions::ActionError;
use super::{ActionCx, MintScope, Performs, ResourceOps, model_refused, refusal_refused};
use crate::footprint::Footprints;
use crate::model::Doc;
struct Held {
record: &'static ResourceOps,
current: Box<dyn Any>,
base: Option<Box<dyn Any>>,
dirty: Option<crate::Delta>,
footprints: Footprints,
}
thread_local! {
static HELD: RefCell<Option<Vec<Held>>> = const { RefCell::new(None) };
}
pub(crate) fn begin() {
HELD.with(|held| *held.borrow_mut() = Some(Vec::new()));
}
pub(crate) fn end() {
HELD.with(|held| held.borrow_mut().take());
}
fn kind(record: &ResourceOps) -> TypeId {
(record.kind)()
}
pub(super) fn holds(record: &ResourceOps) -> bool {
HELD.with(|held| {
held.borrow()
.as_ref()
.is_some_and(|held| held.iter().any(|entry| kind(entry.record) == kind(record)))
})
}
pub(super) fn start(
record: &'static ResourceOps,
current: Box<dyn Any>,
base: Option<Box<dyn Any>>,
dirty: Option<crate::Delta>,
) {
HELD.with(|held| {
if let Some(held) = held.borrow_mut().as_mut() {
held.push(Held {
record,
current,
base,
dirty,
footprints: Footprints::default(),
});
}
});
}
pub(super) fn perform(
record: &'static ResourceOps,
operation: &dyn Performs,
cx: &mut ActionCx,
) -> Result<(), ActionError> {
HELD.with(|held| {
let mut held = held.borrow_mut();
let entry = held
.as_mut()
.and_then(|held| {
held.iter_mut()
.find(|entry| kind(entry.record) == kind(record))
})
.ok_or_else(|| ActionError::Refused("the group does not hold the record".into()))?;
let minting = MintScope::enter(cx);
let performed = operation.perform(entry.current.as_mut(), cx);
drop(minting);
performed.map_err(refusal_refused)?;
entry.footprints.add(&operation.writes());
Ok(())
})
}
pub(super) fn flush(record: &ResourceOps, doc: &mut Doc) -> Result<(), ActionError> {
let taken = HELD.with(|held| {
let mut held = held.borrow_mut();
let held = held.as_mut()?;
let at = held
.iter()
.position(|entry| kind(entry.record) == kind(record))?;
Some(held.remove(at))
});
match taken {
Some(entry) => write(entry, doc, Checked::AtTheEnd),
None => Ok(()),
}
}
pub(crate) fn flush_all(doc: &mut Doc) -> Result<(), ActionError> {
let taken = HELD.with(|held| held.borrow_mut().as_mut().map(std::mem::take));
for entry in taken.unwrap_or_default() {
write(entry, doc, Checked::Now)?;
}
Ok(())
}
#[derive(Clone, Copy)]
enum Checked {
Now,
AtTheEnd,
}
fn write(entry: Held, doc: &mut Doc, checked: Checked) -> Result<(), ActionError> {
let Held {
record,
current,
base,
dirty,
footprints,
} = entry;
let units = crate::footprint::has_units(record.shape);
let read_base;
let before: Option<&dyn Any> = match (&base, units) {
(_, false) => None,
(Some(base), true) => Some(base.as_ref()),
(None, true) => {
read_base = (record.read)(doc).map_err(model_refused)?;
Some(read_base.as_ref())
}
};
match checked {
Checked::Now => (record.check)(current.as_ref()).map_err(refusal_refused)?,
Checked::AtTheEnd => {
crate::group::check_or_defer(
format!("{}@root", (record.name)()),
doc,
move |doc| match (record.read)(doc) {
Ok(read) => (record.check)(read.as_ref()),
Err(error) => Err(crate::Refusal::new(error.to_string())),
},
)
.map_err(refusal_refused)?;
}
}
if let Some(before) = before {
let edits = (record.diff)(before, current.as_ref());
crate::footprint::check_edits_of(record.shape, &edits, &footprints)
.map_err(refusal_refused)?;
}
crate::apply_cache::begin_storing();
match (&base, &dirty) {
(Some(base), Some(dirty)) => {
(record.write_changed)(current.as_ref(), base.as_ref(), doc, dirty)
}
_ => (record.write)(current.as_ref(), doc),
}
.map_err(model_refused)?;
if units {
crate::footprint::index(doc, record.shape).map_err(super::automerge_refused)?;
}
crate::apply_cache::seal_stored(doc);
crate::apply_cache::keep_open((record.kind)(), current, doc);
Ok(())
}
}
pub(crate) use held::{begin as hold_records, end as drop_held, flush_all as write_held};
impl<O: Operation> tilo_actions::Action for Stamped<O> {
fn apply(&self, doc: &mut Doc) -> Result<(), ActionError> {
let payload = serde_json::to_vec(self).map_err(ActionError::Encode)?;
apply_operation(
&ResourceOf::<O::Record>::OPS,
&self.operation,
(&payload, self.now_ms),
doc,
)
}
fn locus(&self) -> ExecutionLocus {
ExecutionLocus::ClientLocal
}
fn risk(&self) -> RiskLevel {
self.operation.risk()
}
fn change_kind(&self) -> tilo_actions::ChangeKind {
match self.operation.edit().map(crate::Edit::op) {
Some(crate::EditOp::Settle { .. }) => tilo_actions::ChangeKind::External,
Some(crate::EditOp::Forget { .. }) => tilo_actions::ChangeKind::Housekeeping,
_ => self.operation.change_kind(),
}
}
fn action_kind(&self) -> ActionKind {
self.operation.kind()
}
fn incoming_message(&self) -> bool {
self.operation.incoming_message()
}
fn irreversible(&self) -> bool {
self.operation.irreversible()
}
fn inverse_encoded(&self, doc: &Doc) -> Option<tilo_actions::EncodedAction> {
self.compensation(doc)
}
fn compensates(&self) -> bool {
self.compensated()
}
fn describe(&self, doc: &Doc) -> Option<tilo_actions::Described> {
let shape = <O::Record as crate::Model>::SHAPE;
if let Some(edit) = self.operation.edit() {
return crate::describe::edit(doc, shape, edit);
}
let value = crate::__private::json_via_bytes(&self.operation).ok()?;
crate::describe::verb(doc, shape, O::KIND, &value)
}
fn made(&self, doc: &Doc) -> Option<tilo_actions::ActionItem> {
crate::describe::made::<O::Record>(doc)
}
}
pub struct ActionRef<R, A> {
pub id: &'static str,
pub params: &'static [&'static str],
kind: ResourceKind,
marker: PhantomData<fn(A) -> R>,
}
impl<R, A> Clone for ActionRef<R, A> {
fn clone(&self) -> Self {
*self
}
}
impl<R, A> Copy for ActionRef<R, A> {}
impl<R, A> std::fmt::Debug for ActionRef<R, A> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ActionRef")
.field("id", &self.id)
.field("params", &self.params)
.field("kind", &self.kind())
.finish_non_exhaustive()
}
}
impl<R, A> ActionRef<R, A> {
#[must_use]
pub const fn id(&self) -> &'static str {
self.id
}
#[must_use]
pub const fn params(&self) -> &'static [&'static str] {
self.params
}
#[must_use]
pub const fn kind(&self) -> &ResourceKind {
&self.kind
}
#[must_use]
pub fn key(&self) -> ActionKey {
ActionKey::new(self.kind.declaring_app(), self.kind.kind(), self.id)
}
}
impl<E: crate::Effect, A> ActionRef<E, A> {
#[must_use]
pub fn spec(&self) -> Option<tilo_actions::ActionSpec> {
E::spec(self.id)
}
pub fn binding(
&self,
resource: impl Into<String>,
) -> Result<tilo_actions::ActionBinding<()>, tilo_actions::ActionBindingError> {
let resource = resource.into();
let spec = E::spec(self.id).ok_or_else(|| {
tilo_actions::ActionBindingError::ActionNotExported {
resource: resource.clone(),
action: self.id.to_owned(),
}
})?;
tilo_actions::ActionBinding::declared(resource, spec)
}
}
impl<R, A: Serialize> ActionRef<R, A> {
#[must_use]
pub const fn new(
id: &'static str,
params: &'static [&'static str],
kind: ResourceKind,
) -> Self {
Self {
id,
params,
kind,
marker: PhantomData,
}
}
#[must_use]
pub fn on(&self, resource: impl Into<String>) -> tilo_actions::ActionAddress {
tilo_actions::ActionAddress::new(resource, self.id)
}
pub fn arguments(
&self,
input: &A,
) -> Result<serde_json::Map<String, serde_json::Value>, String> {
bind_serialized(
self.id,
self.params,
crate::__private::json_via_bytes(input),
)
}
pub fn with(&self, input: impl Into<A>) -> Invoke<R> {
Invoke::bound(self.id, self.arguments(&input.into()))
}
pub fn try_with(&self, input: impl Into<A>) -> Result<Invoke<R>, String> {
let invoke = self.with(input);
match invoke.refusal {
Some(refusal) => Err(refusal),
None => Ok(invoke),
}
}
}
#[inline(never)]
fn bind_serialized(
id: &'static str,
params: &'static [&'static str],
value: Result<serde_json::Value, serde_json::Error>,
) -> Result<serde_json::Map<String, serde_json::Value>, String> {
match value {
Ok(value) => bind_arguments(id, params, value),
Err(error) => Err(format!("`{id}`: {error}")),
}
}
fn bind_arguments(
id: &str,
params: &[&str],
value: serde_json::Value,
) -> Result<serde_json::Map<String, serde_json::Value>, String> {
let given = |fields: Vec<(String, serde_json::Value)>| {
fields
.into_iter()
.filter(|(_, value)| !value.is_null())
.collect()
};
match (params, value) {
([], serde_json::Value::Object(fields)) => Ok(given(fields.into_iter().collect())),
([], serde_json::Value::Null) => Ok(serde_json::Map::new()),
([], other) => Err(format!("`{id}` takes named arguments, not `{other}`")),
([single], value) => Ok(given(vec![((*single).to_owned(), value)])),
(names, serde_json::Value::Array(values)) if values.len() == names.len() => Ok(given(
names
.iter()
.map(|name| (*name).to_owned())
.zip(values)
.collect(),
)),
(names, other) => Err(format!(
"`{id}` takes {} arguments ({}), not `{other}`",
names.len(),
names.join(", ")
)),
}
}
impl<R, A: Serialize> ActionRef<R, A> {
pub fn map<I, T, F>(self, map: F) -> Mapped<R, A, F>
where
F: Fn(I) -> T,
T: Into<A>,
{
Mapped { action: self, map }
}
pub fn try_map<I, T, F>(self, parse: F) -> TryMapped<R, A, F>
where
F: Fn(I) -> Option<T>,
T: Into<A>,
{
TryMapped {
action: self,
parse,
}
}
}
pub struct TryMapped<R, A, F> {
action: ActionRef<R, A>,
parse: F,
}
impl<R, A, F: Clone> Clone for TryMapped<R, A, F> {
fn clone(&self) -> Self {
Self {
action: self.action,
parse: self.parse.clone(),
}
}
}
pub struct Mapped<R, A, F> {
action: ActionRef<R, A>,
map: F,
}
impl<R, A, F: Clone> Clone for Mapped<R, A, F> {
fn clone(&self) -> Self {
Self {
action: self.action,
map: self.map.clone(),
}
}
}
pub trait Binds<R, I>: Send + Sync + 'static {
fn action_id(&self) -> &'static str;
fn action_key(&self) -> ActionKey
where
R: Resource,
{
ActionKey::new(R::APP_ID, R::KIND, self.action_id())
}
fn arguments(&self, input: I) -> Result<serde_json::Map<String, serde_json::Value>, String>;
}
impl<R: 'static, A: Serialize + 'static, I: Into<A>> Binds<R, I> for ActionRef<R, A> {
fn action_id(&self) -> &'static str {
self.id
}
fn action_key(&self) -> ActionKey {
ActionRef::key(self)
}
fn arguments(&self, input: I) -> Result<serde_json::Map<String, serde_json::Value>, String> {
ActionRef::arguments(self, &input.into())
}
}
impl<R, A, I, T, F> Binds<R, I> for Mapped<R, A, F>
where
R: 'static,
A: Serialize + 'static,
T: Into<A>,
F: Fn(I) -> T + Send + Sync + 'static,
{
fn action_id(&self) -> &'static str {
self.action.id
}
fn action_key(&self) -> ActionKey {
ActionRef::key(&self.action)
}
fn arguments(&self, input: I) -> Result<serde_json::Map<String, serde_json::Value>, String> {
self.action.arguments(&(self.map)(input).into())
}
}
impl<R, A, I, T, F> Binds<R, I> for TryMapped<R, A, F>
where
R: 'static,
A: Serialize + 'static,
T: Into<A>,
F: Fn(I) -> Option<T> + Send + Sync + 'static,
{
fn action_id(&self) -> &'static str {
self.action.id
}
fn action_key(&self) -> ActionKey {
ActionRef::key(&self.action)
}
fn arguments(&self, input: I) -> Result<serde_json::Map<String, serde_json::Value>, String> {
let Some(parsed) = (self.parse)(input) else {
return Err(no_arguments(self.action.id));
};
self.action.arguments(&parsed.into())
}
}
#[inline(never)]
fn no_arguments(id: &str) -> String {
format!("the input makes no arguments for `{id}`")
}
pub trait NoParams {}
impl NoParams for () {}
pub trait Params: Serialize + DeserializeOwned + crate::JsonSchema + Clone + 'static {
type Resource;
type Paths: Clone;
const ACTION: ActionRef<Self::Resource, Self>;
fn paths() -> Self::Paths;
}
impl<R, A: NoParams> ActionRef<R, A> {
pub fn invoke(&self) -> Invoke<R> {
Invoke {
id: self.id,
arguments: serde_json::Map::new(),
refusal: None,
effect: false,
on: None,
marker: PhantomData,
}
}
}
pub struct Invoke<R> {
pub id: &'static str,
pub arguments: serde_json::Map<String, serde_json::Value>,
refusal: Option<String>,
effect: bool,
on: Option<String>,
marker: PhantomData<fn() -> R>,
}
impl<R> Clone for Invoke<R> {
fn clone(&self) -> Self {
Self {
id: self.id,
arguments: self.arguments.clone(),
refusal: self.refusal.clone(),
effect: self.effect,
on: self.on.clone(),
marker: PhantomData,
}
}
}
impl<R> std::fmt::Debug for Invoke<R> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Invoke")
.field("id", &self.id)
.field("arguments", &self.arguments)
.field("refusal", &self.refusal)
.field("effect", &self.effect)
.field("on", &self.on)
.finish()
}
}
impl<R> Invoke<R> {
pub fn effect<E: crate::Effect>(effect: &E) -> Self {
let id = effect.id();
let refusal = E::declaration(id)
.is_some_and(|declaration| declaration.row)
.then(|| format!("`{id}` is offered only on rows: invoke it on one"));
Self {
id,
arguments: effect.arguments(),
refusal,
effect: true,
on: None,
marker: PhantomData,
}
}
#[must_use]
pub fn on(mut self, row: impl Into<String>) -> Self {
if self.effect {
self.refusal = None;
}
self.on = Some(row.into());
self
}
pub fn row(&self) -> Option<&str> {
self.on.as_deref()
}
#[inline(never)]
pub(crate) fn bound(
id: &'static str,
bound: Result<serde_json::Map<String, serde_json::Value>, String>,
) -> Self {
let (arguments, refusal) = match bound {
Ok(arguments) => (arguments, None),
Err(refusal) => (serde_json::Map::new(), Some(refusal)),
};
Self {
id,
arguments,
refusal,
effect: false,
on: None,
marker: PhantomData,
}
}
pub fn refusal(&self) -> Option<&str> {
self.refusal.as_deref()
}
pub fn is_effect(&self) -> bool {
self.effect
}
#[must_use]
pub fn address_on(&self, resource: impl Into<String>) -> tilo_actions::ActionAddress {
tilo_actions::ActionAddress::new(resource, self.id)
}
}
impl<R: Resource> Invoke<R> {
#[must_use]
pub fn address(&self) -> tilo_actions::ActionAddress {
self.address_on(R::KIND)
}
pub fn apply(action: &R::Action) -> Result<Self, serde_json::Error> {
let value = match crate::__private::json_via_bytes(action)? {
serde_json::Value::String(variant) => serde_json::Value::Object(
serde_json::Map::from_iter([(variant, serde_json::Value::Null)]),
),
value => value,
};
Ok(Self {
id: crate::APPLY,
arguments: serde_json::Map::from_iter([(crate::APPLY_PARAM.to_owned(), value)]),
refusal: None,
effect: false,
on: None,
marker: PhantomData,
})
}
pub fn edit(edit: &crate::Edit<R>) -> Result<Self, serde_json::Error> {
Ok(Self {
id: crate::FIELD_EDIT,
arguments: serde_json::Map::from_iter([(
crate::EDIT_PARAM.to_owned(),
crate::__private::json_via_bytes(edit)?,
)]),
refusal: None,
effect: false,
on: None,
marker: PhantomData,
})
}
fn from_edit(edit: &crate::Edit<R>) -> Self {
Self::edit(edit).unwrap_or_else(|error| Self {
id: crate::FIELD_EDIT,
arguments: serde_json::Map::new(),
refusal: Some(error.to_string()),
effect: false,
on: None,
marker: PhantomData,
})
}
pub fn group(members: impl IntoIterator<Item = Self>) -> Self {
let mut actions = Vec::new();
let mut refusal = None;
for member in members {
if refusal.is_none() {
refusal.clone_from(&member.refusal);
}
if member.is_group() {
if let Some(serde_json::Value::Array(inner)) =
member.arguments.get(crate::GROUP_PARAM)
{
actions.extend(inner.iter().cloned());
}
} else {
actions.push(serde_json::json!({
"action": member.id,
"args": member.arguments,
}));
}
}
Self {
id: crate::GROUP,
arguments: serde_json::Map::from_iter([(
crate::GROUP_PARAM.to_owned(),
serde_json::Value::Array(actions),
)]),
refusal,
effect: false,
on: None,
marker: PhantomData,
}
}
pub fn is_group(&self) -> bool {
self.id == crate::GROUP
}
pub fn build(&self, now_ms: i64) -> Result<R::Action, String> {
if let Some(refusal) = &self.refusal {
return Err(refusal.clone());
}
if let Some(built) = R::build_by_app(self.id, &self.arguments, now_ms) {
return built;
}
crate::resource::build_action::<R>(self.id, &self.arguments, now_ms)
}
}
impl<R: Resource> From<crate::Edit<R>> for Invoke<R> {
fn from(edit: crate::Edit<R>) -> Self {
Self::from_edit(&edit)
}
}
impl<R: Resource> From<&crate::Edit<R>> for Invoke<R> {
fn from(edit: &crate::Edit<R>) -> Self {
Self::from_edit(edit)
}
}
#[cfg(test)]
mod seed_tests {
use super::*;
use automerge::transaction::Transactable as _;
#[test]
fn a_seed_read_mid_transaction_leaves_it_open_and_moves_with_it() {
let mut doc = Doc::new();
doc.put(ROOT, "a", 1).unwrap();
doc.commit();
let committed = seed(&doc, b"test", b"payload");
doc.put(ROOT, "b", 2).unwrap();
let base = doc.base_heads();
let open = seed(&doc, b"test", b"payload");
assert!(doc.pending_ops() > 0, "reading the seed commits nothing");
assert_eq!(doc.base_heads(), base);
assert_ne!(open, committed, "an open transaction moves the seed");
doc.put(ROOT, "c", 3).unwrap();
assert_ne!(seed(&doc, b"test", b"payload"), open);
doc.commit();
assert_ne!(seed(&doc, b"test", b"payload"), committed);
}
}