1use super::{
2 EventStore,
3 feed::{FeedCursor, MODEL_EVENT},
4};
5use crate::{
6 domain::{
7 entities::Event,
8 value_objects::{EntityId, EventType, TenantId},
9 },
10 error::{AllSourceError, Result},
11 infrastructure::persistence::archive_budget::ArchiveReadBudget,
12};
13use dashmap::DashMap;
14use serde::{Deserialize, Serialize};
15use serde_json::Value;
16use sha2::{Digest, Sha256};
17use std::{
18 collections::{BTreeMap, HashMap},
19 sync::LazyLock,
20};
21use tokio::sync::watch;
22
23const MAX_MODEL_BYTES: usize = 32 * 1024 * 1024;
24pub const MAX_PAGE_BYTES: usize = 128 * 1024;
25
26static WATCHERS: LazyLock<DashMap<String, watch::Sender<u64>>> = LazyLock::new(DashMap::new);
30
31fn watch_key(store: &EventStore, tenant: &str, name: &str) -> String {
32 format!("{store:p}/{tenant}/{name}")
33}
34
35pub struct ModelWatch {
37 key: String,
38 receiver: watch::Receiver<u64>,
39}
40
41impl ModelWatch {
42 pub async fn changed(&mut self) -> bool {
44 self.receiver.changed().await.is_ok()
45 }
46}
47
48impl Drop for ModelWatch {
49 fn drop(&mut self) {
50 WATCHERS.remove_if(&self.key, |_, sender| sender.receiver_count() <= 1);
52 }
53}
54
55#[derive(Debug, Clone, Copy, Serialize)]
56pub struct ModelMeta {
57 pub revision: u64,
58 pub checkpoint: Option<FeedCursor>,
59 pub ready: bool,
60 pub reset_revision: u64,
61}
62
63#[derive(Debug, Clone, Serialize)]
65pub struct ModelRow {
66 pub key: String,
67 pub state: Option<Value>,
68 pub version: u64,
69}
70
71#[derive(Debug)]
72pub struct RowsPage {
73 pub meta: ModelMeta,
74 pub content_revision: u64,
75 pub rows: Vec<ModelRow>,
76 pub next: Option<String>,
77}
78
79#[derive(Debug)]
80pub struct ChangesPage {
81 pub meta: ModelMeta,
82 pub changes: Vec<ModelRow>,
83 pub revision: u64,
84 pub caught_up: bool,
85}
86
87#[derive(Debug)]
88pub enum ModelChanges {
89 Reset {
91 reset_revision: u64,
92 },
93 Page(ChangesPage),
94}
95
96#[derive(Debug, Default, Clone)]
97pub struct ReadModel {
98 pub revision: u64,
99 pub checkpoint: Option<FeedCursor>,
100 pub ready: bool,
101 pub rows: BTreeMap<String, Value>,
102 bytes: usize,
103 versions: BTreeMap<String, u64>,
104 reset_revision: u64,
105 accessed: Option<std::time::Instant>,
106}
107
108#[derive(Debug, Clone, Serialize, Deserialize)]
109pub struct ModelCommit {
110 pub expected_revision: u64,
111 pub checkpoint: FeedCursor,
112 pub ready: bool,
113 #[serde(default)]
114 pub reset: bool,
115 pub changes: BTreeMap<String, Option<Value>>,
116}
117
118#[derive(Debug, Serialize)]
119pub struct ModelPage {
120 pub revision: u64,
121 pub content_revision: u64,
122 pub checkpoint: Option<FeedCursor>,
123 pub ready: bool,
124 pub unchanged: bool,
125 pub rows: BTreeMap<String, Value>,
126 pub next: Option<String>,
127}
128
129fn model_entity(tenant: &str, name: &str) -> Result<String> {
130 TenantId::new(tenant.into())?;
131 if name.is_empty()
132 || name.len() > 64
133 || !name
134 .bytes()
135 .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
136 {
137 return Err(AllSourceError::InvalidInput(
138 "read model name must contain 1..64 ASCII letters, digits, - or _".into(),
139 ));
140 }
141 let mut identity = Sha256::new();
143 identity.update(tenant.as_bytes());
144 identity.update([0]);
145 identity.update(name.as_bytes());
146 Ok(format!("read-model:{:x}", identity.finalize()))
147}
148
149fn evict_model(models: &mut HashMap<String, ReadModel>, keep: &str) {
150 let victim = models
151 .iter()
152 .filter(|(key, _)| key.as_str() != keep)
153 .min_by_key(|(_, model)| model.accessed)
154 .map(|(key, _)| key.clone());
155 if let Some(key) = victim {
156 models.remove(&key);
157 }
158}
159
160fn bound_cache(models: &mut HashMap<String, ReadModel>, keep: &str) {
161 while models.len() > 1
162 && (models.len() > 32
163 || models.values().map(|model| model.bytes).sum::<usize>() > 64 * 1024 * 1024)
164 {
165 evict_model(models, keep);
166 }
167}
168
169impl ReadModel {
170 fn apply(&mut self, commit: &ModelCommit, revision: u64) -> Result<()> {
171 if commit.reset {
172 self.rows.clear();
173 self.versions.clear();
174 self.bytes = 0;
175 self.reset_revision = revision;
176 }
177 for (key, value) in &commit.changes {
178 if !self.versions.contains_key(key) {
179 self.bytes += key.len() + 128;
180 }
181 self.versions.insert(key.clone(), revision);
182 if key.len() > 512 {
183 return Err(AllSourceError::InvalidInput(
184 "read model key exceeds 512 bytes".into(),
185 ));
186 }
187 if let Some(old) = self.rows.remove(key) {
188 self.bytes -= key.len() + serde_json::to_vec(&old)?.len();
189 }
190 if let Some(value) = value {
191 let size = serde_json::to_vec(value)?.len();
192 if size + key.len() > MAX_PAGE_BYTES - 4096 {
193 return Err(AllSourceError::InvalidInput(
194 "read model row exceeds bounded page".into(),
195 ));
196 }
197 self.bytes += key.len() + size;
198 self.rows.insert(key.clone(), value.clone());
199 }
200 }
201 if self.bytes > MAX_MODEL_BYTES || self.versions.len() > 100_000 {
202 return Err(AllSourceError::InvalidInput(
203 "read model exceeds 32 MiB or 100000 keys; shard model".into(),
204 ));
205 }
206 self.revision = revision;
207 self.checkpoint = Some(commit.checkpoint);
208 self.ready = commit.ready;
209 self.accessed = Some(std::time::Instant::now());
210 Ok(())
211 }
212
213 fn meta(&self) -> ModelMeta {
214 ModelMeta {
215 revision: self.revision,
216 checkpoint: self.checkpoint,
217 ready: self.ready,
218 reset_revision: self.reset_revision,
219 }
220 }
221
222 fn content_revision(&self, prefix: &str) -> u64 {
223 self.versions
224 .range(prefix.to_string()..)
225 .take_while(|(key, _)| key.starts_with(prefix))
226 .map(|(_, revision)| *revision)
227 .max()
228 .unwrap_or(0)
229 .max(self.reset_revision)
230 }
231}
232
233fn check_bounds(limit: usize, prefix: &str, after: Option<&str>) -> Result<()> {
234 if !(1..=500).contains(&limit) || prefix.len() > 512 || after.is_some_and(|s| s.len() > 512) {
235 return Err(AllSourceError::InvalidInput(
236 "bounded read requires limit 1..500 and keys <=512 bytes".into(),
237 ));
238 }
239 Ok(())
240}
241
242fn row_bytes(key: &str, state: Option<&Value>) -> Result<usize> {
243 Ok(serde_json::to_vec(key)?.len()
244 + state.map_or(Ok(4), |state| {
245 serde_json::to_vec(state).map(|bytes| bytes.len())
246 })?
247 + 32)
248}
249
250impl EventStore {
251 fn read_model_journal(&self, tenant: &str, entity: &str) -> Result<Vec<Event>> {
255 let mut budget = ArchiveReadBudget::new(self.strict_archive_limits.clone());
256 let _resident = self.cache_residency_gate.read();
259 let mut journal = HashMap::new();
260 if let Some(storage) = &self.storage {
261 storage
262 .read()
263 .visit_retained_entity(tenant, entity, &mut budget, |event, work| {
264 work.check()?;
265 if event.event_type_str() == MODEL_EVENT {
266 journal.insert(event.id, event.clone());
267 }
268 Ok(())
269 })?;
270 }
271 let events = self.events.read();
272 for event in events.iter().filter(|e| {
273 e.tenant_id_str() == tenant
274 && e.entity_id_str() == entity
275 && e.event_type_str() == MODEL_EVENT
276 }) {
277 journal.entry(event.id).or_insert_with(|| event.clone());
278 }
279 let mut commits: Vec<_> = journal.into_values().collect();
280 commits.sort_by_key(Event::version);
281 Ok(commits)
282 }
283
284 fn restore_read_model(&self, tenant: &str, entity: &str) -> Result<ReadModel> {
285 let commits = self.read_model_journal(tenant, entity)?;
286 let mut model = ReadModel::default();
287 for event in commits {
288 let commit: ModelCommit = serde_json::from_value(event.payload().clone())?;
289 if commit.expected_revision != model.revision {
290 return Err(AllSourceError::StorageError(
291 "read model journal is incomplete".into(),
292 ));
293 }
294 model.apply(&commit, model.revision + 1)?;
295 }
296 Ok(model)
297 }
298
299 pub fn commit_read_model(&self, tenant: &str, name: &str, commit: ModelCommit) -> Result<u64> {
300 self.commit_model(tenant, name, commit, true)
301 }
302
303 pub(super) fn commit_core_read_model(
307 &self,
308 tenant: &str,
309 name: &str,
310 commit: ModelCommit,
311 ) -> Result<u64> {
312 self.commit_model(tenant, name, commit, false)
313 }
314
315 fn commit_model(
316 &self,
317 tenant: &str,
318 name: &str,
319 commit: ModelCommit,
320 fold_checkpoint: bool,
321 ) -> Result<u64> {
322 if serde_json::to_vec(&commit)?.len() > 240 * 1024 || commit.changes.len() > 500 {
323 return Err(AllSourceError::InvalidInput(
324 "read model commit exceeds 500 changes or 240 KiB".into(),
325 ));
326 }
327 let entity = model_entity(tenant, name)?;
328 if fold_checkpoint {
329 let head = self.tenant_feed(tenant, None, 0)?.head;
330 if commit.checkpoint.epoch != head.epoch || commit.checkpoint.position > head.position {
331 return Err(AllSourceError::InvalidInput(
332 "read model checkpoint is outside current feed generation".into(),
333 ));
334 }
335 }
336 let key = format!("{tenant}/{name}");
337 let mut models = self.read_models.lock();
338 if !models.contains_key(&key) {
339 if models.len() >= 32 {
340 evict_model(&mut models, &key);
341 }
342 models.insert(key.clone(), self.restore_read_model(tenant, &entity)?);
343 bound_cache(&mut models, &key);
344 }
345 let model = models.get(&key).expect("inserted read model");
346 if model.revision != commit.expected_revision {
347 return Err(AllSourceError::VersionConflict {
348 expected: commit.expected_revision,
349 current: model.revision,
350 });
351 }
352 if fold_checkpoint
353 && !commit.reset
354 && model.checkpoint.is_some_and(|old| {
355 old.epoch != commit.checkpoint.epoch || old.position > commit.checkpoint.position
356 })
357 {
358 return Err(AllSourceError::InvalidInput(
359 "read model checkpoint cannot regress; rebuild with reset".into(),
360 ));
361 }
362 let mut next = model.clone();
363 let revision = model.revision + 1;
364 next.apply(&commit, revision)?;
365 let event = Event::new(
366 EventType::new(MODEL_EVENT.into())?,
367 EntityId::new(entity)?,
368 TenantId::new(tenant.into())?,
369 serde_json::to_value(commit)?,
370 );
371 self.ingest_with_expected_version(&event, Some(model.revision))?;
372 models.insert(key, next);
373 bound_cache(&mut models, &format!("{tenant}/{name}"));
374 drop(models);
375 if let Some(sender) = WATCHERS.get(&watch_key(self, tenant, name)) {
376 sender.send_replace(revision);
377 }
378 Ok(revision)
379 }
380
381 pub fn read_model_watch(&self, tenant: &str, name: &str) -> ModelWatch {
384 let key = watch_key(self, tenant, name);
385 let receiver = WATCHERS
386 .entry(key.clone())
387 .or_insert_with(|| watch::channel(0).0)
388 .subscribe();
389 ModelWatch { key, receiver }
390 }
391
392 fn with_model<R>(
393 &self,
394 tenant: &str,
395 name: &str,
396 read: impl FnOnce(&ReadModel) -> Result<R>,
397 ) -> Result<R> {
398 let entity = model_entity(tenant, name)?;
399 let key = format!("{tenant}/{name}");
400 let mut models = self.read_models.lock();
401 if !models.contains_key(&key) {
402 if models.len() >= 32 {
403 evict_model(&mut models, &key);
404 }
405 models.insert(key.clone(), self.restore_read_model(tenant, &entity)?);
406 bound_cache(&mut models, &key);
407 }
408 let model = models.get_mut(&key).expect("inserted read model");
409 model.accessed = Some(std::time::Instant::now());
410 read(model)
411 }
412
413 pub fn read_model_meta(&self, tenant: &str, name: &str) -> Result<ModelMeta> {
414 self.with_model(tenant, name, |model| Ok(model.meta()))
415 }
416
417 pub fn read_model_row(
419 &self,
420 tenant: &str,
421 name: &str,
422 key: &str,
423 ) -> Result<(ModelMeta, Option<(Value, u64)>)> {
424 if key.len() > 512 {
425 return Err(AllSourceError::InvalidInput(
426 "read model key exceeds 512 bytes".into(),
427 ));
428 }
429 self.with_model(tenant, name, |model| {
430 let row = model.rows.get(key).map(|state| {
431 let version = model.versions.get(key).copied().unwrap_or(model.revision);
432 (state.clone(), version)
433 });
434 Ok((model.meta(), row))
435 })
436 }
437
438 pub fn read_model_rows(
440 &self,
441 tenant: &str,
442 name: &str,
443 prefix: &str,
444 after: Option<&str>,
445 limit: usize,
446 ) -> Result<RowsPage> {
447 check_bounds(limit, prefix, after)?;
448 self.with_model(tenant, name, |model| {
449 let mut page = RowsPage {
450 meta: model.meta(),
451 content_revision: model.content_revision(prefix),
452 rows: Vec::new(),
453 next: None,
454 };
455 let mut bytes = 4096;
456 for (key, value) in model.rows.range(prefix.to_string()..) {
457 if !key.starts_with(prefix) {
458 break;
459 }
460 if after.is_some_and(|after| key.as_str() <= after) {
461 continue;
462 }
463 let size = row_bytes(key, Some(value))?;
464 if page.rows.len() == limit || bytes + size > MAX_PAGE_BYTES {
465 page.next = page.rows.last().map(|row| row.key.clone());
466 break;
467 }
468 bytes += size;
469 page.rows.push(ModelRow {
470 key: key.clone(),
471 state: Some(value.clone()),
472 version: model.versions.get(key).copied().unwrap_or(model.revision),
473 });
474 }
475 Ok(page)
476 })
477 }
478
479 pub fn read_model_changes(
485 &self,
486 tenant: &str,
487 name: &str,
488 after: u64,
489 limit: usize,
490 ) -> Result<ModelChanges> {
491 check_bounds(limit, "", None)?;
492 self.with_model(tenant, name, |model| {
493 if after < model.reset_revision {
494 return Ok(ModelChanges::Reset {
495 reset_revision: model.reset_revision,
496 });
497 }
498 let mut changed: Vec<(u64, &str)> = model
499 .versions
500 .iter()
501 .filter(|(_, version)| **version > after)
502 .map(|(key, version)| (*version, key.as_str()))
503 .collect();
504 changed.sort_unstable();
505 let mut changes = Vec::new();
506 let mut bytes = 4096;
507 let mut caught_up = true;
508 let mut start = 0;
509 while start < changed.len() {
510 let version = changed[start].0;
511 let end = changed[start..]
512 .iter()
513 .position(|(other, _)| *other != version)
514 .map_or(changed.len(), |offset| start + offset);
515 let mut group = Vec::with_capacity(end - start);
516 let mut group_bytes = 0;
517 for (_, key) in &changed[start..end] {
518 let state = model.rows.get(*key).cloned();
519 group_bytes += row_bytes(key, state.as_ref())?;
520 group.push(ModelRow {
521 key: (*key).to_owned(),
522 state,
523 version,
524 });
525 }
526 if !changes.is_empty()
527 && (changes.len() + group.len() > limit || bytes + group_bytes > MAX_PAGE_BYTES)
528 {
529 caught_up = false;
530 break;
531 }
532 bytes += group_bytes;
533 changes.extend(group);
534 start = end;
535 }
536 let revision = if caught_up {
537 model.revision
538 } else {
539 changes.last().map_or(after, |row: &ModelRow| row.version)
540 };
541 Ok(ModelChanges::Page(ChangesPage {
542 meta: model.meta(),
543 changes,
544 revision,
545 caught_up,
546 }))
547 })
548 }
549
550 pub fn read_model_page(
551 &self,
552 tenant: &str,
553 name: &str,
554 prefix: &str,
555 after: Option<&str>,
556 limit: usize,
557 revision: Option<u64>,
558 ) -> Result<ModelPage> {
559 check_bounds(limit, prefix, after)?;
560 self.with_model(tenant, name, |model| {
561 Self::model_page(model, prefix, after, limit, revision)
562 })
563 }
564
565 fn model_page(
566 model: &ReadModel,
567 prefix: &str,
568 after: Option<&str>,
569 limit: usize,
570 revision: Option<u64>,
571 ) -> Result<ModelPage> {
572 let content_revision = model.content_revision(prefix);
573 let unchanged = revision == Some(content_revision);
574 let mut page = ModelPage {
575 revision: model.revision,
576 content_revision,
577 checkpoint: model.checkpoint,
578 ready: model.ready,
579 unchanged,
580 rows: BTreeMap::new(),
581 next: None,
582 };
583 if unchanged {
584 return Ok(page);
585 }
586 let mut bytes = 4096;
587 for (key, value) in model.rows.range(prefix.to_string()..) {
588 if !key.starts_with(prefix) {
589 break;
590 }
591 if after.is_some_and(|after| key.as_str() <= after) {
592 continue;
593 }
594 let size = serde_json::to_vec(key)?.len() + serde_json::to_vec(value)?.len() + 8;
595 if page.rows.len() == limit || bytes + size > MAX_PAGE_BYTES {
596 page.next = page.rows.keys().next_back().cloned();
597 break;
598 }
599 bytes += size;
600 page.rows.insert(key.clone(), value.clone());
601 }
602 Ok(page)
603 }
604}