tilo_resource/replica.rs
1//! An in-memory replica of one resource: the harness for replay-based tests,
2//! and a resource document held apart from any window — the contents of a
3//! file an app saves its resource to and opens it from ([`Replica::load`],
4//! [`Replica::save`]).
5//!
6//! A replica applies actions exactly as the host does: it publishes the
7//! resource's tree, and every invocation goes through the action API —
8//! resolved against what is published, checked for availability and
9//! confirmation, built from the same declarations the palette and agents
10//! use, decoded through the registry a peer would replay with, and committed
11//! with its history entry. A test written against it proves the behaviour
12//! every surface gets. Fork two replicas to test collaboration; replay one
13//! replica's log into a fresh one to prove determinism.
14//!
15//! A replica names the app whose record it is ([`Replica::in_app`]) before it
16//! applies anything: every device decides a change against that app's surface,
17//! and a change that named none would be decided against an app guessed from
18//! its type id. The name is part of the type, so a caller that forgets it does
19//! not compile.
20
21use automerge::ChangeHash;
22use tilo_action_policy::MemberId;
23use tilo_actions::api::{self, InvocationProvenance};
24use tilo_actions::{
25 ActionAddress, ActionEnvelope, ActionError, ActionRegistry, ApiError, LocalTransport,
26};
27use tilo_automerge::ApplyIncoming;
28
29use crate::action::Invoke;
30use crate::history::{self, Version};
31use crate::model::{Doc, ModelError};
32use crate::reader::{Demand, Reader};
33use crate::resource::{self, Resource};
34
35/// The app a replica names when the record is only a model a test exercises: nothing decides
36/// such a change against a surface, and no host ever receives it.
37pub const MODEL_APP_ID: &str = "so.tilo.model";
38
39/// A replica that has named no app: it reads, forks, saves and replays its log, and it cannot
40/// apply an action. [`Replica::in_app`] names the app the record belongs to, and only then does
41/// [`Replica::apply`] exist.
42pub struct NoApp;
43
44/// A replica whose actions name the app the record belongs to ([`Replica::in_app`]): the app
45/// every device decides the change against.
46pub struct AppNamed;
47
48/// One replica of an `R` resource. See the module docs.
49pub struct Replica<R: Resource, A = NoApp> {
50 doc: Doc,
51 registry: ActionRegistry,
52 log: Vec<ActionEnvelope>,
53 author: Option<MemberId>,
54 /// The author as software acting for someone.
55 acting: Option<tilo_actions::Acting>,
56 /// Who invokes from this replica when it acts as its own device
57 /// ([`Self::as_invoker`], [`Self::as_invoker_acting`]).
58 invoker: Option<tilo_actions::Acting>,
59 /// The app later actions are in (id, label), as a host names it.
60 app: Option<(String, String)>,
61 /// What a bot shows for later actions instead of its own name.
62 appearance: Option<tilo_actions::Appearance>,
63 /// The name the host admitted the actor of later actions under.
64 name: Option<String>,
65 /// The work unit later actions belong to (id, label, kind).
66 group: Option<(String, String, String)>,
67 /// The call later actions are made for, as its caller signed it ([`Self::serving`]).
68 serving: Option<(
69 tilo_actions::InvocationId,
70 Box<tilo_actions::remote::SignedCall>,
71 )>,
72 now_ms: i64,
73 /// The incrementally maintained state views would see, once asked for.
74 reader: Option<Reader<R>>,
75 marker: std::marker::PhantomData<fn() -> (R, A)>,
76}
77
78impl<R: Resource> Default for Replica<R> {
79 fn default() -> Self {
80 Self::new()
81 }
82}
83
84/// A replica that names no app: what reads, forking and saving use, and what a unit test's
85/// model is exercised on. It cannot apply an action until [`Replica::in_app`] names the app
86/// whose record it is; a system write has no other way to reach the action API.
87impl<R: Resource> Replica<R, NoApp> {
88 /// The id of the record a new replica holds ([`Self::new`]), which its founding and version
89 /// steps are derived from: bring a document of one up under it
90 /// ([`crate::founding::bring_up_resource`]) to stand on the same chain.
91 pub const ID: &str = "record";
92
93 /// The workspace the record a new replica holds is in ([`Self::new`]): a record's founding
94 /// and steps are derived within its workspace, so bring a document of one up in it as well.
95 pub const WORKSPACE: &str = "replica";
96
97 /// A new resource, initialized as a new record would be.
98 ///
99 /// # Panics
100 /// Panics when [`Resource::initialize`] fails, which is a bug in the
101 /// resource type under test.
102 #[must_use]
103 #[allow(
104 clippy::expect_used,
105 reason = "a test harness surfaces initializer bugs loudly"
106 )]
107 pub fn new() -> Replica<R, NoApp> {
108 let mut doc = crate::founding::new_record::<R>(Self::WORKSPACE, Self::ID)
109 .expect("resource initializer");
110 // What a brand-new record starts with names itself as its genesis.
111 doc.commit_with(
112 automerge::transaction::CommitOptions::default()
113 .with_message(tilo_actions::FrameworkChange::Genesis.change_message()),
114 );
115 Self::from_doc(doc)
116 }
117
118 /// A replica of an existing document.
119 #[must_use]
120 pub fn from_doc(doc: Doc) -> Replica<R, NoApp> {
121 let registry = ActionRegistry::with(crate::group::register::<R>);
122 Self {
123 doc,
124 registry,
125 log: Vec::new(),
126 author: None,
127 acting: None,
128 invoker: None,
129 app: None,
130 appearance: None,
131 name: None,
132 group: None,
133 serving: None,
134 now_ms: 1_700_000_000_000,
135 reader: None,
136 marker: std::marker::PhantomData,
137 }
138 }
139
140 /// A replica of a document [saved](Self::save) as bytes: a file's
141 /// contents.
142 ///
143 /// # Errors
144 /// Returns [`ModelError::Automerge`] when the bytes hold no document.
145 pub fn load(bytes: &[u8]) -> Result<Replica<R, NoApp>, ModelError> {
146 Ok(Self::from_doc(Doc::load(bytes)?))
147 }
148
149 /// Name `id` (labelled `label`) as the app later actions are in, as the
150 /// host running the app does: every member decides them against that
151 /// app's surface.
152 #[must_use]
153 pub fn in_app(mut self, id: &str, label: &str) -> Replica<R, AppNamed> {
154 self.app = Some((id.to_owned(), label.to_owned()));
155 Replica {
156 doc: self.doc,
157 registry: self.registry,
158 log: self.log,
159 author: self.author,
160 acting: self.acting,
161 invoker: self.invoker,
162 app: self.app,
163 appearance: self.appearance,
164 name: self.name,
165 group: self.group,
166 serving: self.serving,
167 now_ms: self.now_ms,
168 reader: self.reader,
169 marker: std::marker::PhantomData,
170 }
171 }
172}
173
174impl<R: Resource> Replica<R, AppNamed> {
175 /// Name another app later actions are in, replacing the one named before.
176 #[must_use]
177 pub fn in_app(mut self, id: &str, label: &str) -> Replica<R, AppNamed> {
178 self.app = Some((id.to_owned(), label.to_owned()));
179 self
180 }
181}
182
183impl<R: Resource, A> Replica<R, A> {
184 /// The document as bytes, for a file that carries the resource whole.
185 pub fn save(&mut self) -> Vec<u8> {
186 self.doc.save()
187 }
188
189 /// Attribute later actions to `author`, as the host does for a signed-in
190 /// member.
191 #[must_use]
192 pub fn as_author(self, person: &str) -> Self {
193 self.as_member(MemberId::person(person))
194 }
195
196 /// Attribute later actions to `member`.
197 #[must_use]
198 pub fn as_member(mut self, member: MemberId) -> Self {
199 self.author = Some(member);
200 self
201 }
202
203 /// Attribute later actions to `author` invoking from this replica, as
204 /// the host does for a person at one of their devices: what a verb reads
205 /// as [`ActionCx::author`](crate::ActionCx::author), while the changes
206 /// stay this replica's own, so the same person on two replicas makes
207 /// changes that merge.
208 #[must_use]
209 pub fn as_invoker(mut self, person: &str) -> Self {
210 self.invoker = Some(tilo_actions::Acting::person(person));
211 self
212 }
213
214 /// Attribute later actions to the invoker `acting` — a person, or an agent or automation
215 /// acting for one — while the changes stay this device's own: what a host
216 /// writes a record for the one that asked it, so every holder decides the change as that
217 /// invoker, exactly as it decides the same action invoked on the invoker's own device.
218 #[must_use]
219 pub fn as_invoker_acting(mut self, acting: tilo_actions::Acting) -> Self {
220 self.invoker = Some(acting);
221 self
222 }
223
224 /// Attribute actions to an actor already admitted by the caller.
225 #[must_use]
226 pub fn as_acting(mut self, acting: tilo_actions::Acting) -> Self {
227 self.author = acting.member_id().cloned();
228 self.acting = Some(acting);
229 self
230 }
231
232 /// Attribute later actions to the agent `agent` acting for `person`, as
233 /// a host does for an agent's calls.
234 #[must_use]
235 pub fn as_agent_for(self, agent: &str, person: &str) -> Self {
236 self.as_acting(
237 tilo_actions::Acting::agent(agent, person)
238 .acting_for(tilo_actions::Acting::person(person)),
239 )
240 }
241
242 /// Attribute later actions to the agent `agent` a device runs on `person`'s turn, handed
243 /// the delegation a device gives the agents it runs ([`tilo_actions::Acting::handed_agent`]):
244 /// whichever member it acts for, it does what their grants and its preset allow, as every
245 /// receiver decides it.
246 #[must_use]
247 pub fn as_handed_agent_for(self, agent: &str, person: &str) -> Self {
248 self.as_acting(tilo_actions::Acting::handed_agent(agent, person))
249 }
250
251 /// Attribute later actions to the bot installation `installation`
252 /// acting for `installer`, as a bot host does for a bot's calls.
253 #[must_use]
254 pub fn as_bot_for(mut self, installation: &str, installer: &str) -> Self {
255 self.author = Some(MemberId::bot(installation));
256 self.acting = Some(
257 tilo_actions::Acting::bot(installation)
258 .acting_for(tilo_actions::Acting::person(installer)),
259 );
260 self
261 }
262
263 /// Show `appearance` for the bot's later actions, as a bot host admits
264 /// a bridge's post under another name.
265 #[must_use]
266 pub fn showing(mut self, appearance: tilo_actions::Appearance) -> Self {
267 self.appearance = Some(appearance);
268 self
269 }
270
271 /// Admit the actor of later actions under the name `name`, as a host
272 /// names an agent it admits (`Company mover`).
273 #[must_use]
274 pub fn named(mut self, name: &str) -> Self {
275 self.name = Some(name.to_owned());
276 self
277 }
278
279 /// Stamp later actions as part of the work unit `id` (labelled `label`,
280 /// of kind `kind`), as a shell does for every action one command line
281 /// asks for: History attributes and undoes them as one.
282 #[must_use]
283 pub fn within_group(mut self, id: &str, label: &str, kind: &str) -> Self {
284 self.group = Some((id.to_owned(), label.to_owned(), kind.to_owned()));
285 self
286 }
287
288 /// Keep `call`, the invocation `invocation` as its caller signed it, with later actions: what
289 /// a host writes for a caller who asked under their own key, so every device reading them checks that
290 /// they asked, and for what.
291 #[must_use]
292 pub fn serving(
293 mut self,
294 invocation: tilo_actions::InvocationId,
295 call: tilo_actions::remote::SignedCall,
296 ) -> Self {
297 self.serving = Some((invocation, Box::new(call)));
298 self
299 }
300
301 /// Set the origin clock later actions are stamped with.
302 pub fn set_now_ms(&mut self, now_ms: i64) {
303 self.now_ms = now_ms;
304 }
305
306 /// The tree the resource publishes now: what the API resolves against.
307 pub fn published(&self) -> Result<tilo_actions::ResourceSpec, ModelError> {
308 Ok(resource::publish::<R>(
309 R::KIND,
310 R::LABEL,
311 &R::read(&self.doc)?,
312 ))
313 }
314
315 /// Who later actions are invoked by, as a verb reads it: the author, or
316 /// the invoker, acting as attributed. `None` when neither is set.
317 #[must_use]
318 pub fn invoker(&self) -> Option<tilo_actions::ActionInvoker> {
319 let acting = match (&self.acting, &self.invoker) {
320 (Some(acting), _) | (None, Some(acting)) => acting.clone(),
321 (None, None) => tilo_actions::Acting::member(self.author.clone()?),
322 };
323 Some(
324 tilo_actions::ActionInvoker::admitted(&acting)
325 .with_appearance(self.appearance.clone())
326 .named(self.name.clone()),
327 )
328 }
329
330 fn invoke(&mut self, invoke: Invoke<R>, confirmed: bool) -> Result<&ActionEnvelope, ApiError> {
331 if let Some(refusal) = invoke.refusal() {
332 return Err(ApiError::InvalidArguments(refusal.to_owned()));
333 }
334 let Invoke { id, arguments, .. } = invoke;
335 // The action's declaration is what the write is dispatched against, and a type declares
336 // its actions: the tree is built from them alone, so a write costs what it changed, not
337 // a read of the whole record (which is what publishing its state would take).
338 let tree = resource::publish_actions::<R>(R::KIND, R::LABEL);
339 let address = ActionAddress::new(tree.id.as_str(), id);
340 // Without an author, the replica's own actor: every replica is a
341 // device of its own.
342 let actor = self.author.as_ref().map_or_else(
343 || self.doc.get_actor().to_bytes().to_vec(),
344 MemberId::actor_bytes,
345 );
346 // An author is also the invoker a verb reads (`ActionCx::author`), as
347 // the host pins the signed-in person.
348 let ambient = self
349 .invoker()
350 .map(|invoker| tilo_actions::ActionContext::default().with_invoker(invoker));
351 let ambient = match &self.app {
352 Some((id, label)) => Some(ambient.unwrap_or_default().with_app(id, label)),
353 None => ambient,
354 };
355 let ambient = match &self.group {
356 Some((id, label, kind)) => {
357 Some(ambient.unwrap_or_default().with_group(id, label, kind))
358 }
359 None => ambient,
360 };
361 let ambient = match &self.serving {
362 Some((invocation, call)) => {
363 let mut ambient = ambient.unwrap_or_default();
364 ambient.source_invocation = Some(*invocation);
365 ambient.signed = Some(call.clone());
366 Some(ambient)
367 }
368 None => ambient,
369 };
370 let mut transport = LocalTransport::new();
371 let (doc, registry) = (&mut self.doc, &self.registry);
372 let dispatched = resource::with_origin_clock(self.now_ms, || {
373 let resources = std::slice::from_ref(&tree);
374 let provenance = match &ambient {
375 Some(ambient) => InvocationProvenance::caller(&actor).within(ambient),
376 None => InvocationProvenance::caller(&actor),
377 };
378 api::invoke_json(
379 doc,
380 resources,
381 &address,
382 &arguments,
383 (provenance, confirmed),
384 registry,
385 &mut transport,
386 )
387 })?;
388 self.log.push(dispatched.envelope().clone());
389 self.log
390 .last()
391 .ok_or_else(|| ApiError::Failed("no envelope".into()))
392 }
393
394 /// Replay an envelope authored on another replica.
395 pub fn replay(&mut self, envelope: &ActionEnvelope) -> Result<(), ActionError> {
396 tilo_actions::replay(&mut self.doc, envelope, &self.registry)?;
397 self.log.push(envelope.clone());
398 Ok(())
399 }
400
401 /// The current state.
402 pub fn state(&self) -> Result<R::State, ModelError> {
403 R::read(&self.doc)
404 }
405
406 /// The state as a view sees it: read once, then kept current by applying
407 /// only what each change touched ([`Resource::refresh`]) and reading
408 /// what is demanded ([`Resource::load`]). A test comparing it with
409 /// [`Self::state`] proves the resource's incremental reads exact.
410 pub fn live(&mut self) -> Result<&R::State, ModelError> {
411 if let Some(reader) = &mut self.reader {
412 reader.sync(&self.doc)?;
413 } else {
414 self.reader = Some(Reader::open(&mut self.doc)?);
415 }
416 match &self.reader {
417 Some(reader) => Ok(reader.state()),
418 None => Err(ModelError::invalid("no reader")),
419 }
420 }
421
422 /// Ask the view state of [`Self::live`] for the parts `demand` names.
423 pub fn demand(&mut self, demand: Demand) -> Result<&R::State, ModelError>
424 where
425 R::State: Clone,
426 {
427 self.live()?;
428 let Some(reader) = self.reader.as_mut() else {
429 return Err(ModelError::invalid("no reader"));
430 };
431 reader.demand(&self.doc, demand)?;
432 Ok(reader.state())
433 }
434
435 /// A second replica sharing this one's history, as a member who
436 /// just joined would hold.
437 #[must_use]
438 pub fn fork(&mut self) -> Self {
439 Self {
440 doc: self.doc.fork(),
441 registry: ActionRegistry::with(crate::group::register::<R>),
442 log: Vec::new(),
443 author: None,
444 acting: None,
445 invoker: None,
446 // The fork acts in the same app's record as the copy it is taken from.
447 app: self.app.clone(),
448 appearance: None,
449 name: None,
450 group: None,
451 serving: None,
452 now_ms: self.now_ms,
453 reader: None,
454 marker: std::marker::PhantomData,
455 }
456 }
457
458 /// Exchange every change with `other`, as sync does.
459 pub fn sync_with(&mut self, other: &mut Self) -> Result<(), ModelError> {
460 self.doc.merge_incoming(&mut other.doc)?;
461 other.doc.merge_incoming(&mut self.doc)?;
462 Ok(())
463 }
464
465 /// Every envelope applied or replayed here, in order.
466 pub fn log(&self) -> &[ActionEnvelope] {
467 &self.log
468 }
469
470 pub fn doc(&self) -> &Doc {
471 &self.doc
472 }
473
474 /// The document, for a test that changes it the way something outside
475 /// the resource's actions would (a restore, a raw merge).
476 pub fn doc_mut(&mut self) -> &mut Doc {
477 &mut self.doc
478 }
479
480 pub fn heads(&mut self) -> Vec<ChangeHash> {
481 self.doc.get_heads()
482 }
483
484 /// The version history.
485 pub fn versions(&mut self) -> Vec<Version> {
486 history::versions(&mut self.doc)
487 }
488
489 pub fn state_at(&mut self, heads: &[ChangeHash]) -> Result<R::State, ModelError> {
490 history::read_at::<R>(&mut self.doc, heads)
491 }
492}
493
494/// A replica whose actions name the app its record belongs to.
495impl<R: Resource> Replica<R, AppNamed> {
496 /// Invoke a published action exactly as a control, the palette, an
497 /// agent or a script does: through the API, which refuses one that
498 /// asks for confirmation ([`Self::apply_confirmed`]).
499 pub fn apply(&mut self, invoke: impl Into<Invoke<R>>) -> Result<&ActionEnvelope, ApiError> {
500 self.invoke(invoke.into(), false)
501 }
502
503 /// [`Self::apply`] after the person confirmed it.
504 ///
505 /// # Errors
506 /// As [`Self::apply`], without asking for confirmation.
507 pub fn apply_confirmed(
508 &mut self,
509 invoke: impl Into<Invoke<R>>,
510 ) -> Result<&ActionEnvelope, ApiError> {
511 self.invoke(invoke.into(), true)
512 }
513
514 /// Apply one typed action value, the path a custom surface takes once
515 /// its person confirmed what it does: the generic
516 /// [`APPLY`](crate::APPLY) action, through the API.
517 pub fn apply_action(&mut self, action: &R::Action) -> Result<&ActionEnvelope, ApiError> {
518 let invoke =
519 Invoke::apply(action).map_err(|error| ApiError::InvalidArguments(error.to_string()))?;
520 self.invoke(invoke, true)
521 }
522}