use std::collections::HashMap;
use super::Engine;
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub struct CallerKey(String);
impl CallerKey {
pub fn new(key: impl Into<String>) -> Self {
Self(key.into())
}
pub fn is_default(&self) -> bool {
self.0.is_empty()
}
}
pub const MAX_TRACKED_CALLERS: usize = 1024;
#[derive(Debug, Default)]
struct CallerState {
seen: HashMap<String, String>,
ahead: HashMap<String, String>,
last_used: u64,
}
impl CallerState {
fn is_ahead_of(&self, mem: &str, head: &str) -> bool {
self.ahead.get(mem).is_some_and(|held| held == head)
}
fn stands_at(&mut self, mem: &str, head: &str) {
if self.is_ahead_of(mem, head) {
return;
}
self.ahead.remove(mem);
self.seen.insert(mem.to_string(), head.to_string());
}
}
#[derive(Debug, Default)]
pub(crate) struct CallerCursors {
callers: HashMap<CallerKey, CallerState>,
tick: u64,
current: CallerKey,
pub(in crate::engine) catching_up: bool,
}
impl CallerCursors {
fn touch(&mut self, key: &CallerKey) {
self.tick += 1;
if let Some(state) = self.callers.get_mut(key) {
state.last_used = self.tick;
}
}
fn evict(&mut self) {
while self.callers.keys().filter(|k| !k.is_default()).count() > MAX_TRACKED_CALLERS {
let victim = self
.callers
.iter()
.filter(|(k, _)| !k.is_default() && **k != self.current)
.min_by_key(|(_, s)| s.last_used)
.map(|(k, _)| k.clone());
match victim {
Some(key) => {
self.callers.remove(&key);
}
None => break,
}
}
}
pub(crate) fn forget_mem(&mut self, mem: &str) {
for state in self.callers.values_mut() {
state.seen.remove(mem);
state.ahead.remove(mem);
}
}
#[cfg(test)]
pub(crate) fn tracked(&self) -> usize {
self.callers.len()
}
}
impl Engine {
fn heads_now(&self) -> Vec<(String, String)> {
self.mounts
.iter()
.map(|m| {
(
m.mount.mem.clone(),
m.last_known_head.clone().unwrap_or_default(),
)
})
.collect()
}
fn heads_in_storage(&self) -> Vec<(String, String)> {
self.mounts
.iter()
.map(|m| {
let head = m
.backend
.current_head()
.ok()
.flatten()
.or_else(|| m.last_known_head.clone())
.unwrap_or_default();
(m.mount.mem.clone(), head)
})
.collect()
}
pub(in crate::engine) fn set_current_caller(&mut self, caller: CallerKey) {
self.callers.current = caller;
self.caller_synced = false;
self.caller_first_contact = false;
}
pub(in crate::engine) fn current_caller_is_default(&self) -> bool {
self.callers.current.is_default()
}
pub(in crate::engine) fn know_default_caller(&mut self) {
let key = CallerKey::default();
if self.callers.callers.contains_key(&key) {
return;
}
let seen = self.heads_now().into_iter().collect();
self.callers.callers.insert(
key,
CallerState {
seen,
..CallerState::default()
},
);
}
fn baseline_from_storage(&mut self, key: &CallerKey) {
let engine: HashMap<String, String> = self.heads_now().into_iter().collect();
let seen: HashMap<String, String> = self.heads_in_storage().into_iter().collect();
let ahead = seen
.iter()
.filter_map(|(mem, head)| {
let held = engine.get(mem)?;
(held != head).then(|| (mem.clone(), held.clone()))
})
.collect();
let last_used = self
.callers
.callers
.get(key)
.map(|s| s.last_used)
.unwrap_or_default();
self.callers.callers.insert(
key.clone(),
CallerState {
seen,
ahead,
last_used,
},
);
}
pub(in crate::engine) fn note_changes_for_caller(&mut self) -> Vec<crate::ops::WarningHint> {
if self.callers.catching_up {
return Vec::new();
}
self.caller_synced = true;
let key = self.callers.current.clone();
if !self.callers.callers.contains_key(&key) || self.caller_first_contact {
self.caller_first_contact = true;
self.baseline_from_storage(&key);
self.callers.touch(&key);
self.callers.evict();
return Vec::new();
}
let behind: Vec<String> = {
let state = self.callers.callers.get(&key);
self.heads_now()
.into_iter()
.filter(|(mem, head)| {
state.is_some_and(|s| {
s.seen.get(mem).is_some_and(|prev| prev != head)
&& !s.is_ahead_of(mem, head)
})
})
.map(|(mem, _)| mem)
.collect()
};
if !behind.is_empty() {
self.callers.catching_up = true;
for mem in &behind {
let _ = self.reload_if_stale_content_only(Some(mem));
}
self.callers.catching_up = false;
}
let heads = self.heads_now();
self.callers.touch(&key);
let mut moved: Vec<(String, String, String)> = Vec::new();
{
let state = self
.callers
.callers
.get_mut(&key)
.expect("the caller was just found");
for (mem, head) in &heads {
match state.seen.get(mem) {
Some(_) if state.is_ahead_of(mem, head) => {}
Some(prev) if prev != head => {
moved.push((mem.clone(), prev.clone(), head.clone()));
}
Some(_) => {
state.ahead.remove(mem);
}
None => {
state.seen.insert(mem.clone(), head.clone());
}
}
}
state
.seen
.retain(|mem, _| heads.iter().any(|(m, _)| m == mem));
state
.ahead
.retain(|mem, _| heads.iter().any(|(m, _)| m == mem));
}
let mut warnings = Vec::new();
for (mem, prev, head) in moved {
let notice = if prev.is_empty() {
let changes: Vec<crate::ops::ChangeEnvelope> = match self.appeared_heads.get(&mem) {
Some(added) => added
.iter()
.map(|id| crate::ops::ChangeEnvelope::Added {
id: id.clone(),
title: None,
entity_type: None,
})
.collect(),
None => self
.changes_since(&mem, "", None)
.map(|r| r.changes)
.unwrap_or_default(),
};
let notes = self
.changes_since(&mem, "", None)
.ok()
.and_then(|r| r.notes);
self.notice_for(&mem, "", &head, changes, notes.as_deref())
} else {
self.mem_changed_notice(&mem, &prev, &head)
};
warnings.push(crate::ops::WarningHint::MemReloaded {
mem: mem.clone(),
old_head: prev,
new_head: head.clone(),
entities_loaded: notice.entity_count(),
});
self.pending_mem_changed.push(notice);
if let Some(state) = self.callers.callers.get_mut(&key) {
state.ahead.remove(&mem);
state.seen.insert(mem, head);
}
}
warnings
}
pub(in crate::engine) fn bring_caller_up_to_date(&mut self) {
if self.caller_synced {
return;
}
self.know_default_caller();
let _ = self.note_changes_for_caller();
}
pub(in crate::engine) fn close_caller_scope(&mut self) {
let key = std::mem::take(&mut self.callers.current);
let first_contact = std::mem::take(&mut self.caller_first_contact);
if !self.caller_synced {
return;
}
self.caller_synced = false;
if first_contact {
return;
}
let heads = self.heads_now();
if let Some(state) = self.callers.callers.get_mut(&key) {
for (mem, head) in heads {
state.stands_at(&mem, &head);
}
}
}
pub(in crate::engine) fn caller_saw_own_write(
&mut self,
mem: &str,
previous: &str,
recorded: &str,
) {
let key = self.callers.current.clone();
if let Some(state) = self.callers.callers.get_mut(&key)
&& (state.seen.get(mem).is_some_and(|seen| seen == previous)
|| state.is_ahead_of(mem, previous))
{
state.ahead.remove(mem);
state.seen.insert(mem.to_string(), recorded.to_string());
}
}
}