Skip to main content

gcloud_observability/logs/api/
batcher.rs

1//! Bounded queue and background batching task behind the Cloud Logging API
2//! sink.
3//!
4//! Recording an event must never block the thread that logged it and must
5//! never log through `tracing` (which would re-enter this layer), so the queue
6//! is bounded and lossy at the producer end and every diagnostic goes straight
7//! to stderr, rate-limited to one line per flush interval.
8
9use super::{entry, GcpCloudLoggingApiConfig};
10use gcloud_sdk::google::api::MonitoredResource;
11use gcloud_sdk::google::logging::v2::{LogEntry, WriteLogEntriesRequest};
12use serde_json::{Map, Value};
13use std::sync::atomic::{AtomicU64, Ordering};
14use std::sync::Arc;
15use std::time::Duration;
16use tokio::sync::{mpsc, oneshot, Mutex};
17use tokio::task::JoinHandle;
18use tokio::time::Instant;
19
20/// One write of a collected batch. Implemented by the Cloud Logging client in
21/// production and by a recording fake in tests, so the batching rules can be
22/// exercised without a network or credentials.
23#[async_trait::async_trait]
24pub(crate) trait LogEntrySink: Send + Sync + 'static {
25    async fn write(&self, request: WriteLogEntriesRequest) -> Result<(), String>;
26}
27
28/// Boxed so the queue's per-message footprint stays a pointer: a `LogEntry` is
29/// several hundred bytes and the queue holds thousands of them.
30enum BatchMessage {
31    Entry(Box<LogEntry>),
32    Flush(oneshot::Sender<()>),
33    Shutdown(oneshot::Sender<()>),
34}
35
36pub(crate) struct ApiSink {
37    sender: mpsc::Sender<BatchMessage>,
38    dropped: Arc<AtomicU64>,
39}
40
41impl ApiSink {
42    /// Queues one record without blocking. An event recorded while the queue
43    /// is full is counted and discarded: stalling the caller until Cloud
44    /// Logging catches up would turn a logging outage into an application one.
45    pub(crate) fn send(&self, record: Map<String, Value>) {
46        let entry = entry::build_log_entry(record);
47        if self
48            .sender
49            .try_send(BatchMessage::Entry(Box::new(entry)))
50            .is_err()
51        {
52            self.dropped.fetch_add(1, Ordering::Relaxed);
53        }
54    }
55}
56
57/// Flushes and stops the background task that writes log entries to the Cloud
58/// Logging API.
59///
60/// Cloning shares one task and one queue. Dropping every clone without calling
61/// [`Self::shutdown`] leaves whatever is still queued unwritten.
62///
63/// [`Self::flush`] and [`Self::shutdown`] are async and block no thread, unlike shutting down an
64/// OpenTelemetry provider, so they work on a current-thread runtime.
65#[derive(Clone)]
66pub struct GcpCloudLoggingHandle {
67    sender: mpsc::Sender<BatchMessage>,
68    task: Arc<Mutex<Option<JoinHandle<()>>>>,
69    shutdown_timeout: Duration,
70}
71
72impl GcpCloudLoggingHandle {
73    /// Writes everything queued before this call and returns once the Cloud
74    /// Logging API has answered, whether it accepted the batch or not.
75    ///
76    /// The marker travels through the same queue as the entries, so it cannot
77    /// overtake them however full the queue is. Entries queued after this call
78    /// are not waited for.
79    pub async fn flush(&self) {
80        let (ack_sender, ack) = oneshot::channel();
81        if self
82            .sender
83            .send(BatchMessage::Flush(ack_sender))
84            .await
85            .is_ok()
86        {
87            let _ = ack.await;
88        }
89    }
90
91    /// Stops accepting entries, writes what is queued, and waits for the
92    /// background task to finish, giving up after the configured shutdown
93    /// timeout. Entries recorded after this call are dropped.
94    ///
95    /// Calling it twice is harmless; the second call returns at once.
96    pub async fn shutdown(&self) {
97        let deadline = Instant::now() + self.shutdown_timeout;
98        let (ack_sender, ack) = oneshot::channel();
99        let queued = tokio::time::timeout_at(
100            deadline,
101            self.sender.send(BatchMessage::Shutdown(ack_sender)),
102        )
103        .await;
104        if matches!(queued, Ok(Ok(()))) {
105            let _ = tokio::time::timeout_at(deadline, ack).await;
106        }
107        let task = self.task.lock().await.take();
108        if let Some(task) = task {
109            // On timeout the join handle is dropped rather than aborted: the
110            // task may still be mid-write, and detaching it gives those
111            // entries a chance to land.
112            let _ = tokio::time::timeout_at(deadline, task).await;
113        }
114    }
115}
116
117/// Starts the batching task on the current Tokio runtime.
118pub(crate) fn spawn(
119    config: &GcpCloudLoggingApiConfig,
120    log_name: String,
121    resource: MonitoredResource,
122    sink: Arc<dyn LogEntrySink>,
123) -> (ApiSink, GcpCloudLoggingHandle) {
124    let (sender, receiver) = mpsc::channel(config.queue_capacity.max(1));
125    let dropped = Arc::new(AtomicU64::new(0));
126    let batcher = Batcher {
127        sink,
128        log_name,
129        resource,
130        batch_size: config.batch_size.max(1),
131        flush_interval: config.flush_interval,
132        dropped: Arc::clone(&dropped),
133        reported_drops: 0,
134        last_drop_report: None,
135        last_failure_report: None,
136        batch: Vec::with_capacity(config.batch_size.max(1)),
137    };
138    let task = tokio::spawn(batcher.run(receiver));
139    (
140        ApiSink {
141            sender: sender.clone(),
142            dropped,
143        },
144        GcpCloudLoggingHandle {
145            sender,
146            task: Arc::new(Mutex::new(Some(task))),
147            shutdown_timeout: config.shutdown_timeout,
148        },
149    )
150}
151
152struct Batcher {
153    sink: Arc<dyn LogEntrySink>,
154    log_name: String,
155    resource: MonitoredResource,
156    batch_size: usize,
157    flush_interval: Duration,
158    dropped: Arc<AtomicU64>,
159    reported_drops: u64,
160    last_drop_report: Option<Instant>,
161    last_failure_report: Option<Instant>,
162    batch: Vec<LogEntry>,
163}
164
165impl Batcher {
166    async fn run(mut self, mut receiver: mpsc::Receiver<BatchMessage>) {
167        // `None` while no batch is open: an idle task must wait for an entry
168        // indefinitely rather than wake once per flush interval forever.
169        let mut deadline: Option<Instant> = None;
170
171        loop {
172            let message = match deadline {
173                Some(at) => match tokio::time::timeout_at(at, receiver.recv()).await {
174                    Ok(message) => message,
175                    Err(_) => {
176                        self.write_batch().await;
177                        deadline = None;
178                        continue;
179                    }
180                },
181                None => receiver.recv().await,
182            };
183
184            match message {
185                None => break,
186                Some(BatchMessage::Entry(logentry)) => {
187                    if self.batch.is_empty() {
188                        deadline = Some(Instant::now() + self.flush_interval);
189                    }
190                    self.batch.push(*logentry);
191                    if self.batch.len() >= self.batch_size {
192                        self.write_batch().await;
193                        deadline = None;
194                    }
195                }
196                Some(BatchMessage::Flush(ack)) => {
197                    self.write_batch().await;
198                    deadline = None;
199                    let _ = ack.send(());
200                }
201                Some(BatchMessage::Shutdown(ack)) => {
202                    self.drain_and_stop(&mut receiver, ack).await;
203                    return;
204                }
205            }
206        }
207
208        self.write_batch().await;
209    }
210
211    /// Closes the queue and writes whatever was already in it, so a shutdown
212    /// observes every entry recorded before it was requested.
213    async fn drain_and_stop(
214        &mut self,
215        receiver: &mut mpsc::Receiver<BatchMessage>,
216        ack: oneshot::Sender<()>,
217    ) {
218        receiver.close();
219        let mut pending_acks = vec![ack];
220        while let Ok(message) = receiver.try_recv() {
221            match message {
222                BatchMessage::Entry(logentry) => {
223                    self.batch.push(*logentry);
224                    if self.batch.len() >= self.batch_size {
225                        self.write_batch().await;
226                    }
227                }
228                BatchMessage::Flush(ack) | BatchMessage::Shutdown(ack) => pending_acks.push(ack),
229            }
230        }
231        self.write_batch().await;
232        for ack in pending_acks {
233            let _ = ack.send(());
234        }
235    }
236
237    async fn write_batch(&mut self) {
238        self.report_drops();
239        if self.batch.is_empty() {
240            return;
241        }
242        let entries = std::mem::take(&mut self.batch);
243        let count = entries.len();
244        let request = WriteLogEntriesRequest {
245            log_name: self.log_name.clone(),
246            resource: Some(self.resource.clone()),
247            entries,
248            partial_success: true,
249            ..WriteLogEntriesRequest::default()
250        };
251        // The client retries on its own; once it gives up there is nothing
252        // useful left to do with the batch but drop it, and a stderr line is
253        // the only report that cannot re-enter this layer.
254        if let Err(message) = self.sink.write(request).await {
255            if report_due(&mut self.last_failure_report, self.flush_interval) {
256                eprintln!(
257                    "gcloud-observability: discarded a batch of {count} log entries: {message}"
258                );
259            }
260        }
261    }
262
263    fn report_drops(&mut self) {
264        let dropped = self.dropped.load(Ordering::Relaxed);
265        let unreported = dropped.saturating_sub(self.reported_drops);
266        if unreported > 0 && report_due(&mut self.last_drop_report, self.flush_interval) {
267            eprintln!(
268                "gcloud-observability: dropped {unreported} log entries, \
269                 the Cloud Logging queue is full"
270            );
271            self.reported_drops = dropped;
272        }
273    }
274}
275
276/// Keeps stderr diagnostics to one line per flush interval, so a sustained
277/// outage cannot itself become the flood.
278fn report_due(last: &mut Option<Instant>, interval: Duration) -> bool {
279    let now = Instant::now();
280    if last.is_some_and(|at| now.duration_since(at) < interval) {
281        return false;
282    }
283    *last = Some(now);
284    true
285}
286
287#[cfg(test)]
288mod tests {
289    use super::*;
290    use crate::ids::LogId;
291    use gcloud_sdk::google::api::MonitoredResource;
292    use serde_json::json;
293    use std::sync::Mutex as StdMutex;
294
295    #[derive(Default)]
296    struct RecordingSink {
297        batches: StdMutex<Vec<WriteLogEntriesRequest>>,
298        fail: bool,
299        delay: Option<Duration>,
300    }
301
302    impl RecordingSink {
303        fn shared() -> Arc<Self> {
304            Arc::new(Self::default())
305        }
306
307        fn batch_sizes(&self) -> Vec<usize> {
308            self.batches
309                .lock()
310                .expect("test sink mutex is never poisoned")
311                .iter()
312                .map(|request| request.entries.len())
313                .collect()
314        }
315
316        fn requests(&self) -> Vec<WriteLogEntriesRequest> {
317            self.batches
318                .lock()
319                .expect("test sink mutex is never poisoned")
320                .clone()
321        }
322    }
323
324    #[async_trait::async_trait]
325    impl LogEntrySink for RecordingSink {
326        async fn write(&self, request: WriteLogEntriesRequest) -> Result<(), String> {
327            if let Some(delay) = self.delay {
328                tokio::time::sleep(delay).await;
329            }
330            self.batches
331                .lock()
332                .expect("test sink mutex is never poisoned")
333                .push(request);
334            if self.fail {
335                Err("write refused".to_string())
336            } else {
337                Ok(())
338            }
339        }
340    }
341
342    fn config() -> GcpCloudLoggingApiConfig {
343        GcpCloudLoggingApiConfig::new(LogId::from_static("test-log"))
344            .with_batch_size(3)
345            .with_flush_interval(Duration::from_secs(2))
346            .with_queue_capacity(64)
347            .with_shutdown_timeout(Duration::from_secs(5))
348    }
349
350    fn resource() -> MonitoredResource {
351        MonitoredResource {
352            r#type: "global".to_string(),
353            labels: [("project_id".to_string(), "p".to_string())]
354                .into_iter()
355                .collect(),
356        }
357    }
358
359    fn start(
360        config: &GcpCloudLoggingApiConfig,
361        sink: Arc<RecordingSink>,
362    ) -> (ApiSink, GcpCloudLoggingHandle) {
363        spawn(
364            config,
365            "projects/p/logs/test-log".to_string(),
366            resource(),
367            sink,
368        )
369    }
370
371    fn record(message: &str) -> Map<String, Value> {
372        match json!({ "message": message, "severity": "INFO" }) {
373            Value::Object(map) => map,
374            other => panic!("test record must be an object, got {other}"),
375        }
376    }
377
378    #[tokio::test(start_paused = true)]
379    async fn a_full_batch_is_written_without_waiting_for_the_interval() {
380        let sink = RecordingSink::shared();
381        let config = config().with_flush_interval(Duration::from_secs(3600));
382        let (api_sink, handle) = start(&config, Arc::clone(&sink));
383
384        for index in 0..7 {
385            api_sink.send(record(&format!("event {index}")));
386        }
387        handle.flush().await;
388
389        assert_eq!(sink.batch_sizes(), vec![3, 3, 1]);
390    }
391
392    #[tokio::test(start_paused = true)]
393    async fn a_partial_batch_is_written_after_the_flush_interval() {
394        let sink = RecordingSink::shared();
395        let config = config();
396        let (api_sink, _handle) = start(&config, Arc::clone(&sink));
397
398        api_sink.send(record("first"));
399        tokio::time::sleep(Duration::from_millis(500)).await;
400        assert_eq!(sink.batch_sizes(), Vec::<usize>::new());
401
402        tokio::time::sleep(Duration::from_secs(3)).await;
403        assert_eq!(sink.batch_sizes(), vec![1]);
404    }
405
406    #[tokio::test(start_paused = true)]
407    async fn entries_over_the_queue_capacity_are_counted_as_dropped() {
408        let sink = Arc::new(RecordingSink {
409            delay: Some(Duration::from_secs(3600)),
410            ..RecordingSink::default()
411        });
412        let config = config().with_queue_capacity(4).with_batch_size(1);
413        let (api_sink, _handle) = start(&config, Arc::clone(&sink));
414
415        for index in 0..40 {
416            api_sink.send(record(&format!("event {index}")));
417        }
418
419        assert!(
420            api_sink.dropped.load(Ordering::Relaxed) > 0,
421            "a queue of 4 cannot hold 40 entries while the sink is blocked"
422        );
423    }
424
425    #[tokio::test(start_paused = true)]
426    async fn flush_writes_everything_queued_before_it() {
427        let sink = RecordingSink::shared();
428        let config = config().with_flush_interval(Duration::from_secs(3600));
429        let (api_sink, handle) = start(&config, Arc::clone(&sink));
430
431        api_sink.send(record("before flush"));
432        handle.flush().await;
433
434        assert_eq!(sink.batch_sizes(), vec![1]);
435        let request = sink.requests().remove(0);
436        assert_eq!(request.log_name, "projects/p/logs/test-log");
437        assert_eq!(request.resource, Some(resource()));
438        assert!(request.partial_success);
439    }
440
441    #[tokio::test(start_paused = true)]
442    async fn shutdown_writes_what_is_queued() {
443        let sink = RecordingSink::shared();
444        let config = config().with_flush_interval(Duration::from_secs(3600));
445        let (api_sink, handle) = start(&config, Arc::clone(&sink));
446
447        api_sink.send(record("before shutdown"));
448        handle.shutdown().await;
449
450        assert_eq!(sink.batch_sizes(), vec![1]);
451    }
452
453    #[tokio::test(start_paused = true)]
454    async fn shutdown_gives_up_after_the_shutdown_timeout() {
455        let sink = Arc::new(RecordingSink {
456            delay: Some(Duration::from_secs(3600)),
457            ..RecordingSink::default()
458        });
459        let config = config()
460            .with_flush_interval(Duration::from_secs(3600))
461            .with_shutdown_timeout(Duration::from_secs(1));
462        let (api_sink, handle) = start(&config, Arc::clone(&sink));
463
464        api_sink.send(record("never written"));
465        let started = tokio::time::Instant::now();
466        handle.shutdown().await;
467
468        let waited = started.elapsed();
469        assert!(
470            waited >= Duration::from_secs(1) && waited < Duration::from_secs(60),
471            "shutdown waited {waited:?}, expected roughly the 1s timeout"
472        );
473    }
474
475    #[tokio::test(start_paused = true)]
476    async fn a_failed_batch_is_discarded_and_the_task_keeps_running() {
477        let sink = Arc::new(RecordingSink {
478            fail: true,
479            ..RecordingSink::default()
480        });
481        let config = config().with_flush_interval(Duration::from_secs(3600));
482        let (api_sink, handle) = start(&config, Arc::clone(&sink));
483
484        api_sink.send(record("first"));
485        handle.flush().await;
486        api_sink.send(record("second"));
487        handle.flush().await;
488
489        assert_eq!(sink.batch_sizes(), vec![1, 1]);
490    }
491}