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