use automerge::ActorId;
use automerge::transaction::{CommitOptions, Transactable};
use crate::action::{Action, ActionError, ActionId, Doc, EncodedAction, ExecutionLocus};
use crate::context::{ActionContext, CONTINUATION_PREFIX, ChangeKind};
use crate::entry::{Described, Did};
use crate::envelope::ActionEnvelope;
use crate::registry::ActionRegistry;
thread_local! {
static REPLAYING: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
static INVOKING: std::cell::RefCell<Option<ActionContext>> = const { std::cell::RefCell::new(None) };
static OPEN_STEP: std::cell::Cell<Option<ActionId>> = const { std::cell::Cell::new(None) };
}
pub fn is_replaying() -> bool {
REPLAYING.with(std::cell::Cell::get)
}
struct ReplayScope(bool);
impl ReplayScope {
fn enter() -> Self {
Self(REPLAYING.with(|replaying| replaying.replace(true)))
}
}
impl Drop for ReplayScope {
fn drop(&mut self) {
REPLAYING.with(|replaying| replaying.set(self.0));
}
}
pub fn replaying_as<T>(replaying: bool, work: impl FnOnce() -> T) -> T {
let outer = REPLAYING.with(|current| current.replace(replaying));
let _restore = ReplayScope(outer);
work()
}
pub fn open_step(step: Option<ActionId>) {
OPEN_STEP.with(|open| open.set(step));
}
pub fn current_step() -> Option<ActionId> {
OPEN_STEP.with(std::cell::Cell::get)
}
pub const UNDONE_KEY: &str = "tilo:undone:";
thread_local! {
static COMPENSATING: std::cell::RefCell<Option<(Vec<String>, bool)>> =
const { std::cell::RefCell::new(None) };
}
pub struct CompensatingScope(Option<(Vec<String>, bool)>);
impl CompensatingScope {
#[must_use]
pub fn enter(marks: Vec<String>) -> Self {
Self(COMPENSATING.with(|current| current.replace(Some((marks, false)))))
}
#[must_use]
pub fn awaited(&self) -> bool {
COMPENSATING.with(|current| {
current
.borrow()
.as_ref()
.is_some_and(|(_, awaited)| *awaited)
})
}
}
impl Drop for CompensatingScope {
fn drop(&mut self) {
COMPENSATING.with(|current| *current.borrow_mut() = self.0.take());
}
}
#[must_use]
pub fn await_compensation() -> Vec<String> {
COMPENSATING.with(|current| {
current
.borrow_mut()
.as_mut()
.map(|(marks, awaited)| {
*awaited = true;
marks.clone()
})
.unwrap_or_default()
})
}
pub fn await_settlement(doc: &mut Doc, hash: &str, redo: bool) -> Result<(), ActionError> {
use automerge::ReadDoc as _;
let key = format!("{UNDONE_KEY}{hash}");
let before = doc
.get(automerge::ROOT, &key)?
.and_then(|(value, _)| value.as_i64())
.filter(|attempt| (*attempt > 0) == redo && *attempt != 0)
.unwrap_or(0);
let attempt = if redo {
before.checked_add(1)
} else {
before.checked_sub(1)
}
.ok_or_else(|| ActionError::Refused("settlement attempts exceed the budget".into()))?;
doc.put(automerge::ROOT, key, attempt)?;
Ok(())
}
pub fn settle_compensation(doc: &mut Doc, hash: &str) -> Result<(), ActionError> {
use automerge::ReadDoc as _;
let key = format!("{UNDONE_KEY}{hash}");
let pending = doc
.get(automerge::ROOT, &key)?
.and_then(|(value, _)| value.as_i64())
.filter(|attempt| *attempt != 0)
.ok_or_else(|| ActionError::Refused("history compensation is not pending".into()))?;
if pending < 0 {
doc.put(automerge::ROOT, key, true)?;
} else {
doc.delete(automerge::ROOT, key)?;
}
Ok(())
}
pub fn invoking_context() -> Option<ActionContext> {
INVOKING.with(|current| current.borrow().clone())
}
pub fn reading_invoking_context<T>(read: impl FnOnce(Option<&ActionContext>) -> T) -> T {
INVOKING.with(|current| read(current.borrow().as_ref()))
}
pub fn with_invoking_context<T>(context: Option<ActionContext>, work: impl FnOnce() -> T) -> T {
let _invoking = InvokingScope::enter(context);
work()
}
struct InvokingScope(Option<ActionContext>);
impl InvokingScope {
fn enter(context: Option<ActionContext>) -> Self {
Self(INVOKING.with(|current| current.replace(context)))
}
}
impl Drop for InvokingScope {
fn drop(&mut self) {
let outer = self.0.take();
INVOKING.with(|current| *current.borrow_mut() = outer);
}
}
enum Before {
Doc,
Written(Option<Box<Described>>),
}
fn envelope_for(
doc: &mut Doc,
action: &dyn Action,
encoded: EncodedAction,
actor: Option<&[u8]>,
context: Option<ActionContext>,
before: Before,
) -> Result<ActionEnvelope, ActionError> {
let pinned = (ActionId::new(), tilo_clock::unix_now_i64());
envelope_pinned(doc, action, encoded, actor, context, before, pinned)
}
pub fn envelope_at(
doc: &mut Doc,
action: &dyn Action,
encoded: EncodedAction,
(actor, context): (&[u8], ActionContext),
pinned: (ActionId, i64),
) -> Result<ActionEnvelope, ActionError> {
envelope_pinned(
doc,
action,
encoded,
Some(actor),
Some(context),
Before::Doc,
pinned,
)
}
fn envelope_pinned(
doc: &mut Doc,
action: &dyn Action,
encoded: EncodedAction,
actor: Option<&[u8]>,
context: Option<ActionContext>,
before: Before,
(id, timestamp): (ActionId, i64),
) -> Result<ActionEnvelope, ActionError> {
let base = match before {
Before::Doc => doc.get_heads(),
Before::Written(_) => doc.committed_heads(),
};
let change = action.change_kind();
let mut context = context.unwrap_or_default();
if change != ChangeKind::Content {
context.change = change;
}
context.kind = Some(action.action_kind());
if action.incoming_message()
&& !context
.facets
.iter()
.any(|facet| facet.key == crate::INCOMING_MESSAGE_FACET)
{
context.facets.push(crate::ActionFacet::new(
crate::INCOMING_MESSAGE_FACET,
"true",
));
}
if let Some(readers) = action.readers() {
context
.facets
.retain(|facet| facet.key != crate::READERS_FACET);
context.facets.push(crate::ActionFacet::new(
crate::READERS_FACET,
crate::contract::readers_facet(&readers),
));
}
if context.gesture.is_none() {
context.gesture = current_step();
}
let app = context.app.as_ref().map(|app| app.id.clone());
let (own, written) = match before {
Before::Doc => {
let _invoking = InvokingScope::enter(Some(context.clone()));
(action.describe(doc), false)
}
Before::Written(described) => (described.map(|described| *described), true),
};
let described = own
.or_else(|| context.described())
.or_else(|| Described::from_encoded(&encoded, app.as_deref()));
if let Some(mut described) = described {
if let Some(app) = app {
name_app(&mut described.what, &app);
}
context = context.with_described(described);
}
let actor = actor.filter(|a| !a.is_empty()).map(<[u8]>::to_vec);
let committing = actor
.clone()
.map_or_else(|| ActorId::from(id.actor_bytes().to_vec()), ActorId::from);
let compensation = if written {
None
} else {
inverse_as(doc, action, committing)
};
if compensation.is_none()
&& let Some(actor) = actor.as_deref()
&& let Some(gesture) = crate::run::continued_gesture(doc, actor, &context, timestamp)
{
context.gesture = Some(gesture);
}
if let Some(compensation) = &compensation
&& serde_json::to_vec(compensation)
.map_err(ActionError::Encode)?
.len()
> crate::context::COMPENSATION_BUDGET
{
return Err(ActionError::Refused(
"document compensation exceeds the history budget".into(),
));
}
context.action = Some(recorded_form(&encoded)?);
context.compensation = compensation;
let context = Some(context);
Ok(ActionEnvelope {
id,
action: encoded,
base_heads: base.iter().map(|h| h.0).collect(),
timestamp,
locus: action.locus(),
actor,
context,
})
}
pub fn inverse_as(doc: &mut Doc, action: &dyn Action, actor: ActorId) -> Option<EncodedAction> {
let previous = doc.get_actor().clone();
doc.set_actor(actor);
let inverse = action.inverse_encoded(doc);
doc.set_actor(previous);
inverse
}
fn name_app(what: &mut Did, app: &str) {
match what {
Did::Verb(verb) if verb.action.app.is_empty() => app.clone_into(&mut verb.action.app),
Did::Group(group) => {
for member in &mut group.members {
name_app(member, app);
}
}
_ => {}
}
}
fn apply_under_envelope(
doc: &mut Doc,
action: &dyn Action,
env: &ActionEnvelope,
content: Option<&tilo_content::ContentStore>,
) -> Result<Option<crate::entry::ActionItem>, ActionError> {
let prev_actor = doc.get_actor().clone();
doc.set_actor(env.actor());
let applied = {
let _invoking = InvokingScope::enter(env.context.clone());
action.apply(doc)
};
if let Err(e) = applied {
abort_pinned_change(doc, prev_actor);
return Err(e);
}
let mut made = None;
if doc.pending_ops() > 0 {
made = env
.context
.as_ref()
.filter(|context| !is_replaying() && context.what.is_some() && context.item.is_none())
.and_then(|_| action.made(doc));
commit_pinned(doc, env, made.as_ref());
doc.set_actor(prev_actor);
crate::content::keep(env, content);
} else {
abort_pinned_change(doc, prev_actor);
}
Ok(made)
}
fn commit_pinned(doc: &mut Doc, env: &ActionEnvelope, made: Option<&crate::entry::ActionItem>) {
let named = made.and_then(|item| {
let context = env.context.as_ref()?;
Some(
context
.clone()
.with_described(context.described()?.on(item.id.clone(), item.label.clone())),
)
});
let context = named.as_ref().or(env.context.as_ref());
let mut options = CommitOptions::default().with_time(env.timestamp);
if let Some(message) = context.and_then(|context| entry_message(doc, &env.actor(), context)) {
options = options.with_message(message);
}
doc.commit_with(options);
}
fn named(mut env: ActionEnvelope, made: Option<crate::entry::ActionItem>) -> ActionEnvelope {
if let Some(item) = made
&& let Some(context) = env.context.as_ref()
&& let Some(described) = context.described()
{
env.context = Some(
context
.clone()
.with_described(described.on(item.id, item.label)),
);
}
env
}
#[must_use]
pub fn entry_message(doc: &Doc, actor: &ActorId, context: &ActionContext) -> Option<String> {
if context.gesture.is_some() && context.compensation.is_none() {
let document = doc.committed_document();
let continuation = document
.hash_of_actor_seq(actor, document.applied_seq(actor))
.and_then(|last| context.continuation_of(&opening_entry(document, last)?));
if continuation.is_some() {
return continuation;
}
}
context.change_message()
}
const MAX_CONTINUATIONS: usize = 256;
const CONTINUATIONS_KEPT: usize = 8;
thread_local! {
static CONTINUATIONS: std::cell::RefCell<std::collections::VecDeque<(automerge::ChangeHash, ActionContext, usize)>> =
const { std::cell::RefCell::new(std::collections::VecDeque::new()) };
}
#[cfg(test)]
thread_local! {
static STEPS_BACK: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
#[must_use]
pub fn entry_of(doc: &automerge::Automerge, hash: automerge::ChangeHash) -> Option<ActionContext> {
let entry = opening_entry(doc, hash)?;
match doc.get_change_meta_by_hash(&hash)?.message.as_deref() {
Some(message) if message.starts_with(CONTINUATION_PREFIX) => {
ActionContext::continued(message, &entry)
}
_ => Some(entry),
}
}
fn opening_entry(doc: &automerge::Automerge, hash: automerge::ChangeHash) -> Option<ActionContext> {
let meta = doc.get_change_meta_by_hash(&hash)?;
let message = meta.message.as_deref()?;
if let Some(entry) = ActionContext::from_change_message(message) {
return Some(entry);
}
if !message.starts_with(CONTINUATION_PREFIX) {
return None;
}
let (first, depth) = first_entry(doc, &meta)?;
CONTINUATIONS.with_borrow_mut(|kept| {
if !kept.iter().any(|(kept, ..)| *kept == hash) {
if kept.len() >= CONTINUATIONS_KEPT {
kept.pop_front();
}
kept.push_back((hash, first.clone(), depth));
}
});
Some(first)
}
fn first_entry(
doc: &automerge::Automerge,
meta: &automerge::ChangeMetadata<'_>,
) -> Option<(ActionContext, usize)> {
for depth in 1..=MAX_CONTINUATIONS {
#[cfg(test)]
STEPS_BACK.with(|steps| steps.set(steps.get().saturating_add(1)));
let seq = meta.seq.checked_sub(u64::try_from(depth).ok()?)?;
let earlier = doc.get_change_meta_by_hash(&doc.hash_of_actor_seq(&meta.actor, seq)?)?;
let text = earlier.message.as_deref()?;
if let Some(first) = ActionContext::from_change_message(text) {
return Some((first, depth));
}
if !text.starts_with(CONTINUATION_PREFIX) {
return None;
}
let kept = CONTINUATIONS.with_borrow(|kept| {
kept.iter()
.find(|(hash, ..)| *hash == earlier.hash)
.map(|(_, first, back)| (first.clone(), *back))
});
if let Some((first, back)) = kept {
let depth = depth.checked_add(back)?;
return (depth <= MAX_CONTINUATIONS).then_some((first, depth));
}
}
None
}
#[cfg(test)]
#[path = "executor_entry_tests.rs"]
mod entry_tests;
#[derive(Default)]
pub struct EntryReader {
firsts: std::collections::HashMap<ActorId, ActionContext>,
}
impl EntryReader {
pub fn read(&mut self, actor: &ActorId, message: Option<&str>) -> Option<ActionContext> {
let message = message?;
if let Some(entry) = ActionContext::from_change_message(message) {
self.firsts.insert(actor.clone(), entry.clone());
return Some(entry);
}
ActionContext::continued(message, self.firsts.get(actor)?)
}
}
fn abort_pinned_change(doc: &mut Doc, prev_actor: ActorId) {
doc.rollback();
doc.reset_diff_cursor();
doc.set_actor(prev_actor);
}
pub fn apply_local(
doc: &mut Doc,
action: &dyn Action,
encoded: EncodedAction,
) -> Result<ActionEnvelope, ActionError> {
apply_local_by(doc, action, encoded, None)
}
pub fn apply_local_by(
doc: &mut Doc,
action: &dyn Action,
encoded: EncodedAction,
actor: Option<&[u8]>,
) -> Result<ActionEnvelope, ActionError> {
apply_steps(doc, action, encoded, (actor, None), &mut |_| {})
}
fn apply_steps(
doc: &mut Doc,
action: &dyn Action,
encoded: EncodedAction,
(actor, context): (Option<&[u8]>, Option<ActionContext>),
each: &mut dyn FnMut(&ActionEnvelope),
) -> Result<ActionEnvelope, ActionError> {
let steps = {
let _invoking = InvokingScope::enter(context.clone());
action.steps(doc).filter(|steps| !steps.is_empty())
};
let Some(steps) = steps else {
let env = envelope_for(doc, action, encoded, actor, context, Before::Doc)?;
let made = apply_under_envelope(doc, action, &env, None)?;
let env = named(env, made);
each(&env);
return Ok(env);
};
let mut context = context.unwrap_or_default();
let asked = {
let _invoking = InvokingScope::enter(Some(context.clone()));
action.describe(doc)
};
let op = match asked.map(|asked| asked.what) {
Some(Did::History(step)) => step.op,
_ => crate::HistoryOp::Undo,
};
let gesture = *context.gesture.get_or_insert_with(ActionId::new);
context.group.get_or_insert_with(|| crate::WorkGroup {
id: gesture.0.to_string(),
label: None,
kind: crate::context::history_group(&op),
declared_id: None,
session: None,
});
let context = Some(context);
let mut last = None;
for (step, payload) in steps {
let encoded = EncodedAction {
type_id: encoded.type_id.clone(),
payload,
};
let env = envelope_for(
doc,
step.as_ref(),
encoded,
actor,
context.clone(),
Before::Doc,
)?;
let made = apply_under_envelope(doc, step.as_ref(), &env, None)?;
let env = named(env, made);
each(&env);
last = Some(env);
}
last.ok_or_else(|| ActionError::Refused("no step to apply".into()))
}
pub fn apply_local_with_context(
doc: &mut Doc,
action: &dyn Action,
encoded: EncodedAction,
actor: Option<&[u8]>,
context: ActionContext,
) -> Result<ActionEnvelope, ActionError> {
apply_steps(doc, action, encoded, (actor, Some(context)), &mut |_| {})
}
pub fn commit_written(
doc: &mut Doc,
action: &dyn Action,
encoded: EncodedAction,
actor: &[u8],
context: ActionContext,
described: Option<Described>,
) -> Result<ActionEnvelope, ActionError> {
if doc.get_actor().to_bytes() != actor || doc.pending_ops() == 0 {
return Err(ActionError::Refused(
"the document holds no writes of this actor to commit".into(),
));
}
let env = envelope_for(
doc,
action,
encoded,
Some(actor),
Some(context),
Before::Written(described.map(Box::new)),
)?;
commit_pinned(doc, &env, None);
Ok(env)
}
pub fn replay(
doc: &mut Doc,
env: &ActionEnvelope,
registry: &ActionRegistry,
) -> Result<(), ActionError> {
let action = registry.decode(&env.action)?;
replay_decoded(doc, env, action.as_ref(), registry.content())
}
pub fn replay_decoded(
doc: &mut Doc,
env: &ActionEnvelope,
action: &dyn Action,
content: Option<&tilo_content::ContentStore>,
) -> Result<(), ActionError> {
let _replaying = ReplayScope::enter();
let base_heads = env.base_change_hashes();
if doc.get_heads() == base_heads {
validate_compensation(doc, action, env)?;
return apply_under_envelope(doc, action, env, content).map(drop);
}
let mut replay_base = doc.fork_at(&base_heads)?;
validate_compensation(&mut replay_base, action, env)?;
apply_under_envelope(&mut replay_base, action, env, content).map(drop)?;
merge_replayed(doc, &mut replay_base)?;
Ok(())
}
#[expect(
clippy::disallowed_methods,
reason = "the action layer's one merge, dropping what it logs"
)]
fn merge_replayed(
doc: &mut Doc,
replayed: &mut Doc,
) -> Result<Vec<automerge::ChangeHash>, automerge::AutomergeError> {
let merged = doc.merge(replayed);
if doc.diff_cursor().is_empty() {
doc.reset_diff_cursor();
}
merged
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Verified {
Reproduced,
NothingRecorded,
UnknownAction(String),
ContentMissing(String),
}
pub fn recorded_form(action: &EncodedAction) -> Result<EncodedAction, ActionError> {
if recorded_size(action) <= crate::context::WHOLE_ACTION_BUDGET {
return Ok(action.clone());
}
let recorded = action.with_content_parts(crate::content::CONTENT_PART_THRESHOLD)?;
if recorded_size(&recorded) > crate::context::HISTORY_BUDGET {
return Err(ActionError::Refused(
"the action is too large to record, even with its large parts kept as content".into(),
));
}
Ok(recorded)
}
fn recorded_size(action: &EncodedAction) -> usize {
action.type_id.len().saturating_add(action.payload.len())
}
pub fn verify_change(
doc: &mut Doc,
hash: automerge::ChangeHash,
registry: &ActionRegistry,
) -> Result<Verified, ActionError> {
let change = doc
.get_change_meta_by_hash(&hash)
.ok_or_else(|| ActionError::Refused("the change is not in the document".into()))?
.into_owned();
let Some(context) = entry_of(doc.committed_document(), hash) else {
return Ok(Verified::NothingRecorded);
};
let Some(recorded) = context.action.as_ref() else {
return Ok(Verified::NothingRecorded);
};
if !registry.contains(&recorded.type_id) {
return Ok(Verified::UnknownAction(recorded.type_id.clone()));
}
let action = match registry.resolve(recorded)? {
Ok(action) => action,
Err(missing) => return Ok(Verified::ContentMissing(missing.0)),
};
let env = ActionEnvelope {
id: ActionId::new(),
action,
base_heads: change.deps.iter().map(|head| head.0).collect(),
timestamp: change.timestamp,
locus: ExecutionLocus::ClientLocal,
actor: Some(change.actor.to_bytes().to_vec()),
context: Some(context),
};
let mut original = doc.fork_at(&change.deps)?;
replay(&mut original, &env, registry)?;
if original.get_heads() != [hash] {
return Err(ActionError::Refused(
"the change is not what its recorded action produces".into(),
));
}
Ok(Verified::Reproduced)
}
pub fn verified_compensation(
doc: &mut Doc,
hash: automerge::ChangeHash,
registry: &ActionRegistry,
) -> Result<Option<Box<dyn Action>>, ActionError> {
doc.get_change_meta_by_hash(&hash)
.ok_or_else(|| ActionError::Refused("history change is unavailable".into()))?;
let inverse = entry_of(doc.committed_document(), hash).and_then(|context| context.compensation);
let Some(inverse) = inverse else {
return Ok(None);
};
match verify_change(doc, hash, registry)? {
Verified::Reproduced => registry.decode(&inverse).map(Some),
Verified::NothingRecorded | Verified::UnknownAction(_) | Verified::ContentMissing(_) => {
Err(ActionError::Refused(
"recorded history action does not reproduce its change".into(),
))
}
}
}
fn validate_compensation(
doc: &mut Doc,
action: &dyn Action,
env: &ActionEnvelope,
) -> Result<(), ActionError> {
let Some(context) = env.context.as_ref() else {
return Ok(());
};
let Some(recorded) = context.action.as_ref() else {
return Ok(());
};
if recorded.recorded_parts_of(&env.action).is_none()
|| inverse_as(doc, action, env.actor()) != context.compensation
{
return Err(ActionError::Refused(
"recorded compensation differs from the action's canonical before state".into(),
));
}
Ok(())
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum HostDecision {
AcceptedByHost,
Unavailable,
}
pub trait ActionTransport {
fn replicate(&mut self, env: &ActionEnvelope);
fn submit_to_host(&mut self, _env: &ActionEnvelope) -> HostDecision {
HostDecision::Unavailable
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Dispatched {
AppliedLocal(ActionEnvelope),
SubmittedToHost(ActionEnvelope),
}
impl Dispatched {
pub fn envelope(&self) -> &ActionEnvelope {
match self {
Dispatched::AppliedLocal(e) | Dispatched::SubmittedToHost(e) => e,
}
}
pub fn mutated_local(&self) -> bool {
!matches!(self, Dispatched::SubmittedToHost(_))
}
}
pub fn dispatch(
doc: &mut Doc,
action: &dyn Action,
encoded: EncodedAction,
transport: &mut dyn ActionTransport,
) -> Result<Dispatched, ActionError> {
dispatch_by(doc, action, encoded, transport, None)
}
pub fn dispatch_by(
doc: &mut Doc,
action: &dyn Action,
encoded: EncodedAction,
transport: &mut dyn ActionTransport,
actor: Option<&[u8]>,
) -> Result<Dispatched, ActionError> {
dispatch_by_maybe_context(doc, action, encoded, transport, actor, None)
}
pub fn dispatch_with_context(
doc: &mut Doc,
action: &dyn Action,
encoded: EncodedAction,
transport: &mut dyn ActionTransport,
context: ActionContext,
) -> Result<Dispatched, ActionError> {
dispatch_by_maybe_context(doc, action, encoded, transport, None, Some(context))
}
pub fn dispatch_by_with_context(
doc: &mut Doc,
action: &dyn Action,
encoded: EncodedAction,
transport: &mut dyn ActionTransport,
actor: Option<&[u8]>,
context: ActionContext,
) -> Result<Dispatched, ActionError> {
dispatch_by_maybe_context(doc, action, encoded, transport, actor, Some(context))
}
fn dispatch_by_maybe_context(
doc: &mut Doc,
action: &dyn Action,
encoded: EncodedAction,
transport: &mut dyn ActionTransport,
actor: Option<&[u8]>,
context: Option<ActionContext>,
) -> Result<Dispatched, ActionError> {
match action.locus() {
ExecutionLocus::ClientLocal => {
apply_steps(doc, action, encoded, (actor, context), &mut |env| {
transport.replicate(env);
})
.map(Dispatched::AppliedLocal)
}
ExecutionLocus::ServerPreferred => {
let env = envelope_for(doc, action, encoded, actor, context, Before::Doc)?;
match transport.submit_to_host(&env) {
HostDecision::AcceptedByHost => Ok(Dispatched::SubmittedToHost(env)),
HostDecision::Unavailable => Err(ActionError::Refused(
"this action requires an authoritative host, but none is reachable".into(),
)),
}
}
}
}
#[derive(Default)]
pub struct LocalTransport {
pub replicated: Vec<ActionEnvelope>,
}
impl LocalTransport {
pub fn new() -> Self {
Self::default()
}
}
impl ActionTransport for LocalTransport {
fn replicate(&mut self, env: &ActionEnvelope) {
self.replicated.push(env.clone());
}
}