Skip to main content

saluki_components/encoders/buffered_incremental/
mod.rs

1use std::time::{Duration, Instant};
2
3use async_trait::async_trait;
4use saluki_common::sync::shutdown::ShutdownCoordinator;
5use saluki_core::accounting::{MemoryBounds, MemoryBoundsBuilder};
6use saluki_core::runtime;
7use saluki_core::{
8    components::{encoders::*, BuildContext},
9    data_model::{event::EventType, payload::PayloadType},
10    observability::ComponentMetricsExt,
11    topology::PayloadsDispatcher,
12};
13use saluki_error::GenericError;
14use saluki_metrics::MetricsBuilder;
15use tokio::{pin, select, time::sleep};
16use tracing::{debug, error};
17
18mod telemetry;
19use self::telemetry::ComponentTelemetry;
20
21/// Buffered incremental encoder.
22///
23/// Wraps an `IncrementalEncoder` and drives it with incoming events, allowing buffering by utilizing a configurable
24/// flush timeout. Payloads are encoded on the global thread pool to avoid affecting latency-sensitive tasks.
25pub struct BufferedIncrementalConfiguration<EB> {
26    /// Flush timeout for pending requests.
27    ///
28    /// When the encoder has written events to the in-flight request payload, but it hasn't yet reached the
29    /// payload size limits that would force the payload to be flushed, the encoder will wait for a period of time
30    /// before flushing the in-flight request payload. This allows for the possibility of other events to be processed
31    /// and written into the request payload, thereby maximizing the payload size and reducing the number of requests
32    /// generated and sent overall.
33    ///
34    /// If set to zero, a minimal timeout is used.
35    flush_timeout: Duration,
36
37    encoder_builder: EB,
38}
39
40impl<EB> BufferedIncrementalConfiguration<EB>
41where
42    EB: IncrementalEncoderBuilder,
43{
44    /// Creates a new `BufferedIncrementalConfiguration` that drives the given incremental encoder builder.
45    pub fn new(encoder_builder: EB, flush_timeout: Duration) -> Self {
46        Self {
47            flush_timeout,
48            encoder_builder,
49        }
50    }
51}
52
53#[async_trait]
54impl<EB> EncoderBuilder for BufferedIncrementalConfiguration<EB>
55where
56    EB: IncrementalEncoderBuilder + Sync,
57    EB::Output: Send + 'static,
58{
59    fn input_event_type(&self) -> EventType {
60        self.encoder_builder.input_event_type()
61    }
62
63    fn output_payload_type(&self) -> PayloadType {
64        self.encoder_builder.output_payload_type()
65    }
66
67    async fn build(&self, context: BuildContext) -> Result<Box<dyn Encoder + Send>, GenericError> {
68        let metrics_builder = MetricsBuilder::from_component_context(context.component_context());
69        let telemetry = ComponentTelemetry::from_builder(&metrics_builder);
70
71        let encoder = self.encoder_builder.build(context).await?;
72
73        let flush_timeout = match self.flush_timeout {
74            // We always give ourselves a minimum flush timeout of 10ms to allow for some very minimal amount of
75            // batching, while still practically flushing things almost immediately.
76            Duration::ZERO => Duration::from_millis(10),
77            dur => dur,
78        };
79
80        Ok(Box::new(BufferedIncremental {
81            encoder,
82            telemetry,
83            flush_timeout,
84        }))
85    }
86}
87
88impl<EB> MemoryBounds for BufferedIncrementalConfiguration<EB>
89where
90    EB: IncrementalEncoderBuilder,
91{
92    fn specify_bounds(&self, builder: &mut MemoryBoundsBuilder) {
93        builder
94            .minimum()
95            .with_single_value::<BufferedIncremental<EB::Output>>("component struct");
96
97        self.encoder_builder.specify_bounds(builder);
98    }
99}
100
101pub struct BufferedIncremental<E> {
102    encoder: E,
103    telemetry: ComponentTelemetry,
104    flush_timeout: Duration,
105}
106
107#[async_trait]
108impl<E> Encoder for BufferedIncremental<E>
109where
110    E: IncrementalEncoder + Send + 'static,
111{
112    async fn run(mut self: Box<Self>, context: EncoderContext) -> Result<(), GenericError> {
113        let Self {
114            encoder,
115            telemetry,
116            flush_timeout,
117        } = *self;
118
119        // Run our encoder task on the worker pool.
120        //
121        // The encoder task owns _everything_ -- health checking, encoding, dispatching payloads, etc -- so we just
122        // end up as a glorified watchdog here, where we block until the encoder task has completed. The encoder task
123        // itself is what waits for the shutdown signal and all of that.
124        //
125        // We're abusing `ShutdownCoordinator` here to basically detect when the encoder task exits: we immediately
126        // call `shutdown_and_wait` after spawning the task, which will wait until the `ShutdownHandle` we've given to
127        // the encoder tasks is dropped... which only happens when the task exits.
128        let worker_pool = context.topology_context().global_thread_pool().clone();
129
130        let mut shutdown_coordinator = ShutdownCoordinator::default();
131        let task_shutdown_handle = shutdown_coordinator.register();
132
133        runtime::worker("incremental_encoder", async move {
134            // TODO: Conceptually, all components downstream of sources/relays should drain their incoming events
135            // consumer until it's empty, so on and so forth until forwarders/destinations have done so and nothing
136            // is left to process.
137            //
138            // However, this isn't feasible if we ever want to support restarting individual components or stitching
139            // in new components to a topology... which we eventually do. We'd have to respond to shutdown (which
140            // we're ignoring here by aliasing the handle as `_shutdown`) to shut down in a timely fashion.
141            //
142            // We should consider a mechanism to expose consumers/dispatchers such that they're borrowed in an owned
143            // fashion, allowing a component to hold on to them when running, but then effectively release them when
144            // they exit. This would allow us to stop a component, and without dropping its interconnect channel and
145            // losing all of the events or payloads within it, reconnect it to the new instance of the component (or
146            // whatever component takes its place, etc) which would allow us to more cleanly respond to shutdown
147            // here as more of an exceptional thing: an immediate stoppage of work, without throwing away _pending_
148            // work.
149            let _task_shutdown_handle = task_shutdown_handle;
150            run_incremental_encoder(context, encoder, telemetry, flush_timeout).await
151        })
152        .on_runtime(worker_pool)
153        .needed()
154        .spawn();
155
156        debug!("Buffered Incremental encoder started.");
157
158        shutdown_coordinator.shutdown_and_wait().await;
159
160        debug!("Buffered Incremental encoder stopped.");
161
162        Ok(())
163    }
164}
165
166async fn run_incremental_encoder<E>(
167    mut context: EncoderContext, mut encoder: E, telemetry: ComponentTelemetry, flush_timeout: Duration,
168) -> Result<(), GenericError>
169where
170    E: IncrementalEncoder,
171{
172    let mut health = context.take_health_handle();
173
174    health.mark_ready();
175
176    let mut pending_flush = false;
177    let pending_flush_timeout = sleep(flush_timeout);
178    pin!(pending_flush_timeout);
179
180    loop {
181        select! {
182            _ = health.live() => continue,
183            maybe_event_buffer = context.events().next() => {
184                // Break out of our loop when the events channel is closed.
185                let event_buffer = match maybe_event_buffer {
186                    Some(event_buffer) => event_buffer,
187                    None => break,
188                };
189
190                for event in event_buffer {
191                    // Try to process the event.
192                    //
193                    // If we're informed that we need to flush, we'll hold on to this event before triggering a flush and then
194                    // retry processing it after flushing.
195                    let event_to_retry = match encoder.process_event(event).await? {
196                        ProcessResult::Continue => continue,
197                        ProcessResult::FlushRequired(event) => event,
198                    };
199
200                    // Flush the encoder, waiting any payloads it has generated.
201                    flush_encoder(&mut encoder, context.dispatcher(), &telemetry).await?;
202
203                    // Now try to process the event again.
204                    //
205                    // If this fails, then we drop the event because it's a logical bug to not be able to encode an event after
206                    // flushing, and we don't want to get stuck in an infinite loop.
207                    match encoder.process_event(event_to_retry).await? {
208                        ProcessResult::Continue => {},
209                        ProcessResult::FlushRequired(_) => {
210                            error!("Failed to process event after flushing.");
211                            telemetry.events_dropped_encoder().increment(1);
212                        },
213                    }
214                }
215
216                debug!("Processed event buffer.");
217
218                // If we're not already pending a flush, we'll start the countdown.
219                if !pending_flush {
220                    pending_flush_timeout.as_mut().reset(tokio::time::Instant::now() + flush_timeout);
221                    pending_flush = true;
222                }
223            },
224            _ = &mut pending_flush_timeout, if pending_flush => {
225                debug!("Flushing encoder of any pending payload(s).");
226
227                pending_flush = false;
228
229                flush_encoder(&mut encoder, context.dispatcher(), &telemetry).await?;
230
231                debug!("All pending payloads flushed.");
232            }
233        }
234    }
235
236    // Do a final flush since we may have had a pending payloads before breaking out of the loop.
237    flush_encoder(&mut encoder, context.dispatcher(), &telemetry).await?;
238
239    Ok(())
240}
241
242/// Flushes the encoder, recording flush telemetry for the events it dispatched.
243///
244/// The telemetry counts the events in the payloads the encoder actually dispatched, not the events it accepted: an
245/// encoder can discard a payload it can't build, such as one that exceeds its size limit and can't be split, and those
246/// events were never flushed. Events dispatched before a flush fails are still counted. Flushes that dispatch nothing
247/// aren't recorded, so the last-flush telemetry always describes a flush that sent something.
248async fn flush_encoder<E>(
249    encoder: &mut E, dispatcher: &PayloadsDispatcher, telemetry: &ComponentTelemetry,
250) -> Result<(), GenericError>
251where
252    E: IncrementalEncoder,
253{
254    let flush_start = Instant::now();
255    let result = encoder.flush(dispatcher).await;
256
257    let dispatched_events = match &result {
258        Ok(dispatched_events) => *dispatched_events,
259        Err(e) => e.dispatched_events(),
260    };
261    if dispatched_events > 0 {
262        telemetry.record_flush(dispatched_events as u64, flush_start.elapsed());
263    }
264
265    result.map(|_| ()).map_err(FlushError::into_source)
266}
267
268#[cfg(test)]
269mod tests {
270    use saluki_core::{
271        data_model::event::{
272            eventd::EventD,
273            service_check::{CheckStatus, ServiceCheck},
274            Event,
275        },
276        topology::{OutputName, PayloadsBuffer},
277    };
278    use saluki_error::generic_error;
279    use saluki_metrics::test::TestRecorder;
280    use tokio::sync::mpsc;
281
282    use super::*;
283    use crate::encoders::datadog::{DatadogEventsConfiguration, DatadogServiceChecksConfiguration};
284
285    const PAYLOAD_SIZE_LIMIT: usize = 4 * 1024 * 1024;
286
287    fn dispatcher_with_receiver(context: &BuildContext) -> (PayloadsDispatcher, mpsc::Receiver<PayloadsBuffer>) {
288        let mut dispatcher = PayloadsDispatcher::new(context.component_context().clone());
289        dispatcher.add_output(OutputName::Default).unwrap();
290        let (tx, rx) = mpsc::channel(8);
291        dispatcher.attach_sender_to_output(&OutputName::Default, tx).unwrap();
292        (dispatcher, rx)
293    }
294
295    fn dispatched_payloads(rx: &mut mpsc::Receiver<PayloadsBuffer>) -> usize {
296        let mut payloads = 0;
297        while rx.try_recv().is_ok() {
298            payloads += 1;
299        }
300        payloads
301    }
302
303    async fn events_encoder(context: BuildContext, max_payload_size: usize) -> impl IncrementalEncoder {
304        DatadogEventsConfiguration {
305            max_payload_size,
306            max_uncompressed_payload_size: PAYLOAD_SIZE_LIMIT,
307            compressor_kind: "zstd".to_string(),
308            zstd_level: 3,
309            log_payloads: false,
310        }
311        .build(context)
312        .await
313        .expect("events encoder should build")
314    }
315
316    async fn accept_events(encoder: &mut impl IncrementalEncoder, count: usize) {
317        for i in 0..count {
318            let event = Event::EventD(EventD::new(format!("title {i}"), "text"));
319            assert!(matches!(
320                encoder.process_event(event).await.unwrap(),
321                ProcessResult::Continue
322            ));
323        }
324    }
325
326    #[tokio::test]
327    async fn flush_records_the_events_in_dispatched_payloads() {
328        let recorder = TestRecorder::default();
329        let _recorder_guard = metrics::set_default_local_recorder(&recorder);
330        let context = BuildContext::test_encoder("flush_telemetry");
331        let (dispatcher, mut rx) = dispatcher_with_receiver(&context);
332        let telemetry = ComponentTelemetry::from_builder(&MetricsBuilder::default());
333        let mut encoder = events_encoder(context, PAYLOAD_SIZE_LIMIT).await;
334
335        accept_events(&mut encoder, 3).await;
336        flush_encoder(&mut encoder, &dispatcher, &telemetry).await.unwrap();
337
338        assert_eq!(dispatched_payloads(&mut rx), 1);
339        assert_eq!(recorder.counter("encoder_flushed_events_total"), Some(3));
340        assert_eq!(recorder.gauge("encoder_last_flush_events"), Some(3.0));
341    }
342
343    // The labels on the encoder's "dropped because the payload couldn't be built" counter.
344    fn encoder_dropped_events_labels(component_id: &'static str) -> [(&'static str, &'static str); 4] {
345        [
346            ("component_id", component_id),
347            ("component_type", "encoder"),
348            ("intentional", "false"),
349            ("drop_reason", "encoder_failure"),
350        ]
351    }
352
353    #[tokio::test]
354    async fn flush_does_not_record_events_in_discarded_payloads() {
355        // A compressed payload that exceeds the size limit and can't be split is discarded and logged, but the flush
356        // itself succeeds. The events it held were never flushed, so they must not be counted as flushed. They were
357        // lost, though, so they are counted as dropped.
358        let recorder = TestRecorder::default();
359        let _recorder_guard = metrics::set_default_local_recorder(&recorder);
360        let context = BuildContext::test_encoder("flush_telemetry_discarded");
361        let (dispatcher, mut rx) = dispatcher_with_receiver(&context);
362        let telemetry = ComponentTelemetry::from_builder(&MetricsBuilder::default());
363        let mut encoder = events_encoder(context, 1).await;
364
365        accept_events(&mut encoder, 1).await;
366        flush_encoder(&mut encoder, &dispatcher, &telemetry).await.unwrap();
367
368        assert_eq!(dispatched_payloads(&mut rx), 0);
369        assert_eq!(recorder.counter("encoder_flushed_events_total"), Some(0));
370        assert_eq!(recorder.gauge("encoder_last_flush_events"), Some(0.0));
371        assert_eq!(
372            recorder.counter((
373                "component_events_dropped_total",
374                &encoder_dropped_events_labels("flush_telemetry_discarded")[..]
375            )),
376            Some(1)
377        );
378    }
379
380    #[tokio::test]
381    async fn flush_does_not_report_dropped_events_when_everything_is_dispatched() {
382        let recorder = TestRecorder::default();
383        let _recorder_guard = metrics::set_default_local_recorder(&recorder);
384        let context = BuildContext::test_encoder("flush_no_drops");
385        let (dispatcher, mut rx) = dispatcher_with_receiver(&context);
386        let telemetry = ComponentTelemetry::from_builder(&MetricsBuilder::default());
387        let mut encoder = events_encoder(context, PAYLOAD_SIZE_LIMIT).await;
388
389        accept_events(&mut encoder, 3).await;
390        flush_encoder(&mut encoder, &dispatcher, &telemetry).await.unwrap();
391
392        assert_eq!(dispatched_payloads(&mut rx), 1);
393        assert_eq!(
394            recorder.counter((
395                "component_events_dropped_total",
396                &encoder_dropped_events_labels("flush_no_drops")[..]
397            )),
398            Some(0)
399        );
400    }
401
402    #[tokio::test]
403    async fn flush_returns_the_number_of_dispatched_events() {
404        let context = BuildContext::test_encoder("flush_count");
405        let (dispatcher, mut rx) = dispatcher_with_receiver(&context);
406
407        let mut events = events_encoder(context.clone(), PAYLOAD_SIZE_LIMIT).await;
408        accept_events(&mut events, 2).await;
409        assert_eq!(events.flush(&dispatcher).await.unwrap(), 2);
410
411        let mut service_checks = DatadogServiceChecksConfiguration {
412            max_payload_size: PAYLOAD_SIZE_LIMIT,
413            max_uncompressed_payload_size: PAYLOAD_SIZE_LIMIT,
414            compressor_kind: "zstd".to_string(),
415            zstd_level: 3,
416            log_payloads: false,
417        }
418        .build(context)
419        .await
420        .expect("service checks encoder should build");
421        for i in 0..4 {
422            let service_check = Event::ServiceCheck(ServiceCheck::new(format!("check {i}"), CheckStatus::Ok));
423            assert!(matches!(
424                service_checks.process_event(service_check).await.unwrap(),
425                ProcessResult::Continue
426            ));
427        }
428        assert_eq!(service_checks.flush(&dispatcher).await.unwrap(), 4);
429
430        // An empty encoder has nothing to dispatch.
431        assert_eq!(service_checks.flush(&dispatcher).await.unwrap(), 0);
432        assert_eq!(dispatched_payloads(&mut rx), 2);
433    }
434
435    // An encoder whose flush dispatches some events and then fails, as when a later payload can't be dispatched.
436    struct FailingFlushEncoder {
437        dispatched_before_failure: usize,
438    }
439
440    #[async_trait]
441    impl IncrementalEncoder for FailingFlushEncoder {
442        async fn process_event(&mut self, _event: Event) -> Result<ProcessResult, GenericError> {
443            Ok(ProcessResult::Continue)
444        }
445
446        async fn flush(&mut self, _dispatcher: &PayloadsDispatcher) -> Result<usize, FlushError> {
447            Err(FlushError::new(
448                self.dispatched_before_failure,
449                generic_error!("output closed"),
450            ))
451        }
452    }
453
454    #[tokio::test]
455    async fn failed_flush_still_records_the_events_it_dispatched() {
456        let recorder = TestRecorder::default();
457        let _recorder_guard = metrics::set_default_local_recorder(&recorder);
458        let context = BuildContext::test_encoder("flush_failure");
459        let (dispatcher, _rx) = dispatcher_with_receiver(&context);
460        let telemetry = ComponentTelemetry::from_builder(&MetricsBuilder::default());
461        let mut encoder = FailingFlushEncoder {
462            dispatched_before_failure: 3,
463        };
464
465        let error = flush_encoder(&mut encoder, &dispatcher, &telemetry)
466            .await
467            .expect_err("the flush should fail");
468
469        assert_eq!(error.to_string(), "output closed");
470        assert_eq!(recorder.counter("encoder_flushed_events_total"), Some(3));
471        assert_eq!(recorder.gauge("encoder_last_flush_events"), Some(3.0));
472    }
473
474    #[tokio::test]
475    async fn failed_flush_that_dispatched_nothing_records_nothing() {
476        let recorder = TestRecorder::default();
477        let _recorder_guard = metrics::set_default_local_recorder(&recorder);
478        let context = BuildContext::test_encoder("flush_failure_empty");
479        let (dispatcher, _rx) = dispatcher_with_receiver(&context);
480        let telemetry = ComponentTelemetry::from_builder(&MetricsBuilder::default());
481        let mut encoder = FailingFlushEncoder {
482            dispatched_before_failure: 0,
483        };
484
485        flush_encoder(&mut encoder, &dispatcher, &telemetry)
486            .await
487            .expect_err("the flush should fail");
488
489        assert_eq!(recorder.counter("encoder_flushed_events_total"), Some(0));
490        assert_eq!(recorder.gauge("encoder_last_flush_events"), Some(0.0));
491    }
492
493    #[tokio::test]
494    async fn events_encoder_reports_an_error_when_its_output_is_closed() {
495        let context = BuildContext::test_encoder("flush_closed_output");
496        let (dispatcher, rx) = dispatcher_with_receiver(&context);
497        drop(rx);
498        let mut encoder = events_encoder(context, PAYLOAD_SIZE_LIMIT).await;
499
500        accept_events(&mut encoder, 1).await;
501        let error = encoder
502            .flush(&dispatcher)
503            .await
504            .expect_err("dispatching to a closed output should fail");
505
506        // Nothing was dispatched before the failure, so there is nothing to account for.
507        assert_eq!(error.dispatched_events(), 0);
508    }
509}