Skip to main content

reddb_server/runtime/
impl_cdc.rs

1use super::*;
2use crate::application::entity::metadata_to_json;
3use crate::replication::cdc::{server_json_to_wire_json, ChangeRecord};
4use crate::runtime::impl_core::current_connection_id;
5use std::time::{SystemTime, UNIX_EPOCH};
6
7impl RedDBRuntime {
8    fn latest_metadata_for(
9        &self,
10        collection: &str,
11        entity_id: u64,
12    ) -> Option<reddb_wire::replication::ChangeRecordJsonValue> {
13        self.inner
14            .db
15            .store()
16            .get_metadata(collection, EntityId::new(entity_id))
17            .map(|metadata| server_json_to_wire_json(metadata_to_json(&metadata)))
18    }
19
20    /// Emit a CDC record without invalidating the result cache.
21    ///
22    /// Used by `MutationEngine::append_batch` which calls
23    /// `invalidate_result_cache` once for the whole batch before this
24    /// loop, avoiding N write-lock acquisitions.
25    pub(crate) fn cdc_emit_no_cache_invalidate(
26        &self,
27        operation: crate::replication::cdc::ChangeOperation,
28        collection: &str,
29        entity_id: u64,
30        entity_kind: &str,
31    ) -> RedDBResult<u64> {
32        let lsn = self
33            .inner
34            .cdc
35            .emit(operation, collection, entity_id, entity_kind);
36
37        // Append to logical WAL replication buffer (if primary mode)
38        if self.inner.db.replication.is_some() {
39            let store = self.inner.db.store();
40            let entity = if operation == crate::replication::cdc::ChangeOperation::Delete {
41                None
42            } else {
43                store.get(collection, EntityId::new(entity_id))
44            };
45            let record = ChangeRecord {
46                term: self.current_replication_term(),
47                lsn,
48                timestamp: SystemTime::now()
49                    .duration_since(UNIX_EPOCH)
50                    .unwrap_or_default()
51                    .as_millis() as u64,
52                operation,
53                collection: collection.to_string(),
54                entity_id,
55                entity_kind: entity_kind.to_string(),
56                entity_bytes: entity
57                    .as_ref()
58                    .map(|e| UnifiedStore::serialize_entity(e, store.format_version())),
59                metadata: self.latest_metadata_for(collection, entity_id),
60                refresh_records: None,
61                range_id: None,
62                ownership_epoch: None,
63            };
64            self.stage_or_publish_logical_record(record)?;
65        }
66        Ok(lsn)
67    }
68
69    pub(crate) fn cdc_emit_insert_batch_no_cache_invalidate(
70        &self,
71        collection: &str,
72        ids: &[EntityId],
73        entity_kind: &str,
74    ) -> RedDBResult<Vec<u64>> {
75        if ids.is_empty() {
76            return Ok(Vec::new());
77        }
78
79        // Without logical replication, CDC only needs the in-memory event
80        // ring. Reserve all LSNs and push the batch under one mutex instead
81        // of taking the ring lock once per inserted row.
82        if self.inner.db.replication.is_none() {
83            return Ok(self.inner.cdc.emit_batch_same_collection(
84                crate::replication::cdc::ChangeOperation::Insert,
85                collection,
86                entity_kind,
87                ids.iter().map(|id| id.raw()),
88            ));
89        }
90
91        // Replication needs one logical-WAL record per entity with the
92        // serialized entity bytes, so keep the existing per-row path.
93        ids.iter()
94            .map(|id| {
95                self.cdc_emit_no_cache_invalidate(
96                    crate::replication::cdc::ChangeOperation::Insert,
97                    collection,
98                    id.raw(),
99                    entity_kind,
100                )
101            })
102            .collect()
103    }
104
105    pub fn cdc_emit(
106        &self,
107        operation: crate::replication::cdc::ChangeOperation,
108        collection: &str,
109        entity_id: u64,
110        entity_kind: &str,
111    ) -> RedDBResult<u64> {
112        self.cdc_emit_with_replaced_id(operation, collection, entity_id, entity_kind, None)
113    }
114
115    pub(super) fn cdc_emit_with_replaced_id(
116        &self,
117        operation: crate::replication::cdc::ChangeOperation,
118        collection: &str,
119        entity_id: u64,
120        entity_kind: &str,
121        replaced_id: Option<EntityId>,
122    ) -> RedDBResult<u64> {
123        let lsn = self
124            .inner
125            .cdc
126            .emit(operation, collection, entity_id, entity_kind);
127        // Perf: prior to this we called `invalidate_result_cache()`
128        // which wipes EVERY cached query, across every table, under
129        // a write lock — turning each INSERT into a serialisation
130        // point for all readers. Swap to the per-table variant so
131        // unrelated query caches survive.
132        self.invalidate_result_cache_for_table(collection);
133
134        // Append to logical WAL replication buffer (if primary mode)
135        if self.inner.db.replication.is_some() {
136            let store = self.inner.db.store();
137            let entity = if operation == crate::replication::cdc::ChangeOperation::Delete {
138                None
139            } else {
140                store.get(collection, EntityId::new(entity_id))
141            };
142            let record = ChangeRecord {
143                term: self.current_replication_term(),
144                lsn,
145                timestamp: SystemTime::now()
146                    .duration_since(UNIX_EPOCH)
147                    .unwrap_or_default()
148                    .as_millis() as u64,
149                operation,
150                collection: collection.to_string(),
151                entity_id,
152                entity_kind: entity_kind.to_string(),
153                entity_bytes: entity
154                    .as_ref()
155                    .map(|entity| UnifiedStore::serialize_entity(entity, store.format_version())),
156                metadata: self.latest_metadata_for(collection, entity_id),
157                refresh_records: None,
158                range_id: None,
159                ownership_epoch: None,
160            };
161            // One source commit and one replica cursor for the entire keyed replacement.
162            let record = if let Some(previous) = replaced_id {
163                let deletion = ChangeRecord {
164                    term: record.term,
165                    lsn,
166                    timestamp: record.timestamp,
167                    operation: crate::replication::cdc::ChangeOperation::Delete,
168                    collection: collection.to_owned(),
169                    entity_id: previous.raw(),
170                    entity_kind: entity_kind.to_owned(),
171                    entity_bytes: None,
172                    metadata: None,
173                    refresh_records: None,
174                    range_id: record.range_id,
175                    ownership_epoch: record.ownership_epoch,
176                };
177                let term = record.term;
178                ChangeRecord::for_transaction(lsn, record.timestamp, vec![deletion, record])
179                    .with_term(term)
180            } else {
181                record
182            };
183            self.stage_or_publish_logical_record(record)?;
184        }
185        Ok(lsn)
186    }
187
188    pub(crate) fn cdc_emit_kv(
189        &self,
190        operation: crate::replication::cdc::ChangeOperation,
191        collection: &str,
192        key: &str,
193        entity_id: u64,
194        before: Option<crate::json::Value>,
195        after: Option<crate::json::Value>,
196    ) -> u64 {
197        let lsn = self
198            .inner
199            .cdc
200            .emit_kv(operation, collection, key, entity_id, before, after);
201        self.inner.kv_stats.incr_watch_events_emitted();
202        self.invalidate_result_cache_for_table(collection);
203        lsn
204    }
205
206    pub(crate) fn record_kv_watch_event(
207        &self,
208        operation: crate::replication::cdc::ChangeOperation,
209        collection: &str,
210        key: &str,
211        entity_id: u64,
212        before: Option<crate::json::Value>,
213        after: Option<crate::json::Value>,
214    ) {
215        if let Some(writer_xid) = self.current_xid() {
216            let conn_id = current_connection_id();
217            let event = crate::replication::cdc::KvWatchEvent {
218                collection: collection.to_string(),
219                key: key.to_string(),
220                op: operation,
221                before,
222                after,
223                lsn: 0,
224                committed_at: 0,
225                dropped_event_count: 0,
226            };
227            self.inner
228                .pending_kv_watch_events
229                .write()
230                .entry(conn_id)
231                .or_default()
232                .push((writer_xid, event));
233            return;
234        }
235
236        self.cdc_emit_kv(operation, collection, key, entity_id, before, after);
237    }
238
239    pub(crate) fn cdc_emit_prebuilt(
240        &self,
241        operation: crate::replication::cdc::ChangeOperation,
242        collection: &str,
243        entity: &UnifiedEntity,
244        entity_kind: &str,
245        metadata: Option<&crate::storage::Metadata>,
246        invalidate_cache: bool,
247    ) -> RedDBResult<u64> {
248        self.cdc_emit_prebuilt_with_columns(
249            operation,
250            collection,
251            entity,
252            entity_kind,
253            metadata,
254            invalidate_cache,
255            None,
256        )
257    }
258
259    /// `cdc_emit_prebuilt` plus the list of column names whose values
260    /// changed on this update. Callers that have already computed a
261    /// `RowDamageVector` pass it here so downstream CDC consumers can
262    /// filter events by touched column without re-diffing.
263    /// `changed_columns` is only meaningful for `Update` operations —
264    /// insert and delete events ignore it.
265    pub(crate) fn cdc_emit_prebuilt_with_columns(
266        &self,
267        operation: crate::replication::cdc::ChangeOperation,
268        collection: &str,
269        entity: &UnifiedEntity,
270        entity_kind: &str,
271        metadata: Option<&crate::storage::Metadata>,
272        invalidate_cache: bool,
273        changed_columns: Option<Vec<String>>,
274    ) -> RedDBResult<u64> {
275        if invalidate_cache {
276            self.invalidate_result_cache();
277        }
278
279        let public_id = entity.logical_id().raw();
280        let lsn = self.inner.cdc.emit_with_columns(
281            operation,
282            collection,
283            public_id,
284            entity_kind,
285            changed_columns,
286        );
287
288        if self.inner.db.replication.is_some() {
289            let store = self.inner.db.store();
290            let record = ChangeRecord {
291                term: self.current_replication_term(),
292                lsn,
293                timestamp: SystemTime::now()
294                    .duration_since(UNIX_EPOCH)
295                    .unwrap_or_default()
296                    .as_millis() as u64,
297                operation,
298                collection: collection.to_string(),
299                entity_id: entity.id.raw(),
300                entity_kind: entity_kind.to_string(),
301                entity_bytes: Some(UnifiedStore::serialize_entity(
302                    entity,
303                    store.format_version(),
304                )),
305                metadata: metadata
306                    .map(metadata_to_json)
307                    .map(server_json_to_wire_json)
308                    .or_else(|| self.latest_metadata_for(collection, entity.id.raw())),
309                refresh_records: None,
310                range_id: None,
311                ownership_epoch: None,
312            };
313            self.stage_or_publish_logical_record(record)?;
314        }
315
316        Ok(lsn)
317    }
318
319    pub(crate) fn current_replication_term(&self) -> u64 {
320        self.inner.db.options().replication.term
321    }
322
323    pub(crate) fn cdc_emit_prebuilt_batch<'a, I>(
324        &self,
325        operation: crate::replication::cdc::ChangeOperation,
326        entity_kind: &str,
327        items: I,
328        invalidate_cache: bool,
329    ) -> RedDBResult<()>
330    where
331        I: IntoIterator<
332            Item = (
333                &'a str,
334                &'a UnifiedEntity,
335                Option<&'a crate::storage::Metadata>,
336            ),
337        >,
338    {
339        let items: Vec<(&str, &UnifiedEntity, Option<&crate::storage::Metadata>)> =
340            items.into_iter().collect();
341        if items.is_empty() {
342            return Ok(());
343        }
344
345        if invalidate_cache {
346            self.invalidate_result_cache();
347        }
348
349        for (collection, entity, metadata) in items {
350            self.cdc_emit_prebuilt(operation, collection, entity, entity_kind, metadata, false)?;
351        }
352        Ok(())
353    }
354
355    /// Poll CDC events since a given LSN.
356    pub fn cdc_poll(
357        &self,
358        since_lsn: u64,
359        max_count: usize,
360    ) -> Vec<crate::replication::cdc::ChangeEvent> {
361        self.inner.cdc.poll(since_lsn, max_count)
362    }
363
364    /// Current event cursor for CDC polling. A committed replication batch
365    /// can contain several events, so this is not a replica ACK position.
366    pub fn cdc_current_lsn(&self) -> u64 {
367        self.inner.cdc.current_lsn()
368    }
369
370    /// Published logical commit frontier; standalone instances retain their
371    /// local event cursor. Request-specific receipts are handled separately.
372    pub fn replication_commit_lsn(&self) -> u64 {
373        if self.inner.db.replication.is_some() {
374            self.primary_logical_head_lsn()
375        } else {
376            self.cdc_current_lsn()
377        }
378    }
379
380    pub fn kv_watch_events_since(
381        &self,
382        collection: &str,
383        key: &str,
384        since_lsn: u64,
385        max_count: usize,
386    ) -> Vec<crate::replication::cdc::KvWatchEvent> {
387        self.kv_watch_batch_since(collection, key, since_lsn, max_count)
388            .0
389    }
390
391    pub(crate) fn kv_watch_batch_since(
392        &self,
393        collection: &str,
394        key: &str,
395        since_lsn: u64,
396        max_count: usize,
397    ) -> (Vec<crate::replication::cdc::KvWatchEvent>, u64) {
398        let events = self.inner.cdc.poll(since_lsn, max_count);
399        let scanned_through = events.last().map(|event| event.lsn).unwrap_or(since_lsn);
400        let visible = events
401            .into_iter()
402            .filter_map(|event| event.kv)
403            .filter(|event| event.collection == collection && event.key == key)
404            .filter(|event| crate::runtime::rls_injection::kv_watch_event_passes_rls(self, event))
405            .collect();
406        (visible, scanned_through)
407    }
408
409    pub fn kv_watch_events_since_prefix(
410        &self,
411        collection: &str,
412        prefix: &str,
413        since_lsn: u64,
414        max_count: usize,
415    ) -> Vec<crate::replication::cdc::KvWatchEvent> {
416        self.kv_watch_batch_since_prefix(collection, prefix, since_lsn, max_count)
417            .0
418    }
419
420    pub(crate) fn kv_watch_batch_since_prefix(
421        &self,
422        collection: &str,
423        prefix: &str,
424        since_lsn: u64,
425        max_count: usize,
426    ) -> (Vec<crate::replication::cdc::KvWatchEvent>, u64) {
427        let events = self.inner.cdc.poll(since_lsn, max_count);
428        let scanned_through = events.last().map(|event| event.lsn).unwrap_or(since_lsn);
429        let visible = events
430            .into_iter()
431            .filter_map(|event| event.kv)
432            .filter(|event| event.collection == collection && event.key.starts_with(prefix))
433            .filter(|event| crate::runtime::rls_injection::kv_watch_event_passes_rls(self, event))
434            .collect();
435        (visible, scanned_through)
436    }
437
438    pub(crate) fn kv_watch_subscribe<'a>(
439        &'a self,
440        collection: impl Into<String>,
441        key: impl Into<String>,
442        from_lsn: Option<u64>,
443    ) -> crate::runtime::kv_watch::KvWatchStream<'a> {
444        crate::runtime::kv_watch::KvWatchStream::subscribe(
445            &self.inner.cdc,
446            &self.inner.kv_stats,
447            collection,
448            key,
449            from_lsn,
450            self.kv_watch_idle_timeout_ms(),
451        )
452    }
453
454    pub(crate) fn kv_watch_subscribe_prefix<'a>(
455        &'a self,
456        collection: impl Into<String>,
457        prefix: impl Into<String>,
458        from_lsn: Option<u64>,
459    ) -> crate::runtime::kv_watch::KvWatchStream<'a> {
460        crate::runtime::kv_watch::KvWatchStream::subscribe_prefix(
461            &self.inner.cdc,
462            &self.inner.kv_stats,
463            collection,
464            prefix,
465            from_lsn,
466            self.kv_watch_idle_timeout_ms(),
467        )
468    }
469
470    pub(crate) fn kv_watch_idle_timeout_ms(&self) -> u64 {
471        self.config_u64("kv.watch.idle_timeout_ms", 60_000)
472    }
473}