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