Skip to main content

egui_pop_api/
host.rs

1//! The host: the application's kernel, which egui-pop wraps (ADR 0010).
2//!
3//! <div class="warning">Experimental: may change in any release
4//! (docs/stability.md).</div>
5//!
6//! egui-pop keeps the interface's part: command declarations (name,
7//! keys, `when`, menus) feeding the menus, the palette, the keymap and the
8//! traces; focus, overlays, layout, theme and interface settings. The
9//! application's part goes through a [`Host`]:
10//!
11//! - [`Host::dispatch`] runs a command, now or later ([`Reply`]), so a
12//!   long or remote command never holds a frame;
13//! - an event journal ([`Host::publish`], [`Host::since`],
14//!   [`Host::last_seq`]): each event has a sequence number, a source and
15//!   a cause, and tests and the debug bridge read it since a sequence
16//!   number instead of sleeping. A host keeps it in a [`Journal`] it
17//!   hands out ([`Host::journal`]), or on its own bus (it answers
18//!   `publish`, `since` and `last_seq` itself), or not at all: egui-pop
19//!   then keeps one in memory, as `LocalHost` does. When the
20//!   application's bus offers the contract's journal and the host keeps
21//!   none of its own (`LocalHost` keeps none then), the journal is the
22//!   bus's: one per process (`crate::bus::HOST_JOURNAL`);
23//! - the value store holding settings ([`Host::store`]);
24//! - the owner of the application's histories ([`Host::history`], ADR
25//!   0014): its scopes, their steps and labels ("Undo exposure change"),
26//!   undo, redo and jump. egui-pop owns the keys, the commands and the
27//!   steps around them (`edit.undo`, `edit.redo`, `edit.jump`, ADR 0011)
28//!   and routes Ctrl+Z by focus; the owner says what an undo is. The
29//!   default undoes the store's application history;
30//! - a [`Waker`] the host calls from any thread when something changed
31//!   ([`Host::set_waker`]);
32//! - where the workbench's layout is kept ([`Host::layout_document`]):
33//!   one document by default, a workspace's own, or none (the host keeps
34//!   it);
35//! - the owner of the context stack ([`Host::contexts`]): the kernel's,
36//!   or egui-pop's `LocalContexts` by default;
37//! - the owner of the clipboard ([`Host::clipboard`]): the kernel's, or
38//!   egui-pop's `LocalClipboard` by default; and the history groups a
39//!   paste is made in ([`Host::begin_group`], [`Host::end_group`]): the
40//!   store's by default.
41//!
42//! [`LocalHost`] is the default: commands run in-process on the
43//! interface thread (their handlers given to `Ctx::command`), the journal
44//! is kept in memory. An application with its own kernel implements
45//! `Host`, declares its commands with `Ctx::declare` and gives the host
46//! to `AppBuilder::host`.
47//!
48//! ```
49//! use egui_pop_api::host::{self, Dispatch, Host, Journal, Reply, Waker};
50//! use egui_pop_api::{App, Ctx, Plugin, PluginError};
51//! use egui_pop_model::commands::{CommandSpec, Origin};
52//! use egui_pop_model::ids::{CommandId, PluginId};
53//!
54//! /// A kernel elsewhere: answers later, from another thread.
55//! #[derive(Default)]
56//! struct Remote {
57//!     journal: Journal,
58//!     store: egui_pop_core::binding::SharedStore,
59//!     waker: Waker,
60//! }
61//!
62//! impl Host for Remote {
63//!     fn dispatch(&mut self, d: &Dispatch<'_>) -> Reply {
64//!         let (pending, resolver) = host::pending();
65//!         let waker = self.waker.clone();
66//!         let n = d.args.as_i64().unwrap_or(0);
67//!         std::thread::spawn(move || {
68//!             resolver.resolve(Ok(serde_json::json!(n * 2)));
69//!             waker.wake();
70//!         })
71//!         .join()
72//!         .unwrap();
73//!         Reply::Later(pending)
74//!     }
75//!     fn journal(&self) -> Option<&Journal> { Some(&self.journal) }
76//!     fn journal_mut(&mut self) -> Option<&mut Journal> { Some(&mut self.journal) }
77//!     fn store(&self) -> egui_pop_core::binding::SharedStore { self.store.clone() }
78//!     fn set_waker(&mut self, waker: Waker) { self.waker = waker; }
79//! }
80//!
81//! struct Doubler;
82//! impl Plugin for Doubler {
83//!     fn id(&self) -> PluginId { PluginId::from_static("doubler") }
84//!     fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
85//!         ctx.declare(CommandSpec::new(CommandId::from_static("doubler.go"), "Double", "Demo"))?;
86//!         Ok(())
87//!     }
88//! }
89//!
90//! let mut app = App::builder().host(Remote::default()).plugin(Doubler)
91//!     .build(&egui::Context::default()).unwrap();
92//! let go = CommandId::from_static("doubler.go");
93//! assert!(matches!(app.run(&go, serde_json::json!(21), Origin::User), Reply::Later(_)));
94//! assert!(app.handle().running(&go));
95//! app.settle();
96//! assert_eq!(app.handle().history().last().unwrap().result, Ok(serde_json::json!(42)));
97//! ```
98
99use std::collections::VecDeque;
100use std::fmt;
101use std::rc::Rc;
102use std::sync::{Arc, Mutex};
103
104use egui_pop_core::binding::SharedStore;
105use egui_pop_core::lock;
106use egui_pop_model::commands::Origin;
107use egui_pop_model::ids::{CommandId, OwnerId};
108use egui_pop_model::values::{GestureId, Store};
109use egui_pop_model::when::WhenContext;
110use serde::Serialize;
111use serde_json::Value as Json;
112
113use crate::app::{AppHandle, Call, CommandFn};
114
115/// A position in the journal: events are numbered from 1, in order.
116pub type Seq = u64;
117
118/// Something that happened, as the journal keeps it.
119#[derive(Clone, Debug, PartialEq, Serialize)]
120pub struct Event {
121    pub seq: Seq,
122    /// Who did it: `user`, `agent:<name>`, a plugin, the host.
123    pub source: String,
124    /// The event it follows from (a command's dispatch for its result).
125    pub cause: Option<Seq>,
126    /// What happened: `command.dispatched`, `command.done`,
127    /// `command.failed`, or the application's own names.
128    pub name: String,
129    pub data: Json,
130}
131
132/// How many events a [`Journal`] keeps by default.
133pub const JOURNAL: usize = 1024;
134
135/// Events in order, the oldest dropped past a capacity.
136#[derive(Clone, Debug)]
137pub struct Journal {
138    events: VecDeque<Event>,
139    next: Seq,
140    capacity: usize,
141}
142
143impl Default for Journal {
144    fn default() -> Self {
145        Self::with_capacity(JOURNAL)
146    }
147}
148
149impl Journal {
150    pub fn with_capacity(capacity: usize) -> Self {
151        Self {
152            events: VecDeque::new(),
153            next: 1,
154            capacity: capacity.max(1),
155        }
156    }
157
158    /// Appends an event; returns its sequence number.
159    pub fn publish(&mut self, source: &str, cause: Option<Seq>, name: &str, data: Json) -> Seq {
160        let seq = self.next;
161        self.next += 1;
162        if self.events.len() == self.capacity {
163            self.events.pop_front();
164        }
165        self.events.push_back(Event {
166            seq,
167            source: source.into(),
168            cause,
169            name: name.into(),
170            data,
171        });
172        seq
173    }
174
175    /// The events after `seq` still kept, oldest first (`since(0)`: all).
176    pub fn since(&self, seq: Seq) -> Vec<Event> {
177        self.events
178            .iter()
179            .filter(|e| e.seq > seq)
180            .cloned()
181            .collect()
182    }
183
184    /// The last sequence number given (0: none yet).
185    pub fn last(&self) -> Seq {
186        self.next - 1
187    }
188}
189
190/// Wakes the interface (asks for a frame) from any thread.
191#[derive(Clone)]
192pub struct Waker(Arc<dyn Fn() + Send + Sync>);
193
194impl Waker {
195    pub fn new(wake: impl Fn() + Send + Sync + 'static) -> Self {
196        Self(Arc::new(wake))
197    }
198
199    pub fn wake(&self) {
200        (self.0)();
201    }
202}
203
204impl Default for Waker {
205    /// Wakes nothing (before the application gives its own).
206    fn default() -> Self {
207        Self::new(|| {})
208    }
209}
210
211impl fmt::Debug for Waker {
212    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
213        f.write_str("Waker")
214    }
215}
216
217type Slot = Arc<Mutex<Option<Result<Json, String>>>>;
218
219/// A result to come, held by the interface.
220#[derive(Clone, Debug)]
221pub struct Pending(Slot);
222
223/// Gives a [`Pending`] its result, from any thread.
224#[derive(Debug)]
225pub struct Resolver(Slot);
226
227/// A result to come and the way to give it.
228pub fn pending() -> (Pending, Resolver) {
229    let slot: Slot = Arc::default();
230    (Pending(slot.clone()), Resolver(slot))
231}
232
233impl Pending {
234    /// The result, once given (taken once).
235    pub fn take(&self) -> Option<Result<Json, String>> {
236        lock(&self.0).take()
237    }
238}
239
240impl Resolver {
241    pub fn resolve(self, result: Result<Json, String>) {
242        *lock(&self.0) = Some(result);
243    }
244}
245
246/// What a dispatch gives back.
247#[derive(Debug)]
248pub enum Reply {
249    /// The result, now.
250    Done(Result<Json, String>),
251    /// The result comes later; the command shows as running until then.
252    Later(Pending),
253}
254
255impl Reply {
256    /// The result if it is there now.
257    pub fn now(self) -> Option<Result<Json, String>> {
258        match self {
259            Reply::Done(r) => Some(r),
260            Reply::Later(_) => None,
261        }
262    }
263}
264
265impl PartialEq for Reply {
266    /// Two results now compare by value; results to come never equal.
267    fn eq(&self, other: &Self) -> bool {
268        matches!((self, other), (Reply::Done(a), Reply::Done(b)) if a == b)
269    }
270}
271
272/// A command handed to the host.
273pub struct Dispatch<'a> {
274    pub command: &'a CommandId,
275    pub args: &'a Json,
276    pub origin: &'a Origin,
277    /// The context it runs in (its `when` held there).
278    pub context: &'a WhenContext,
279    /// Its `command.dispatched` event: the cause of its result.
280    pub seq: Seq,
281    pub app: &'a AppHandle,
282    local: Option<&'a CommandFn>,
283    /// Who declared it: the scope its in-process handler writes as.
284    owner: Option<&'a OwnerId>,
285    deferred: bool,
286}
287
288impl fmt::Debug for Dispatch<'_> {
289    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
290        f.debug_struct("Dispatch")
291            .field("command", self.command)
292            .field("args", self.args)
293            .field("origin", self.origin)
294            .field("seq", &self.seq)
295            .field("local", &self.local.is_some())
296            .finish_non_exhaustive()
297    }
298}
299
300impl<'a> Dispatch<'a> {
301    pub(crate) fn new(
302        command: &'a CommandId,
303        args: &'a Json,
304        origin: &'a Origin,
305        context: &'a WhenContext,
306        seq: Seq,
307        app: &'a AppHandle,
308        local: Option<&'a CommandFn>,
309    ) -> Self {
310        Self {
311            command,
312            args,
313            origin,
314            context,
315            seq,
316            app,
317            local,
318            owner: None,
319            deferred: false,
320        }
321    }
322
323    /// Its handler runs after the dispatch.
324    pub(crate) fn deferring(mut self, deferred: bool) -> Self {
325        self.deferred = deferred;
326        self
327    }
328
329    /// Whether this command's in-process handler runs after the dispatch
330    /// returns rather than inside it: its run calls the host itself
331    /// (undo and redo, `history.*`, the context stack's and the
332    /// clipboard's commands), which the dispatch holds. `run_local`
333    /// approves it and answers `null` at once; the interface then runs
334    /// the handler and the command's result is the handler's. A host
335    /// refuses such a command as any other, by answering an error
336    /// without calling `run_local`.
337    pub fn deferred(&self) -> bool {
338        self.deferred
339    }
340
341    /// Who declared it.
342    pub(crate) fn owned_by(mut self, owner: Option<&'a OwnerId>) -> Self {
343        self.owner = owner;
344        self
345    }
346
347    /// The plugin that declared it, if one did.
348    pub fn owner(&self) -> Option<&OwnerId> {
349        self.owner
350    }
351
352    /// Whether a plugin gave this command an in-process handler.
353    pub fn has_local(&self) -> bool {
354        self.local.is_some()
355    }
356
357    /// Runs the in-process handler, if there is one, as the plugin that
358    /// declared the command: what it writes to the store is written in
359    /// that plugin's scope (`egui_pop_model::values::enter_scope`).
360    pub fn run_local(&self) -> Option<Result<Json, String>> {
361        self.local.map(|h| {
362            let _scope = self.owner.map(egui_pop_model::values::enter_scope);
363            h(&Call {
364                args: self.args,
365                origin: self.origin,
366                app: self.app,
367            })
368        })
369    }
370}
371
372/// The application's kernel, as the interface sees it.
373pub trait Host {
374    /// Runs a command (its `when` already holds in `d.context`).
375    fn dispatch(&mut self, d: &Dispatch<'_>) -> Reply;
376
377    /// The host's journal, when it keeps one in memory (`LocalHost`
378    /// does). `None` (the default): the host answers `publish`, `since`
379    /// and `last_seq` from its own bus, or keeps no journal and egui-pop
380    /// keeps one.
381    fn journal(&self) -> Option<&Journal> {
382        None
383    }
384
385    /// The host's journal, to append to.
386    fn journal_mut(&mut self) -> Option<&mut Journal> {
387        None
388    }
389
390    /// Appends an event to the host's journal; its sequence number, or
391    /// `None` when the host keeps no journal (egui-pop's in-memory one
392    /// keeps the event then).
393    fn publish(&mut self, source: &str, cause: Option<Seq>, name: &str, data: Json) -> Option<Seq> {
394        self.journal_mut()
395            .map(|j| j.publish(source, cause, name, data))
396    }
397
398    /// The events after `seq`, oldest first; `None` when the host keeps
399    /// no journal.
400    fn since(&self, seq: Seq) -> Option<Vec<Event>> {
401        self.journal().map(|j| j.since(seq))
402    }
403
404    /// The last sequence number given (0: none yet); `None` when the host
405    /// keeps no journal.
406    fn last_seq(&self) -> Option<Seq> {
407        self.journal().map(Journal::last)
408    }
409
410    /// The value store holding settings and values.
411    fn store(&self) -> SharedStore;
412
413    /// The owner of the application's histories (ADR 0014), when the
414    /// kernel keeps them. `None` (the default): egui-pop's
415    /// [`StoreHistory`](crate::history::StoreHistory) over [`Host::store`],
416    /// which keeps its newest `HISTORY_CAP` (500) steps per history; a
417    /// host keeps more or fewer with `Store::set_history_cap`. egui-pop
418    /// owns the keys, the commands and the steps around them
419    /// (`edit.undo`, `edit.redo`, `edit.jump`); the owner says what an
420    /// undo is.
421    fn history(&mut self) -> Option<&mut dyn crate::history::History> {
422        None
423    }
424
425    /// How to wake the interface; the host calls it from any thread when
426    /// a result or an event arrives.
427    fn set_waker(&mut self, waker: Waker);
428
429    /// Where the host says its jobs: the application hands it the
430    /// publisher of `pop.job.event` when it is built. A host whose kernel
431    /// runs jobs keeps it and publishes each job fact on it, typed
432    /// ([`JobEventKind`](egui_pop_model::jobs::JobEventKind)), from any
433    /// thread; the jobs centre follows those events only, never journal
434    /// entries by their name. Ignored by default.
435    fn set_job_publisher(&mut self, publisher: crate::bus::JobPublisher) {
436        let _ = publisher;
437    }
438
439    /// The document the workbench's layout is kept in, under the
440    /// application's persistence directory (`AppBuilder::persist`):
441    /// [`LAYOUT_DOCUMENT`] by default, a workspace's own
442    /// (`workspaces/photos/layout`), asked again at each load and save.
443    /// `None`: egui-pop neither loads nor saves the layout; the host keeps
444    /// it (`AppHandle::layout`, `AppHandle::set_layout`). Loading and
445    /// saving are the `layout.load` and `layout.save` steps.
446    fn layout_document(&self) -> Option<String> {
447        Some(LAYOUT_DOCUMENT.into())
448    }
449
450    /// The owner of the context stack (places and modes, ADR 0012), when
451    /// the application's kernel keeps it. `None` (the default): egui-pop's
452    /// own [`LocalContexts`](crate::contexts::LocalContexts), kept by
453    /// `ContextsPlugin`. The interface only reads it and asks it for
454    /// transitions; it never writes the stack.
455    fn contexts(&mut self) -> Option<&mut dyn crate::contexts::Contexts> {
456        None
457    }
458
459    /// The owner of the clipboard (ADR 0015), when the application's
460    /// kernel keeps it. `None` (the default): egui-pop's own
461    /// [`LocalClipboard`](crate::clipboard::LocalClipboard), kept by
462    /// `ClipboardPlugin`.
463    fn clipboard(&mut self) -> Option<&mut dyn crate::clipboard::Clipboard> {
464        None
465    }
466
467    /// Opens a history group labelled `label` ("Paste a colour"): what is
468    /// written in it until [`Host::end_group`] is one undo step. egui-pop
469    /// opens one around a paste and around a cut's delete, and
470    /// `AppHandle::group` opens one for the application; the writes
471    /// carry it (`Set::gesture`). The default opens one through
472    /// [`Host::groups`], else a group of the store; `None`: the host
473    /// groups nothing.
474    fn begin_group(&mut self, origin: &Origin, label: &str) -> Option<GestureId> {
475        if let Some(groups) = self.groups() {
476            return groups.begin(origin, label);
477        }
478        Some(lock(&self.store()).begin_group(origin.clone(), label))
479    }
480
481    /// The history groups of a host keeping its own history, for the
482    /// groups a command opens while the host dispatches it
483    /// (`Call::group`). `None` (the default): such groups are the
484    /// store's, as the default [`Host::begin_group`]'s are; a host
485    /// overriding `begin_group` gives its groups here too, so a
486    /// command's groups reach its history.
487    fn groups(&self) -> Option<Rc<dyn Groups>> {
488        None
489    }
490
491    /// Ends a history group: kept as one undo step, or (`keep` false)
492    /// put back as it was.
493    fn end_group(&mut self, group: GestureId, keep: bool) {
494        if let Some(groups) = self.groups() {
495            groups.end(group, keep);
496            return;
497        }
498        let store = self.store();
499        let mut s = lock(&store);
500        if keep {
501            s.end(group);
502        } else {
503            s.cancel(group);
504        }
505    }
506}
507
508/// Opens and ends a host's history groups without the host itself:
509/// while the host dispatches a command it is out of reach, and a
510/// command's `AppHandle::group` (`Call::group`) goes through this.
511/// A host keeping its own history hands one out from [`Host::groups`];
512/// the default [`Host::begin_group`] and [`Host::end_group`] use it too.
513pub trait Groups {
514    /// Opens a group (see [`Host::begin_group`]); `None`: nothing grouped.
515    fn begin(&self, origin: &Origin, label: &str) -> Option<GestureId>;
516    /// Ends a group: kept, or (`keep` false) put back as it was.
517    fn end(&self, group: GestureId, keep: bool);
518}
519
520/// The layout's document when the host names none of its own.
521pub const LAYOUT_DOCUMENT: &str = "layout";
522
523/// The default host: commands run in-process with their handlers, the
524/// journal is in memory.
525#[derive(Debug)]
526pub struct LocalHost {
527    journal: Journal,
528    store: SharedStore,
529    waker: Waker,
530    layout: Option<String>,
531}
532
533impl Default for LocalHost {
534    fn default() -> Self {
535        Self::new(Arc::new(Mutex::new(Store::new())))
536    }
537}
538
539impl LocalHost {
540    /// A local host over a store.
541    pub fn new(store: SharedStore) -> Self {
542        Self {
543            journal: Journal::default(),
544            store,
545            waker: Waker::default(),
546            layout: Some(LAYOUT_DOCUMENT.into()),
547        }
548    }
549
550    /// Where the layout is kept (see [`Host::layout_document`]); `None`:
551    /// the application keeps it itself.
552    pub fn with_layout_document(mut self, document: Option<&str>) -> Self {
553        self.layout = document.map(Into::into);
554        self
555    }
556
557    /// The waker the application gave (to wake it from a thread).
558    pub fn waker(&self) -> Waker {
559        self.waker.clone()
560    }
561}
562
563impl Host for LocalHost {
564    fn dispatch(&mut self, d: &Dispatch<'_>) -> Reply {
565        Reply::Done(
566            d.run_local()
567                .unwrap_or_else(|| Err(format!("no handler for `{}` in this host", d.command))),
568        )
569    }
570
571    fn journal(&self) -> Option<&Journal> {
572        Some(&self.journal)
573    }
574
575    fn journal_mut(&mut self) -> Option<&mut Journal> {
576        Some(&mut self.journal)
577    }
578
579    fn store(&self) -> SharedStore {
580        self.store.clone()
581    }
582
583    fn set_waker(&mut self, waker: Waker) {
584        self.waker = waker;
585    }
586
587    fn layout_document(&self) -> Option<String> {
588        self.layout.clone()
589    }
590}
591
592/// The journal's name for an origin: `user`, `agent:<session>`,
593/// `script:<name>`... (the origin's `Display`).
594pub fn source_of(origin: &Origin) -> String {
595    origin.to_string()
596}
597
598/// What stands for a private command's arguments, result or error when
599/// its reader does not read private data ([`redact_private`]).
600pub const REDACTED: &str = "<private>";
601
602/// Hides what a private command (`CommandSpec::private`) carries from a
603/// reader that does not read private data, wherever it sits in `v`: a
604/// debug-bridge answer, a snapshot, a wait's event.
605///
606/// The journal keeps a private command's events whole, marked
607/// `"private": true` in their data (`command.dispatched`, `command.done`,
608/// `command.failed`), and the `commands` collector marks its runs the
609/// same way in `history`; this is the redaction at read time, per
610/// reader. So a reader allowed private data (the user, the application,
611/// an agent whose grant shows it) still reads a queued command's result
612/// from its `command.done`, as `egui-pop-agent-mcp` does, and one that is
613/// not reads [`REDACTED`] instead:
614///
615/// - an event (`seq`, `name`, `data`) whose data says `private: true`:
616///   its `args`, `result` and `error` become [`REDACTED`];
617/// - a run (`id`, `origin`, `result`) that says `private: true`: its
618///   `args` become [`REDACTED`], and so does its result's value or error
619///   (`{"Ok": "<private>"}`, `{"Err": "<private>"}`).
620///
621/// The rest is left as it is: a command's declaration (`private`,
622/// `args` as a schema) is not data and is not touched.
623///
624/// ```
625/// use egui_pop_api::host::{REDACTED, redact_private};
626/// use serde_json::json;
627///
628/// let mut events = json!([
629///     { "seq": 1, "name": "command.done", "source": "user", "cause": null,
630///       "data": { "command": "library.folder", "result": "/home/me", "private": true } },
631///     { "seq": 2, "name": "command.done", "source": "user", "cause": null,
632///       "data": { "command": "view.zoom", "result": 2 } },
633/// ]);
634/// redact_private(&mut events);
635/// assert_eq!(events[0]["data"]["result"], REDACTED);
636/// assert_eq!(events[1]["data"]["result"], 2);
637/// ```
638pub fn redact_private(v: &mut Json) {
639    match v {
640        Json::Array(items) => items.iter_mut().for_each(redact_private),
641        Json::Object(o) => {
642            let event = o.contains_key("seq") && o.get("name").is_some_and(Json::is_string);
643            if event
644                && let Some(Json::Object(data)) = o.get_mut("data")
645                && data.get("private") == Some(&Json::Bool(true))
646            {
647                for key in ["args", "result", "error"] {
648                    if let Some(x) = data.get_mut(key) {
649                        *x = Json::from(REDACTED);
650                    }
651                }
652                return;
653            }
654            // A step's trace (the `steps` collector's runs) asked with
655            // private arguments (`steps::PRIVATE`).
656            let trace = o.contains_key("step") && o.contains_key("asked");
657            if trace && o.get("private") == Some(&Json::Bool(true)) {
658                for key in ["asked", "args"] {
659                    if let Some(x) = o.get_mut(key) {
660                        *x = Json::from(REDACTED);
661                    }
662                }
663                match o.get_mut("result") {
664                    Some(Json::Object(r)) => r.values_mut().for_each(|x| *x = Json::from(REDACTED)),
665                    Some(Json::Null) | None => {}
666                    Some(x) => *x = Json::from(REDACTED),
667                }
668                return;
669            }
670            let run = o.contains_key("id") && o.contains_key("origin") && o.contains_key("result");
671            if run && o.get("private") == Some(&Json::Bool(true)) {
672                if let Some(x) = o.get_mut("args") {
673                    *x = Json::from(REDACTED);
674                }
675                match o.get_mut("result") {
676                    Some(Json::Object(r)) => r.values_mut().for_each(|x| *x = Json::from(REDACTED)),
677                    Some(x) => *x = Json::from(REDACTED),
678                    None => {}
679                }
680                return;
681            }
682            o.values_mut().for_each(redact_private);
683        }
684        _ => {}
685    }
686}
687
688#[cfg(test)]
689mod tests {
690    use super::*;
691
692    #[test]
693    fn the_journal_is_read_since_a_sequence_number() {
694        let mut j = Journal::with_capacity(3);
695        assert_eq!(j.last(), 0);
696        let a = j.publish("user", None, "a", Json::Null);
697        let b = j.publish("host", Some(a), "b", Json::Null);
698        assert_eq!((a, b), (1, 2));
699        assert_eq!(j.since(a).len(), 1);
700        assert_eq!(j.since(a)[0].cause, Some(1));
701        for n in 0..3 {
702            j.publish("x", None, &format!("{n}"), Json::Null);
703        }
704        // Past the capacity, the oldest go; numbers keep counting.
705        assert_eq!(j.since(0).first().map(|e| e.seq), Some(3));
706        assert_eq!(j.last(), 5);
707    }
708
709    #[test]
710    fn a_result_can_come_from_another_thread() {
711        let (p, r) = pending();
712        assert_eq!(p.take(), None);
713        std::thread::spawn(move || r.resolve(Ok(Json::Bool(true))))
714            .join()
715            .unwrap();
716        assert_eq!(p.take(), Some(Ok(Json::Bool(true))));
717        assert_eq!(p.take(), None);
718        assert_eq!(source_of(&Origin::User), "user");
719    }
720}