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
30type RetryStrategy = core::iter::Take<ExponentialBackoff>;
32
33#[derive(Clone, Debug)]
40enum IngestionClientError {
41 Transient(String),
43 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 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#[derive(Copy, Clone, Debug, PartialEq, Eq)]
124pub enum UploadPriority {
125 Metadata = 0,
127 Logs = 1,
129 Metrics = 2,
131 Traces = 3,
133}
134
135const NUM_PRIORITIES: usize = 4;
136
137const SHUTDOWN_WAIT_TIMEOUT: Duration = Duration::from_secs(5);
140
141fn 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 bytes: usize,
192 payload: Payload,
193}
194
195struct SharedQueue {
205 queues: Mutex<[VecDeque<QueuedItem>; NUM_PRIORITIES]>,
206 queue_bytes: AtomicIsize,
207 queue_count: AtomicIsize,
208 in_flight_count: AtomicIsize,
214 notify: Condvar,
215 shutdown: AtomicBool,
216 soft_bytes: usize,
217 hard_bytes: usize,
218 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 fn note_dropped(&self, priority: UploadPriority) {
255 self.dropped[priority as usize].fetch_add(1, Ordering::Relaxed);
256 }
257
258 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 let mut guard = self.queues.lock().unwrap();
279 if self.shutdown.load(Ordering::SeqCst) {
280 drop(guard);
281 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 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 fn wake(&self) {
319 let _guard = self.queues.lock().unwrap();
320 self.notify.notify_all();
321 }
322}
323
324struct WakeOnDrop {
329 queue: Arc<SharedQueue>,
330 _permit: Option<OwnedSemaphorePermit>,
331}
332
333impl Drop for WakeOnDrop {
334 fn drop(&mut self) {
335 drop(self._permit.take());
343 self.queue.wake();
344 }
345}
346
347pub struct HttpSinkConfig {
355 pub max_queue_bytes: usize,
358 pub hard_queue_bytes: usize,
363 pub max_in_flight_requests: usize,
366 pub request_timeout: Duration,
378 pub retry_by_priority: [RetryStrategy; NUM_PRIORITIES],
381}
382
383impl HttpSinkConfig {
384 pub const DEFAULT_MAX_QUEUE_BYTES: usize = 128 * 1024 * 1024;
386 pub const DEFAULT_HARD_QUEUE_BYTES: usize = 256 * 1024 * 1024;
388 pub const DEFAULT_MAX_IN_FLIGHT_REQUESTS: usize = 3;
390 pub const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
392
393 pub fn default_retry_by_priority() -> [RetryStrategy; NUM_PRIORITIES] {
397 [
398 ExponentialBackoff::from_millis(10).take(10), ExponentialBackoff::from_millis(10).take(5), ExponentialBackoff::from_millis(10).take(2), ExponentialBackoff::from_millis(10).take(1), ]
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
418struct 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
430struct 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 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 eprintln!("Warning: telemetry thread join failed: {:?}", e);
464 }
465 }
466}
467
468impl HttpEventSink {
469 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 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 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 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 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 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 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 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 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 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 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 self.signal_shutdown_and_wait();
889 }
890
891 fn on_log_enabled(&self, _metadata: &LogMetadata) -> bool {
892 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}