memstead_base/engine/callers.rs
1//! Change notices are relative to the caller.
2//!
3//! An engine may serve many callers: several agents behind one server,
4//! each of which must be told what changed in a mem since *that
5//! caller* last saw it, including what another caller wrote through
6//! this same engine. The engine therefore keeps, per caller key and
7//! mem, the head that caller last saw. The notice for a caller is the
8//! delta from its last-seen head to the head the engine holds when the
9//! caller's operation has reloaded and before it writes; afterwards its
10//! last-seen head is the head the operation left, so a caller is never
11//! told about its own write.
12//!
13//! A caller seen for the first time starts from what storage holds, so
14//! nothing that landed before it came is news to it; where storage was
15//! ahead of the engine then, the engine's head is kept beside the
16//! caller's, so the gap is no move. And before a notice is built for a
17//! mem, the engine catches up with storage for that mem, so a notice's
18//! two ends agree with its entries and nothing is told twice.
19//!
20//! There is one mechanism. A surface with a single caller (the CLI, a
21//! stdio server) uses the default key, which the engine knows from its
22//! first reload on; what such a surface is told is what it was told
23//! when the notice was relative to the engine itself.
24//!
25//! The key is handed in by the surface that opens the operation
26//! ([`super::drift::OperationScope::begin_as`]). It is not an identity:
27//! two callers may declare the same identity and are still told
28//! separately.
29
30use std::collections::HashMap;
31
32use super::Engine;
33
34/// Who an operation is for, as far as change notices go. The default
35/// key is the single caller of a CLI process or a stdio server.
36#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
37pub struct CallerKey(String);
38
39impl CallerKey {
40 /// A caller named by the surface: a session handle, a connection
41 /// id, any string the surface keeps stable for one caller.
42 pub fn new(key: impl Into<String>) -> Self {
43 Self(key.into())
44 }
45
46 /// Whether this is the default key of a single-caller surface.
47 pub fn is_default(&self) -> bool {
48 self.0.is_empty()
49 }
50}
51
52/// How many callers besides the default one the engine tracks. Past
53/// this, the least recently used caller is forgotten and reads as a
54/// first contact when it returns.
55pub const MAX_TRACKED_CALLERS: usize = 1024;
56
57/// One caller's last-seen head per mem. The empty string stands for
58/// "saw the mem with no head".
59#[derive(Debug, Default)]
60struct CallerState {
61 seen: HashMap<String, String>,
62 /// Mems whose last-seen head is ahead of the engine: the caller
63 /// came while storage held more than the engine had reloaded. The
64 /// value is the head the engine held then. While the engine still
65 /// stands there, the difference between the two heads is no move
66 /// and gives no reason to look at that mem's storage; once the
67 /// engine moves, the caller is told what lies beyond its own head.
68 ahead: HashMap<String, String>,
69 last_used: u64,
70}
71
72impl CallerState {
73 /// Whether the caller's head for `mem` is ahead of an engine that
74 /// still stands at `head`.
75 fn is_ahead_of(&self, mem: &str, head: &str) -> bool {
76 self.ahead.get(mem).is_some_and(|held| held == head)
77 }
78
79 /// The engine stands at `head` for `mem` and the caller has seen
80 /// it, unless its own head is ahead of an engine that has not moved.
81 fn stands_at(&mut self, mem: &str, head: &str) {
82 if self.is_ahead_of(mem, head) {
83 return;
84 }
85 self.ahead.remove(mem);
86 self.seen.insert(mem.to_string(), head.to_string());
87 }
88}
89
90/// The engine's memory of what each caller last saw.
91#[derive(Debug, Default)]
92pub(crate) struct CallerCursors {
93 callers: HashMap<CallerKey, CallerState>,
94 tick: u64,
95 /// The caller of the operation in progress; the default key between
96 /// operations and for a caller that opens no scope.
97 current: CallerKey,
98 /// Set while the engine reloads a mem on behalf of a notice it is
99 /// about to build: that reload is not an operation of the caller's
100 /// and runs no per-caller step of its own.
101 pub(in crate::engine) catching_up: bool,
102}
103
104impl CallerCursors {
105 fn touch(&mut self, key: &CallerKey) {
106 self.tick += 1;
107 if let Some(state) = self.callers.get_mut(key) {
108 state.last_used = self.tick;
109 }
110 }
111
112 /// Forget the least recently used callers past the cap. The default
113 /// caller and the current one are never forgotten.
114 fn evict(&mut self) {
115 while self.callers.keys().filter(|k| !k.is_default()).count() > MAX_TRACKED_CALLERS {
116 let victim = self
117 .callers
118 .iter()
119 .filter(|(k, _)| !k.is_default() && **k != self.current)
120 .min_by_key(|(_, s)| s.last_used)
121 .map(|(k, _)| k.clone());
122 match victim {
123 Some(key) => {
124 self.callers.remove(&key);
125 }
126 None => break,
127 }
128 }
129 }
130
131 /// Drop a mem from every caller's memory: it left the roster.
132 pub(crate) fn forget_mem(&mut self, mem: &str) {
133 for state in self.callers.values_mut() {
134 state.seen.remove(mem);
135 state.ahead.remove(mem);
136 }
137 }
138
139 /// How many callers are tracked, the default one included.
140 #[cfg(test)]
141 pub(crate) fn tracked(&self) -> usize {
142 self.callers.len()
143 }
144}
145
146impl Engine {
147 /// The head each mount stands at, as the engine holds it: no probe,
148 /// the empty string for a mount with no head.
149 fn heads_now(&self) -> Vec<(String, String)> {
150 self.mounts
151 .iter()
152 .map(|m| {
153 (
154 m.mount.mem.clone(),
155 m.last_known_head.clone().unwrap_or_default(),
156 )
157 })
158 .collect()
159 }
160
161 /// The head each mount's storage holds at this instant, probed: a
162 /// head the engine has not reloaded to yet counts. A probe that
163 /// fails falls back to the head the engine holds. This is the
164 /// baseline of a first contact: a caller that has seen nothing yet
165 /// starts from what is there, so a change that landed before it
166 /// came, and that the engine itself has yet to reload, is never
167 /// news to it.
168 fn heads_in_storage(&self) -> Vec<(String, String)> {
169 self.mounts
170 .iter()
171 .map(|m| {
172 let head = m
173 .backend
174 .current_head()
175 .ok()
176 .flatten()
177 .or_else(|| m.last_known_head.clone())
178 .unwrap_or_default();
179 (m.mount.mem.clone(), head)
180 })
181 .collect()
182 }
183
184 /// Name the caller of the operation that begins. Called by the
185 /// operation scope; an engine used without a scope stays on the
186 /// default caller.
187 pub(in crate::engine) fn set_current_caller(&mut self, caller: CallerKey) {
188 self.callers.current = caller;
189 // A new operation: nothing has brought this caller up to date
190 // yet, whatever an unscoped call left behind.
191 self.caller_synced = false;
192 self.caller_first_contact = false;
193 }
194
195 /// Whether the operation in progress is the default caller's.
196 pub(in crate::engine) fn current_caller_is_default(&self) -> bool {
197 self.callers.current.is_default()
198 }
199
200 /// Before a reload: make sure the default caller is known, with the
201 /// heads as they stand before anything is reloaded. A single-caller
202 /// surface has been there since boot, so what a reload brings in is
203 /// news to it. Any other caller becomes known after its first
204 /// reload instead ([`Self::note_changes_for_caller`]) and is told
205 /// nothing on that first contact.
206 pub(in crate::engine) fn know_default_caller(&mut self) {
207 let key = CallerKey::default();
208 if self.callers.callers.contains_key(&key) {
209 return;
210 }
211 let seen = self.heads_now().into_iter().collect();
212 self.callers.callers.insert(
213 key,
214 CallerState {
215 seen,
216 ..CallerState::default()
217 },
218 );
219 }
220
221 /// A first contact: the caller starts from what storage holds, so a
222 /// change that landed before it came is never news to it, whether
223 /// the engine has reloaded that change yet or not. Where storage is
224 /// ahead of the engine, the engine's head is kept beside the
225 /// caller's, so the gap neither reads as a move nor makes a later
226 /// operation of this caller look at a mem outside its scope.
227 fn baseline_from_storage(&mut self, key: &CallerKey) {
228 let engine: HashMap<String, String> = self.heads_now().into_iter().collect();
229 let seen: HashMap<String, String> = self.heads_in_storage().into_iter().collect();
230 let ahead = seen
231 .iter()
232 .filter_map(|(mem, head)| {
233 let held = engine.get(mem)?;
234 (held != head).then(|| (mem.clone(), held.clone()))
235 })
236 .collect();
237 let last_used = self
238 .callers
239 .callers
240 .get(key)
241 .map(|s| s.last_used)
242 .unwrap_or_default();
243 self.callers.callers.insert(
244 key.clone(),
245 CallerState {
246 seen,
247 ahead,
248 last_used,
249 },
250 );
251 }
252
253 /// After a reload and before the operation writes: tell the current
254 /// caller what moved since it last looked. For each mem whose head
255 /// differs from the head this caller last saw, a notice describing
256 /// that delta is recorded for the operation's response and the
257 /// caller's memory moves to the head now. A caller seen for the
258 /// first time, and a mem a caller sees for the first time, set the
259 /// baseline and record nothing.
260 ///
261 /// Returns one `MEM_RELOADED` warning per notice, for the mems this
262 /// call's own reload did not already warn about: a caller told
263 /// about another caller's write through the same engine saw no
264 /// reload, yet its cached hashes are as stale as after one, and the
265 /// text channel of a response speaks through that warning.
266 pub(in crate::engine) fn note_changes_for_caller(&mut self) -> Vec<crate::ops::WarningHint> {
267 if self.callers.catching_up {
268 return Vec::new();
269 }
270 self.caller_synced = true;
271 let key = self.callers.current.clone();
272 // A first contact: the caller starts from what storage holds,
273 // and its whole first operation hands out nothing. An operation
274 // reloads mem by mem, so a later reload of the same operation
275 // must not read as news to a caller that came with it.
276 if !self.callers.callers.contains_key(&key) || self.caller_first_contact {
277 self.caller_first_contact = true;
278 self.baseline_from_storage(&key);
279 self.callers.touch(&key);
280 self.callers.evict();
281 return Vec::new();
282 }
283 // A notice runs from the head the caller last saw to the head
284 // the engine holds, and its entries are what storage holds
285 // beyond the former. Where the two heads differ, the engine
286 // first catches up with storage for that mem, so the ends of
287 // the notice agree with its entries and nothing that lies
288 // beyond is told a second time when the engine reloads it
289 // later. A caller that started from a storage head the engine
290 // has not reached is not behind, and its operation looks at no
291 // mem on that account.
292 let behind: Vec<String> = {
293 let state = self.callers.callers.get(&key);
294 self.heads_now()
295 .into_iter()
296 .filter(|(mem, head)| {
297 state.is_some_and(|s| {
298 s.seen.get(mem).is_some_and(|prev| prev != head)
299 && !s.is_ahead_of(mem, head)
300 })
301 })
302 .map(|(mem, _)| mem)
303 .collect()
304 };
305 if !behind.is_empty() {
306 self.callers.catching_up = true;
307 for mem in &behind {
308 let _ = self.reload_if_stale_content_only(Some(mem));
309 }
310 self.callers.catching_up = false;
311 }
312 let heads = self.heads_now();
313 self.callers.touch(&key);
314 let mut moved: Vec<(String, String, String)> = Vec::new();
315 {
316 let state = self
317 .callers
318 .callers
319 .get_mut(&key)
320 .expect("the caller was just found");
321 for (mem, head) in &heads {
322 match state.seen.get(mem) {
323 // Ahead of an engine that has not moved: nothing
324 // happened.
325 Some(_) if state.is_ahead_of(mem, head) => {}
326 Some(prev) if prev != head => {
327 moved.push((mem.clone(), prev.clone(), head.clone()));
328 }
329 Some(_) => {
330 state.ahead.remove(mem);
331 }
332 None => {
333 state.seen.insert(mem.clone(), head.clone());
334 }
335 }
336 }
337 // A mem that is no longer mounted is no longer remembered.
338 state
339 .seen
340 .retain(|mem, _| heads.iter().any(|(m, _)| m == mem));
341 state
342 .ahead
343 .retain(|mem, _| heads.iter().any(|(m, _)| m == mem));
344 }
345 let mut warnings = Vec::new();
346 for (mem, prev, head) in moved {
347 let notice = if prev.is_empty() {
348 // The mem had no head when this caller last saw it (its
349 // branch was born, fetched or pushed into place since, or
350 // its first write landed). What is new to the caller: the
351 // entities the reload in progress brought in, when this
352 // reload is where the head appeared; else whatever the
353 // backend can tell of its history from the start.
354 let changes: Vec<crate::ops::ChangeEnvelope> = match self.appeared_heads.get(&mem) {
355 Some(added) => added
356 .iter()
357 .map(|id| crate::ops::ChangeEnvelope::Added {
358 id: id.clone(),
359 title: None,
360 entity_type: None,
361 })
362 .collect(),
363 None => self
364 .changes_since(&mem, "", None)
365 .map(|r| r.changes)
366 .unwrap_or_default(),
367 };
368 // Who wrote what in a mem whose head appeared: read
369 // from its history from the start, when there is one.
370 let notes = self
371 .changes_since(&mem, "", None)
372 .ok()
373 .and_then(|r| r.notes);
374 self.notice_for(&mem, "", &head, changes, notes.as_deref())
375 } else {
376 self.mem_changed_notice(&mem, &prev, &head)
377 };
378 warnings.push(crate::ops::WarningHint::MemReloaded {
379 mem: mem.clone(),
380 old_head: prev,
381 new_head: head.clone(),
382 entities_loaded: notice.entity_count(),
383 });
384 self.pending_mem_changed.push(notice);
385 if let Some(state) = self.callers.callers.get_mut(&key) {
386 state.ahead.remove(&mem);
387 state.seen.insert(mem, head);
388 }
389 }
390 warnings
391 }
392
393 /// Bring the current caller up to date when the operation has not
394 /// done so yet: an operation that reloads nothing before it acts (an
395 /// explicit reload, a settings write, a read of engine state) still
396 /// tells its caller what other callers wrote through this engine,
397 /// and still counts as a first contact. A no-op once the operation's
398 /// own reload ran the step.
399 pub(in crate::engine) fn bring_caller_up_to_date(&mut self) {
400 if self.caller_synced {
401 return;
402 }
403 self.know_default_caller();
404 // The warnings are the text form of the notices just recorded;
405 // a surface that speaks through them rebuilds them from the
406 // notices the operation hands out.
407 let _ = self.note_changes_for_caller();
408 }
409
410 /// The operation is over: whatever head the engine holds now is one
411 /// the current caller has seen, because everything that moved since
412 /// [`Self::note_changes_for_caller`] ran is the caller's own write.
413 /// A caller the operation never brought up to date keeps its memory
414 /// as it was, so it is still told later. Then the engine is back on
415 /// the default caller.
416 pub(in crate::engine) fn close_caller_scope(&mut self) {
417 let key = std::mem::take(&mut self.callers.current);
418 let first_contact = std::mem::take(&mut self.caller_first_contact);
419 if !self.caller_synced {
420 return;
421 }
422 self.caller_synced = false;
423 // After a first contact the caller stands at what storage holds
424 // (its own writes of this operation included); otherwise at the
425 // heads the engine holds, which moved only by the caller's own
426 // writes since it was brought up to date.
427 // A first contact keeps the baseline its last reload took, moved
428 // on by its own writes: what another process writes between that
429 // reload and here is told to it later.
430 if first_contact {
431 return;
432 }
433 let heads = self.heads_now();
434 if let Some(state) = self.callers.callers.get_mut(&key) {
435 for (mem, head) in heads {
436 state.stands_at(&mem, &head);
437 }
438 }
439 }
440
441 /// The engine's own write moved a mem's head from `previous` to
442 /// `recorded`: the current caller, if it stood at `previous`, has
443 /// seen the new head, since the write is its own. A later reload in
444 /// the same operation then finds nothing to tell it.
445 pub(in crate::engine) fn caller_saw_own_write(
446 &mut self,
447 mem: &str,
448 previous: &str,
449 recorded: &str,
450 ) {
451 let key = self.callers.current.clone();
452 if let Some(state) = self.callers.callers.get_mut(&key)
453 && (state.seen.get(mem).is_some_and(|seen| seen == previous)
454 || state.is_ahead_of(mem, previous))
455 {
456 state.ahead.remove(mem);
457 state.seen.insert(mem.to_string(), recorded.to_string());
458 }
459 }
460}