Skip to main content

allsource_core/
store_strict_read.rs

1use super::{EventStore, ReadScope};
2use crate::{
3    domain::{
4        entities::Event,
5        value_objects::{EntityId, TenantId},
6    },
7    error::{AllSourceError, Result},
8    infrastructure::persistence::archive_budget::ArchiveReadBudget,
9};
10use chrono::SubsecRound;
11use std::{
12    collections::HashSet,
13    io,
14    sync::{Arc, atomic::AtomicBool},
15};
16
17const MAX_ENTITY_EVENTS: usize = 1_001;
18// Leave room inside the consumer's 2 MiB wire cap for the response envelope.
19const MAX_ENCODED_EVENTS: usize = 2 * 1024 * 1024 - 16 * 1024;
20
21impl EventStore {
22    /// Read one complete retained entity snapshot under an explicit read scope.
23    /// Archive errors, oversized input and cancellation refuse the
24    /// read; this is not evidence that retention never removed older history.
25    /// Timestamp precision and ordering match Parquet's microseconds so the
26    /// same retained evidence stays stable across cache eviction and restart.
27    pub fn query_retained_entity(
28        &self,
29        tenant_id: &str,
30        entity_id: &str,
31        limit: usize,
32        scope: &ReadScope,
33    ) -> Result<(Vec<Event>, usize)> {
34        self.query_retained_entity_cancellable(tenant_id, entity_id, limit, scope, None)
35    }
36
37    pub(crate) fn query_retained_entity_cancellable(
38        &self,
39        tenant_id: &str,
40        entity_id: &str,
41        limit: usize,
42        scope: &ReadScope,
43        cancellation: Option<&Arc<AtomicBool>>,
44    ) -> Result<(Vec<Event>, usize)> {
45        TenantId::new(tenant_id.to_string())?;
46        EntityId::new(entity_id.to_string())?;
47        if !(1..=MAX_ENTITY_EVENTS).contains(&limit) || !scope.permits(entity_id) {
48            return Err(AllSourceError::InvalidInput(
49                "Strict retained read target or limit refused".into(),
50            ));
51        }
52        let mut budget = ArchiveReadBudget::new(self.strict_archive_limits.clone())
53            .with_cancellation(cancellation.cloned());
54        budget.check()?;
55        let _resident = self
56            .cache_residency_gate
57            .try_read_for(budget.remaining()?)
58            .ok_or_else(|| {
59                AllSourceError::StorageError("Strict retained read residency lock timed out".into())
60            })?;
61        let mut selected = Vec::new();
62        let mut seen = HashSet::new();
63        let mut remaining = MAX_ENCODED_EVENTS;
64        let mut version = 0;
65        let mut retain = |event: &Event, work: &ArchiveReadBudget| -> Result<()> {
66            work.check()?;
67            let observed = u64::try_from(event.version).map_err(|_| {
68                AllSourceError::StorageError("Archived entity version cannot be represented".into())
69            })?;
70            version = version.max(observed);
71            if seen.contains(&event.id) {
72                return Ok(());
73            }
74            if selected.len() == MAX_ENTITY_EVENTS {
75                return Err(AllSourceError::StorageError(
76                    "Strict retained read event budget exceeded".into(),
77                ));
78            }
79            let mut encoded = EncodedBudget { remaining, work };
80            // The writer also fails on cancellation and deadline; report those, not size.
81            serde_json::to_writer(&mut encoded, event).map_err(|_| {
82                work.check().err().unwrap_or_else(|| {
83                    AllSourceError::StorageError(
84                        "Strict retained read encoded data budget exceeded".into(),
85                    )
86                })
87            })?;
88            remaining = encoded.remaining;
89            seen.insert(event.id);
90            selected.push(event.clone());
91            Ok(())
92        };
93        if let Some(storage) = &self.storage {
94            storage
95                .try_read_for(budget.remaining()?)
96                .ok_or_else(|| {
97                    AllSourceError::StorageError(
98                        "Strict retained read storage lock timed out".into(),
99                    )
100                })?
101                .visit_retained_entity(tenant_id, entity_id, &mut budget, &mut retain)?;
102        }
103        let events = self
104            .events
105            .try_read_for(budget.remaining()?)
106            .ok_or_else(|| {
107                AllSourceError::StorageError("Strict retained read event lock timed out".into())
108            })?;
109        let entries = self
110            .index
111            .get_by_entity_bounded(entity_id, MAX_ENTITY_EVENTS)?;
112        for entry in entries {
113            budget.check()?;
114            let event = events
115                .get(entry.offset)
116                .filter(|event| event.id == entry.event_id && event.entity_id_str() == entity_id)
117                .ok_or_else(|| {
118                    AllSourceError::StorageError(
119                        "Strict retained read encountered an inconsistent index".into(),
120                    )
121                })?;
122            if event.tenant_id_str() != tenant_id {
123                continue;
124            }
125            retain(event, &budget)?;
126        }
127        selected.sort_by(|left, right| {
128            left.timestamp
129                .timestamp_micros()
130                .cmp(&right.timestamp.timestamp_micros())
131                .then_with(|| left.version.cmp(&right.version))
132        });
133        let total = selected.len();
134        let result = selected
135            .into_iter()
136            .take(limit)
137            .map(|mut event| {
138                event.timestamp = event.timestamp.trunc_subsecs(6);
139                event
140            })
141            .collect();
142        budget.check()?;
143        self.entity_versions
144            .entry(entity_id.to_string())
145            .and_modify(|current| *current = (*current).max(version))
146            .or_insert(version);
147        self.version_index_entities
148            .insert(entity_id.to_string(), ());
149        Ok((result, total))
150    }
151}
152
153pub(super) struct EncodedBudget<'a> {
154    pub(super) remaining: usize,
155    pub(super) work: &'a ArchiveReadBudget,
156}
157
158impl io::Write for EncodedBudget<'_> {
159    fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
160        self.work
161            .check()
162            .map_err(|error| io::Error::other(error.to_string()))?;
163        self.remaining = self
164            .remaining
165            .checked_sub(bytes.len())
166            .ok_or_else(|| io::Error::other("encoded event budget exceeded"))?;
167        Ok(bytes.len())
168    }
169
170    fn flush(&mut self) -> io::Result<()> {
171        Ok(())
172    }
173}
174
175#[cfg(test)]
176#[path = "store_strict_read_tests.rs"]
177mod tests;