Skip to main content

feldera_samply/
lib.rs

1//! Annotations for Firefox Profiler profiles.
2//!
3//! [Firefox Profiler] can display user-defined annotations for timespans and
4//! events, as well as information about network activity and memory use, but
5//! only if the profiler added those annotations.  The popular [samply]
6//! profiler, however, has only very limited support for adding these
7//! annotations.  This crate provides a way for a process that is being profiled
8//! to record its own annotations and then merge them into profiler output in a
9//! postprocessing step.
10//!
11//! # Use
12//!
13//! This crate can be integrated into an existing profiler workflow.  For
14//! example, the [Feldera incremental compute engine] runs `samply` as a
15//! subprocess, targeting itself.  While `samply` runs, Feldera uses [Capture],
16//! [Span], and [Event] to record annotations.  After `samply` completes,
17//! Feldera finishes the capture to obtain [Annotations], applies them, and then
18//! passes the postprocessed output to the user.  The annotation step is
19//! invisible to the user.
20//!
21//! Short of this kind of integration, where a process effectively profiles
22//! itself, there must be some way to enable capturing and saving profile data.
23//! For example, a command-line option or an environment variable could do the
24//! trick.  Once the capture is complete, the process needs to somehow save the
25//! annotations.
26//!
27//! # Viewing in Firefox Profiler
28//!
29//! Spans and events logged by this module show up in the Marker Chart and
30//! Marker Table tabs for a given thread. They are linked to particular threads
31//! and the profiler will only show them when those threads are selected.
32//!
33//! Spans and events are enabled only when a profile is running.  They have
34//! minimal overhead otherwise.
35//!
36//! [samply]: https://github.com/mstange/samply?tab=readme-ov-file#samply
37//! [Firefox Profiler]: https://profiler.firefox.com/
38//! [Feldera incremental compute engine]: https://feldera.com
39#![warn(missing_docs)]
40use std::{
41    borrow::Cow,
42    collections::{HashMap, HashSet},
43    fmt::{Debug, Display},
44    io::{Cursor, Read},
45    iter::{once, repeat_n},
46    sync::{
47        Arc,
48        atomic::{AtomicBool, AtomicI64, Ordering},
49    },
50    thread::JoinHandle,
51    time::{Duration, Instant},
52};
53
54use crossbeam::sync::{Parker, Unparker};
55use flate2::{
56    Compression,
57    bufread::{GzDecoder, GzEncoder},
58};
59use itertools::Itertools;
60use memory_stats::memory_stats;
61use nix::time::{ClockId, clock_gettime};
62use serde::{Deserialize, Serialize};
63use serde_json::{Value, json};
64use size_of::HumanBytes;
65use tracing::warn;
66
67#[derive(Copy, Clone, Debug)]
68struct Timestamp(
69    /// In nanoseconds in terms of `CLOCK_MONOTONIC`.
70    i64,
71);
72
73impl Timestamp {
74    fn now() -> Self {
75        let now = clock_gettime(ClockId::CLOCK_MONOTONIC).unwrap();
76        Self(now.tv_sec() as i64 * 1_000_000_000 + now.tv_nsec() as i64)
77    }
78}
79
80impl From<Instant> for Timestamp {
81    fn from(value: Instant) -> Self {
82        // SAFETY: On Unix, `Instant` is implemented using CLOCK_MONOTONIC,
83        // which is the clock that we need to use for the profiler, but the Rust
84        // standard library provides no way to get the value out.  We don't want
85        // to make assumptions about the layout of [Instant], and in fact it is
86        // not defined as libc's struct timespec but different and
87        // Rust-specific.  If we just transmute then we get the wrong value.  It
88        // seems rather safer to assume that the all-bytes-zeros `Instant` is
89        // the origin, and it works OK for now at least.
90        //
91        // The completely safe alternative would be to make Timestamp public and
92        // force clients to always get both a Timestamp and an Instant if they
93        // need both, which is wasteful.
94        let zero = unsafe { std::mem::zeroed::<Instant>() };
95        Self((value - zero).as_nanos() as i64)
96    }
97}
98
99impl Display for Timestamp {
100    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
101        write!(f, "{}", self.0)
102    }
103}
104
105impl Serialize for Timestamp {
106    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
107    where
108        S: serde::Serializer,
109    {
110        let microseconds = self.0 as f64 / 1_000_000.0;
111        microseconds.serialize(serializer)
112    }
113}
114
115impl<'de> Deserialize<'de> for Timestamp {
116    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
117    where
118        D: serde::Deserializer<'de>,
119    {
120        let microseconds = f64::deserialize(deserializer)?;
121        Ok(Self((microseconds * 1_000_000.0) as i64))
122    }
123}
124
125impl Debug for Span {
126    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
127        write!(f, "Span")?;
128        if let Some(inner) = &self.0 {
129            write!(f, "({})", &inner.name)?;
130        }
131        Ok(())
132    }
133}
134
135struct SpanInner {
136    start: Timestamp,
137    category: &'static str,
138    name: &'static str,
139    tooltip: String,
140}
141
142impl SpanInner {
143    #[cold]
144    fn new(name: &'static str) -> Self {
145        Self {
146            start: Timestamp::now(),
147            category: "Other",
148            name,
149            tooltip: String::new(),
150        }
151    }
152
153    #[cold]
154    fn record(self, is_span: bool) {
155        let marker = Marker {
156            start: self.start,
157            end: if is_span {
158                Timestamp::now()
159            } else {
160                self.start
161            },
162            category: self.category,
163            name: self.name,
164            tooltip: self.tooltip,
165        };
166        QUEUE.with(|queue| queue.push(marker));
167    }
168}
169
170/// Annotates a timespan during a [Capture].
171///
172/// Constructing and dropping a [Span], when marker spans are being captured
173/// with [Capture], records the start and end times of the [Span] along with a
174/// name, category, and tooltip.
175///
176/// `Span` is for timespans.  Use [Event] for point-in-time events.
177///
178/// When [Capture] is not active, `Span` has minimal overhead.
179///
180/// [samply]: https://github.com/mstange/samply?tab=readme-ov-file#samply
181pub struct Span(Option<SpanInner>);
182
183impl Span {
184    /// The number of bytes of memory used during capture to record a [Span] or
185    /// [Event].
186    pub const BYTES: usize = std::mem::size_of::<Marker>();
187
188    /// Constructs a new [Span] with the given name.  When the constructed
189    /// span is dropped, it is automatically recorded.
190    ///
191    /// [Span] does nothing when markers are not being captured.  A span
192    /// will be recorded in a profile only if markers were being captured both
193    /// when it was created and when it was dropped.
194    ///
195    /// The name should ordinarily be a short static string indicating what
196    /// happens during the span.  The Firefox Profiler's marker chart view shows
197    /// all the spans in a thread with the same name and category on a single
198    /// horizontal timeline (unless that would cause overlaps).
199    #[must_use]
200    pub fn new(name: &'static str) -> Self {
201        Self(Capture::is_active().then(|| SpanInner::new(name)))
202    }
203
204    /// Adds `category` to this span.
205    ///
206    /// The Firefox Profiler's marker chart view groups the markers in each
207    /// category and labels them with the category name.
208    ///
209    /// The default category is "Other".
210    #[must_use]
211    pub fn with_category(mut self, category: &'static str) -> Self {
212        if let Some(inner) = &mut self.0 {
213            inner.category = category;
214        }
215        self
216    }
217
218    /// Evaluates `tooltip` and adds it to this span.
219    ///
220    /// The Firefox Profiler shows the given tooltip in the marker chart
221    /// timeline (often truncated) and on hover, and as "details" in the marker
222    /// table view.
223    ///
224    /// `tooltip` is only evaluated if capturing is active.
225    #[must_use]
226    pub fn with_tooltip<F>(mut self, tooltip: F) -> Self
227    where
228        F: FnOnce() -> String,
229    {
230        if let Some(inner) = &mut self.0 {
231            inner.tooltip = tooltip();
232        }
233        self
234    }
235
236    /// Sets the starting time for this span to `start`.  The default starting
237    /// time is when the [Span] was constructed, so this is only useful if
238    /// it's easier to create the span just before recording it.
239    #[must_use]
240    pub fn with_start(mut self, start: Instant) -> Self {
241        if let Some(inner) = &mut self.0 {
242            inner.start = start.into();
243        }
244        self
245    }
246
247    /// Calls `f` and records the span.  Returns whatever `f` returned.
248    pub fn in_scope<F, T>(self, f: F) -> T
249    where
250        F: FnOnce() -> T,
251    {
252        f()
253    }
254
255    /// Records the span.
256    pub fn record(self) {
257        // [Drop] records the span.
258    }
259
260    /// Consumes the span without recording it.
261    pub fn cancel(mut self) {
262        let _ = self.0.take();
263    }
264}
265
266impl Drop for Span {
267    fn drop(&mut self) {
268        if let Some(inner) = self.0.take() {
269            inner.record(true)
270        }
271    }
272}
273
274/// Annotates an event during a [Capture].
275///
276/// When a [Capture] is running, use this type to record an event along
277/// with a name, category, and tooltip.
278///
279/// An event happens at a point in time; use [Span] to record a timespan.
280///
281/// When [Capture] is not active, `Event` has minimal overhead.
282///
283/// [samply]: https://github.com/mstange/samply?tab=readme-ov-file#samply
284/// [module documentation]: crate
285pub struct Event(Option<SpanInner>);
286
287impl Event {
288    /// Constructs a new [Event] with the given name.
289    ///
290    /// [Event] does nothing when markers are not being captured.
291    ///
292    /// The name should ordinarily be a short static string indicating what the
293    /// event did.  The Firefox Profiler's marker chart view shows all the
294    /// events in a thread with the same name and category on a single
295    /// horizontal timeline (unless that would cause overlaps).
296    #[must_use]
297    pub fn new(name: &'static str) -> Self {
298        Self(Capture::is_active().then(|| SpanInner::new(name)))
299    }
300
301    /// Adds `category` to this event.
302    ///
303    /// The Firefox Profiler's marker chart view groups the markers in each
304    /// category and labels them with the category name.
305    ///
306    /// The default category is "Other".
307    #[must_use]
308    pub fn with_category(mut self, category: &'static str) -> Self {
309        if let Some(inner) = &mut self.0 {
310            inner.category = category;
311        }
312        self
313    }
314
315    /// Evaluates `tooltip` and adds it to this event.
316    ///
317    /// The Firefox Profiler shows the given tooltip in the marker chart
318    /// timeline (often truncated) and on hover, and as "details" in the marker
319    /// table view.
320    ///
321    /// `tooltip` is only evaluated if capturing is active.
322    #[must_use]
323    pub fn with_tooltip<F>(mut self, tooltip: F) -> Self
324    where
325        F: FnOnce() -> String,
326    {
327        if let Some(inner) = &mut self.0 {
328            inner.tooltip = tooltip();
329        }
330        self
331    }
332
333    /// Records the event.
334    pub fn record(self) {
335        if let Some(inner) = self.0 {
336            inner.record(false);
337        }
338    }
339}
340
341/// Options for capturing profile annotations.
342#[derive(Clone, Debug)]
343pub struct CaptureOptions {
344    memory_limit: Option<usize>,
345    record_rss: bool,
346}
347
348impl Default for CaptureOptions {
349    fn default() -> Self {
350        Self {
351            memory_limit: None,
352            record_rss: true,
353        }
354    }
355}
356
357impl CaptureOptions {
358    /// Creates new capture parameters with default settings.
359    pub fn new() -> Self {
360        Self::default()
361    }
362
363    /// Sets a limit on the amount of memory that can be used for recording
364    /// captured spans to `memory_limit`, in bytes.  If `memory_limit` is
365    /// `None`, then there will be no limit (which is also the default).
366    ///
367    /// The limit is honored approximately.  Recording a span takes
368    /// [Span::BYTES] bytes.
369    pub fn with_memory_limit(self, memory_limit: Option<usize>) -> Self {
370        Self {
371            memory_limit,
372            ..self
373        }
374    }
375
376    /// Enables or disables recording the amount of memory in use (the resident
377    /// set size) during the capture.  By default, RSS is recorded every 100
378    /// milliseconds.  When this feature is enabled, capture runs a thread for
379    /// recording the data.
380    pub fn with_record_rss(self, record_rss: bool) -> Self {
381        Self { record_rss, ..self }
382    }
383
384    /// Starts capturing profile annotations, returning a [Capture] that can be
385    /// used to finish or abort captures.  Dropping the [Capture] will also
386    /// abort capturing.
387    ///
388    /// For use in asynchronous contexts.  If a capture is already in progress,
389    /// this function will wait for it to complete before starting a new one.
390    pub async fn start(self) -> Capture {
391        Capture::new(self, CAPTURE_MUTEX.lock().await)
392    }
393
394    /// Starts capturing profile annotations, returning a [Capture] that can be
395    /// used to finish or abort captures.  Dropping the [Capture] will also
396    /// abort capturing.
397    ///
398    /// For use in blocking contexts.  If a capture is already in progress, this
399    /// function will wait for it to complete before starting a new one.
400    ///
401    /// # Panic
402    ///
403    /// Panics if called from an asynchronous execution context.
404    pub fn blocking_start(self) -> Capture {
405        Capture::new(self, CAPTURE_MUTEX.blocking_lock())
406    }
407
408    /// Starts capturing profile annotations, returning a [Capture] that can be
409    /// used to finish or abort captures.  Dropping the [Capture] will also
410    /// abort capturing.
411    ///
412    /// If a capture is already in progress, this function returns an error
413    /// instead of waiting.
414    pub fn try_start(self) -> Result<Capture, Self> {
415        let guard = match CAPTURE_MUTEX.try_lock() {
416            Ok(guard) => guard,
417            Err(_) => return Err(self),
418        };
419        Ok(Capture::new(self, guard))
420    }
421}
422
423static CAPTURE_MUTEX: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
424
425/// An in-progress capture of profile annotations.
426///
427/// To start a capture, use [CaptureOptions::start],
428/// [CaptureOptions::blocking_start], or [CaptureOptions::try_start].
429///
430/// Only one `Capture` may exist at one time.
431pub struct Capture {
432    _guard: tokio::sync::MutexGuard<'static, ()>,
433    memory: Option<JoinHandle<Vec<(Timestamp, usize)>>>,
434    unparker: Unparker,
435    request_exit: Arc<AtomicBool>,
436    block_limit: i64,
437}
438
439impl Capture {
440    fn new(params: CaptureOptions, guard: tokio::sync::MutexGuard<'static, ()>) -> Self {
441        if let Some(memory_limit) = params.memory_limit {
442            tracing::info!(
443                "marker capture limited to {}",
444                HumanBytes::from(memory_limit)
445            );
446        }
447        let block_limit = params.memory_limit.map_or(i64::MAX, |memory_limit| {
448            (memory_limit / BYTES_PER_BLOCK) as i64
449        });
450        let parker = Parker::new();
451        let unparker = parker.unparker().clone();
452        let request_exit = Arc::new(AtomicBool::new(false));
453        let memory = params.record_rss.then(|| {
454            std::thread::Builder::new()
455                .name(String::from("capture-rss"))
456                .spawn({
457                    let request_exit = request_exit.clone();
458                    move || {
459                        let mut memory = Vec::new();
460                        while !request_exit.load(Ordering::Acquire) {
461                            if let Some(memory_stats) = memory_stats() {
462                                memory.push((Timestamp::now(), memory_stats.physical_mem));
463                            }
464                            parker.park_timeout(Duration::from_millis(100));
465                        }
466                        memory
467                    }
468                })
469                .expect("should be able to start a capture thread")
470        });
471        FREE_BLOCKS.store(block_limit, Ordering::Relaxed);
472        CAPTURING.store(true, Ordering::Release);
473        Self {
474            block_limit,
475            memory,
476            unparker,
477            request_exit,
478            _guard: guard,
479        }
480    }
481
482    /// Finishes recording profile annotations and returns what was recorded.
483    pub fn finish(mut self) -> Annotations {
484        CAPTURING.store(false, Ordering::Release);
485        let remaining_blocks = FREE_BLOCKS.load(Ordering::Relaxed);
486        if remaining_blocks <= 0 {
487            tracing::info!("marker capture exceeded the limit");
488        } else {
489            let used_bytes = (self.block_limit - remaining_blocks) as usize * BYTES_PER_BLOCK;
490            tracing::info!("marker capture used {}", HumanBytes::from(used_bytes));
491        }
492
493        Annotations {
494            markers: self.take_markers(),
495            memory: self.take_memory(),
496        }
497    }
498
499    /// Aborts recording profile annotations.
500    ///
501    /// This is equivalent to dropping the `Capture` object.
502    pub fn abort(self) {
503        tracing::info!("aborting profile annotation capture");
504    }
505
506    /// Returns true if a profile annotation capture is ongoing.
507    ///
508    /// This only reports the status of annotation captures.  It does not
509    /// indicate whether `samply` or `perf` or another profiler is currently
510    /// capturing profile data for this process (this crate does not provide a
511    /// way to do that).
512    pub fn is_active() -> bool {
513        CAPTURING.load(Ordering::Acquire)
514    }
515
516    fn take_markers(&mut self) -> HashMap<usize, (Option<String>, Blocks)> {
517        let all_threads = ALL_THREAD_MARKERS.lock().unwrap();
518        let mut markers = HashMap::new();
519        for thread in &*all_threads {
520            markers.insert(thread.tid, (thread.name.clone(), thread.queue.take()));
521        }
522        markers
523    }
524
525    fn take_memory(&mut self) -> Vec<(Timestamp, usize)> {
526        if let Some(memory) = self.memory.take() {
527            self.request_exit.store(true, Ordering::Release);
528            self.unparker.unpark();
529            memory.join().unwrap_or_default()
530        } else {
531            Default::default()
532        }
533    }
534}
535
536impl Drop for Capture {
537    fn drop(&mut self) {
538        self.take_memory();
539
540        // Might already have been done in [Capture::finish] but it doesn't hurt
541        // to do it again (since the lock is still held).
542        CAPTURING.store(false, Ordering::Release);
543    }
544}
545
546/// Error returned by [Annotations::apply].
547#[derive(thiserror::Error, Debug)]
548pub enum Error {
549    /// Error decompressing the profile.
550    #[error("Error decompressing profile ")]
551    GzDecoderError(#[from] std::io::Error),
552
553    /// Error parsing the profile.
554    #[error("Error parsing profile")]
555    SerdeError(#[from] serde_json_path_to_error::Error),
556}
557
558/// Options for applying annotations.
559#[derive(Default, Clone, Debug)]
560pub struct AnnotationOptions {
561    product: Option<String>,
562    os_cpu: Option<String>,
563}
564
565impl AnnotationOptions {
566    /// Constructs a default set of options.
567    pub fn new() -> Self {
568        Self::default()
569    }
570
571    /// Overrides the product string in the profile.  `None` uses the default,
572    /// which is `PID <pid>`.
573    ///
574    /// The Firefox Profiler prominently displays the product and OS-CPU string
575    /// together in the form `<product> - <OS-CPU>`.
576    pub fn with_product(self, product: Option<impl Into<String>>) -> Self {
577        Self {
578            product: product.map(|s| s.into()),
579            ..self
580        }
581    }
582
583    /// Overrides the OS and CPU string in the profile.  `None` uses the
584    /// default, which looks like `Ubuntu 24.0.04.4 LTS`.
585    ///
586    /// The Firefox Profiler prominently displays the product and OS-CPU string
587    /// together in the form `<product> - <OS-CPU>`.
588    pub fn with_os_cpu(self, os_cpu: Option<impl Into<String>>) -> Self {
589        Self {
590            os_cpu: os_cpu.map(|s| s.into()),
591            ..self
592        }
593    }
594}
595
596/// Profile annotation data.
597///
598/// Obtained from [Capture::finish].
599pub struct Annotations {
600    markers: HashMap<usize, (Option<String>, Blocks)>,
601    memory: Vec<(Timestamp, usize)>,
602}
603
604impl Annotations {
605    /// Applies these annotations with the given `options` to `profile`, which
606    /// must be the `profile.json` output by samply, and returns the annotated
607    /// profile.
608    ///
609    /// The input may be gzipped or already decompressed.  The output will be in
610    /// the same form.
611    pub fn apply(&self, profile: &[u8], options: AnnotationOptions) -> Result<Vec<u8>, Error> {
612        // Decompress `profile` if it starts with the GZIP magic number,
613        // otherwise assume it has already been decompressed.
614        let mut buffer = Vec::new();
615        let json = if profile.starts_with(&[0x1f, 0x8b]) {
616            GzDecoder::new(profile).read_to_end(&mut buffer)?;
617            &buffer
618        } else {
619            profile
620        };
621        let gzip = !buffer.is_empty();
622
623        // Deserialize.
624        let mut profile = serde_json_path_to_error::from_slice::<Profile>(json)?;
625        if let Some(product) = options.product {
626            profile.meta.product = product;
627        }
628        if let Some(os_cpu) = options.os_cpu {
629            profile.meta.os_cpu = os_cpu;
630        }
631        profile.meta.marker_schema.push(json!({
632            "name": "FelderaMarker",
633            "display": [
634                "marker-chart",
635                "marker-table"
636            ],
637            "chartLabel": "{marker.data.name}",
638            "tooltipLabel": "{marker.data.name}",
639            "tableLabel": "{marker.data.name}",
640            "description": "Marker generated by Feldera.",
641            "fields": [
642                {
643                    "key": "name",
644                    "label": "Name",
645                    "format": "unique-string"
646                }
647            ]
648        }));
649        /// The colors that the profiler accepts for categories (see
650        /// https://github.com/firefox-devtools/profiler/blob/main/src/types/profile.ts).
651        static CATEGORY_COLORS: [&str; 12] = [
652            "purple",
653            "green",
654            "orange",
655            "yellow",
656            "lightblue",
657            "blue",
658            "brown",
659            "magenta",
660            "red",
661            "lightred",
662            "darkgrey",
663            "grey",
664        ];
665        let mut categories = profile
666            .meta
667            .categories
668            .iter()
669            .enumerate()
670            .map(|(index, category)| (category.name.clone(), index))
671            .collect::<HashMap<_, _>>();
672        for (category, color) in self
673            .markers
674            .values()
675            .flat_map(|(_, markers)| markers.iter())
676            .map(|marker| marker.category)
677            .collect::<HashSet<_>>()
678            .into_iter()
679            .zip(CATEGORY_COLORS.iter().cycle())
680        {
681            categories.insert(category.into(), profile.meta.categories.len());
682            profile.meta.categories.push(Category {
683                color: (*color).into(),
684                name: category.into(),
685                other: [(String::from("subcategories"), json!(["Other"]))]
686                    .into_iter()
687                    .collect(),
688            });
689        }
690        for thread in &mut profile.threads {
691            if let Some(tid) = &thread.tid
692                && let Ok(tid) = tid.parse::<usize>()
693                && let Some((name, markers)) = self.markers.get(&tid)
694            {
695                if let Some(name) = name {
696                    thread.name = Some(name.clone());
697                }
698                for marker in markers.iter() {
699                    thread.markers.length += 1;
700                    thread.markers.category.push(categories[marker.category]);
701                    thread.markers.data.push(ProfileMarkerData {
702                        type_: Cow::from("FelderaMarker"),
703                        name: profile.shared.add_name(&marker.tooltip),
704                    });
705                    thread.markers.start_time.push(marker.start);
706                    thread.markers.end_time.push(marker.end);
707                    thread
708                        .markers
709                        .name
710                        .push(profile.shared.add_name(marker.name));
711                    thread.markers.phase.push(1);
712                }
713            }
714        }
715
716        if !self.memory.is_empty() {
717            profile.counters.push(RawCounter {
718                name: String::from("RSS"),
719                category: String::from("Memory"),
720                description: String::from("RSS in bytes"),
721                pid: profile.threads.first().unwrap().pid.clone(),
722                main_thread_index: 0,
723                samples: {
724                    RawCounterSamplesTable {
725                        time: self
726                            .memory
727                            .iter()
728                            .copied()
729                            .map(|(time, _rss)| time)
730                            .collect(),
731                        time_deltas: Vec::new(),
732                        number: repeat_n(0, self.memory.len()).collect(),
733                        count: once(self.memory[0].1 as i64)
734                            .chain(
735                                self.memory
736                                    .iter()
737                                    .map(|(_time, rss)| *rss as i64)
738                                    .tuple_windows()
739                                    .map(|(prev, next)| next - prev),
740                            )
741                            .collect(),
742                        length: self.memory.len(),
743                        other: Default::default(),
744                    }
745                },
746                other: Default::default(),
747            });
748        }
749
750        // Produce the output, gzipping it if the input was gzipped.
751        let output = serde_json::to_vec(&profile).unwrap();
752        let output = if gzip {
753            let mut gzipped_output = Vec::new();
754            GzEncoder::new(Cursor::new(output), Compression::fast())
755                .read_to_end(&mut gzipped_output)
756                .unwrap();
757            gzipped_output
758        } else {
759            output
760        };
761
762        return Ok(output);
763
764        #[derive(Debug, Serialize, Deserialize)]
765        #[serde(rename_all = "camelCase")]
766        struct Profile {
767            meta: Meta,
768            threads: Vec<Thread>,
769            #[serde(default)]
770            counters: Vec<RawCounter>,
771            shared: Shared,
772            #[serde(flatten)]
773            other: HashMap<String, Value>,
774        }
775
776        #[derive(Debug, Serialize, Deserialize)]
777        #[serde(rename_all = "camelCase")]
778        struct Meta {
779            product: String,
780            #[serde(rename = "oscpu")]
781            os_cpu: String,
782            categories: Vec<Category>,
783            marker_schema: Vec<Value>,
784            #[serde(flatten)]
785            other: HashMap<String, Value>,
786        }
787
788        #[derive(Debug, Serialize, Deserialize)]
789        #[serde(rename_all = "camelCase")]
790        struct Category {
791            color: String,
792            name: String,
793            #[serde(flatten)]
794            other: HashMap<String, Value>,
795        }
796
797        #[derive(Debug, Serialize, Deserialize)]
798        #[serde(rename_all = "camelCase")]
799        struct Thread {
800            name: Option<String>,
801            #[serde(default)]
802            markers: ProfileMarkers,
803            tid: Option<String>,
804            pid: String,
805            #[serde(flatten)]
806            other: HashMap<String, Value>,
807        }
808
809        #[derive(Default, Debug, Serialize, Deserialize)]
810        #[serde(rename_all = "camelCase")]
811        struct ProfileMarkers {
812            length: usize,
813            category: Vec<usize>,
814            data: Vec<ProfileMarkerData>,
815            start_time: Vec<Timestamp>,
816            end_time: Vec<Timestamp>,
817            name: Vec<usize>,
818            phase: Vec<usize>,
819        }
820
821        #[derive(Default, Debug, Serialize, Deserialize)]
822        #[serde(rename_all = "camelCase")]
823        struct ProfileMarkerData {
824            #[serde(rename = "type")]
825            type_: Cow<'static, str>,
826            name: usize,
827        }
828
829        #[derive(Debug, Serialize, Deserialize)]
830        #[serde(rename_all = "camelCase")]
831        struct Shared {
832            string_array: Vec<String>,
833            #[serde(flatten)]
834            other: HashMap<String, Value>,
835        }
836
837        impl Shared {
838            fn add_name(&mut self, name: &str) -> usize {
839                let index = self.string_array.len();
840                self.string_array.push(name.into());
841                index
842            }
843        }
844
845        #[derive(Default, Debug, Serialize, Deserialize)]
846        #[serde(rename_all = "camelCase")]
847        struct RawCounter {
848            name: String,
849            category: String,
850            description: String,
851            pid: String,
852            main_thread_index: usize,
853            samples: RawCounterSamplesTable,
854            #[serde(flatten)]
855            other: HashMap<String, Value>,
856        }
857
858        #[derive(Default, Debug, Serialize, Deserialize)]
859        #[serde(rename_all = "camelCase")]
860        struct RawCounterSamplesTable {
861            #[serde(default, skip_serializing_if = "Vec::is_empty")]
862            time: Vec<Timestamp>,
863            #[serde(default, skip_serializing_if = "Vec::is_empty")]
864            time_deltas: Vec<Timestamp>,
865            #[serde(default, skip_serializing_if = "Vec::is_empty")]
866            number: Vec<usize>,
867            count: Vec<i64>,
868            length: usize,
869            #[serde(flatten)]
870            other: HashMap<String, Value>,
871        }
872    }
873}
874
875/// Whether capturing is active.
876static CAPTURING: AtomicBool = AtomicBool::new(false);
877
878/// A single marker as captured.
879struct Marker {
880    /// Start time.
881    start: Timestamp,
882    /// End time.
883    end: Timestamp,
884    /// Category (used for outer grouping).
885    category: &'static str,
886    /// Name (used for inner grouping).
887    name: &'static str,
888    /// Shown on hover.
889    tooltip: String,
890}
891
892/// Markers for a given thread.
893struct ThreadMarkers {
894    /// The thread's tid.
895    ///
896    /// We need this to identify this thread in the profiler file.
897    tid: usize,
898
899    /// The thread's name.
900    ///
901    /// The profiler gets thread names from the kernel, but they are truncated
902    /// at 15 bytes.  We supply the full thread name.
903    name: Option<String>,
904
905    /// The thread's markers.
906    ///
907    /// The thread itself records markers by pushing them onto the queue.
908    /// [Capture::finish] pops them all off.
909    queue: Arc<Queue>,
910}
911
912impl ThreadMarkers {
913    fn new(queue: Arc<Queue>) -> Self {
914        #[cfg(target_os = "linux")]
915        let tid = nix::unistd::gettid().as_raw() as usize;
916        #[cfg(not(target_os = "linux"))]
917        let tid = thread_id::get();
918
919        Self {
920            tid,
921            name: std::thread::current().name().map(|s| s.into()),
922            queue,
923        }
924    }
925}
926
927/// [ThreadMarkers] for every thread that has recorded a marker.
928static ALL_THREAD_MARKERS: std::sync::Mutex<Vec<ThreadMarkers>> = std::sync::Mutex::new(Vec::new());
929
930static FREE_BLOCKS: AtomicI64 = AtomicI64::new(0);
931const MARKERS_PER_BLOCK: usize = 32;
932const BYTES_PER_BLOCK: usize = MARKERS_PER_BLOCK * Span::BYTES;
933
934struct Block(Vec<Marker>);
935impl Block {
936    fn new(marker: Marker) -> Self {
937        let mut markers = Vec::with_capacity(MARKERS_PER_BLOCK);
938        markers.push(marker);
939        Self(markers)
940    }
941    fn is_full(&self) -> bool {
942        self.0.len() >= self.0.capacity()
943    }
944    fn push(&mut self, marker: Marker) {
945        self.0.push(marker);
946    }
947}
948
949struct Blocks(Vec<Block>);
950
951impl Default for Blocks {
952    fn default() -> Self {
953        Self(Vec::with_capacity(32))
954    }
955}
956
957impl Blocks {
958    fn push(&mut self, marker: Marker) {
959        if let Some(block) = self.0.last_mut()
960            && !block.is_full()
961        {
962            block.push(marker);
963        } else {
964            match FREE_BLOCKS.fetch_sub(1, Ordering::Relaxed) {
965                1.. => self.0.push(Block::new(marker)),
966                0 => warn!("marker capture space exhausted"),
967                _ => (),
968            }
969        }
970    }
971
972    fn iter(&self) -> impl Iterator<Item = &Marker> {
973        self.0.iter().flat_map(|block| block.0.iter())
974    }
975}
976
977struct Queue(std::sync::Mutex<Blocks>);
978
979impl Queue {
980    fn new() -> Arc<Self> {
981        let queue = Arc::new(Self(Default::default()));
982        ALL_THREAD_MARKERS
983            .lock()
984            .unwrap()
985            .push(ThreadMarkers::new(queue.clone()));
986        queue
987    }
988
989    fn push(&self, marker: Marker) {
990        self.0.lock().unwrap().push(marker);
991    }
992
993    fn take(&self) -> Blocks {
994        std::mem::take(&mut *self.0.lock().unwrap())
995    }
996}
997
998thread_local! {
999    static QUEUE: Arc<Queue> = Queue::new();
1000}