Skip to main content

oxirs_cluster/streaming/
cluster_sink.rs

1//! [`StreamSink`] trait + [`ClusterSink`] production implementation.
2//!
3//! A [`ClusterSink`] is the bridge between an external streaming source and
4//! the cluster's Raft log. Each batch of [`StreamMessage`] events is
5//! translated through an [`EventMapper`] into [`crate::raft::RdfCommand`] entries which
6//! are then proposed to the leader through the [`ConsensusManager`]. Once
7//! committed, read replicas serve queries against the resulting `RdfApp`
8//! state.
9//!
10//! ## Design notes
11//!
12//! * The sink trait is intentionally **local** to `oxirs-cluster`. It avoids
13//!   pulling `oxirs-stream` into the cluster's dependency closure (which
14//!   would create a cycle once W3-S11 wires the producer side from the
15//!   `oxirs-stream` direction).
16//! * Backpressure is exposed through a [`BackpressureBridge`]. The sink
17//!   adjusts the bridge's queue depth as it accepts and completes batches;
18//!   upstream operators read [`BackpressureBridge::signal`] and respond.
19//! * If the local node is **not the leader**, the sink returns
20//!   [`SinkError::NotLeader`] without losing the batch — the caller is
21//!   expected to redirect or retry (matching `ClusterNode::insert_triple`
22//!   semantics).
23//! * [`ClusterSinkConfig::max_batch_commands`] caps the number of `RdfCommand`
24//!   entries proposed per `write_batch` call to bound the time the sink
25//!   spends inside a single proposal cycle.
26
27use std::sync::atomic::{AtomicU64, Ordering};
28use std::sync::Arc;
29
30use async_trait::async_trait;
31use serde::{Deserialize, Serialize};
32use thiserror::Error;
33use tracing::{debug, warn};
34
35use crate::consensus::ConsensusManager;
36use crate::stream_integration::StreamMessage;
37use crate::streaming::backpressure_bridge::{BackpressureBridge, BackpressureSignal};
38use crate::streaming::event_mapper::{EventMapper, MapperError};
39
40/// Errors returned by [`StreamSink::write_batch`].
41#[derive(Debug, Error)]
42pub enum SinkError {
43    /// This node is not the cluster leader; the batch was not proposed.
44    #[error("local node is not the leader; cannot accept stream batch")]
45    NotLeader,
46    /// The cluster is in `Stop` backpressure state.
47    #[error("cluster backpressure is Stop; refusing batch")]
48    BackpressureStopped,
49    /// Mapping a stream event into Raft commands failed.
50    #[error(transparent)]
51    Mapping(#[from] MapperError),
52    /// Proposing a command through Raft failed.
53    #[error("consensus error: {0}")]
54    Consensus(String),
55}
56
57/// Convenience alias for fallible sink operations.
58pub type SinkResult<T> = std::result::Result<T, SinkError>;
59
60/// Local trait describing a write-only streaming sink.
61///
62/// Producers (such as the upstream `oxirs-stream` ingest pipeline) call
63/// [`StreamSink::write_batch`] with a batch of events. The implementation
64/// is responsible for delivering the batch durably (in the cluster case,
65/// through Raft).
66#[async_trait]
67pub trait StreamSink: Send + Sync {
68    /// Writes a batch of [`StreamMessage`] events.
69    async fn write_batch(&self, events: Vec<StreamMessage>) -> SinkResult<()>;
70
71    /// Returns the latest [`BackpressureSignal`] the sink would surface.
72    /// Default implementation returns [`BackpressureSignal::Continue`].
73    fn backpressure_signal(&self) -> BackpressureSignal {
74        BackpressureSignal::Continue
75    }
76}
77
78/// Configuration for [`ClusterSink`].
79#[derive(Debug, Clone, Serialize, Deserialize)]
80pub struct ClusterSinkConfig {
81    /// If `true`, the sink will refuse a `write_batch` call when the
82    /// backpressure bridge reports [`BackpressureSignal::Stop`].
83    pub honor_backpressure_stop: bool,
84    /// Maximum number of `RdfCommand` entries proposed per `write_batch`
85    /// call. If `0`, no cap is applied.
86    pub max_batch_commands: usize,
87    /// If `true`, [`ClusterSink::write_batch`] will require leadership
88    /// before proposing. If `false`, the sink will propose unconditionally
89    /// (used in single-node and test setups).
90    pub require_leader: bool,
91}
92
93impl Default for ClusterSinkConfig {
94    fn default() -> Self {
95        Self {
96            honor_backpressure_stop: true,
97            max_batch_commands: 4_096,
98            require_leader: true,
99        }
100    }
101}
102
103/// Runtime statistics for [`ClusterSink`].
104#[derive(Debug, Default)]
105pub struct ClusterSinkStats {
106    /// Total batches accepted by `write_batch` (regardless of outcome).
107    pub batches_received: AtomicU64,
108    /// Total batches successfully committed.
109    pub batches_committed: AtomicU64,
110    /// Total batches rejected with [`SinkError::NotLeader`].
111    pub batches_rejected_not_leader: AtomicU64,
112    /// Total batches rejected with [`SinkError::BackpressureStopped`].
113    pub batches_rejected_backpressure: AtomicU64,
114    /// Total individual `RdfCommand` entries successfully committed.
115    pub commands_committed: AtomicU64,
116    /// Total individual `RdfCommand` entries that returned a `RdfResponse::Error`.
117    pub commands_failed: AtomicU64,
118}
119
120/// Production [`StreamSink`] that forwards events through Raft.
121pub struct ClusterSink {
122    consensus: Arc<ConsensusManager>,
123    mapper: Arc<dyn EventMapper>,
124    bridge: BackpressureBridge,
125    config: ClusterSinkConfig,
126    stats: Arc<ClusterSinkStats>,
127}
128
129impl ClusterSink {
130    /// Creates a new sink wired to the given consensus manager and mapper.
131    pub fn new(
132        consensus: Arc<ConsensusManager>,
133        mapper: Arc<dyn EventMapper>,
134        config: ClusterSinkConfig,
135    ) -> Self {
136        Self {
137            consensus,
138            mapper,
139            bridge: BackpressureBridge::default(),
140            config,
141            stats: Arc::new(ClusterSinkStats::default()),
142        }
143    }
144
145    /// Creates a new sink with a caller-provided [`BackpressureBridge`].
146    pub fn with_bridge(
147        consensus: Arc<ConsensusManager>,
148        mapper: Arc<dyn EventMapper>,
149        bridge: BackpressureBridge,
150        config: ClusterSinkConfig,
151    ) -> Self {
152        Self {
153            consensus,
154            mapper,
155            bridge,
156            config,
157            stats: Arc::new(ClusterSinkStats::default()),
158        }
159    }
160
161    /// Returns a clone of the underlying backpressure bridge so upstream
162    /// operators can poll it without holding a reference to the sink.
163    pub fn bridge(&self) -> BackpressureBridge {
164        self.bridge.clone()
165    }
166
167    /// Returns the runtime statistics.
168    pub fn stats(&self) -> &Arc<ClusterSinkStats> {
169        &self.stats
170    }
171
172    /// Returns the active configuration.
173    pub fn config(&self) -> &ClusterSinkConfig {
174        &self.config
175    }
176
177    /// Accessor: `consensus` for tests / advanced callers.
178    pub fn consensus(&self) -> &Arc<ConsensusManager> {
179        &self.consensus
180    }
181}
182
183#[async_trait]
184impl StreamSink for ClusterSink {
185    async fn write_batch(&self, events: Vec<StreamMessage>) -> SinkResult<()> {
186        self.stats.batches_received.fetch_add(1, Ordering::Relaxed);
187
188        // Backpressure gate.
189        if self.config.honor_backpressure_stop
190            && matches!(self.bridge.signal(), BackpressureSignal::Stop)
191        {
192            self.stats
193                .batches_rejected_backpressure
194                .fetch_add(1, Ordering::Relaxed);
195            return Err(SinkError::BackpressureStopped);
196        }
197
198        // Leader check.
199        if self.config.require_leader && !self.consensus.is_leader().await {
200            self.stats
201                .batches_rejected_not_leader
202                .fetch_add(1, Ordering::Relaxed);
203            return Err(SinkError::NotLeader);
204        }
205
206        // Map streaming events to Raft commands.
207        let mut commands = self.mapper.map_batch(&events)?;
208
209        // Apply per-batch cap.
210        if self.config.max_batch_commands > 0 && commands.len() > self.config.max_batch_commands {
211            warn!(
212                command_count = commands.len(),
213                cap = self.config.max_batch_commands,
214                "ClusterSink batch exceeds max_batch_commands; truncating"
215            );
216            commands.truncate(self.config.max_batch_commands);
217        }
218
219        let cmd_count = commands.len() as u64;
220        debug!(
221            event_count = events.len(),
222            command_count = cmd_count,
223            "ClusterSink proposing batch"
224        );
225
226        // Track the in-flight queue depth via the bridge.
227        let _ = self.bridge.add(cmd_count);
228
229        // Dispatch each command through consensus.
230        let mut errors = 0u64;
231        for cmd in commands.into_iter() {
232            match self.consensus.propose_command(cmd).await {
233                Ok(resp) => {
234                    if let crate::raft::RdfResponse::Error(msg) = resp {
235                        warn!(?msg, "ClusterSink: command apply returned error");
236                        errors += 1;
237                    } else {
238                        self.stats
239                            .commands_committed
240                            .fetch_add(1, Ordering::Relaxed);
241                    }
242                }
243                Err(e) => {
244                    let _ = self.bridge.sub(1);
245                    self.stats.commands_failed.fetch_add(1, Ordering::Relaxed);
246                    return Err(SinkError::Consensus(e.to_string()));
247                }
248            }
249        }
250
251        // All proposals returned (errors counted separately).
252        let _ = self.bridge.sub(cmd_count);
253        self.stats
254            .commands_failed
255            .fetch_add(errors, Ordering::Relaxed);
256
257        if errors == 0 {
258            self.stats.batches_committed.fetch_add(1, Ordering::Relaxed);
259        }
260
261        Ok(())
262    }
263
264    fn backpressure_signal(&self) -> BackpressureSignal {
265        self.bridge.signal()
266    }
267}
268
269/// Helper used by callers (and tests) that want to short-circuit when the
270/// signal would refuse new data anyway.
271pub fn should_pause(signal: BackpressureSignal) -> bool {
272    !matches!(signal, BackpressureSignal::Continue)
273}
274
275#[cfg(test)]
276mod tests {
277    use super::*;
278    use crate::raft::{init_global_shared_storage, reset_global_shared_storage};
279    use crate::stream_integration::{StreamMessage, StreamTriple};
280    use crate::streaming::event_mapper::DefaultEventMapper;
281
282    static TEST_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
283
284    fn make_sink(node_id: u64) -> ClusterSink {
285        let consensus = Arc::new(ConsensusManager::new(node_id, vec![]));
286        let mapper = Arc::new(DefaultEventMapper::default());
287        ClusterSink::new(consensus, mapper, ClusterSinkConfig::default())
288    }
289
290    fn triple(i: usize) -> StreamTriple {
291        StreamTriple::new(
292            format!("http://example.org/s/{i}"),
293            "http://example.org/p/has",
294            format!("\"value-{i}\""),
295        )
296    }
297
298    #[tokio::test]
299    async fn write_batch_proposes_through_consensus() {
300        let _g = TEST_LOCK.lock().await;
301        init_global_shared_storage();
302        reset_global_shared_storage().await;
303
304        let sink = make_sink(1);
305        let msg = StreamMessage::insert("rdf-stream", 1, vec![triple(0), triple(1)]);
306        sink.write_batch(vec![msg]).await.expect("commit");
307
308        assert_eq!(sink.stats().batches_committed.load(Ordering::Relaxed), 1);
309        assert_eq!(sink.stats().commands_committed.load(Ordering::Relaxed), 2);
310
311        // Triples are now visible through the regular cluster query path.
312        let len = sink.consensus().len().await;
313        assert_eq!(len, 2);
314    }
315
316    #[tokio::test]
317    async fn write_batch_respects_backpressure_stop() {
318        let _g = TEST_LOCK.lock().await;
319        init_global_shared_storage();
320        reset_global_shared_storage().await;
321
322        let sink = make_sink(2);
323        // Force the bridge into Stop.
324        let _ = sink.bridge().observe(10_000_000);
325        assert_eq!(sink.bridge().signal(), BackpressureSignal::Stop);
326
327        let msg = StreamMessage::insert("rdf-stream", 1, vec![triple(0)]);
328        let err = sink
329            .write_batch(vec![msg])
330            .await
331            .expect_err("should refuse");
332        assert!(matches!(err, SinkError::BackpressureStopped));
333        assert_eq!(
334            sink.stats()
335                .batches_rejected_backpressure
336                .load(Ordering::Relaxed),
337            1
338        );
339    }
340
341    #[tokio::test]
342    async fn write_batch_truncates_oversized() {
343        let _g = TEST_LOCK.lock().await;
344        init_global_shared_storage();
345        reset_global_shared_storage().await;
346
347        let consensus = Arc::new(ConsensusManager::new(3, vec![]));
348        let mapper = Arc::new(DefaultEventMapper::default());
349        let cfg = ClusterSinkConfig {
350            max_batch_commands: 2,
351            ..Default::default()
352        };
353        let sink = ClusterSink::new(consensus, mapper, cfg);
354
355        let triples: Vec<_> = (0..5).map(triple).collect();
356        let msg = StreamMessage::insert("rdf-stream", 1, triples);
357        sink.write_batch(vec![msg]).await.expect("commit");
358
359        // Only 2 commands should have been committed because of the cap.
360        assert_eq!(sink.stats().commands_committed.load(Ordering::Relaxed), 2);
361    }
362
363    #[tokio::test]
364    async fn write_batch_handles_empty_input() {
365        let _g = TEST_LOCK.lock().await;
366        init_global_shared_storage();
367        reset_global_shared_storage().await;
368
369        let sink = make_sink(4);
370        sink.write_batch(vec![]).await.expect("ok");
371        assert_eq!(sink.stats().batches_committed.load(Ordering::Relaxed), 1);
372    }
373
374    #[tokio::test]
375    async fn backpressure_signal_default_is_continue() {
376        let _g = TEST_LOCK.lock().await;
377        init_global_shared_storage();
378        reset_global_shared_storage().await;
379
380        let sink = make_sink(5);
381        assert_eq!(sink.backpressure_signal(), BackpressureSignal::Continue);
382    }
383
384    #[test]
385    fn should_pause_flags_non_continue() {
386        assert!(!should_pause(BackpressureSignal::Continue));
387        assert!(should_pause(BackpressureSignal::Slow));
388        assert!(should_pause(BackpressureSignal::Stop));
389    }
390
391    #[tokio::test]
392    async fn require_leader_false_proposes_anyway() {
393        let _g = TEST_LOCK.lock().await;
394        init_global_shared_storage();
395        reset_global_shared_storage().await;
396
397        let consensus = Arc::new(ConsensusManager::new(6, vec![]));
398        let mapper = Arc::new(DefaultEventMapper::default());
399        let cfg = ClusterSinkConfig {
400            require_leader: false,
401            ..Default::default()
402        };
403        let sink = ClusterSink::new(consensus, mapper, cfg);
404
405        let msg = StreamMessage::insert("rdf-stream", 1, vec![triple(7)]);
406        sink.write_batch(vec![msg]).await.expect("ok");
407        assert_eq!(sink.stats().commands_committed.load(Ordering::Relaxed), 1);
408    }
409}