Skip to main content

allsource_core/
store_feed.rs

1use super::EventStore;
2use crate::{
3    application::dto::EventDto,
4    domain::entities::Event,
5    error::{AllSourceError, Result},
6    infrastructure::persistence::{
7        archive_budget::ArchiveReadBudget,
8        feed_log::{Appended, FeedLog, FeedLogRecord, FeedLogScope},
9    },
10};
11use serde::{Deserialize, Serialize};
12use std::{
13    collections::{HashMap, HashSet},
14    path::{Path, PathBuf},
15    sync::{Arc, OnceLock},
16};
17use uuid::Uuid;
18
19pub const MODEL_EVENT: &str = "allsource.read_model.committed";
20pub const FEED_BYTES: usize = 512 * 1024;
21const SCAN_WINDOW: usize = 10_000;
22pub const DURABLE_LOG_ENV: &str = "ALLSOURCE_FEED_DURABLE_LOG";
23/// Under the WAL directory.
24pub const FEED_LOG_DIR: &str = "feed-log";
25
26/// `ALLSOURCE_FEED_DURABLE_LOG` (default off, syntax in
27/// [`FeedLogScope::parse`]) keeps the named tenants' feed epoch and positions
28/// in a log, so a restart does not renumber them.
29pub(super) fn open_feed_log(wal_dir: Option<&Path>, read_only: bool) -> Option<Arc<FeedLog>> {
30    let scope = FeedLogScope::parse(std::env::var(DURABLE_LOG_ENV).ok().as_deref())?;
31    let Some(wal_dir) = wal_dir.filter(|_| !read_only) else {
32        tracing::warn!(
33            "{DURABLE_LOG_ENV} needs a writable store with a WAL; feed positions stay per process"
34        );
35        return None;
36    };
37    let dir = wal_dir.join(FEED_LOG_DIR);
38    match FeedLog::open(dir.clone(), scope) {
39        Ok(log) => Some(Arc::new(log)),
40        Err(error) => {
41            tracing::error!(
42                "Durable feed log unavailable at {}: {error}; feed positions stay per process",
43                dir.display()
44            );
45            None
46        }
47    }
48}
49
50/// `ALLSOURCE_FEED_NARROW_INDEX=0` restores the feed that hydrates the whole
51/// tenant on every call.
52fn narrow_feed_enabled() -> bool {
53    static ENABLED: OnceLock<bool> = OnceLock::new();
54    *ENABLED.get_or_init(|| {
55        std::env::var("ALLSOURCE_FEED_NARROW_INDEX").map_or(true, |value| value.trim() != "0")
56    })
57}
58
59#[derive(Clone)]
60enum Locator {
61    Memory,
62    Archive { file: Arc<PathBuf>, row: u64 },
63}
64
65struct FeedEntry {
66    id: Uuid,
67    event_type: Arc<str>,
68    entity_id: Arc<str>,
69    at: Locator,
70}
71
72pub(super) struct FeedIndex {
73    epoch: u64,
74    events: Vec<FeedEntry>,
75    ids: HashSet<Uuid>,
76    /// Built from the tenant's whole archive plus memory, so it numbers every
77    /// event without the tenant being resident.
78    narrow: bool,
79    /// Mirrors the tenant's [`FeedLog`] record for record: same epoch, same
80    /// positions.
81    durable: bool,
82}
83
84impl Default for FeedIndex {
85    fn default() -> Self {
86        Self {
87            epoch: Uuid::new_v4().as_u64_pair().0 & ((1_u64 << 52) - 1),
88            events: Vec::new(),
89            ids: HashSet::new(),
90            narrow: false,
91            durable: false,
92        }
93    }
94}
95
96#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
97pub struct FeedCursor {
98    pub epoch: u64,
99    pub position: usize,
100}
101
102#[derive(Debug, Serialize)]
103pub struct FeedPage {
104    pub tenant_id: String,
105    pub cursor: FeedCursor,
106    pub head: FeedCursor,
107    pub events: Vec<EventDto>,
108    pub positions: Vec<usize>,
109    pub caught_up: bool,
110}
111
112struct Candidate {
113    position: usize,
114    id: Uuid,
115    at: Locator,
116}
117
118struct Scan {
119    epoch: u64,
120    head: usize,
121    start: FeedCursor,
122    candidates: Vec<Candidate>,
123    stop: usize,
124}
125
126/// Positions past `visible` are not served yet.
127fn scan_feed(
128    feed: &FeedIndex,
129    visible: usize,
130    cursor: Option<FeedCursor>,
131    limit: usize,
132    prefixes: &[String],
133    entity: Option<&str>,
134) -> Result<Scan> {
135    let epoch = feed.epoch;
136    let head = feed.events.len().min(visible);
137    let start = cursor.unwrap_or(FeedCursor { epoch, position: 0 });
138    if start.epoch != epoch || start.position > head {
139        return Err(AllSourceError::VersionConflict {
140            expected: start.epoch,
141            current: epoch,
142        });
143    }
144    let mut candidates = Vec::new();
145    let mut position = start.position;
146    if limit > 0 {
147        let scan_end = head.min(start.position.saturating_add(SCAN_WINDOW));
148        while position < scan_end {
149            let entry = &feed.events[position];
150            position += 1;
151            if entity.is_none_or(|entity| &*entry.entity_id == entity)
152                && (prefixes.is_empty()
153                    || prefixes
154                        .iter()
155                        .any(|prefix| entry.event_type.starts_with(prefix.as_str())))
156            {
157                candidates.push(Candidate {
158                    position: position - 1,
159                    id: entry.id,
160                    at: entry.at.clone(),
161                });
162                if candidates.len() == limit {
163                    break;
164                }
165            }
166        }
167    }
168    Ok(Scan {
169        epoch,
170        head,
171        start,
172        candidates,
173        stop: position,
174    })
175}
176
177impl EventStore {
178    fn durable_feed_log(&self, tenant: &str) -> Option<&FeedLog> {
179        self.feed_log.as_deref().filter(|log| log.includes(tenant))
180    }
181
182    pub(super) fn observe_feed_head(&self, event: &Event, _position: usize) {
183        if event.event_type_str() == MODEL_EVENT {
184            return;
185        }
186        if let Some(log) = self.durable_feed_log(event.tenant_id_str()) {
187            self.observe_durable_feed(log, event);
188            return;
189        }
190        let mut feed = self
191            .feed_indexes
192            .entry(event.tenant_id_str().to_owned())
193            .or_default();
194        if feed.ids.insert(event.id) {
195            feed.events.push(FeedEntry {
196                id: event.id,
197                event_type: Arc::from(event.event_type_str()),
198                entity_id: Arc::from(event.entity_id_str()),
199                at: Locator::Memory,
200            });
201        }
202    }
203
204    pub(super) fn rebuild_tenant_feed(&self, tenant: &str, events: &[Event]) {
205        self.feed_indexes.remove(tenant);
206        for event in events
207            .iter()
208            .filter(|event| event.tenant_id_str() == tenant)
209        {
210            self.observe_feed_head(event, 0);
211        }
212    }
213
214    /// Called under the events write lock, as is every durable index build,
215    /// so the index and the log take records in the same order.
216    fn observe_durable_feed(&self, log: &FeedLog, event: &Event) {
217        let tenant = event.tenant_id_str();
218        let record = FeedLogRecord::new(event.id, event.event_type_str(), event.entity_id_str());
219        match log.append(tenant, record.clone()) {
220            Ok(Appended::New) => {
221                if let Some(mut feed) = self.feed_indexes.get_mut(tenant)
222                    && feed.durable
223                {
224                    feed.ids.insert(record.id);
225                    feed.events.push(FeedEntry {
226                        id: record.id,
227                        event_type: record.event_type,
228                        entity_id: record.entity_id,
229                        at: Locator::Memory,
230                    });
231                }
232            }
233            Ok(Appended::Duplicate | Appended::NotOpen) => {}
234            Err(error) => {
235                tracing::error!("Feed log append failed for event {}: {error}", event.id);
236                // The next read rebuilds the index and re-appends what the log lacks.
237                self.feed_indexes.remove(tenant);
238            }
239        }
240    }
241
242    /// Make every pending feed-log record durable. Runs before a checkpoint
243    /// retires WAL segments and before boot recovery truncates the WAL, so
244    /// the order the log gave recovered events is not lost with them.
245    pub(super) fn sync_feed_log(&self) -> Result<()> {
246        match &self.feed_log {
247            Some(log) => self.publish_feed_log(log, None),
248            None => Ok(()),
249        }
250    }
251
252    /// The WAL is fsynced first so that no visible position outlives the
253    /// event it names.
254    fn publish_feed_log(&self, log: &FeedLog, tenant: Option<&str>) -> Result<()> {
255        let pending = match tenant {
256            Some(tenant) => log.has_pending(tenant),
257            None => log.has_any_pending(),
258        };
259        if !pending {
260            return Ok(());
261        }
262        if let Some(wal) = &self.wal {
263            wal.sync()?;
264        }
265        match tenant {
266            Some(tenant) => log.sync_tenant(tenant),
267            None => log.sync_all(),
268        }
269    }
270
271    fn ensure_durable_feed(&self, tenant: &str, log: &FeedLog) -> Result<()> {
272        if !self
273            .feed_indexes
274            .get(tenant)
275            .is_some_and(|feed| feed.durable)
276        {
277            self.build_durable_feed(tenant, log)?;
278        }
279        self.publish_feed_log(log, Some(tenant))
280    }
281
282    /// Index the tenant's log. A tenant without one is backfilled from the
283    /// archive in path order plus memory, as the narrow index numbers it; a
284    /// tenant with one gets any event the log lacks appended at the end, so
285    /// no served position moves.
286    fn build_durable_feed(&self, tenant: &str, log: &FeedLog) -> Result<()> {
287        let _resident = self.cache_residency_gate.read();
288        let keys = match &self.storage {
289            Some(storage) => {
290                let mut budget = ArchiveReadBudget::new(self.strict_archive_limits.clone());
291                storage.read().scan_feed_keys(tenant, &mut budget)?
292            }
293            None => Vec::new(),
294        };
295        let events = self.events.write();
296        if self
297            .feed_indexes
298            .get(tenant)
299            .is_some_and(|feed| feed.durable)
300        {
301            return Ok(());
302        }
303        let mut names: HashMap<String, Arc<str>> = HashMap::new();
304        let mut intern = |value: String| -> Arc<str> {
305            names
306                .entry(value)
307                .or_insert_with_key(|value| Arc::from(value.as_str()))
308                .clone()
309        };
310        let mut located: HashMap<Uuid, Locator> = HashMap::with_capacity(keys.len());
311        let mut seen = HashSet::with_capacity(keys.len());
312        let mut history = Vec::new();
313        for key in keys {
314            if key.event_type == MODEL_EVENT {
315                continue;
316            }
317            located.entry(key.id).or_insert(Locator::Archive {
318                file: key.file,
319                row: key.row,
320            });
321            if seen.insert(key.id) {
322                history.push(FeedLogRecord {
323                    id: key.id,
324                    event_type: intern(key.event_type),
325                    entity_id: intern(key.entity_id),
326                });
327            }
328        }
329        for event in events.iter().filter(|event| {
330            event.tenant_id_str() == tenant && event.event_type_str() != MODEL_EVENT
331        }) {
332            if seen.insert(event.id) {
333                history.push(FeedLogRecord {
334                    id: event.id,
335                    event_type: intern(event.event_type_str().to_owned()),
336                    entity_id: intern(event.entity_id_str().to_owned()),
337                });
338            }
339        }
340        if log.is_open(tenant) {
341            let mut appended = 0_usize;
342            for record in history {
343                if log.append(tenant, record)? == Appended::New {
344                    appended += 1;
345                }
346            }
347            if appended > 0 {
348                tracing::warn!("Feed log lacked {appended} archived or resident events; appended");
349            }
350        } else {
351            if let Some(wal) = &self.wal {
352                wal.sync()?;
353            }
354            log.create(tenant, &history)?;
355        }
356        let (epoch, records) = log
357            .records(tenant)
358            .ok_or_else(|| AllSourceError::StorageError("feed log is not open; retry".into()))?;
359        let mut feed = FeedIndex {
360            epoch,
361            events: Vec::with_capacity(records.len()),
362            ids: HashSet::with_capacity(records.len()),
363            narrow: true,
364            durable: true,
365        };
366        for record in records {
367            feed.ids.insert(record.id);
368            feed.events.push(FeedEntry {
369                at: located.get(&record.id).cloned().unwrap_or(Locator::Memory),
370                id: record.id,
371                event_type: record.event_type,
372                entity_id: record.entity_id,
373            });
374        }
375        self.feed_indexes.insert(tenant.to_owned(), feed);
376        drop(events);
377        Ok(())
378    }
379
380    /// Number the tenant's whole history from the archive's id, type and
381    /// entity columns plus the events still only in memory. The epoch is new:
382    /// positions from any earlier index of this tenant do not carry over.
383    fn ensure_narrow_feed(&self, tenant: &str) -> Result<()> {
384        if self
385            .feed_indexes
386            .get(tenant)
387            .is_some_and(|feed| feed.narrow)
388        {
389            return Ok(());
390        }
391        let _resident = self.cache_residency_gate.read();
392        let keys = match &self.storage {
393            Some(storage) => {
394                let mut budget = ArchiveReadBudget::new(self.strict_archive_limits.clone());
395                storage.read().scan_feed_keys(tenant, &mut budget)?
396            }
397            None => Vec::new(),
398        };
399        // Ingest observes the feed under the events write lock, so holding it
400        // makes the swap atomic with every concurrent append.
401        let events = self.events.write();
402        if self
403            .feed_indexes
404            .get(tenant)
405            .is_some_and(|feed| feed.narrow)
406        {
407            return Ok(());
408        }
409        let mut names: HashMap<String, Arc<str>> = HashMap::new();
410        let mut intern = |value: String| -> Arc<str> {
411            names
412                .entry(value)
413                .or_insert_with_key(|value| Arc::from(value.as_str()))
414                .clone()
415        };
416        let mut feed = FeedIndex {
417            narrow: true,
418            ..FeedIndex::default()
419        };
420        for key in keys {
421            if key.event_type == MODEL_EVENT || !feed.ids.insert(key.id) {
422                continue;
423            }
424            feed.events.push(FeedEntry {
425                id: key.id,
426                event_type: intern(key.event_type),
427                entity_id: intern(key.entity_id),
428                at: Locator::Archive {
429                    file: key.file,
430                    row: key.row,
431                },
432            });
433        }
434        for event in events.iter().filter(|event| {
435            event.tenant_id_str() == tenant && event.event_type_str() != MODEL_EVENT
436        }) {
437            if feed.ids.insert(event.id) {
438                feed.events.push(FeedEntry {
439                    id: event.id,
440                    event_type: intern(event.event_type_str().to_owned()),
441                    entity_id: intern(event.entity_id_str().to_owned()),
442                    at: Locator::Memory,
443                });
444            }
445        }
446        self.feed_indexes.insert(tenant.to_owned(), feed);
447        drop(events);
448        Ok(())
449    }
450
451    /// Epoch changes force a rebuild instead of silently skipping reordered history.
452    pub fn tenant_feed(
453        &self,
454        tenant: &str,
455        cursor: Option<FeedCursor>,
456        limit: usize,
457    ) -> Result<FeedPage> {
458        self.tenant_feed_filtered(tenant, cursor, limit, &[])
459    }
460
461    pub fn tenant_feed_filtered(
462        &self,
463        tenant: &str,
464        cursor: Option<FeedCursor>,
465        limit: usize,
466        prefixes: &[String],
467    ) -> Result<FeedPage> {
468        self.tenant_feed_scoped(tenant, cursor, limit, prefixes, None)
469    }
470
471    pub fn tenant_feed_scoped(
472        &self,
473        tenant: &str,
474        cursor: Option<FeedCursor>,
475        limit: usize,
476        prefixes: &[String],
477        entity: Option<&str>,
478    ) -> Result<FeedPage> {
479        if limit > 500 {
480            return Err(AllSourceError::InvalidInput(
481                "feed limit must be 0..500".into(),
482            ));
483        }
484        let durable = self.durable_feed_log(tenant);
485        if let Some(log) = durable {
486            self.ensure_durable_feed(tenant, log)?;
487        } else if narrow_feed_enabled() {
488            self.ensure_narrow_feed(tenant)?;
489        } else {
490            self.ensure_tenant_loaded_with_integrity(tenant, true)?;
491            if self.storage.is_some() && !self.tenant_loader.is_complete(tenant) {
492                return Err(AllSourceError::StorageError(
493                    "feed archive certification was evicted; retry".into(),
494                ));
495            }
496        }
497        let _resident = self.cache_residency_gate.read();
498        let Scan {
499            epoch,
500            head: head_position,
501            start,
502            candidates,
503            stop: scan_stop,
504        } = match durable {
505            Some(log) => {
506                let visible = log.durable_len(tenant);
507                match self.feed_indexes.get(tenant) {
508                    Some(feed) if feed.durable => {
509                        scan_feed(&feed, visible, cursor, limit, prefixes, entity)
510                    }
511                    // A default index here would serve a random epoch.
512                    _ => Err(AllSourceError::StorageError(
513                        "feed index was evicted; retry".into(),
514                    )),
515                }
516            }
517            None => scan_feed(
518                &self.feed_indexes.entry(tenant.to_owned()).or_default(),
519                usize::MAX,
520                cursor,
521                limit,
522                prefixes,
523                entity,
524            ),
525        }?;
526        let head = FeedCursor {
527            epoch,
528            position: head_position,
529        };
530        if limit == 0 {
531            return Ok(FeedPage {
532                tenant_id: tenant.to_owned(),
533                cursor: head,
534                head,
535                events: vec![],
536                positions: vec![],
537                caught_up: true,
538            });
539        }
540        let events = self.feed_payloads(tenant, &candidates)?;
541        let mut output = Vec::new();
542        let mut positions = Vec::new();
543        let mut bytes = 1024;
544        let mut cursor_position = scan_stop.max(start.position);
545        for (candidate, event) in candidates.iter().zip(events) {
546            let dto = EventDto::from(&event);
547            let size = serde_json::to_vec(&dto)?.len() + 24;
548            if bytes + size > FEED_BYTES {
549                if output.is_empty() {
550                    return Err(AllSourceError::InvalidInput(
551                        "single feed event exceeds bounded feed response".into(),
552                    ));
553                }
554                cursor_position = candidate.position;
555                break;
556            }
557            bytes += size;
558            output.push(dto);
559            positions.push(candidate.position + 1);
560        }
561        Ok(FeedPage {
562            tenant_id: tenant.to_owned(),
563            cursor: FeedCursor {
564                epoch,
565                position: cursor_position,
566            },
567            head,
568            events: output,
569            positions,
570            caught_up: cursor_position >= head_position,
571        })
572    }
573
574    /// Payloads for `candidates`, in order. If an archive file moved under the
575    /// index (compaction or repack), locators are remapped from a fresh narrow
576    /// scan once; positions do not change.
577    fn feed_payloads(&self, tenant: &str, candidates: &[Candidate]) -> Result<Vec<Event>> {
578        if let Some(events) = self.read_feed_payloads(tenant, candidates)? {
579            return Ok(events);
580        }
581        let remapped = self.remap_feed_locators(tenant, candidates)?;
582        self.read_feed_payloads(tenant, &remapped)?.ok_or_else(|| {
583            self.feed_indexes.remove(tenant);
584            AllSourceError::StorageError("feed archive changed; retry".into())
585        })
586    }
587
588    /// `None` when a locator no longer resolves.
589    fn read_feed_payloads(
590        &self,
591        tenant: &str,
592        candidates: &[Candidate],
593    ) -> Result<Option<Vec<Event>>> {
594        let mut found: HashMap<Uuid, Event> = HashMap::with_capacity(candidates.len());
595        let mut by_file: HashMap<Arc<PathBuf>, Vec<u64>> = HashMap::new();
596        {
597            let events = self.events.read();
598            for candidate in candidates {
599                match &candidate.at {
600                    Locator::Memory => {
601                        let event = self
602                            .index
603                            .get_by_id(&candidate.id)
604                            .and_then(|offset| events.get(offset))
605                            .filter(|event| event.id == candidate.id);
606                        match event {
607                            Some(event) => {
608                                found.insert(candidate.id, event.clone());
609                            }
610                            None => return Ok(None),
611                        }
612                    }
613                    Locator::Archive { file, row } => {
614                        by_file.entry(Arc::clone(file)).or_default().push(*row);
615                    }
616                }
617            }
618        }
619        if !by_file.is_empty() {
620            let Some(storage) = &self.storage else {
621                return Ok(None);
622            };
623            let storage = storage.read();
624            let mut budget = ArchiveReadBudget::new(self.strict_archive_limits.clone());
625            for (file, mut rows) in by_file {
626                rows.sort_unstable();
627                rows.dedup();
628                match storage.read_feed_rows(&file, &rows, tenant, &mut budget) {
629                    Ok(events) => {
630                        for event in events {
631                            found.insert(event.id, event);
632                        }
633                    }
634                    Err(_) if !file.exists() => return Ok(None),
635                    Err(error) => return Err(error),
636                }
637            }
638        }
639        let mut ordered = Vec::with_capacity(candidates.len());
640        for candidate in candidates {
641            match found.remove(&candidate.id) {
642                Some(event) => ordered.push(event),
643                None => return Ok(None),
644            }
645        }
646        Ok(Some(ordered))
647    }
648
649    fn remap_feed_locators(
650        &self,
651        tenant: &str,
652        candidates: &[Candidate],
653    ) -> Result<Vec<Candidate>> {
654        let keys = match &self.storage {
655            Some(storage) => {
656                let mut budget = ArchiveReadBudget::new(self.strict_archive_limits.clone());
657                storage.read().scan_feed_keys(tenant, &mut budget)?
658            }
659            None => Vec::new(),
660        };
661        let mut located: HashMap<Uuid, Locator> = HashMap::with_capacity(keys.len());
662        for key in keys {
663            located.entry(key.id).or_insert(Locator::Archive {
664                file: key.file,
665                row: key.row,
666            });
667        }
668        if let Some(mut feed) = self.feed_indexes.get_mut(tenant) {
669            for entry in &mut feed.events {
670                if let Some(at) = located.get(&entry.id) {
671                    entry.at = at.clone();
672                }
673            }
674        }
675        Ok(candidates
676            .iter()
677            .map(|candidate| Candidate {
678                position: candidate.position,
679                id: candidate.id,
680                at: located
681                    .get(&candidate.id)
682                    .cloned()
683                    .unwrap_or(Locator::Memory),
684            })
685            .collect())
686    }
687}