Skip to main content

micromegas_telemetry_sink/
http_event_sink.rs

1use micromegas_telemetry::stream_info::StreamInfo;
2use micromegas_telemetry::wire_format::encode_cbor;
3use micromegas_tracing::{
4    event::{EventSink, TracingBlock},
5    flush_monitor::FlushMonitor,
6    images::{ImageBlock, ImageStream},
7    logs::{LogBlock, LogMetadata, LogStream},
8    metrics::{MetricsBlock, MetricsStream},
9    prelude::*,
10    property_set::DynProperty,
11    spans::{ThreadBlock, ThreadStream},
12};
13use std::{
14    cmp::max,
15    collections::{HashMap, VecDeque},
16    fmt,
17    sync::{
18        Arc, Condvar, Mutex,
19        atomic::{AtomicBool, AtomicIsize, AtomicU64, Ordering},
20    },
21    time::Duration,
22};
23use tokio::sync::{OwnedSemaphorePermit, Semaphore};
24use tokio_retry2::{RetryError, strategy::ExponentialBackoff};
25
26use crate::request_decorator::RequestDecorator;
27use crate::stream_block::StreamBlock;
28use crate::stream_info::make_stream_info;
29
30/// A retry strategy: an exponential backoff, capped to a fixed number of attempts.
31type RetryStrategy = core::iter::Take<ExponentialBackoff>;
32
33/// Error type for ingestion client operations.
34/// Explicitly categorizes errors to control retry behavior.
35///
36/// Logging strategy: Transient errors (5xx, 429, network) use `debug!` to avoid
37/// polluting instrumented applications' logs with telemetry infrastructure noise.
38/// Permanent errors (4xx except 429) use `warn!` since they indicate a bug in the client.
39#[derive(Clone, Debug)]
40enum IngestionClientError {
41    /// Transient error - should retry (network issues, 5xx and 429 responses)
42    Transient(String),
43    /// Permanent error - should NOT retry (4xx responses except 429, malformed data)
44    Permanent(String),
45}
46
47impl std::fmt::Display for IngestionClientError {
48    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49        match self {
50            IngestionClientError::Transient(msg) => write!(f, "transient error: {msg}"),
51            IngestionClientError::Permanent(msg) => write!(f, "permanent error: {msg}"),
52        }
53    }
54}
55
56impl std::error::Error for IngestionClientError {}
57
58impl IngestionClientError {
59    fn into_retry(self) -> RetryError<Self> {
60        match self {
61            IngestionClientError::Transient(_) => RetryError::transient(self),
62            IngestionClientError::Permanent(_) => RetryError::permanent(self),
63        }
64    }
65}
66
67#[derive(Copy, Clone, Debug, PartialEq, Eq)]
68enum StatusClass {
69    Success,
70    Transient,
71    Permanent,
72}
73
74fn classify_status(status: u16) -> StatusClass {
75    match status {
76        200..=299 => StatusClass::Success,
77        // The proxy or load balancer is shedding load; backing off lets the
78        // payload through later instead of dropping it.
79        429 => StatusClass::Transient,
80        400..=499 => StatusClass::Permanent,
81        500..=599 => StatusClass::Transient,
82        _ => StatusClass::Permanent,
83    }
84}
85
86async fn response_to_result(
87    op: &str,
88    response: reqwest::Response,
89) -> Result<(), RetryError<IngestionClientError>> {
90    let status = response.status();
91    let class = classify_status(status.as_u16());
92    if class == StatusClass::Success {
93        return Ok(());
94    }
95    let body = response.text().await.unwrap_or_default();
96    match class {
97        StatusClass::Success => unreachable!(),
98        StatusClass::Transient => {
99            if status.as_u16() == 429 {
100                debug!("{op} rate limited ({status}): {body}");
101            } else {
102                debug!("{op} server error ({status}): {body}");
103            }
104            Err(IngestionClientError::Transient(format!("{status}: {body}")).into_retry())
105        }
106        StatusClass::Permanent if (400..=499).contains(&status.as_u16()) => {
107            warn!("{op} client error ({status}): {body}");
108            Err(IngestionClientError::Permanent(body).into_retry())
109        }
110        StatusClass::Permanent => {
111            warn!("{op} unexpected status ({status}): {body}");
112            Err(IngestionClientError::Permanent(format!("{status}: {body}")).into_retry())
113        }
114    }
115}
116
117/// Upload priority classes, drained strictly in this order (Metadata first,
118/// Traces last) and used to decide which items are shed first under
119/// backpressure. Mirrors the Unreal telemetry sink's `EUploadPriority`.
120///
121/// Also indexes [`HttpSinkConfig::retry_by_priority`]: index 0 is Metadata,
122/// 1 is Logs, 2 is Metrics, 3 is Traces.
123#[derive(Copy, Clone, Debug, PartialEq, Eq)]
124pub enum UploadPriority {
125    /// `insert_process` / `insert_stream` — never dropped.
126    Metadata = 0,
127    /// Log blocks.
128    Logs = 1,
129    /// Metrics blocks.
130    Metrics = 2,
131    /// Thread and image blocks.
132    Traces = 3,
133}
134
135const NUM_PRIORITIES: usize = 4;
136
137/// How long `on_shutdown`/`Drop` wait for the worker's final drain before
138/// giving up on a graceful shutdown.
139const SHUTDOWN_WAIT_TIMEOUT: Duration = Duration::from_secs(5);
140
141/// Reports drops accumulated by [`SharedQueue::note_dropped`], emitting one
142/// metric and one log line per priority class that dropped anything since the
143/// last call.
144///
145/// Must only be called from the worker thread's top-level loop, never from
146/// inside an `EventSink` callback: the enqueue path (`try_push` runs on the
147/// caller's thread) is reached from `on_process_*_block`, so emitting telemetry
148/// there would recurse into the sink, and every dropped block could produce
149/// another one.
150fn report_dropped_items(queue: &SharedQueue) {
151    for priority in [
152        UploadPriority::Metadata,
153        UploadPriority::Logs,
154        UploadPriority::Metrics,
155        UploadPriority::Traces,
156    ] {
157        let count = queue.dropped[priority as usize].swap(0, Ordering::Relaxed);
158        if count == 0 {
159            continue;
160        }
161        warn!("dropped {count} telemetry items, priority={priority:?}");
162        match priority {
163            UploadPriority::Metadata => {
164                imetric!("telemetry_dropped_metadata", "count", count);
165            }
166            UploadPriority::Logs => {
167                imetric!("telemetry_dropped_logs", "count", count);
168            }
169            UploadPriority::Metrics => {
170                imetric!("telemetry_dropped_metrics", "count", count);
171            }
172            UploadPriority::Traces => {
173                imetric!("telemetry_dropped_traces", "count", count);
174            }
175        }
176    }
177}
178
179enum Payload {
180    Process(Arc<ProcessInfo>),
181    Stream(Arc<StreamInfo>),
182    Block {
183        block: Arc<dyn StreamBlock + Send + Sync>,
184        kind: &'static str,
185    },
186}
187
188struct QueuedItem {
189    priority: UploadPriority,
190    /// Raw uncompressed queued size (`0` for metadata, `len_bytes()` for blocks).
191    bytes: usize,
192    payload: Payload,
193}
194
195/// A priority-ordered, byte-budgeted queue shared between the application
196/// threads (enqueue side) and the dedicated upload worker thread (drain side).
197///
198/// The `notify` condvar is paired with the `queues` mutex: every state change
199/// that the worker might be waiting on (a new item, a freed in-flight slot, or
200/// shutdown) is signaled while holding (or right after briefly re-acquiring)
201/// that same mutex. This is what prevents a lost wakeup: the worker always
202/// re-checks its wake predicate under the lock immediately before waiting, so
203/// a signal can never land in the gap between the check and the wait.
204struct SharedQueue {
205    queues: Mutex<[VecDeque<QueuedItem>; NUM_PRIORITIES]>,
206    queue_bytes: AtomicIsize,
207    queue_count: AtomicIsize,
208    /// Number of items dispatched to a send task (via `spawn_item`) whose
209    /// task has not completed yet. Unlike `queue_count`, which drops as soon
210    /// as an item is popped off the deque, this stays elevated for the
211    /// entire lifetime of the HTTP send (including retries), so it reflects
212    /// genuine outstanding network activity.
213    in_flight_count: AtomicIsize,
214    notify: Condvar,
215    shutdown: AtomicBool,
216    soft_bytes: usize,
217    hard_bytes: usize,
218    /// Per-priority count of items dropped since the worker last reported.
219    /// Incremented on the enqueue path and drained by the worker thread's
220    /// `report_dropped_items` — the enqueue path itself must never emit
221    /// telemetry (see `report_dropped_items`).
222    dropped: [AtomicU64; NUM_PRIORITIES],
223}
224
225impl SharedQueue {
226    fn new(soft_bytes: usize, hard_bytes: usize) -> Self {
227        Self {
228            queues: Mutex::new([
229                VecDeque::new(),
230                VecDeque::new(),
231                VecDeque::new(),
232                VecDeque::new(),
233            ]),
234            queue_bytes: AtomicIsize::new(0),
235            queue_count: AtomicIsize::new(0),
236            in_flight_count: AtomicIsize::new(0),
237            notify: Condvar::new(),
238            shutdown: AtomicBool::new(false),
239            soft_bytes,
240            hard_bytes: hard_bytes.max(soft_bytes),
241            dropped: [
242                AtomicU64::new(0),
243                AtomicU64::new(0),
244                AtomicU64::new(0),
245                AtomicU64::new(0),
246            ],
247        }
248    }
249
250    /// Records a dropped item for later reporting by the worker thread. Kept
251    /// to a plain atomic increment on purpose: this runs on the enqueue path,
252    /// inside dispatch callbacks, where emitting telemetry would recurse into
253    /// the sink.
254    fn note_dropped(&self, priority: UploadPriority) {
255        self.dropped[priority as usize].fetch_add(1, Ordering::Relaxed);
256    }
257
258    /// Enqueues `item`, applying the graded byte-budget drop policy. Returns
259    /// `false` if the item was dropped instead of queued.
260    fn try_push(&self, item: QueuedItem) -> bool {
261        let current = self.queue_bytes.load(Ordering::Relaxed).max(0) as usize;
262        let should_drop = match item.priority {
263            UploadPriority::Metadata => false,
264            UploadPriority::Traces => current >= self.soft_bytes,
265            UploadPriority::Logs | UploadPriority::Metrics => current >= self.hard_bytes,
266        };
267        if should_drop {
268            self.note_dropped(item.priority);
269            return false;
270        }
271        // The shutdown check and the push must happen under the same lock
272        // that guards `pop_highest`'s drain loop: otherwise an enqueuer could
273        // observe `shutdown == false`, get preempted, and push after the
274        // worker's final drain has already run to completion and signaled
275        // `shutdown_complete` — silently leaking the item into an abandoned
276        // queue. Checking here, inside the critical section, makes this
277        // mutually exclusive with the drain's emptiness check.
278        let mut guard = self.queues.lock().unwrap();
279        if self.shutdown.load(Ordering::SeqCst) {
280            drop(guard);
281            // The worker has committed to (or already finished) its final
282            // drain and will never pop this item, so queuing it would leak
283            // it forever. Reject and count the drop instead. No log/metric
284            // is emitted here: this path can run inside a dispatch callback
285            // (see `report_dropped_items`), and post-shutdown the dispatch
286            // sink is gone anyway.
287            self.note_dropped(item.priority);
288            return false;
289        }
290        self.queue_bytes
291            .fetch_add(item.bytes as isize, Ordering::Relaxed);
292        self.queue_count.fetch_add(1, Ordering::Relaxed);
293        guard[item.priority as usize].push_back(item);
294        self.notify.notify_all();
295        true
296    }
297
298    /// Pops the highest-priority queued item (Metadata, then Logs, Metrics,
299    /// Traces), if any.
300    fn pop_highest(&self) -> Option<QueuedItem> {
301        let mut guard = self.queues.lock().unwrap();
302        for deque in guard.iter_mut() {
303            if let Some(item) = deque.pop_front() {
304                drop(guard);
305                self.queue_bytes
306                    .fetch_sub(item.bytes as isize, Ordering::Relaxed);
307                self.queue_count.fetch_sub(1, Ordering::Relaxed);
308                return Some(item);
309            }
310        }
311        None
312    }
313
314    /// Wakes the worker. Used both for actual state changes (shutdown) and as
315    /// a pure synchronization fence (a completed send freeing an in-flight
316    /// slot) — see the struct-level doc comment for why acquiring `queues`
317    /// here is required for correctness, not just a mutation guard.
318    fn wake(&self) {
319        let _guard = self.queues.lock().unwrap();
320        self.notify.notify_all();
321    }
322}
323
324/// Releases a semaphore permit and wakes the worker when a spawned send task
325/// finishes, whether it returns normally or panics — an ordinary statement at
326/// the end of the task body would be skipped on unwind, stranding the permit
327/// until the next timeout tick.
328struct WakeOnDrop {
329    queue: Arc<SharedQueue>,
330    _permit: Option<OwnedSemaphorePermit>,
331}
332
333impl Drop for WakeOnDrop {
334    fn drop(&mut self) {
335        // Release the permit BEFORE waking. `wake()` does `notify_all` under
336        // the queues lock and returns before drop-glue would drop `_permit`,
337        // so a worker that wasn't waiting at notify time could grab the lock
338        // in the gap between the notify and the permit release, read
339        // `available_permits() == 0` with the queue non-empty, and re-sleep
340        // until the next flush tick. Freeing the slot first makes it visible
341        // to any worker that evaluates its wait predicate after the notify.
342        drop(self._permit.take());
343        self.queue.wake();
344    }
345}
346
347/// Configuration for [`HttpEventSink`]'s transport: how much to buffer, how
348/// aggressively to shed load under backpressure, how much concurrency to
349/// allow, and how hard to retry each priority class.
350///
351/// The byte caps sit far above what a healthy co-located ingestion service
352/// (e.g. a monolith) will ever accumulate, so a normal run drops nothing;
353/// they only bite during a real outage.
354pub struct HttpSinkConfig {
355    /// Soft cap, in bytes: once the queue holds at least this many bytes,
356    /// new `Traces` items (thread and image blocks) are dropped. Default 128 MiB.
357    pub max_queue_bytes: usize,
358    /// Hard cap, in bytes: once the queue holds at least this many bytes,
359    /// new `Logs`/`Metrics` items are dropped too. Clamped to be at least
360    /// `max_queue_bytes`. `Metadata` (process/stream) is never dropped.
361    /// Default 256 MiB.
362    pub hard_queue_bytes: usize,
363    /// Maximum number of `insert_*` HTTP requests in flight at once. Set to
364    /// `1` to restore strictly serial sends. Default 3.
365    pub max_in_flight_requests: usize,
366    /// Per-request timeout (covers connect + send + receive for one attempt).
367    ///
368    /// This is a deliberate addition beyond Unreal parity: Unreal's
369    /// per-priority retry window is a total retry *budget*, not a socket
370    /// timeout (it never sets one either), so a single attempt against an
371    /// ingestion service that accepts the TCP connection but never responds
372    /// can hang indefinitely. Without a bound here, that hang is fatal at
373    /// shutdown: `Drop for HttpEventSink` joins the worker thread, so a
374    /// short-lived process would freeze on exit whenever ingestion is
375    /// unresponsive (as opposed to merely offline, which fails fast with a
376    /// connection error). Default 10 seconds.
377    pub request_timeout: Duration,
378    /// Retry strategy per [`UploadPriority`] (indexed by
379    /// `UploadPriority as usize`).
380    pub retry_by_priority: [RetryStrategy; NUM_PRIORITIES],
381}
382
383impl HttpSinkConfig {
384    /// Default soft byte cap: 128 MiB.
385    pub const DEFAULT_MAX_QUEUE_BYTES: usize = 128 * 1024 * 1024;
386    /// Default hard byte cap: 256 MiB.
387    pub const DEFAULT_HARD_QUEUE_BYTES: usize = 256 * 1024 * 1024;
388    /// Default in-flight request cap (Unreal parity).
389    pub const DEFAULT_MAX_IN_FLIGHT_REQUESTS: usize = 3;
390    /// Default per-request timeout.
391    pub const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
392
393    /// The default per-priority retry table: Metadata gets the most retries,
394    /// Traces the fewest, mirroring the Unreal sink's
395    /// `RetryCountByPriority` (`{10,5,2,1}`).
396    pub fn default_retry_by_priority() -> [RetryStrategy; NUM_PRIORITIES] {
397        [
398            ExponentialBackoff::from_millis(10).take(10), // Metadata
399            ExponentialBackoff::from_millis(10).take(5),  // Logs
400            ExponentialBackoff::from_millis(10).take(2),  // Metrics
401            ExponentialBackoff::from_millis(10).take(1),  // Traces
402        ]
403    }
404}
405
406impl Default for HttpSinkConfig {
407    fn default() -> Self {
408        Self {
409            max_queue_bytes: Self::DEFAULT_MAX_QUEUE_BYTES,
410            hard_queue_bytes: Self::DEFAULT_HARD_QUEUE_BYTES,
411            max_in_flight_requests: Self::DEFAULT_MAX_IN_FLIGHT_REQUESTS,
412            request_timeout: Self::DEFAULT_REQUEST_TIMEOUT,
413            retry_by_priority: Self::default_retry_by_priority(),
414        }
415    }
416}
417
418/// State shared by every send spawned by the worker loop: the HTTP client,
419/// the current process info (set synchronously as soon as the `Startup` item
420/// is dequeued, independently of whether the send itself succeeds), and the
421/// per-priority retry table.
422struct WorkerShared {
423    client: reqwest::Client,
424    addr: String,
425    process_info: Mutex<Option<Arc<ProcessInfo>>>,
426    decorator: Arc<dyn RequestDecorator>,
427    retry_by_priority: [RetryStrategy; NUM_PRIORITIES],
428}
429
430/// The subset of [`HttpSinkConfig`] needed by the worker thread, grouped to
431/// keep `thread_proc`/`run`'s parameter lists manageable.
432struct WorkerConfig {
433    max_in_flight_requests: usize,
434    request_timeout: Duration,
435    retry_by_priority: [RetryStrategy; NUM_PRIORITIES],
436}
437
438pub struct HttpEventSink {
439    thread: Option<std::thread::JoinHandle<()>>,
440    queue: Arc<SharedQueue>,
441    pending_stream_meta: Mutex<HashMap<uuid::Uuid, Arc<StreamInfo>>>,
442    shutdown_complete: Arc<(Mutex<bool>, std::sync::Condvar)>,
443}
444
445impl Drop for HttpEventSink {
446    fn drop(&mut self) {
447        // Bounded like `on_shutdown`: if the worker is stuck (e.g. mid-retry
448        // against an ingestion service that accepts connections but never
449        // responds), we must not block process exit on `handle.join()`
450        // indefinitely. Abandon the thread instead: the OS reclaims it when
451        // the process exits, or if it eventually finishes on its own.
452        if !self.signal_shutdown_and_wait() {
453            eprintln!(
454                "Warning: telemetry thread did not shut down within the timeout, abandoning it"
455            );
456            return;
457        }
458
459        if let Some(handle) = self.thread.take()
460            && let Err(e) = handle.join()
461        {
462            // Don't panic on join failure, just log it
463            eprintln!("Warning: telemetry thread join failed: {:?}", e);
464        }
465    }
466}
467
468impl HttpEventSink {
469    /// Creates a new `HttpEventSink`.
470    ///
471    /// This function spawns a new thread that handles sending telemetry data
472    /// to the specified HTTP server. Sends run on a dedicated tokio runtime,
473    /// with up to `config.max_in_flight_requests` requests in flight
474    /// concurrently, drained strictly in priority order (Metadata, Logs,
475    /// Metrics, Traces).
476    ///
477    /// # Arguments
478    ///
479    /// * `addr_server` - The address of the HTTP server to send data to.
480    /// * `config` - Transport configuration: byte budgets, concurrency, retries.
481    /// * `make_decorator` - A closure that returns a `RequestDecorator` for modifying HTTP requests.
482    pub fn new(
483        addr_server: &str,
484        config: HttpSinkConfig,
485        make_decorator: Box<dyn FnOnce() -> Arc<dyn RequestDecorator> + Send>,
486    ) -> Self {
487        let addr = addr_server.to_owned();
488        let queue = Arc::new(SharedQueue::new(
489            config.max_queue_bytes,
490            config.hard_queue_bytes,
491        ));
492        let thread_queue = queue.clone();
493        let worker_config = WorkerConfig {
494            max_in_flight_requests: config.max_in_flight_requests,
495            request_timeout: config.request_timeout,
496            retry_by_priority: config.retry_by_priority,
497        };
498        let shutdown_complete = Arc::new((Mutex::new(false), std::sync::Condvar::new()));
499        let thread_shutdown_complete = shutdown_complete.clone();
500        Self {
501            thread: Some(std::thread::spawn(move || {
502                Self::thread_proc(
503                    addr,
504                    thread_queue,
505                    worker_config,
506                    make_decorator,
507                    thread_shutdown_complete,
508                );
509            })),
510            queue,
511            pending_stream_meta: Mutex::new(HashMap::new()),
512            shutdown_complete,
513        }
514    }
515
516    /// Signals shutdown and waits (bounded) for the worker's final drain to
517    /// complete. Returns `false` if the wait timed out — the worker may
518    /// still be stuck mid-send, and the thread should not be joined
519    /// unconditionally in that case.
520    fn signal_shutdown_and_wait(&self) -> bool {
521        self.queue.shutdown.store(true, Ordering::SeqCst);
522        self.queue.wake();
523
524        let (lock, cvar) = &*self.shutdown_complete;
525        let completed = lock.lock().unwrap();
526        let (completed, result) = cvar
527            .wait_timeout_while(completed, SHUTDOWN_WAIT_TIMEOUT, |&mut c| !c)
528            .unwrap();
529        drop(completed);
530        !result.timed_out()
531    }
532
533    fn flush_pending_stream_meta(&self, stream_id: uuid::Uuid) {
534        if let Some(stream_info) = self.pending_stream_meta.lock().unwrap().remove(&stream_id) {
535            self.queue.try_push(QueuedItem {
536                priority: UploadPriority::Metadata,
537                bytes: 0,
538                payload: Payload::Stream(stream_info),
539            });
540        }
541    }
542
543    #[span_fn]
544    async fn push_process(
545        client: &reqwest::Client,
546        root_path: &str,
547        process_info: Arc<ProcessInfo>,
548        retry_strategy: RetryStrategy,
549        decorator: &dyn RequestDecorator,
550    ) -> Result<(), IngestionClientError> {
551        debug!("sending process {process_info:?}");
552        let url = format!("{root_path}/ingestion/insert_process");
553        let body: bytes::Bytes = encode_cbor(&*process_info)
554            .map_err(|e| IngestionClientError::Permanent(format!("encoding process: {e}")))?
555            .into();
556        tokio_retry2::Retry::spawn(retry_strategy, || async {
557            let mut request = client.post(&url).body(body.clone()).build().map_err(|e| {
558                IngestionClientError::Permanent(format!("building request: {e}")).into_retry()
559            })?;
560
561            if let Err(e) = decorator.decorate(&mut request).await {
562                debug!("request decorator: {e:?}");
563                return Err(
564                    IngestionClientError::Transient(format!("decorating request: {e}"))
565                        .into_retry(),
566                );
567            }
568
569            let response = client.execute(request).await.map_err(|e| {
570                IngestionClientError::Transient(format!("network error: {e}")).into_retry()
571            })?;
572
573            response_to_result("insert_process", response).await
574        })
575        .await
576    }
577
578    #[span_fn]
579    async fn push_stream(
580        client: &reqwest::Client,
581        root_path: &str,
582        stream_info: Arc<StreamInfo>,
583        retry_strategy: RetryStrategy,
584        decorator: &dyn RequestDecorator,
585    ) -> Result<(), IngestionClientError> {
586        let url = format!("{root_path}/ingestion/insert_stream");
587        let body: bytes::Bytes = encode_cbor(&*stream_info)
588            .map_err(|e| IngestionClientError::Permanent(format!("encoding stream: {e}")))?
589            .into();
590        tokio_retry2::Retry::spawn(retry_strategy, || async {
591            let mut request = client.post(&url).body(body.clone()).build().map_err(|e| {
592                IngestionClientError::Permanent(format!("building request: {e}")).into_retry()
593            })?;
594
595            if let Err(e) = decorator.decorate(&mut request).await {
596                debug!("request decorator: {e:?}");
597                return Err(
598                    IngestionClientError::Transient(format!("decorating request: {e}"))
599                        .into_retry(),
600                );
601            }
602
603            let response = client.execute(request).await.map_err(|e| {
604                IngestionClientError::Transient(format!("network error: {e}")).into_retry()
605            })?;
606
607            response_to_result("insert_stream", response).await
608        })
609        .await
610    }
611
612    #[span_fn]
613    async fn push_block(
614        client: &reqwest::Client,
615        root_path: &str,
616        buffer: &dyn StreamBlock,
617        retry_strategy: RetryStrategy,
618        decorator: &dyn RequestDecorator,
619        process_info: &ProcessInfo,
620    ) -> Result<(), IngestionClientError> {
621        trace!("push_block");
622        let encoded_block: bytes::Bytes = buffer
623            .encode_bin(process_info)
624            .map_err(|e| IngestionClientError::Permanent(format!("encoding block: {e}")))?
625            .into();
626
627        let url = format!("{root_path}/ingestion/insert_block");
628
629        tokio_retry2::Retry::spawn(retry_strategy, || async {
630            let mut request = client
631                .post(&url)
632                .body(encoded_block.clone())
633                .build()
634                .map_err(|e| {
635                    IngestionClientError::Permanent(format!("building request: {e}")).into_retry()
636                })?;
637
638            if let Err(e) = decorator.decorate(&mut request).await {
639                debug!("request decorator: {e:?}");
640                return Err(
641                    IngestionClientError::Transient(format!("decorating request: {e}"))
642                        .into_retry(),
643                );
644            }
645
646            trace!("push_block: executing request");
647
648            let response = client.execute(request).await.map_err(|e| {
649                IngestionClientError::Transient(format!("network error: {e}")).into_retry()
650            })?;
651
652            response_to_result("insert_block", response).await
653        })
654        .await
655    }
656
657    /// Dispatches one dequeued item onto the tokio runtime. `permit`, if
658    /// present, is held for the duration of the send and gates concurrency;
659    /// during the final shutdown drain it is `None` so all remaining items go
660    /// out at once. `Payload::Process` sets the shared `process_info`
661    /// synchronously here (before spawning), matching the pre-existing
662    /// guarantee that blocks can rely on it being set as soon as `Startup` is
663    /// dequeued, independently of whether the send itself succeeds.
664    fn spawn_item(
665        shared: &Arc<WorkerShared>,
666        queue: &Arc<SharedQueue>,
667        item: QueuedItem,
668        join_set: &mut tokio::task::JoinSet<()>,
669        permit: Option<OwnedSemaphorePermit>,
670    ) {
671        // Counted as outstanding from the moment it's handed to a send task
672        // until that task is reaped in one of the `run` loop's join-set
673        // drain points, so `is_busy()` stays true for the whole send
674        // (including retries), not just while the item sits in the deque.
675        queue.in_flight_count.fetch_add(1, Ordering::Relaxed);
676        if let Payload::Process(ref info) = item.payload {
677            *shared.process_info.lock().unwrap() = Some(info.clone());
678        }
679        let shared = shared.clone();
680        let queue = queue.clone();
681        let retry_strategy = shared.retry_by_priority[item.priority as usize].clone();
682        join_set.spawn(async move {
683            // Releases the permit and wakes the worker on both normal
684            // completion and panic/unwind, so a panicking send doesn't
685            // strand a semaphore permit or a waiting enqueuer until the
686            // next timeout tick.
687            let _wake_on_drop = WakeOnDrop {
688                queue,
689                _permit: permit,
690            };
691            match item.payload {
692                Payload::Process(info) => {
693                    if let Err(e) = Self::push_process(
694                        &shared.client,
695                        &shared.addr,
696                        info,
697                        retry_strategy,
698                        shared.decorator.as_ref(),
699                    )
700                    .await
701                    {
702                        error!("error sending process: {e}");
703                    }
704                }
705                Payload::Stream(stream_info) => {
706                    if let Err(e) = Self::push_stream(
707                        &shared.client,
708                        &shared.addr,
709                        stream_info,
710                        retry_strategy,
711                        shared.decorator.as_ref(),
712                    )
713                    .await
714                    {
715                        error!("error sending stream: {e}");
716                    }
717                }
718                Payload::Block { block, kind } => {
719                    let maybe_process_info = shared.process_info.lock().unwrap().clone();
720                    if let Some(process_info) = maybe_process_info {
721                        if let Err(e) = Self::push_block(
722                            &shared.client,
723                            &shared.addr,
724                            block.as_ref(),
725                            retry_strategy,
726                            shared.decorator.as_ref(),
727                            &process_info,
728                        )
729                        .await
730                        {
731                            error!("error sending {kind}: {e}");
732                        }
733                    } else {
734                        error!("trying to send blocks before Startup message");
735                    }
736                }
737            }
738        });
739    }
740
741    async fn run(
742        addr: String,
743        queue: Arc<SharedQueue>,
744        config: WorkerConfig,
745        make_decorator: Box<dyn FnOnce() -> Arc<dyn RequestDecorator> + Send>,
746        shutdown_complete: Arc<(Mutex<bool>, std::sync::Condvar)>,
747    ) {
748        let client = match reqwest::Client::builder()
749            .pool_idle_timeout(Some(core::time::Duration::from_secs(2)))
750            .timeout(config.request_timeout)
751            .user_agent(concat!(
752                "micromegas-telemetry-sink/",
753                env!("CARGO_PKG_VERSION")
754            ))
755            .build()
756        {
757            Ok(client) => client,
758            Err(e) => {
759                error!("Error creating http client: {e:?}");
760                return;
761            }
762        };
763        // eagerly connect, a new process message is sure to follow if it's not already in queue
764        if let Some(process_id) = micromegas_tracing::dispatch::process_id() {
765            let cpu_tracing_enabled =
766                micromegas_tracing::dispatch::cpu_tracing_enabled().unwrap_or(false);
767            info!("process_id={process_id}, cpu_tracing_enabled={cpu_tracing_enabled}");
768        }
769        let shared = Arc::new(WorkerShared {
770            client,
771            addr,
772            process_info: Mutex::new(None),
773            decorator: make_decorator(),
774            retry_by_priority: config.retry_by_priority,
775        });
776        let semaphore = Arc::new(Semaphore::new(config.max_in_flight_requests.max(1)));
777        let mut join_set: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
778        let flusher = FlushMonitor::default();
779
780        loop {
781            if queue.shutdown.load(Ordering::SeqCst) {
782                break;
783            }
784
785            loop {
786                let permit = match Arc::clone(&semaphore).try_acquire_owned() {
787                    Ok(permit) => permit,
788                    Err(_) => break,
789                };
790                match queue.pop_highest() {
791                    Some(item) => {
792                        Self::spawn_item(&shared, &queue, item, &mut join_set, Some(permit))
793                    }
794                    None => {
795                        drop(permit);
796                        break;
797                    }
798                }
799            }
800            // Reap finished sends so the JoinSet doesn't grow unbounded.
801            while let Some(result) = join_set.try_join_next() {
802                queue.in_flight_count.fetch_sub(1, Ordering::Relaxed);
803                if let Err(e) = result {
804                    error!("telemetry send task panicked: {e}");
805                }
806            }
807
808            // clamp to zero as the original code did: time_to_flush_seconds() returns i64
809            // and goes negative when a flush is overdue; a negative value cast to
810            // Duration::from_secs(u64) would wrap to ~u64::MAX and never wake.
811            let timeout = Duration::from_secs(max(0, flusher.time_to_flush_seconds()) as u64);
812            {
813                let guard = queue.queues.lock().unwrap();
814                let empty = guard.iter().all(VecDeque::is_empty);
815                let permit_available = semaphore.available_permits() > 0;
816                if !queue.shutdown.load(Ordering::SeqCst) && (empty || !permit_available) {
817                    let _ = queue.notify.wait_timeout(guard, timeout);
818                }
819            }
820            flusher.tick();
821            report_dropped_items(&queue);
822        }
823
824        debug!("received shutdown signal, flushing remaining data");
825        // Final drain: submit everything left, bypassing the concurrency gate
826        // so shutdown doesn't wait on `max_in_flight_requests` round trips.
827        let mut drained = 0;
828        while let Some(item) = queue.pop_highest() {
829            drained += 1;
830            Self::spawn_item(&shared, &queue, item, &mut join_set, None);
831        }
832        while let Some(result) = join_set.join_next().await {
833            queue.in_flight_count.fetch_sub(1, Ordering::Relaxed);
834            if let Err(e) = result {
835                error!("telemetry send task panicked: {e}");
836            }
837        }
838        debug!("telemetry thread shutdown complete, drained {drained} remaining items");
839        // Best-effort: post-shutdown the dispatch sink is usually already
840        // swapped out, but any drops still pending from the last window get
841        // one final chance to be reported.
842        report_dropped_items(&queue);
843
844        let (lock, cvar) = &*shutdown_complete;
845        let mut completed = lock.lock().unwrap();
846        *completed = true;
847        cvar.notify_all();
848    }
849
850    fn thread_proc(
851        addr: String,
852        queue: Arc<SharedQueue>,
853        config: WorkerConfig,
854        make_decorator: Box<dyn FnOnce() -> Arc<dyn RequestDecorator> + Send>,
855        shutdown_complete: Arc<(Mutex<bool>, std::sync::Condvar)>,
856    ) {
857        // TODO: add runtime as configuration option (or create one only if global don't exist)
858        let tokio_runtime = match tokio::runtime::Runtime::new() {
859            Ok(rt) => rt,
860            Err(e) => {
861                error!("Failed to create tokio runtime for telemetry: {e}");
862                return;
863            }
864        };
865        tokio_runtime.block_on(Self::run(
866            addr,
867            queue,
868            config,
869            make_decorator,
870            shutdown_complete,
871        ));
872    }
873}
874
875impl EventSink for HttpEventSink {
876    fn on_startup(&self, process_info: Arc<ProcessInfo>) {
877        self.queue.try_push(QueuedItem {
878            priority: UploadPriority::Metadata,
879            bytes: 0,
880            payload: Payload::Process(process_info),
881        });
882    }
883
884    fn on_shutdown(&self) {
885        // Signals shutdown, wakes the worker, and waits (bounded) for its
886        // final drain. If it times out, the caller (and the eventual `Drop`)
887        // still won't block indefinitely — see `signal_shutdown_and_wait`.
888        self.signal_shutdown_and_wait();
889    }
890
891    fn on_log_enabled(&self, _metadata: &LogMetadata) -> bool {
892        // If all previous filter succeeds this sink always agrees
893        true
894    }
895
896    fn on_log(
897        &self,
898        _metadata: &LogMetadata,
899        _properties: &[DynProperty<'_>],
900        _time: i64,
901        _args: fmt::Arguments<'_>,
902    ) {
903    }
904
905    fn on_init_log_stream(&self, log_stream: &LogStream) {
906        self.pending_stream_meta.lock().unwrap().insert(
907            log_stream.stream_id(),
908            Arc::new(make_stream_info(log_stream)),
909        );
910    }
911
912    fn on_process_log_block(&self, log_block: Arc<LogBlock>) {
913        self.flush_pending_stream_meta(log_block.stream_id);
914        let bytes = log_block.len_bytes();
915        self.queue.try_push(QueuedItem {
916            priority: UploadPriority::Logs,
917            bytes,
918            payload: Payload::Block {
919                block: log_block,
920                kind: "log block",
921            },
922        });
923    }
924
925    fn on_init_metrics_stream(&self, metrics_stream: &MetricsStream) {
926        self.pending_stream_meta.lock().unwrap().insert(
927            metrics_stream.stream_id(),
928            Arc::new(make_stream_info(metrics_stream)),
929        );
930    }
931
932    fn on_process_metrics_block(&self, metrics_block: Arc<MetricsBlock>) {
933        self.flush_pending_stream_meta(metrics_block.stream_id);
934        let bytes = metrics_block.len_bytes();
935        self.queue.try_push(QueuedItem {
936            priority: UploadPriority::Metrics,
937            bytes,
938            payload: Payload::Block {
939                block: metrics_block,
940                kind: "metrics block",
941            },
942        });
943    }
944
945    fn on_init_thread_stream(&self, thread_stream: &ThreadStream) {
946        self.pending_stream_meta.lock().unwrap().insert(
947            thread_stream.stream_id(),
948            Arc::new(make_stream_info(thread_stream)),
949        );
950    }
951
952    fn on_process_thread_block(&self, thread_block: Arc<ThreadBlock>) {
953        self.flush_pending_stream_meta(thread_block.stream_id);
954        let bytes = thread_block.len_bytes();
955        self.queue.try_push(QueuedItem {
956            priority: UploadPriority::Traces,
957            bytes,
958            payload: Payload::Block {
959                block: thread_block,
960                kind: "thread block",
961            },
962        });
963    }
964
965    fn on_init_image_stream(&self, stream: &ImageStream) {
966        self.pending_stream_meta
967            .lock()
968            .unwrap()
969            .insert(stream.stream_id(), Arc::new(make_stream_info(stream)));
970    }
971
972    fn on_process_image_block(&self, block: Arc<ImageBlock>) {
973        self.flush_pending_stream_meta(block.stream_id);
974        let bytes = block.len_bytes();
975        self.queue.try_push(QueuedItem {
976            priority: UploadPriority::Traces,
977            bytes,
978            payload: Payload::Block {
979                block,
980                kind: "image block",
981            },
982        });
983    }
984
985    fn is_busy(&self) -> bool {
986        let queued = self.queue.queue_count.load(Ordering::Relaxed);
987        debug_assert!(queued >= 0, "queue_count went negative: {queued}");
988        let in_flight = self.queue.in_flight_count.load(Ordering::Relaxed);
989        debug_assert!(in_flight >= 0, "in_flight_count went negative: {in_flight}");
990        queued > 0 || in_flight > 0
991    }
992}
993
994#[cfg(test)]
995mod tests {
996    use super::*;
997
998    #[test]
999    fn classify_status_cases() {
1000        for s in [200, 204] {
1001            assert_eq!(classify_status(s), StatusClass::Success, "{s}");
1002        }
1003        for s in [429, 500, 503] {
1004            assert_eq!(classify_status(s), StatusClass::Transient, "{s}");
1005        }
1006        for s in [400, 401, 404, 302] {
1007            assert_eq!(classify_status(s), StatusClass::Permanent, "{s}");
1008        }
1009    }
1010}