Skip to main content

micromegas_tracing/
dispatch.rs

1//! Where events are recorded and eventually sent to a sink
2use crate::dyn_deps::merge_properties;
3pub use crate::errors::{Error, Result};
4use crate::images::{ImageBlock, ImageEvent, ImageStream};
5use crate::logs::{
6    LogMsgForm, TaggedLogInteropEvent, TaggedLogStaticStrEvent, TaggedLogString,
7    TaggedLogTemplateEvent,
8};
9use crate::metrics::{TaggedFloatMetricEvent, TaggedIntegerMetricEvent};
10use crate::prelude::*;
11use crate::property_set::{DynProperty, PropertySet, PropertySetId};
12use crate::{
13    event::{EventBlock, EventSink, EventStream, ExtractDeps, NullEventSink, TracingBlock},
14    info,
15    logs::{
16        LogMetadata, LogStaticStrEvent, LogStaticStrInteropEventV2, LogStream, LogStringEvent,
17        LogStringInteropEvent,
18    },
19    metrics::{FloatMetricEvent, IntegerMetricEvent, MetricsStream, StaticMetricMetadata},
20    spans::{
21        BeginAsyncDynNamedSpanEvent, BeginAsyncNamedSpanEvent, BeginAsyncSpanEvent,
22        BeginThreadDynNamedSpanEvent, BeginThreadNamedSpanEvent, BeginThreadSpanEvent,
23        EndAsyncDynNamedSpanEvent, EndAsyncNamedSpanEvent, EndAsyncSpanEvent,
24        EndThreadDynNamedSpanEvent, EndThreadNamedSpanEvent, EndThreadSpanEvent, SpanLocation,
25        SpanMetadata, TaggedEndAsyncNamedSpanEvent, TaggedEndAsyncSpanEvent,
26        TaggedEndThreadNamedSpanEvent, TaggedEndThreadSpanEvent, ThreadBlock,
27        ThreadEventQueueTypeIndex, ThreadStream,
28    },
29    string_id::DynStringId,
30    warn,
31};
32
33const IMAGE_BUFFER_SIZE: usize = 1024 * 1024;
34use chrono::Utc;
35use std::cell::OnceCell;
36use std::cell::UnsafeCell;
37use std::collections::HashMap;
38use std::fmt;
39use std::sync::RwLock;
40use std::{
41    cell::Cell,
42    sync::{Arc, Mutex, MutexGuard},
43};
44
45pub fn init_event_dispatch(
46    logs_buffer_size: usize,
47    metrics_buffer_size: usize,
48    threads_buffer_size: usize,
49    sink: Arc<dyn EventSink>,
50    process_properties: HashMap<String, String>,
51    cpu_tracing_enabled: bool,
52) -> Result<()> {
53    lazy_static::lazy_static! {
54        static ref INIT_MUTEX: Mutex<()> = Mutex::new(());
55    }
56    let _guard = INIT_MUTEX.lock().unwrap();
57    let dispatch_ref = &G_DISPATCH.inner;
58    unsafe {
59        if (*dispatch_ref.get()).get().is_none() {
60            (*dispatch_ref.get())
61                .set(Dispatch::new(
62                    logs_buffer_size,
63                    metrics_buffer_size,
64                    threads_buffer_size,
65                    sink,
66                    process_properties,
67                    cpu_tracing_enabled,
68                ))
69                .map_err(|_| Error::AlreadyInitialized())
70        } else {
71            info!("event dispatch already initialized");
72            Err(Error::AlreadyInitialized())
73        }
74    }
75}
76
77#[inline]
78pub fn process_id() -> Option<uuid::Uuid> {
79    G_DISPATCH.get().map(Dispatch::get_process_id)
80}
81
82#[inline]
83pub fn cpu_tracing_enabled() -> Option<bool> {
84    G_DISPATCH.get().map(Dispatch::get_cpu_tracing_enabled)
85}
86
87pub fn get_sink() -> Option<Arc<dyn EventSink>> {
88    G_DISPATCH.get().map(Dispatch::get_sink)
89}
90
91pub fn shutdown_dispatch() {
92    G_DISPATCH.get().map(Dispatch::shutdown);
93}
94
95#[inline(always)]
96pub fn int_metric(metric_desc: &'static StaticMetricMetadata, value: u64) {
97    if let Some(d) = G_DISPATCH.get() {
98        d.int_metric(metric_desc, value);
99    }
100}
101
102#[inline(always)]
103pub fn float_metric(metric_desc: &'static StaticMetricMetadata, value: f64) {
104    if let Some(d) = G_DISPATCH.get() {
105        d.float_metric(metric_desc, value);
106    }
107}
108
109#[inline(always)]
110pub fn tagged_float_metric(
111    desc: &'static StaticMetricMetadata,
112    properties: &'static PropertySet,
113    value: f64,
114) {
115    if let Some(d) = G_DISPATCH.get() {
116        d.tagged_float_metric(desc, properties, value);
117    }
118}
119
120#[inline(always)]
121pub fn tagged_integer_metric(
122    desc: &'static StaticMetricMetadata,
123    properties: &'static PropertySet,
124    value: u64,
125) {
126    if let Some(d) = G_DISPATCH.get() {
127        d.tagged_integer_metric(desc, properties, value);
128    }
129}
130
131#[inline(always)]
132pub fn tagged_float_metric_dyn(
133    desc: &'static StaticMetricMetadata,
134    properties: &'static PropertySet,
135    dyn_properties: &[DynProperty<'_>],
136    value: f64,
137) {
138    if let Some(d) = G_DISPATCH.get() {
139        d.tagged_float_metric_dyn(desc, properties, dyn_properties, value);
140    }
141}
142
143#[inline(always)]
144pub fn tagged_integer_metric_dyn(
145    desc: &'static StaticMetricMetadata,
146    properties: &'static PropertySet,
147    dyn_properties: &[DynProperty<'_>],
148    value: u64,
149) {
150    if let Some(d) = G_DISPATCH.get() {
151        d.tagged_integer_metric_dyn(desc, properties, dyn_properties, value);
152    }
153}
154
155/// Logs with an interned property set plus dynamic values.
156#[inline(always)]
157pub fn log_dyn_tagged(
158    desc: &'static LogMetadata,
159    properties: &'static PropertySet,
160    dyn_properties: &[DynProperty<'_>],
161    form: LogMsgForm,
162    args: fmt::Arguments<'_>,
163) {
164    if let Some(d) = G_DISPATCH.get() {
165        d.log_dyn_tagged(desc, properties, dyn_properties, form, args);
166    }
167}
168
169/// A sink that has accepted a log callsite; obtained from `enabled_log_sink`.
170#[doc(hidden)]
171pub struct EnabledLogSink {
172    dispatch: &'static Dispatch,
173    sink: Arc<dyn EventSink>,
174}
175
176/// Fetches the sink once and checks the callsite against it, so that the gated macro arm
177/// neither re-checks nor re-fetches.
178#[doc(hidden)]
179#[inline(always)]
180pub fn enabled_log_sink(desc: &LogMetadata) -> Option<EnabledLogSink> {
181    let dispatch = G_DISPATCH.get()?;
182    let sink = dispatch.get_sink();
183    if sink.on_log_enabled(desc) {
184        Some(EnabledLogSink { dispatch, sink })
185    } else {
186        None
187    }
188}
189
190#[doc(hidden)]
191#[inline(always)]
192pub fn log_dyn_tagged_enabled(
193    sink: EnabledLogSink,
194    desc: &'static LogMetadata,
195    properties: &'static PropertySet,
196    dyn_properties: &[DynProperty<'_>],
197    form: LogMsgForm,
198    args: fmt::Arguments<'_>,
199) {
200    sink.dispatch
201        .log_dyn_tagged_to_sink(&*sink.sink, desc, properties, dyn_properties, form, args);
202}
203
204#[inline(always)]
205pub fn log_interop_dyn_tagged(
206    metadata: &LogMetadata,
207    dyn_properties: &[DynProperty<'_>],
208    args: fmt::Arguments<'_>,
209) {
210    if let Some(d) = G_DISPATCH.get() {
211        d.log_interop_dyn_tagged(metadata, dyn_properties, args);
212    }
213}
214
215#[inline(always)]
216pub fn log(desc: &'static LogMetadata, form: LogMsgForm, args: fmt::Arguments<'_>) {
217    if let Some(d) = G_DISPATCH.get() {
218        d.log(desc, form, args);
219    }
220}
221
222/// Logs with an interned property set only.
223#[inline(always)]
224pub fn log_tagged(
225    desc: &'static LogMetadata,
226    properties: &'static PropertySet,
227    form: LogMsgForm,
228    args: fmt::Arguments<'_>,
229) {
230    if let Some(d) = G_DISPATCH.get() {
231        d.log_tagged(desc, properties, form, args);
232    }
233}
234
235#[inline(always)]
236pub fn log_interop(metadata: &LogMetadata, args: fmt::Arguments<'_>) {
237    if let Some(d) = G_DISPATCH.get() {
238        d.log_interop(metadata, args);
239    }
240}
241
242#[inline(always)]
243pub fn log_enabled(metadata: &LogMetadata) -> bool {
244    if let Some(d) = G_DISPATCH.get() {
245        d.log_enabled(metadata)
246    } else {
247        false
248    }
249}
250
251#[inline(always)]
252pub fn flush_log_buffer() {
253    if let Some(d) = G_DISPATCH.get() {
254        d.flush_log_buffer();
255    }
256}
257
258pub fn send_image(name: &str, format: &str, data: Vec<u8>) {
259    if let Some(d) = G_DISPATCH.get() {
260        d.send_image(name, format, data);
261    }
262}
263
264#[inline(always)]
265pub fn flush_image_buffer() {
266    if let Some(d) = G_DISPATCH.get() {
267        d.flush_image_buffer();
268    }
269}
270
271#[inline(always)]
272pub fn flush_metrics_buffer() {
273    if let Some(d) = G_DISPATCH.get() {
274        d.flush_metrics_buffer();
275    }
276}
277
278//todo: should be implicit by default but limit the maximum number of tracked
279// threads
280#[inline(always)]
281pub fn init_thread_stream() {
282    LOCAL_THREAD_STREAM.with(|cell| unsafe {
283        if (*cell.as_ptr()).is_some() {
284            return;
285        }
286        #[allow(static_mut_refs)]
287        if let Some(d) = G_DISPATCH.get() {
288            // Check if CPU tracing is enabled before creating thread stream
289            if !d.cpu_tracing_enabled {
290                return;
291            }
292            d.init_thread_stream(cell);
293        } else {
294            warn!("dispatch not initialized, cannot init thread stream, events will be lost for this thread");
295        }
296    });
297}
298
299/// Whether the current thread has a registered thread stream, i.e. whether its thread events
300/// are recorded.
301#[inline(always)]
302pub fn has_thread_stream() -> bool {
303    // try_with: a span can be created from another TLS destructor at thread exit, where `with` would panic.
304    LOCAL_THREAD_STREAM
305        .try_with(|cell| unsafe { (*cell.as_ptr()).is_some() })
306        .unwrap_or(false)
307}
308
309pub fn for_each_thread_stream(fun: &mut dyn FnMut(*mut ThreadStream)) {
310    if let Some(d) = G_DISPATCH.get() {
311        d.for_each_thread_stream(fun);
312    }
313}
314
315#[inline(always)]
316pub fn flush_thread_buffer() {
317    LOCAL_THREAD_STREAM.with(|cell| unsafe {
318        let opt_stream = &mut *cell.as_ptr();
319        if let Some(stream) = opt_stream {
320            #[allow(static_mut_refs)]
321            match G_DISPATCH.get() {
322                Some(d) => {
323                    d.flush_thread_buffer(stream);
324                }
325                None => {
326                    panic!("threads are recording but there is no event dispatch");
327                }
328            }
329        }
330    });
331}
332
333/// Unregisters the current thread's stream from the global dispatch to prevent
334/// dangling pointers when the thread is destroyed.
335#[inline(always)]
336pub fn unregister_thread_stream() {
337    LOCAL_THREAD_STREAM.with(|cell| unsafe {
338        let opt_stream = &mut *cell.as_ptr();
339        if let Some(stream) = opt_stream {
340            #[allow(static_mut_refs)]
341            match G_DISPATCH.get() {
342                Some(d) => {
343                    // Flush any remaining events before unregistering
344                    d.flush_thread_buffer(stream);
345                    // Unregister the thread stream
346                    d.unregister_thread_stream(stream);
347                    // Clear the local thread stream
348                    *opt_stream = None;
349                }
350                None => {
351                    // If dispatch is already shut down, just clear the local stream
352                    *opt_stream = None;
353                }
354            }
355        }
356    });
357}
358
359#[inline(always)]
360pub fn on_begin_scope(scope: &'static SpanMetadata) {
361    on_thread_event(BeginThreadSpanEvent {
362        time: now(),
363        thread_span_desc: scope,
364    });
365}
366
367#[inline(always)]
368pub fn on_end_scope(scope: &'static SpanMetadata) {
369    on_thread_event(EndThreadSpanEvent {
370        time: now(),
371        thread_span_desc: scope,
372    });
373}
374
375#[inline(always)]
376pub fn on_begin_named_scope(thread_span_location: &'static SpanLocation, name: &'static str) {
377    on_thread_event(BeginThreadNamedSpanEvent {
378        thread_span_location,
379        name: name.into(),
380        time: now(),
381    });
382}
383
384#[inline(always)]
385pub fn on_end_named_scope(thread_span_location: &'static SpanLocation, name: &'static str) {
386    on_thread_event(EndThreadNamedSpanEvent {
387        thread_span_location,
388        name: name.into(),
389        time: now(),
390    });
391}
392
393#[inline(always)]
394pub fn on_begin_async_scope(scope: &'static SpanMetadata, parent_span_id: u64, depth: u32) -> u64 {
395    let id = G_ASYNC_SPAN_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
396    on_thread_event(BeginAsyncSpanEvent {
397        span_desc: scope,
398        span_id: id as u64,
399        parent_span_id,
400        depth,
401        time: now(),
402    });
403    id as u64
404}
405
406#[inline(always)]
407pub fn on_end_async_scope(
408    span_id: u64,
409    parent_span_id: u64,
410    scope: &'static SpanMetadata,
411    depth: u32,
412) {
413    on_thread_event(EndAsyncSpanEvent {
414        span_desc: scope,
415        span_id,
416        parent_span_id,
417        depth,
418        time: now(),
419    });
420}
421
422#[inline(always)]
423pub fn on_begin_async_named_scope(
424    span_location: &'static SpanLocation,
425    name: &'static str,
426    parent_span_id: u64,
427    depth: u32,
428) -> u64 {
429    let id = G_ASYNC_SPAN_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
430    on_thread_event(BeginAsyncNamedSpanEvent {
431        span_location,
432        name: name.into(),
433        span_id: id as u64,
434        parent_span_id,
435        depth,
436        time: now(),
437    });
438    id as u64
439}
440
441#[inline(always)]
442pub fn on_end_async_named_scope(
443    span_id: u64,
444    parent_span_id: u64,
445    span_location: &'static SpanLocation,
446    name: &'static str,
447    depth: u32,
448) {
449    on_thread_event(EndAsyncNamedSpanEvent {
450        span_location,
451        name: name.into(),
452        span_id,
453        parent_span_id,
454        depth,
455        time: now(),
456    });
457}
458
459/// Like `on_begin_named_scope`, for a name built at runtime. The name is copied into the
460/// current block, so it needs to outlive only this call.
461#[inline(always)]
462pub fn on_begin_named_scope_dyn(thread_span_location: &'static SpanLocation, name: &str) {
463    on_thread_dyn_named_event(name, |name| BeginThreadDynNamedSpanEvent {
464        thread_span_location,
465        name,
466        time: now(),
467    });
468}
469
470/// Like `on_end_named_scope`, for a name built at runtime. The name is written again to the
471/// block that is current now, which may differ from the block of the begin event.
472#[inline(always)]
473pub fn on_end_named_scope_dyn(thread_span_location: &'static SpanLocation, name: &str) {
474    let time = now();
475    on_thread_dyn_named_event(name, |name| EndThreadDynNamedSpanEvent {
476        thread_span_location,
477        name,
478        time,
479    });
480}
481
482/// Like `on_begin_async_named_scope`, for a name built at runtime. The name is copied into the
483/// current block, so it needs to outlive only this call.
484#[inline(always)]
485pub fn on_begin_async_named_scope_dyn(
486    span_location: &'static SpanLocation,
487    name: &str,
488    parent_span_id: u64,
489    depth: u32,
490) -> u64 {
491    let id = G_ASYNC_SPAN_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
492    on_thread_dyn_named_event(name, |name| BeginAsyncDynNamedSpanEvent {
493        span_location,
494        name,
495        span_id: id as u64,
496        parent_span_id,
497        depth,
498        time: now(),
499    });
500    id as u64
501}
502
503/// Like `on_end_async_named_scope`, for a name built at runtime. The name is written again to
504/// the block that is current now, which may differ from the block of the begin event and from
505/// the thread it ran on.
506#[inline(always)]
507pub fn on_end_async_named_scope_dyn(
508    span_id: u64,
509    parent_span_id: u64,
510    span_location: &'static SpanLocation,
511    name: &str,
512    depth: u32,
513) {
514    let time = now();
515    on_thread_dyn_named_event(name, |name| EndAsyncDynNamedSpanEvent {
516        span_location,
517        name,
518        span_id,
519        parent_span_id,
520        depth,
521        time,
522    });
523}
524
525/// Ends a thread span with properties: `properties` plus `dyn_properties`, the latter winning
526/// on a name clash. Without any, it is the plain end event.
527#[inline(always)]
528pub fn on_end_scope_tagged(
529    scope: &'static SpanMetadata,
530    properties: &'static PropertySet,
531    dyn_properties: &[DynProperty<'_>],
532) {
533    if properties.get_properties().is_empty() && dyn_properties.is_empty() {
534        return on_end_scope(scope);
535    }
536    let time = now();
537    on_thread_tagged_event(properties, dyn_properties, |properties| {
538        TaggedEndThreadSpanEvent {
539            thread_span_desc: scope,
540            properties,
541            time,
542        }
543    });
544}
545
546/// Like `on_end_scope_tagged`, for a named span. The name is written to the block that is
547/// current now.
548#[inline(always)]
549pub fn on_end_named_scope_tagged(
550    thread_span_location: &'static SpanLocation,
551    name: &str,
552    properties: &'static PropertySet,
553    dyn_properties: &[DynProperty<'_>],
554) {
555    if properties.get_properties().is_empty() && dyn_properties.is_empty() {
556        return on_end_named_scope_dyn(thread_span_location, name);
557    }
558    let time = now();
559    on_thread_tagged_named_event(name, properties, dyn_properties, |name, properties| {
560        TaggedEndThreadNamedSpanEvent {
561            thread_span_location,
562            name,
563            properties,
564            time,
565        }
566    });
567}
568
569/// Like `on_end_async_scope`, with the properties of `on_end_scope_tagged`.
570#[inline(always)]
571pub fn on_end_async_scope_tagged(
572    span_id: u64,
573    parent_span_id: u64,
574    scope: &'static SpanMetadata,
575    depth: u32,
576    properties: &'static PropertySet,
577    dyn_properties: &[DynProperty<'_>],
578) {
579    if properties.get_properties().is_empty() && dyn_properties.is_empty() {
580        return on_end_async_scope(span_id, parent_span_id, scope, depth);
581    }
582    let time = now();
583    on_thread_tagged_event(properties, dyn_properties, |properties| {
584        TaggedEndAsyncSpanEvent {
585            span_desc: scope,
586            properties,
587            span_id,
588            parent_span_id,
589            depth,
590            time,
591        }
592    });
593}
594
595/// Like `on_end_async_named_scope`, with the properties of `on_end_scope_tagged`. The name is
596/// written to the block that is current now, which may differ from the block of the begin event.
597#[inline(always)]
598pub fn on_end_async_named_scope_tagged(
599    span_id: u64,
600    parent_span_id: u64,
601    span_location: &'static SpanLocation,
602    name: &str,
603    depth: u32,
604    properties: &'static PropertySet,
605    dyn_properties: &[DynProperty<'_>],
606) {
607    if properties.get_properties().is_empty() && dyn_properties.is_empty() {
608        return on_end_async_named_scope_dyn(span_id, parent_span_id, span_location, name, depth);
609    }
610    let time = now();
611    on_thread_tagged_named_event(name, properties, dyn_properties, |name, properties| {
612        TaggedEndAsyncNamedSpanEvent {
613            span_location,
614            name,
615            properties,
616            span_id,
617            parent_span_id,
618            depth,
619            time,
620        }
621    });
622}
623
624pub struct DispatchCell {
625    // unsafecell is only necessary for force_uninit()
626    inner: UnsafeCell<OnceCell<Dispatch>>,
627}
628
629impl DispatchCell {
630    const fn new() -> Self {
631        Self {
632            inner: UnsafeCell::new(OnceCell::new()),
633        }
634    }
635
636    fn get(&self) -> Option<&Dispatch> {
637        unsafe { (*self.inner.get()).get() }
638    }
639
640    unsafe fn take(&self) -> Option<Dispatch> {
641        unsafe { (*self.inner.get()).take() }
642    }
643}
644
645// very unsafe indeed - we don't want to pay for locking every time we need to record an event
646unsafe impl Sync for DispatchCell {}
647
648static G_DISPATCH: DispatchCell = DispatchCell::new();
649static G_ASYNC_SPAN_COUNTER: std::sync::atomic::AtomicUsize =
650    std::sync::atomic::AtomicUsize::new(1);
651
652/// # Safety
653/// very unsafe! make sure there is no thread running that could be sending events
654/// normally that global state should not be destroyed
655pub unsafe fn force_uninit() {
656    unsafe {
657        G_DISPATCH.take();
658    }
659}
660
661thread_local! {
662    static LOCAL_THREAD_STREAM: Cell<Option<ThreadStream>> = const { Cell::new(None) };
663}
664
665#[inline(always)]
666fn on_thread_event<T>(event: T)
667where
668    T: micromegas_transit::InProcSerialize + ThreadEventQueueTypeIndex,
669{
670    LOCAL_THREAD_STREAM.with(|cell| unsafe {
671        let opt_stream = &mut *cell.as_ptr();
672        if let Some(stream) = opt_stream {
673            stream.get_events_mut().push(event);
674            if stream.is_full() {
675                flush_thread_buffer();
676            }
677        }
678    });
679}
680
681#[inline(always)]
682fn on_thread_dyn_named_event<T>(name: &str, make: impl FnOnce(DynStringId) -> T)
683where
684    T: micromegas_transit::InProcSerialize + ThreadEventQueueTypeIndex,
685{
686    LOCAL_THREAD_STREAM.with(|cell| unsafe {
687        let opt_stream = &mut *cell.as_ptr();
688        if let Some(stream) = opt_stream {
689            stream.push_dyn_named(name, make);
690            if stream.is_full() {
691                flush_thread_buffer();
692            }
693        }
694    });
695}
696
697#[inline(always)]
698fn on_thread_tagged_event<T>(
699    properties: &'static PropertySet,
700    dyn_properties: &[DynProperty<'_>],
701    make: impl FnOnce(PropertySetId) -> T,
702) where
703    T: micromegas_transit::InProcSerialize + ThreadEventQueueTypeIndex,
704{
705    LOCAL_THREAD_STREAM.with(|cell| unsafe {
706        let opt_stream = &mut *cell.as_ptr();
707        if let Some(stream) = opt_stream {
708            stream.push_tagged(properties, dyn_properties, make);
709            if stream.is_full() {
710                flush_thread_buffer();
711            }
712        }
713    });
714}
715
716#[inline(always)]
717fn on_thread_tagged_named_event<T>(
718    name: &str,
719    properties: &'static PropertySet,
720    dyn_properties: &[DynProperty<'_>],
721    make: impl FnOnce(DynStringId, PropertySetId) -> T,
722) where
723    T: micromegas_transit::InProcSerialize + ThreadEventQueueTypeIndex,
724{
725    LOCAL_THREAD_STREAM.with(|cell| unsafe {
726        let opt_stream = &mut *cell.as_ptr();
727        if let Some(stream) = opt_stream {
728            stream.push_tagged_named(name, properties, dyn_properties, make);
729            if stream.is_full() {
730                flush_thread_buffer();
731            }
732        }
733    });
734}
735
736struct Dispatch {
737    process_id: uuid::Uuid,
738    logs_buffer_size: usize,
739    metrics_buffer_size: usize,
740    threads_buffer_size: usize,
741    cpu_tracing_enabled: bool,
742    image_stream: Mutex<ImageStream>,
743    log_stream: Mutex<LogStream>,
744    metrics_stream: Mutex<MetricsStream>,
745    thread_streams: Mutex<Vec<*mut ThreadStream>>, // very very unsafe - threads would need to be unregistered before they are destroyed
746    sink: RwLock<Arc<dyn EventSink>>,
747}
748
749impl Dispatch {
750    pub fn new(
751        logs_buffer_size: usize,
752        metrics_buffer_size: usize,
753        threads_buffer_size: usize,
754        sink: Arc<dyn EventSink>,
755        process_properties: HashMap<String, String>,
756        cpu_tracing_enabled: bool,
757    ) -> Self {
758        let process_id = uuid::Uuid::new_v4();
759        let obj = Self {
760            process_id,
761            logs_buffer_size,
762            metrics_buffer_size,
763            threads_buffer_size,
764            cpu_tracing_enabled,
765            image_stream: Mutex::new(ImageStream::new(
766                IMAGE_BUFFER_SIZE,
767                process_id,
768                &[String::from("image")],
769                HashMap::new(),
770            )),
771            log_stream: Mutex::new(LogStream::new(
772                logs_buffer_size,
773                process_id,
774                &[String::from("log")],
775                HashMap::new(),
776            )),
777            metrics_stream: Mutex::new(MetricsStream::new(
778                metrics_buffer_size,
779                process_id,
780                &[String::from("metrics")],
781                HashMap::new(),
782            )),
783            thread_streams: Mutex::new(vec![]),
784            sink: RwLock::new(sink),
785        };
786        obj.startup(process_properties);
787        obj.init_image_stream();
788        obj.init_log_stream();
789        obj.init_metrics_stream();
790        obj
791    }
792
793    pub fn get_process_id(&self) -> uuid::Uuid {
794        self.process_id
795    }
796
797    pub fn get_cpu_tracing_enabled(&self) -> bool {
798        self.cpu_tracing_enabled
799    }
800
801    pub fn get_sink(&self) -> Arc<dyn EventSink> {
802        if let Ok(guard) = self.sink.try_read() {
803            (*guard).clone()
804        } else {
805            Arc::new(NullEventSink {})
806        }
807    }
808
809    fn shutdown(&self) {
810        let old_sink = self.get_sink();
811        let null_sink = Arc::new(NullEventSink {});
812        if let Ok(mut guard) = self.sink.write() {
813            *guard = null_sink;
814            drop(guard)
815        }
816        old_sink.on_shutdown();
817    }
818
819    fn startup(&self, process_properties: HashMap<String, String>) {
820        let mut parent_process = None;
821
822        if let Ok(parent_process_guid) = std::env::var("MICROMEGAS_TELEMETRY_PARENT_PROCESS")
823            && let Ok(parent_process_id) = uuid::Uuid::try_parse(&parent_process_guid)
824        {
825            parent_process = Some(parent_process_id);
826        }
827
828        unsafe {
829            std::env::set_var(
830                "MICROMEGAS_TELEMETRY_PARENT_PROCESS",
831                self.process_id.to_string(),
832            );
833        }
834
835        let process_info = Arc::new(make_process_info(
836            self.process_id,
837            parent_process,
838            process_properties,
839        ));
840
841        self.get_sink().on_startup(process_info);
842    }
843
844    fn init_log_stream(&self) {
845        let log_stream = self.log_stream.lock().unwrap();
846        self.get_sink().on_init_log_stream(&log_stream);
847    }
848
849    fn init_image_stream(&self) {
850        let image_stream = self.image_stream.lock().expect("image_stream lock");
851        self.get_sink().on_init_image_stream(&image_stream);
852    }
853
854    fn init_metrics_stream(&self) {
855        let metrics_stream = self.metrics_stream.lock().unwrap();
856        self.get_sink().on_init_metrics_stream(&metrics_stream);
857    }
858
859    pub fn send_image(&self, name: &str, format: &str, data: Vec<u8>) {
860        let time = now();
861        let mut image_stream = self.image_stream.lock().expect("image_stream lock");
862        image_stream.get_events_mut().push(ImageEvent {
863            time,
864            name: micromegas_transit::DynString(name.to_owned()),
865            format: micromegas_transit::DynString(format.to_owned()),
866            data: micromegas_transit::DynBlob(data),
867        });
868        if image_stream.is_full() {
869            drop(image_stream);
870            self.flush_image_buffer();
871        }
872    }
873
874    fn flush_image_buffer(&self) {
875        let mut image_stream = self.image_stream.lock().expect("image_stream lock");
876        if image_stream.is_empty() {
877            return;
878        }
879        let stream_id = image_stream.stream_id();
880        let next_offset = image_stream.get_block_ref().object_offset()
881            + image_stream.get_block_ref().nb_objects();
882        let new_block = Arc::new(ImageBlock::new(
883            IMAGE_BUFFER_SIZE,
884            self.process_id,
885            stream_id,
886            next_offset,
887        ));
888        let begin = new_block.begin;
889        let mut old_event_block = image_stream.replace_block(new_block);
890        assert!(!image_stream.is_full());
891        Arc::get_mut(&mut old_event_block)
892            .expect("image block exclusive ref")
893            .close_at(begin);
894        drop(image_stream);
895        self.get_sink().on_process_image_block(old_event_block);
896    }
897
898    fn init_thread_stream(&self, cell: &Cell<Option<ThreadStream>>) {
899        // Early return if CPU tracing is disabled
900        if !self.cpu_tracing_enabled {
901            return;
902        }
903
904        let mut properties = HashMap::new();
905        properties.insert(String::from("thread-id"), thread_id::get().to_string());
906        if let Some(name) = std::thread::current().name() {
907            properties.insert("thread-name".to_owned(), name.to_owned());
908        }
909        let thread_stream = ThreadStream::new(
910            self.threads_buffer_size,
911            self.process_id,
912            &["cpu".to_owned()],
913            properties,
914        );
915        unsafe {
916            let opt_ref = &mut *cell.as_ptr();
917            self.get_sink().on_init_thread_stream(&thread_stream);
918            *opt_ref = Some(thread_stream);
919            let mut vec_guard = self.thread_streams.lock().unwrap();
920            vec_guard.push(opt_ref.as_mut().unwrap());
921        }
922    }
923
924    fn for_each_thread_stream(&self, fun: &mut dyn FnMut(*mut ThreadStream)) {
925        let mut vec_guard = self.thread_streams.lock().unwrap();
926        for stream in &mut *vec_guard {
927            fun(*stream);
928        }
929    }
930
931    fn unregister_thread_stream(&self, stream_to_remove: &mut ThreadStream) {
932        let mut vec_guard = self.thread_streams.lock().unwrap();
933        let stream_ptr = stream_to_remove as *mut ThreadStream;
934
935        // Find and remove the thread stream pointer from the vector
936        if let Some(pos) = vec_guard.iter().position(|&ptr| ptr == stream_ptr) {
937            vec_guard.remove(pos);
938        }
939    }
940
941    #[inline]
942    fn int_metric(&self, desc: &'static StaticMetricMetadata, value: u64) {
943        let time = now();
944        let mut metrics_stream = self.metrics_stream.lock().unwrap();
945        metrics_stream
946            .get_events_mut()
947            .push(IntegerMetricEvent { desc, value, time });
948        self.on_metrics_pushed(metrics_stream);
949    }
950
951    #[inline]
952    fn float_metric(&self, desc: &'static StaticMetricMetadata, value: f64) {
953        let time = now();
954        let mut metrics_stream = self.metrics_stream.lock().unwrap();
955        metrics_stream
956            .get_events_mut()
957            .push(FloatMetricEvent { desc, value, time });
958        self.on_metrics_pushed(metrics_stream);
959    }
960
961    #[inline]
962    fn tagged_float_metric(
963        &self,
964        desc: &'static StaticMetricMetadata,
965        properties: &'static PropertySet,
966        value: f64,
967    ) {
968        let time = now();
969        let mut metrics_stream = self.metrics_stream.lock().unwrap();
970        metrics_stream
971            .get_events_mut()
972            .push(TaggedFloatMetricEvent {
973                desc,
974                properties: PropertySetId::interned(properties),
975                value,
976                time,
977            });
978        self.on_metrics_pushed(metrics_stream);
979    }
980
981    #[inline]
982    fn tagged_integer_metric(
983        &self,
984        desc: &'static StaticMetricMetadata,
985        properties: &'static PropertySet,
986        value: u64,
987    ) {
988        let time = now();
989        let mut metrics_stream = self.metrics_stream.lock().unwrap();
990        metrics_stream
991            .get_events_mut()
992            .push(TaggedIntegerMetricEvent {
993                desc,
994                properties: PropertySetId::interned(properties),
995                value,
996                time,
997            });
998        self.on_metrics_pushed(metrics_stream);
999    }
1000
1001    #[inline]
1002    fn tagged_float_metric_dyn(
1003        &self,
1004        desc: &'static StaticMetricMetadata,
1005        properties: &'static PropertySet,
1006        dyn_properties: &[DynProperty<'_>],
1007        value: f64,
1008    ) {
1009        if dyn_properties.is_empty() {
1010            return self.tagged_float_metric(desc, properties, value);
1011        }
1012        let time = now();
1013        let merged = merge_properties(properties, dyn_properties);
1014        let mut metrics_stream = self.metrics_stream.lock().unwrap();
1015        let (events, dyn_deps) = metrics_stream.get_block_mut_parts();
1016        let properties = dyn_deps.intern_set(&merged);
1017        events.push(TaggedFloatMetricEvent {
1018            desc,
1019            properties,
1020            value,
1021            time,
1022        });
1023        self.on_metrics_pushed(metrics_stream);
1024    }
1025
1026    #[inline]
1027    fn tagged_integer_metric_dyn(
1028        &self,
1029        desc: &'static StaticMetricMetadata,
1030        properties: &'static PropertySet,
1031        dyn_properties: &[DynProperty<'_>],
1032        value: u64,
1033    ) {
1034        if dyn_properties.is_empty() {
1035            return self.tagged_integer_metric(desc, properties, value);
1036        }
1037        let time = now();
1038        let merged = merge_properties(properties, dyn_properties);
1039        let mut metrics_stream = self.metrics_stream.lock().unwrap();
1040        let (events, dyn_deps) = metrics_stream.get_block_mut_parts();
1041        let properties = dyn_deps.intern_set(&merged);
1042        events.push(TaggedIntegerMetricEvent {
1043            desc,
1044            properties,
1045            value,
1046            time,
1047        });
1048        self.on_metrics_pushed(metrics_stream);
1049    }
1050
1051    #[inline]
1052    fn on_metrics_pushed(&self, mut metrics_stream: MutexGuard<'_, MetricsStream>) {
1053        if !metrics_stream.is_full() {
1054            return;
1055        }
1056        // Swapped in the critical section that filled the block, so no other thread can push
1057        // into it past the size margin or flush it a second time.
1058        let old_block = swap_block(
1059            &mut metrics_stream,
1060            self.metrics_buffer_size,
1061            self.process_id,
1062        );
1063        drop(metrics_stream);
1064        self.get_sink().on_process_metrics_block(old_block);
1065    }
1066
1067    #[inline]
1068    fn flush_metrics_buffer(&self) {
1069        let mut metrics_stream = self.metrics_stream.lock().unwrap();
1070        if metrics_stream.is_empty() {
1071            return;
1072        }
1073        let old_block = swap_block(
1074            &mut metrics_stream,
1075            self.metrics_buffer_size,
1076            self.process_id,
1077        );
1078        drop(metrics_stream);
1079        self.get_sink().on_process_metrics_block(old_block);
1080    }
1081
1082    fn log_enabled(&self, metadata: &LogMetadata) -> bool {
1083        self.get_sink().on_log_enabled(metadata)
1084    }
1085
1086    #[inline]
1087    fn log(&self, metadata: &'static LogMetadata, form: LogMsgForm, args: fmt::Arguments<'_>) {
1088        let sink = self.get_sink();
1089        if !sink.on_log_enabled(metadata) {
1090            return;
1091        }
1092        let time = now();
1093        sink.on_log(metadata, &[], time, args);
1094        let msg = match form {
1095            LogMsgForm::Static => None,
1096            // Untagged calls have no properties to render from.
1097            LogMsgForm::Template | LogMsgForm::Formatted => {
1098                Some(micromegas_transit::DynString(args.to_string()))
1099            }
1100        };
1101        let mut log_stream = self.log_stream.lock().unwrap();
1102        match msg {
1103            None => log_stream.get_events_mut().push(LogStaticStrEvent {
1104                desc: metadata,
1105                time,
1106            }),
1107            Some(msg) => log_stream.get_events_mut().push(LogStringEvent {
1108                desc: metadata,
1109                time,
1110                msg,
1111            }),
1112        }
1113        self.on_log_pushed(log_stream);
1114    }
1115
1116    #[inline]
1117    fn log_tagged(
1118        &self,
1119        desc: &'static LogMetadata,
1120        properties: &'static PropertySet,
1121        form: LogMsgForm,
1122        args: fmt::Arguments<'_>,
1123    ) {
1124        let sink = self.get_sink();
1125        if !sink.on_log_enabled(desc) {
1126            return;
1127        }
1128        self.log_tagged_to_sink(&*sink, desc, properties, form, args);
1129    }
1130
1131    #[inline]
1132    fn log_tagged_to_sink(
1133        &self,
1134        sink: &dyn EventSink,
1135        desc: &'static LogMetadata,
1136        properties: &'static PropertySet,
1137        form: LogMsgForm,
1138        args: fmt::Arguments<'_>,
1139    ) {
1140        let time = now();
1141        sink.on_log(desc, properties.dyn_properties(), time, args);
1142        let properties = PropertySetId::interned(properties);
1143        let mut log_stream = self.log_stream.lock().unwrap();
1144        let events = log_stream.get_events_mut();
1145        match form {
1146            LogMsgForm::Static => events.push(TaggedLogStaticStrEvent {
1147                desc,
1148                properties,
1149                time,
1150            }),
1151            LogMsgForm::Template => events.push(TaggedLogTemplateEvent {
1152                desc,
1153                properties,
1154                time,
1155            }),
1156            LogMsgForm::Formatted => events.push(TaggedLogString {
1157                desc,
1158                properties,
1159                time,
1160                msg: micromegas_transit::DynString(args.to_string()),
1161            }),
1162        }
1163        self.on_log_pushed(log_stream);
1164    }
1165
1166    #[inline]
1167    fn log_interop(&self, desc: &LogMetadata, args: fmt::Arguments<'_>) {
1168        let time = now();
1169        self.get_sink().on_log(desc, &[], time, args);
1170        let msg = args
1171            .as_str()
1172            .ok_or_else(|| micromegas_transit::DynString(args.to_string()));
1173        let mut log_stream = self.log_stream.lock().unwrap();
1174        let (events, dyn_deps) = log_stream.get_block_mut_parts();
1175        match msg {
1176            Ok(static_msg) => {
1177                let id = dyn_deps.intern_str(desc.target);
1178                events.push(LogStaticStrInteropEventV2 {
1179                    time,
1180                    level: desc.level as u32,
1181                    target: DynStringId { id },
1182                    msg: static_msg.into(),
1183                });
1184            }
1185            Err(msg) => {
1186                let target = dyn_deps.intern_str_ref(desc.target);
1187                events.push(LogStringInteropEvent {
1188                    time,
1189                    level: desc.level as u8,
1190                    target,
1191                    msg,
1192                });
1193            }
1194        }
1195        self.on_log_pushed(log_stream);
1196    }
1197
1198    #[inline]
1199    fn log_dyn_tagged(
1200        &self,
1201        desc: &'static LogMetadata,
1202        properties: &'static PropertySet,
1203        dyn_properties: &[DynProperty<'_>],
1204        form: LogMsgForm,
1205        args: fmt::Arguments<'_>,
1206    ) {
1207        let sink = self.get_sink();
1208        if !sink.on_log_enabled(desc) {
1209            return;
1210        }
1211        self.log_dyn_tagged_to_sink(&*sink, desc, properties, dyn_properties, form, args);
1212    }
1213
1214    #[inline]
1215    fn log_dyn_tagged_to_sink(
1216        &self,
1217        sink: &dyn EventSink,
1218        desc: &'static LogMetadata,
1219        properties: &'static PropertySet,
1220        dyn_properties: &[DynProperty<'_>],
1221        form: LogMsgForm,
1222        args: fmt::Arguments<'_>,
1223    ) {
1224        if dyn_properties.is_empty() {
1225            return self.log_tagged_to_sink(sink, desc, properties, form, args);
1226        }
1227        let time = now();
1228        let merged = merge_properties(properties, dyn_properties);
1229        // Before taking the lock, so that local sinks can log without deadlocking.
1230        sink.on_log(desc, merged.properties(), time, args);
1231        let mut log_stream = self.log_stream.lock().unwrap();
1232        let (events, dyn_deps) = log_stream.get_block_mut_parts();
1233        let properties = dyn_deps.intern_set(&merged);
1234        match form {
1235            LogMsgForm::Static => events.push(TaggedLogStaticStrEvent {
1236                desc,
1237                properties,
1238                time,
1239            }),
1240            LogMsgForm::Template => events.push(TaggedLogTemplateEvent {
1241                desc,
1242                properties,
1243                time,
1244            }),
1245            LogMsgForm::Formatted => events.push(TaggedLogString {
1246                desc,
1247                properties,
1248                time,
1249                msg: micromegas_transit::DynString(args.to_string()),
1250            }),
1251        }
1252        self.on_log_pushed(log_stream);
1253    }
1254
1255    #[inline]
1256    fn log_interop_dyn_tagged(
1257        &self,
1258        desc: &LogMetadata,
1259        dyn_properties: &[DynProperty<'_>],
1260        args: fmt::Arguments<'_>,
1261    ) {
1262        let time = now();
1263        let merged = merge_properties(PropertySet::empty(), dyn_properties);
1264        // Sinks treat `target`/`level` properties as overrides; interop logs must keep their own.
1265        let is_override = |p: &DynProperty<'_>| {
1266            p.name().eq_ignore_ascii_case("target") || p.name().eq_ignore_ascii_case("level")
1267        };
1268        if merged.properties().iter().any(is_override) {
1269            let filtered: Vec<DynProperty<'_>> = merged
1270                .properties()
1271                .iter()
1272                .copied()
1273                .filter(|p| !is_override(p))
1274                .collect();
1275            self.get_sink().on_log(desc, &filtered, time, args);
1276        } else {
1277            self.get_sink()
1278                .on_log(desc, merged.properties(), time, args);
1279        }
1280        let msg = micromegas_transit::DynString(args.to_string());
1281        let mut log_stream = self.log_stream.lock().unwrap();
1282        let (events, dyn_deps) = log_stream.get_block_mut_parts();
1283        let target = dyn_deps.intern_str_ref(desc.target);
1284        let properties = dyn_deps.intern_set(&merged);
1285        events.push(TaggedLogInteropEvent {
1286            time,
1287            level: desc.level as u8,
1288            target,
1289            properties,
1290            msg,
1291        });
1292        self.on_log_pushed(log_stream);
1293    }
1294
1295    #[inline]
1296    fn on_log_pushed(&self, mut log_stream: MutexGuard<'_, LogStream>) {
1297        if !log_stream.is_full() {
1298            return;
1299        }
1300        let old_block = swap_block(&mut log_stream, self.logs_buffer_size, self.process_id);
1301        drop(log_stream);
1302        self.get_sink().on_process_log_block(old_block);
1303    }
1304
1305    #[inline]
1306    fn flush_log_buffer(&self) {
1307        let mut log_stream = self.log_stream.lock().unwrap();
1308        if log_stream.is_empty() {
1309            return;
1310        }
1311        let old_block = swap_block(&mut log_stream, self.logs_buffer_size, self.process_id);
1312        drop(log_stream);
1313        self.get_sink().on_process_log_block(old_block);
1314    }
1315
1316    #[inline]
1317    fn flush_thread_buffer(&self, stream: &mut ThreadStream) {
1318        if stream.is_empty() {
1319            return;
1320        }
1321        let next_offset =
1322            stream.get_block_ref().object_offset() + stream.get_block_ref().nb_objects();
1323        let new_block = Arc::new(ThreadBlock::new(
1324            self.threads_buffer_size,
1325            self.process_id,
1326            stream.stream_id(),
1327            next_offset,
1328        ));
1329        let begin = new_block.begin;
1330        let mut old_block = stream.replace_block(new_block);
1331        assert!(!stream.is_full());
1332        Arc::get_mut(&mut old_block).unwrap().close_at(begin);
1333        self.get_sink().on_process_thread_block(old_block);
1334    }
1335}
1336
1337/// Replaces the stream's current block with an empty one and returns the closed old block.
1338///
1339/// Must be called with the stream locked: `begin` is stamped here so that consecutive blocks
1340/// stay contiguous.
1341fn swap_block<Q>(
1342    stream: &mut EventStream<EventBlock<Q>>,
1343    buffer_size: usize,
1344    process_id: uuid::Uuid,
1345) -> Arc<EventBlock<Q>>
1346where
1347    Q: micromegas_transit::HeterogeneousQueue + ExtractDeps,
1348    EventBlock<Q>: TracingBlock,
1349{
1350    let stream_id = stream.stream_id();
1351    let next_offset = stream.get_block_ref().object_offset() + stream.get_block_ref().nb_objects();
1352    let new_block = Arc::new(EventBlock::<Q>::new(
1353        buffer_size,
1354        process_id,
1355        stream_id,
1356        next_offset,
1357    ));
1358    let begin = new_block.begin;
1359    let mut old_block = stream.replace_block(new_block);
1360    assert!(!stream.is_full());
1361    Arc::get_mut(&mut old_block).unwrap().close_at(begin);
1362    old_block
1363}
1364
1365pub fn make_process_info(
1366    process_id: uuid::Uuid,
1367    parent_process_id: Option<uuid::Uuid>,
1368    properties: HashMap<String, String>,
1369) -> ProcessInfo {
1370    let start_ticks = now();
1371    let start_time = Utc::now();
1372    let cpu_brand = crate::cpu_brand::get_cpu_brand();
1373    ProcessInfo {
1374        process_id,
1375        username: whoami::username(),
1376        realname: whoami::realname(),
1377        exe: std::env::current_exe()
1378            .unwrap_or_default()
1379            .to_string_lossy()
1380            .into_owned(),
1381        computer: whoami::devicename(),
1382        distro: whoami::distro(),
1383        cpu_brand,
1384        tsc_frequency: frequency(),
1385        start_time,
1386        start_ticks,
1387        parent_process_id,
1388        properties,
1389    }
1390}