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], [LongSpan], and [Event] to record annotations.  After `samply`
17//! completes, Feldera finishes the capture to obtain [Annotations], applies
18//! them, and then passes the postprocessed output to the user.  The annotation
19//! step is 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    mem::swap,
47    sync::{
48        Arc,
49        atomic::{AtomicBool, AtomicI64, Ordering},
50    },
51    thread::JoinHandle,
52    time::{Duration, Instant},
53};
54
55#[cfg(target_os = "macos")]
56use std::time::{SystemTime, UNIX_EPOCH};
57
58use crossbeam::sync::{Parker, Unparker};
59use flate2::{
60    Compression,
61    bufread::{GzDecoder, GzEncoder},
62};
63use itertools::Itertools;
64use memory_stats::memory_stats;
65#[cfg(not(target_os = "macos"))]
66use nix::time::{ClockId, clock_gettime};
67use serde::{Deserialize, Serialize};
68use serde_json::{Value, json};
69use size_of::HumanBytes;
70use tracing::warn;
71
72/// Atomic `Option<Timestamp>`.
73///
74/// Treats `i64::MIN` as a niche.
75#[derive(Debug)]
76struct AtomicOptionTimestamp(AtomicI64);
77
78impl Default for AtomicOptionTimestamp {
79    fn default() -> Self {
80        Self::new(None)
81    }
82}
83
84impl AtomicOptionTimestamp {
85    fn new(value: Option<Timestamp>) -> Self {
86        Self(AtomicI64::new(
87            value.map_or(i64::MIN, |timestamp| timestamp.0),
88        ))
89    }
90
91    fn load(&self) -> Option<Timestamp> {
92        let value = self.0.load(Ordering::Relaxed);
93        (value != i64::MIN).then_some(Timestamp(value))
94    }
95
96    fn store(&self, value: Option<Timestamp>) {
97        self.0.store(
98            value.map_or(i64::MIN, |timestamp| timestamp.0),
99            Ordering::Relaxed,
100        )
101    }
102}
103
104#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
105#[repr(transparent)]
106struct Timestamp(
107    /// Monotonic time in nanoseconds.
108    ///
109    /// On macOS this is [`mach_absolute_time`] converted to nanoseconds via
110    /// [`mach_timebase_info`].  On other Unix platforms this is
111    /// `CLOCK_MONOTONIC`.
112    ///
113    /// [`mach_absolute_time`]: https://developer.apple.com/documentation/kernel/1462446-mach_absolute_time
114    /// [`mach_timebase_info`]: https://developer.apple.com/documentation/kernel/1462447-mach_timebase_info
115    i64,
116);
117
118#[cfg(target_os = "macos")]
119fn mach_absolute_time_nanos() -> i64 {
120    use mach2::mach_time::{mach_absolute_time, mach_timebase_info, mach_timebase_info_data_t};
121    use std::sync::OnceLock;
122
123    static NANOS_PER_TICK: OnceLock<(u32, u32)> = OnceLock::new();
124    let (numer, denom) = *NANOS_PER_TICK.get_or_init(|| {
125        let mut info = mach_timebase_info_data_t { numer: 0, denom: 0 };
126        unsafe {
127            mach_timebase_info(&mut info);
128        }
129        if info.denom == 0 {
130            (1, 1)
131        } else {
132            (info.numer, info.denom)
133        }
134    });
135    let ticks = unsafe { mach_absolute_time() };
136    (ticks * u64::from(numer) / u64::from(denom)) as i64
137}
138
139impl Timestamp {
140    fn now() -> Self {
141        #[cfg(target_os = "macos")]
142        {
143            Self(mach_absolute_time_nanos())
144        }
145
146        #[cfg(not(target_os = "macos"))]
147        {
148            let now = clock_gettime(ClockId::CLOCK_MONOTONIC).unwrap();
149            Self(now.tv_sec() as i64 * 1_000_000_000 + now.tv_nsec() as i64)
150        }
151    }
152}
153
154/// Nanoseconds since the Unix epoch.
155#[cfg(target_os = "macos")]
156fn unix_epoch_nanos() -> i64 {
157    SystemTime::now()
158        .duration_since(UNIX_EPOCH)
159        .expect("system clock is before Unix epoch")
160        .as_nanos() as i64
161}
162
163impl From<Instant> for Timestamp {
164    fn from(value: Instant) -> Self {
165        // SAFETY: On Unix, `Instant` is implemented using CLOCK_MONOTONIC,
166        // which is the clock that we need to use for the profiler, but the Rust
167        // standard library provides no way to get the value out.  We don't want
168        // to make assumptions about the layout of [Instant], and in fact it is
169        // not defined as libc's struct timespec but different and
170        // Rust-specific.  If we just transmute then we get the wrong value.  It
171        // seems rather safer to assume that the all-bytes-zeros `Instant` is
172        // the origin, and it works OK for now at least.
173        //
174        // The completely safe alternative would be to make Timestamp public and
175        // force clients to always get both a Timestamp and an Instant if they
176        // need both, which is wasteful.
177        let zero = unsafe { std::mem::zeroed::<Instant>() };
178        Self((value - zero).as_nanos() as i64)
179    }
180}
181
182impl Display for Timestamp {
183    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
184        write!(f, "{}", self.0)
185    }
186}
187
188impl Serialize for Timestamp {
189    /// Serializes the format used in the [Gecko profiler] format.
190    ///
191    /// [Gecko profiler]: https://github.com/firefox-devtools/profiler/blob/main/src/types/profile.ts
192    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
193    where
194        S: serde::Serializer,
195    {
196        let milliseconds = self.0 as f64 / 1_000_000.0;
197        milliseconds.serialize(serializer)
198    }
199}
200
201impl<'de> Deserialize<'de> for Timestamp {
202    /// Deserializes the format used in the [Gecko profiler] format.
203    ///
204    /// [Gecko profiler]: https://github.com/firefox-devtools/profiler/blob/main/src/types/profile.ts
205    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
206    where
207        D: serde::Deserializer<'de>,
208    {
209        let milliseconds = f64::deserialize(deserializer)?;
210        Ok(Self((milliseconds * 1_000_000.0) as i64))
211    }
212}
213
214impl Debug for Span {
215    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
216        write!(f, "Span")?;
217        if let Some(inner) = &self.0 {
218            write!(f, "({})", &inner.name)?;
219        }
220        Ok(())
221    }
222}
223
224struct SpanInner {
225    start: Timestamp,
226    category: &'static str,
227    name: &'static str,
228    tooltip: String,
229}
230
231impl SpanInner {
232    #[cold]
233    fn new(name: &'static str) -> Self {
234        Self {
235            start: Timestamp::now(),
236            category: "Other",
237            name,
238            tooltip: String::new(),
239        }
240    }
241
242    fn into_marker(self, end: MarkerEnd) -> Marker {
243        Marker {
244            start: self.start,
245            end,
246            category: self.category,
247            name: self.name,
248            tooltip: self.tooltip,
249        }
250    }
251
252    #[cold]
253    fn record(self, end: MarkerEnd) {
254        QUEUE.with(|queue| queue.push(self.into_marker(end)));
255    }
256}
257
258/// Annotates a timespan during a [Capture].
259///
260/// Constructing and dropping a [Span], when marker spans are being captured
261/// with [Capture], records the start and end times of the [Span] along with a
262/// name, category, and tooltip.
263///
264/// `Span` is for timespans.  Use [Event] for point-in-time events.
265///
266/// When [Capture] is not active, `Span` has minimal overhead.
267///
268/// [samply]: https://github.com/mstange/samply?tab=readme-ov-file#samply
269pub struct Span(Option<SpanInner>);
270
271impl Span {
272    /// The number of bytes of memory used during capture to record a [Span],
273    /// [LongSpan], or [Event].
274    pub const BYTES: usize = std::mem::size_of::<Marker>();
275
276    /// Constructs a new [Span] with the given name.  When the constructed
277    /// span is dropped, it is automatically recorded.
278    ///
279    /// [Span] does nothing when markers are not being captured.  A span
280    /// will be recorded in a profile only if markers were being captured both
281    /// when it was created and when it was dropped.
282    ///
283    /// The name should ordinarily be a short static string indicating what
284    /// happens during the span.  The Firefox Profiler's marker chart view shows
285    /// all the spans in a thread with the same name and category on a single
286    /// horizontal timeline (unless that would cause overlaps).
287    #[must_use]
288    pub fn new(name: &'static str) -> Self {
289        Self(Capture::is_active().then(|| SpanInner::new(name)))
290    }
291
292    /// Adds `category` to this span.
293    ///
294    /// The Firefox Profiler's marker chart view groups the markers in each
295    /// category and labels them with the category name.
296    ///
297    /// The default category is "Other".
298    #[must_use]
299    pub fn with_category(mut self, category: &'static str) -> Self {
300        if let Some(inner) = &mut self.0 {
301            inner.category = category;
302        }
303        self
304    }
305
306    /// Evaluates `tooltip` and adds it to this span.
307    ///
308    /// The Firefox Profiler shows the given tooltip in the marker chart
309    /// timeline (often truncated) and on hover, and as "details" in the marker
310    /// table view.
311    ///
312    /// `tooltip` is only evaluated if capturing is active.
313    #[must_use]
314    pub fn with_tooltip<F>(mut self, tooltip: F) -> Self
315    where
316        F: FnOnce() -> String,
317    {
318        if let Some(inner) = &mut self.0 {
319            inner.tooltip = tooltip();
320        }
321        self
322    }
323
324    /// Sets the starting time for this span to `start`.  The default starting
325    /// time is when the [Span] was constructed, so this is only useful if
326    /// it's easier to create the span just before recording it.
327    #[must_use]
328    pub fn with_start(mut self, start: Instant) -> Self {
329        if let Some(inner) = &mut self.0 {
330            inner.start = start.into();
331        }
332        self
333    }
334
335    /// Calls `f` and records the span.  Returns whatever `f` returned.
336    pub fn in_scope<F, T>(self, f: F) -> T
337    where
338        F: FnOnce() -> T,
339    {
340        f()
341    }
342
343    /// Records the span.
344    pub fn record(self) {
345        // [Drop] records the span.
346    }
347
348    /// Consumes the span without recording it.
349    pub fn cancel(mut self) {
350        let _ = self.0.take();
351    }
352}
353
354impl Drop for Span {
355    fn drop(&mut self) {
356        if let Some(inner) = self.0.take() {
357            inner.record(MarkerEnd::At(Timestamp::now()))
358        }
359    }
360}
361
362/// Builds a [LongSpan] for annotating a long timespan.
363pub struct LongSpanBuilder(SpanInner);
364
365impl LongSpanBuilder {
366    /// Constructs a new [LongSpanBuilder] with the given name.
367    ///
368    /// The name should ordinarily be a short static string indicating what
369    /// happens during the span.  The Firefox Profiler's marker chart view shows
370    /// all the spans in a thread with the same name and category on a single
371    /// horizontal timeline (unless that would cause overlaps).
372    #[must_use]
373    pub fn new(name: &'static str) -> Self {
374        Self(SpanInner::new(name))
375    }
376
377    /// Adds `category` to this span.
378    ///
379    /// The Firefox Profiler's marker chart view groups the markers in each
380    /// category and labels them with the category name.
381    ///
382    /// The default category is "Other".
383    #[must_use]
384    pub fn with_category(mut self, category: &'static str) -> Self {
385        self.0.category = category;
386        self
387    }
388
389    /// Adds `tooltip` to this span.
390    ///
391    /// The Firefox Profiler shows the given tooltip in the marker chart
392    /// timeline (often truncated) and on hover, and as "details" in the marker
393    /// table view.
394    #[must_use]
395    pub fn with_tooltip(mut self, tooltip: impl Into<String>) -> Self {
396        self.0.tooltip = tooltip.into();
397        self
398    }
399
400    /// Sets the starting time for this span to `start`.  The default starting
401    /// time is when the [LongSpanBuilder] was constructed, so this is only
402    /// useful if it's easier to create the span just before recording it.
403    #[must_use]
404    pub fn with_start(mut self, start: Instant) -> Self {
405        self.0.start = start.into();
406        self
407    }
408
409    /// Builds the [LongSpan].
410    #[must_use]
411    pub fn build(self) -> LongSpan {
412        let timestamp = Arc::new(AtomicOptionTimestamp::default());
413        QUEUE.with(|queue| {
414            queue.push_long_span(self.0.into_marker(MarkerEnd::Long(timestamp.clone())))
415        });
416        LongSpan(timestamp)
417    }
418}
419
420/// A relatively expensive way to annotate a longer timespan during [Capture]s.
421///
422/// `LongSpan` is much like [Span].  However, whereas [Span] is optimized to
423/// minimize time and space overhead when a capture is not active, `LongSpan`
424/// always tracks the span.  This allows it to show up in captures that start
425/// after the `LongSpan` is allocated or that end before the `LongSpan` is
426/// recorded.
427///
428/// [samply]: https://github.com/mstange/samply?tab=readme-ov-file#samply
429pub struct LongSpan(Arc<AtomicOptionTimestamp>);
430
431impl LongSpan {
432    /// Marks this `LongSpan` as complete.
433    ///
434    /// This is equivalent to dropping it.
435    pub fn complete(self) {
436        // [Drop] completes the span.
437    }
438}
439
440impl Drop for LongSpan {
441    fn drop(&mut self) {
442        self.0.store(Some(Timestamp::now()));
443    }
444}
445
446/// Annotates an event during a [Capture].
447///
448/// When a [Capture] is running, use this type to record an event along
449/// with a name, category, and tooltip.
450///
451/// An event happens at a point in time; use [Span] to record a timespan.
452///
453/// When [Capture] is not active, `Event` has minimal overhead.
454///
455/// [samply]: https://github.com/mstange/samply?tab=readme-ov-file#samply
456/// [module documentation]: crate
457pub struct Event(Option<SpanInner>);
458
459impl Event {
460    /// Constructs a new [Event] with the given name.
461    ///
462    /// [Event] does nothing when markers are not being captured.
463    ///
464    /// The name should ordinarily be a short static string indicating what the
465    /// event did.  The Firefox Profiler's marker chart view shows all the
466    /// events in a thread with the same name and category on a single
467    /// horizontal timeline (unless that would cause overlaps).
468    #[must_use]
469    pub fn new(name: &'static str) -> Self {
470        Self(Capture::is_active().then(|| SpanInner::new(name)))
471    }
472
473    /// Adds `category` to this event.
474    ///
475    /// The Firefox Profiler's marker chart view groups the markers in each
476    /// category and labels them with the category name.
477    ///
478    /// The default category is "Other".
479    #[must_use]
480    pub fn with_category(mut self, category: &'static str) -> Self {
481        if let Some(inner) = &mut self.0 {
482            inner.category = category;
483        }
484        self
485    }
486
487    /// Evaluates `tooltip` and adds it to this event.
488    ///
489    /// The Firefox Profiler shows the given tooltip in the marker chart
490    /// timeline (often truncated) and on hover, and as "details" in the marker
491    /// table view.
492    ///
493    /// `tooltip` is only evaluated if capturing is active.
494    #[must_use]
495    pub fn with_tooltip<F>(mut self, tooltip: F) -> Self
496    where
497        F: FnOnce() -> String,
498    {
499        if let Some(inner) = &mut self.0 {
500            inner.tooltip = tooltip();
501        }
502        self
503    }
504
505    /// Records the event.
506    pub fn record(self) {
507        if let Some(inner) = self.0 {
508            let end = MarkerEnd::At(inner.start);
509            inner.record(end);
510        }
511    }
512}
513
514/// Options for capturing profile annotations.
515#[derive(Clone, Debug)]
516pub struct CaptureOptions {
517    memory_limit: Option<usize>,
518    record_rss: bool,
519}
520
521impl Default for CaptureOptions {
522    fn default() -> Self {
523        Self {
524            memory_limit: None,
525            record_rss: true,
526        }
527    }
528}
529
530impl CaptureOptions {
531    /// Creates new capture parameters with default settings.
532    pub fn new() -> Self {
533        Self::default()
534    }
535
536    /// Sets a limit on the amount of memory that can be used for recording
537    /// captured spans to `memory_limit`, in bytes.  If `memory_limit` is
538    /// `None`, then there will be no limit (which is also the default).
539    ///
540    /// The limit is honored approximately.  Recording a span takes
541    /// [Span::BYTES] bytes.
542    pub fn with_memory_limit(self, memory_limit: Option<usize>) -> Self {
543        Self {
544            memory_limit,
545            ..self
546        }
547    }
548
549    /// Enables or disables recording the amount of memory in use (the resident
550    /// set size) during the capture.  By default, RSS is recorded every 100
551    /// milliseconds.  When this feature is enabled, capture runs a thread for
552    /// recording the data.
553    pub fn with_record_rss(self, record_rss: bool) -> Self {
554        Self { record_rss, ..self }
555    }
556
557    /// Starts capturing profile annotations, returning a [Capture] that can be
558    /// used to finish or abort captures.  Dropping the [Capture] will also
559    /// abort capturing.
560    ///
561    /// For use in asynchronous contexts.  If a capture is already in progress,
562    /// this function will wait for it to complete before starting a new one.
563    pub async fn start(self) -> Capture {
564        Capture::new(self, CAPTURE_MUTEX.lock().await)
565    }
566
567    /// Starts capturing profile annotations, returning a [Capture] that can be
568    /// used to finish or abort captures.  Dropping the [Capture] will also
569    /// abort capturing.
570    ///
571    /// For use in blocking contexts.  If a capture is already in progress, this
572    /// function will wait for it to complete before starting a new one.
573    ///
574    /// # Panic
575    ///
576    /// Panics if called from an asynchronous execution context.
577    pub fn blocking_start(self) -> Capture {
578        Capture::new(self, CAPTURE_MUTEX.blocking_lock())
579    }
580
581    /// Starts capturing profile annotations, returning a [Capture] that can be
582    /// used to finish or abort captures.  Dropping the [Capture] will also
583    /// abort capturing.
584    ///
585    /// If a capture is already in progress, this function returns an error
586    /// instead of waiting.
587    pub fn try_start(self) -> Result<Capture, Self> {
588        let guard = match CAPTURE_MUTEX.try_lock() {
589            Ok(guard) => guard,
590            Err(_) => return Err(self),
591        };
592        Ok(Capture::new(self, guard))
593    }
594}
595
596static CAPTURE_MUTEX: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
597
598/// An in-progress capture of profile annotations.
599///
600/// To start a capture, use [CaptureOptions::start],
601/// [CaptureOptions::blocking_start], or [CaptureOptions::try_start].
602///
603/// Only one `Capture` may exist at one time.
604pub struct Capture {
605    _guard: tokio::sync::MutexGuard<'static, ()>,
606    memory: Option<JoinHandle<Vec<(Timestamp, usize)>>>,
607    unparker: Unparker,
608    request_exit: Arc<AtomicBool>,
609    block_limit: i64,
610    #[cfg(target_os = "macos")]
611    anchor: (Timestamp, i64),
612}
613
614impl Capture {
615    fn new(params: CaptureOptions, guard: tokio::sync::MutexGuard<'static, ()>) -> Self {
616        if let Some(memory_limit) = params.memory_limit {
617            tracing::info!(
618                "marker capture limited to {}",
619                HumanBytes::from(memory_limit)
620            );
621        }
622        let block_limit = params.memory_limit.map_or(i64::MAX, |memory_limit| {
623            (memory_limit / BYTES_PER_BLOCK) as i64
624        });
625        let parker = Parker::new();
626        let unparker = parker.unparker().clone();
627        let request_exit = Arc::new(AtomicBool::new(false));
628        let memory = params.record_rss.then(|| {
629            std::thread::Builder::new()
630                .name(String::from("capture-rss"))
631                .spawn({
632                    let request_exit = request_exit.clone();
633                    move || {
634                        let mut memory = Vec::new();
635                        while !request_exit.load(Ordering::Acquire) {
636                            if let Some(memory_stats) = memory_stats() {
637                                memory.push((Timestamp::now(), memory_stats.physical_mem));
638                            }
639                            parker.park_timeout(Duration::from_millis(100));
640                        }
641                        memory
642                    }
643                })
644                .expect("should be able to start a capture thread")
645        });
646        FREE_BLOCKS.store(block_limit, Ordering::Relaxed);
647        CAPTURING.store(true, Ordering::Release);
648        Self {
649            block_limit,
650            memory,
651            unparker,
652            request_exit,
653            #[cfg(target_os = "macos")]
654            anchor: (Timestamp::now(), unix_epoch_nanos()),
655            _guard: guard,
656        }
657    }
658
659    /// Finishes recording profile annotations and returns what was recorded.
660    pub fn finish(mut self) -> Annotations {
661        let end_time = Timestamp::now();
662        CAPTURING.store(false, Ordering::Release);
663        let remaining_blocks = FREE_BLOCKS.load(Ordering::Relaxed);
664        if remaining_blocks <= 0 {
665            tracing::info!("marker capture exceeded the limit");
666        } else {
667            let used_bytes = (self.block_limit - remaining_blocks) as usize * BYTES_PER_BLOCK;
668            tracing::info!("marker capture used {}", HumanBytes::from(used_bytes));
669        }
670
671        let markers = self
672            .all_threads()
673            .into_iter()
674            .map(|thread| {
675                let mut blocks = thread.queue.take_blocks();
676
677                let long_spans = thread.queue.take_long_spans();
678                if !long_spans.is_empty() {
679                    blocks.0.push(Block(long_spans));
680                }
681
682                (thread.tid, (thread.name, blocks))
683            })
684            .collect();
685
686        Annotations {
687            end_time,
688            markers,
689            memory: self.take_memory(),
690            #[cfg(target_os = "macos")]
691            anchor: self.anchor,
692        }
693    }
694
695    /// Aborts recording profile annotations.
696    ///
697    /// This is equivalent to dropping the `Capture` object.
698    pub fn abort(self) {
699        tracing::info!("aborting profile annotation capture");
700    }
701
702    /// Returns true if a profile annotation capture is ongoing.
703    ///
704    /// This only reports the status of annotation captures.  It does not
705    /// indicate whether `samply` or `perf` or another profiler is currently
706    /// capturing profile data for this process (this crate does not provide a
707    /// way to do that).
708    pub fn is_active() -> bool {
709        CAPTURING.load(Ordering::Acquire)
710    }
711
712    fn all_threads(&mut self) -> Vec<ThreadMarkers> {
713        ALL_THREAD_MARKERS.lock().unwrap().clone()
714    }
715
716    fn take_memory(&mut self) -> Vec<(Timestamp, usize)> {
717        if let Some(memory) = self.memory.take() {
718            self.request_exit.store(true, Ordering::Release);
719            self.unparker.unpark();
720            memory.join().unwrap_or_default()
721        } else {
722            Default::default()
723        }
724    }
725}
726
727impl Drop for Capture {
728    fn drop(&mut self) {
729        self.take_memory();
730
731        // Might already have been done in [Capture::finish] but it doesn't hurt
732        // to do it again (since the lock is still held).
733        CAPTURING.store(false, Ordering::Release);
734    }
735}
736
737/// Error returned by [Annotations::apply].
738#[derive(thiserror::Error, Debug)]
739pub enum Error {
740    /// Error decompressing the profile.
741    #[error("Error decompressing profile ")]
742    GzDecoderError(#[from] std::io::Error),
743
744    /// Error parsing the profile.
745    #[error("Error parsing profile")]
746    SerdeError(#[from] serde_json_path_to_error::Error),
747}
748
749/// Options for applying annotations.
750#[derive(Default, Clone, Debug)]
751pub struct AnnotationOptions {
752    product: Option<String>,
753    os_cpu: Option<String>,
754}
755
756impl AnnotationOptions {
757    /// Constructs a default set of options.
758    pub fn new() -> Self {
759        Self::default()
760    }
761
762    /// Overrides the product string in the profile.  `None` uses the default,
763    /// which is `PID <pid>`.
764    ///
765    /// The Firefox Profiler prominently displays the product and OS-CPU string
766    /// together in the form `<product> - <OS-CPU>`.
767    pub fn with_product(self, product: Option<impl Into<String>>) -> Self {
768        Self {
769            product: product.map(|s| s.into()),
770            ..self
771        }
772    }
773
774    /// Overrides the OS and CPU string in the profile.  `None` uses the
775    /// default, which looks like `Ubuntu 24.0.04.4 LTS`.
776    ///
777    /// The Firefox Profiler prominently displays the product and OS-CPU string
778    /// together in the form `<product> - <OS-CPU>`.
779    pub fn with_os_cpu(self, os_cpu: Option<impl Into<String>>) -> Self {
780        Self {
781            os_cpu: os_cpu.map(|s| s.into()),
782            ..self
783        }
784    }
785}
786
787/// Profile annotation data.
788///
789/// Obtained from [Capture::finish].
790pub struct Annotations {
791    end_time: Timestamp,
792    markers: HashMap<usize, (Option<String>, Blocks)>,
793    memory: Vec<(Timestamp, usize)>,
794    #[cfg(target_os = "macos")]
795    anchor: (Timestamp, i64),
796}
797
798impl Annotations {
799    /// Applies these annotations with the given `options` to `profile`, which
800    /// must be the `profile.json` output by samply, and returns the annotated
801    /// profile.
802    ///
803    /// The input may be gzipped or already decompressed.  The output will be in
804    /// the same form.
805    pub fn apply(&self, profile: &[u8], options: AnnotationOptions) -> Result<Vec<u8>, Error> {
806        // Decompress `profile` if it starts with the GZIP magic number,
807        // otherwise assume it has already been decompressed.
808        let mut buffer = Vec::new();
809        let json = if profile.starts_with(&[0x1f, 0x8b]) {
810            GzDecoder::new(profile).read_to_end(&mut buffer)?;
811            &buffer
812        } else {
813            profile
814        };
815        let gzip = !buffer.is_empty();
816
817        // Deserialize.
818        let mut profile = serde_json_path_to_error::from_slice::<Profile>(json)?;
819
820        // On macOS, timestamps in the samply profile are nanoseconds relative to `startTime`
821        // recorded in the profile's metadata. startTime is measured using wall-clock time,
822        // _not_ the monotonic clock time.
823        //
824        // Below `anchor_monotonic_ns` and `anchor_wall_clock_ns` represent the same point in time expressed
825        // in monotonic clock units and wall clock units respectively.
826        //
827        // `profile_start_wall_clock_ms` is the wall clock time when the profile started, extracted
828        // from the profile's metadata.
829        //
830        // `timestamp` is the event timestamp to convert to profile time.
831        //
832        // ```text
833        // -----------------|---------------------------------------|--------------------------|----------> time
834        //  (anchor_monotonic_ns, anchor_wall_clock_ns)      profile_start_wall_clock_ms   timestamp
835        // ```
836        //
837        // To convert a timestamp to relative nanoseconds expected by samply, we need to:
838        // 1. Calculate elapsed since the Timestamp recorded in anchor.
839        // 2. Add adjustment - the difference between the anchor wall-clock time and the profile start wall-clock time.
840        #[cfg(target_os = "macos")]
841        let to_profile_time = {
842            let profile_start_time_ms = profile.meta.start_time;
843            let (anchor_monotonic_ns, anchor_wall_clock_ns) = self.anchor;
844            let profile_start_wall_clock_ns = (profile_start_time_ms * 1_000_000.0) as i64;
845            let adjustment_ns = anchor_wall_clock_ns - profile_start_wall_clock_ns;
846            move |timestamp: Timestamp| {
847                Timestamp(timestamp.0 - anchor_monotonic_ns.0 + adjustment_ns)
848            }
849        };
850        #[cfg(not(target_os = "macos"))]
851        let to_profile_time = |timestamp: Timestamp| timestamp;
852
853        if let Some(product) = options.product {
854            profile.meta.product = product;
855        }
856        if let Some(os_cpu) = options.os_cpu {
857            profile.meta.os_cpu = os_cpu;
858        }
859        profile.meta.marker_schema.push(json!({
860            "name": "FelderaMarker",
861            "display": [
862                "marker-chart",
863                "marker-table"
864            ],
865            "chartLabel": "{marker.data.name}",
866            "tooltipLabel": "{marker.data.name}",
867            "tableLabel": "{marker.data.name}",
868            "description": "Marker generated by Feldera.",
869            "fields": [
870                {
871                    "key": "name",
872                    "label": "Name",
873                    "format": "unique-string"
874                }
875            ]
876        }));
877        /// The colors that the profiler accepts for categories (see
878        /// https://github.com/firefox-devtools/profiler/blob/main/src/types/profile.ts).
879        static CATEGORY_COLORS: [&str; 12] = [
880            "purple",
881            "green",
882            "orange",
883            "yellow",
884            "lightblue",
885            "blue",
886            "brown",
887            "magenta",
888            "red",
889            "lightred",
890            "darkgrey",
891            "grey",
892        ];
893        let mut categories = profile
894            .meta
895            .categories
896            .iter()
897            .enumerate()
898            .map(|(index, category)| (category.name.clone(), index))
899            .collect::<HashMap<_, _>>();
900        for (category, color) in self
901            .markers
902            .values()
903            .flat_map(|(_, markers)| markers.iter())
904            .map(|marker| marker.category)
905            .collect::<HashSet<_>>()
906            .into_iter()
907            .zip(CATEGORY_COLORS.iter().cycle())
908        {
909            categories.insert(category.into(), profile.meta.categories.len());
910            profile.meta.categories.push(Category {
911                color: (*color).into(),
912                name: category.into(),
913                other: [(String::from("subcategories"), json!(["Other"]))]
914                    .into_iter()
915                    .collect(),
916            });
917        }
918        for thread in &mut profile.threads {
919            if let Some(tid) = &thread.tid
920                && let Ok(tid) = tid.parse::<usize>()
921                && let Some((name, markers)) = self.markers.get(&tid)
922            {
923                if let Some(name) = name {
924                    thread.name = Some(name.clone());
925                }
926                for marker in markers.iter() {
927                    thread.markers.length += 1;
928                    thread.markers.category.push(categories[marker.category]);
929                    thread.markers.data.push(ProfileMarkerData {
930                        type_: Cow::from("FelderaMarker"),
931                        name: profile.shared.add_name(&marker.tooltip),
932                    });
933                    thread
934                        .markers
935                        .start_time
936                        .push(to_profile_time(marker.start));
937                    thread.markers.end_time.push(to_profile_time(
938                        marker.end.timestamp().unwrap_or(self.end_time),
939                    ));
940                    thread
941                        .markers
942                        .name
943                        .push(profile.shared.add_name(marker.name));
944                    thread.markers.phase.push(1);
945                }
946            }
947        }
948
949        if !self.memory.is_empty() {
950            profile.counters.push(RawCounter {
951                name: String::from("RSS"),
952                category: String::from("Memory"),
953                description: String::from("RSS in bytes"),
954                pid: profile.threads.first().unwrap().pid.clone(),
955                main_thread_index: 0,
956                samples: {
957                    RawCounterSamplesTable {
958                        time: self
959                            .memory
960                            .iter()
961                            .map(|(time, _rss)| to_profile_time(*time))
962                            .collect(),
963                        time_deltas: Vec::new(),
964                        number: repeat_n(0, self.memory.len()).collect(),
965                        count: once(self.memory[0].1 as i64)
966                            .chain(
967                                self.memory
968                                    .iter()
969                                    .map(|(_time, rss)| *rss as i64)
970                                    .tuple_windows()
971                                    .map(|(prev, next)| next - prev),
972                            )
973                            .collect(),
974                        length: self.memory.len(),
975                        other: Default::default(),
976                    }
977                },
978                other: Default::default(),
979            });
980        }
981
982        // Produce the output, gzipping it if the input was gzipped.
983        let output = serde_json::to_vec(&profile).unwrap();
984        let output = if gzip {
985            let mut gzipped_output = Vec::new();
986            GzEncoder::new(Cursor::new(output), Compression::fast())
987                .read_to_end(&mut gzipped_output)
988                .unwrap();
989            gzipped_output
990        } else {
991            output
992        };
993
994        return Ok(output);
995
996        /// This is the [Gecko profiler] format.
997        ///
998        /// [Gecko profiler]: https://github.com/firefox-devtools/profiler/blob/main/src/types/profile.ts
999        #[derive(Debug, Serialize, Deserialize)]
1000        #[serde(rename_all = "camelCase")]
1001        struct Profile {
1002            meta: Meta,
1003            threads: Vec<Thread>,
1004            #[serde(default)]
1005            counters: Vec<RawCounter>,
1006            shared: Shared,
1007            #[serde(flatten)]
1008            other: HashMap<String, Value>,
1009        }
1010
1011        #[derive(Debug, Serialize, Deserialize)]
1012        #[serde(rename_all = "camelCase")]
1013        struct Meta {
1014            product: String,
1015            #[serde(rename = "oscpu")]
1016            os_cpu: String,
1017            start_time: f64,
1018            categories: Vec<Category>,
1019            marker_schema: Vec<Value>,
1020            #[serde(flatten)]
1021            other: HashMap<String, Value>,
1022        }
1023
1024        #[derive(Debug, Serialize, Deserialize)]
1025        #[serde(rename_all = "camelCase")]
1026        struct Category {
1027            color: String,
1028            name: String,
1029            #[serde(flatten)]
1030            other: HashMap<String, Value>,
1031        }
1032
1033        #[derive(Debug, Serialize, Deserialize)]
1034        #[serde(rename_all = "camelCase")]
1035        struct Thread {
1036            name: Option<String>,
1037            #[serde(default)]
1038            markers: ProfileMarkers,
1039            tid: Option<String>,
1040            pid: String,
1041            #[serde(flatten)]
1042            other: HashMap<String, Value>,
1043        }
1044
1045        #[derive(Default, Debug, Serialize, Deserialize)]
1046        #[serde(rename_all = "camelCase")]
1047        struct ProfileMarkers {
1048            length: usize,
1049            category: Vec<usize>,
1050            data: Vec<ProfileMarkerData>,
1051            start_time: Vec<Timestamp>,
1052            end_time: Vec<Timestamp>,
1053            name: Vec<usize>,
1054            phase: Vec<usize>,
1055        }
1056
1057        #[derive(Default, Debug, Serialize, Deserialize)]
1058        #[serde(rename_all = "camelCase")]
1059        struct ProfileMarkerData {
1060            #[serde(rename = "type")]
1061            type_: Cow<'static, str>,
1062            name: usize,
1063        }
1064
1065        #[derive(Debug, Serialize, Deserialize)]
1066        #[serde(rename_all = "camelCase")]
1067        struct Shared {
1068            string_array: Vec<String>,
1069            #[serde(flatten)]
1070            other: HashMap<String, Value>,
1071        }
1072
1073        impl Shared {
1074            fn add_name(&mut self, name: &str) -> usize {
1075                let index = self.string_array.len();
1076                self.string_array.push(name.into());
1077                index
1078            }
1079        }
1080
1081        #[derive(Default, Debug, Serialize, Deserialize)]
1082        #[serde(rename_all = "camelCase")]
1083        struct RawCounter {
1084            name: String,
1085            category: String,
1086            description: String,
1087            pid: String,
1088            main_thread_index: usize,
1089            samples: RawCounterSamplesTable,
1090            #[serde(flatten)]
1091            other: HashMap<String, Value>,
1092        }
1093
1094        #[derive(Default, Debug, Serialize, Deserialize)]
1095        #[serde(rename_all = "camelCase")]
1096        struct RawCounterSamplesTable {
1097            #[serde(default, skip_serializing_if = "Vec::is_empty")]
1098            time: Vec<Timestamp>,
1099            #[serde(default, skip_serializing_if = "Vec::is_empty")]
1100            time_deltas: Vec<Timestamp>,
1101            #[serde(default, skip_serializing_if = "Vec::is_empty")]
1102            number: Vec<usize>,
1103            count: Vec<i64>,
1104            length: usize,
1105            #[serde(flatten)]
1106            other: HashMap<String, Value>,
1107        }
1108    }
1109}
1110
1111/// Whether capturing is active.
1112static CAPTURING: AtomicBool = AtomicBool::new(false);
1113
1114/// End time of a marker.
1115#[derive(Clone, Debug)]
1116enum MarkerEnd {
1117    /// A particular end time for a [Span].
1118    At(Timestamp),
1119
1120    /// A possible end time for a [LongSpan].  If the span has not yet ended,
1121    /// this is `None`.
1122    Long(Arc<AtomicOptionTimestamp>),
1123}
1124
1125impl MarkerEnd {
1126    /// Returns false if this marker should be dropped because it is no longer
1127    /// significant.
1128    ///
1129    /// `capturing` specifies whether a capture is currently running.  More
1130    /// markers are relevant when a capture is running because they will be
1131    /// recorded when the capture ends.
1132    fn should_keep(&self, capturing: bool) -> bool {
1133        if let MarkerEnd::Long(timestamp) = self {
1134            if timestamp.load().is_some() {
1135                // Drop it if there is no capture running, because it ended
1136                // before any new capture can start.
1137                capturing
1138            } else if Arc::strong_count(timestamp) > 1 {
1139                // There's another owner who might eventually complete this span.
1140                true
1141            } else {
1142                // This span is orphaned and will never complete.  One could
1143                // argue for keeping it.  We drop it to avoid having a kind of
1144                // memory leak.
1145                //
1146                // We keep it if a capture is running, so that it is included in
1147                // the current capture.
1148                capturing
1149            }
1150        } else {
1151            false
1152        }
1153    }
1154
1155    /// Returns the inner timestamp, or `None` if there isn't one yet because
1156    /// this is an ongoing [LongSpan].
1157    fn timestamp(&self) -> Option<Timestamp> {
1158        match self {
1159            MarkerEnd::At(timestamp) => Some(*timestamp),
1160            MarkerEnd::Long(timestamp) => timestamp.load(),
1161        }
1162    }
1163}
1164
1165/// A single marker as captured.
1166#[derive(Clone, Debug)]
1167struct Marker {
1168    /// Start time.
1169    start: Timestamp,
1170    /// End time.
1171    end: MarkerEnd,
1172    /// Category (used for outer grouping).
1173    category: &'static str,
1174    /// Name (used for inner grouping).
1175    name: &'static str,
1176    /// Shown on hover.
1177    tooltip: String,
1178}
1179
1180/// Markers for a given thread.
1181#[derive(Clone)]
1182struct ThreadMarkers {
1183    /// The thread's tid.
1184    ///
1185    /// We need this to identify this thread in the profiler file.
1186    tid: usize,
1187
1188    /// The thread's name.
1189    ///
1190    /// The profiler gets thread names from the kernel, but they are truncated
1191    /// at 15 bytes.  We supply the full thread name.
1192    name: Option<String>,
1193
1194    /// The thread's markers.
1195    ///
1196    /// The thread itself records [Event]s and [Span]s by pushing them onto the
1197    /// queue.  [Capture::finish] pops them all off.
1198    queue: Arc<Queue>,
1199}
1200
1201impl ThreadMarkers {
1202    fn new(queue: Arc<Queue>) -> Self {
1203        #[cfg(target_os = "linux")]
1204        let tid = nix::unistd::gettid().as_raw() as usize;
1205        #[cfg(not(target_os = "linux"))]
1206        let tid = thread_id::get();
1207
1208        Self {
1209            tid,
1210            name: std::thread::current().name().map(|s| s.into()),
1211            queue,
1212        }
1213    }
1214}
1215
1216/// [ThreadMarkers] for every thread that has recorded a marker.
1217static ALL_THREAD_MARKERS: std::sync::Mutex<Vec<ThreadMarkers>> = std::sync::Mutex::new(Vec::new());
1218
1219static FREE_BLOCKS: AtomicI64 = AtomicI64::new(0);
1220const MARKERS_PER_BLOCK: usize = 32;
1221const BYTES_PER_BLOCK: usize = MARKERS_PER_BLOCK * Span::BYTES;
1222
1223struct Block(Vec<Marker>);
1224impl Block {
1225    fn new(marker: Marker) -> Self {
1226        let mut markers = Vec::with_capacity(MARKERS_PER_BLOCK);
1227        markers.push(marker);
1228        Self(markers)
1229    }
1230    fn is_full(&self) -> bool {
1231        self.0.len() >= self.0.capacity()
1232    }
1233    fn push(&mut self, marker: Marker) {
1234        self.0.push(marker);
1235    }
1236}
1237
1238struct Blocks(Vec<Block>);
1239
1240impl Default for Blocks {
1241    fn default() -> Self {
1242        Self(Vec::with_capacity(32))
1243    }
1244}
1245
1246impl Blocks {
1247    fn push(&mut self, marker: Marker) {
1248        if let Some(block) = self.0.last_mut()
1249            && !block.is_full()
1250        {
1251            block.push(marker);
1252        } else {
1253            match FREE_BLOCKS.fetch_sub(1, Ordering::Relaxed) {
1254                1.. => self.0.push(Block::new(marker)),
1255                0 => warn!("marker capture space exhausted"),
1256                _ => (),
1257            }
1258        }
1259    }
1260
1261    fn iter(&self) -> impl Iterator<Item = &Marker> {
1262        self.0.iter().flat_map(|block| block.0.iter())
1263    }
1264}
1265
1266#[derive(Debug, Default)]
1267struct LongSpans {
1268    markers: Vec<Marker>,
1269}
1270
1271impl LongSpans {
1272    fn push(&mut self, marker: Marker) {
1273        if self.markers.len() == self.markers.capacity() {
1274            // Do garbage collection.
1275            let capturing = Capture::is_active();
1276            self.markers
1277                .retain(|marker| marker.end.should_keep(capturing));
1278        }
1279        self.markers.push(marker);
1280    }
1281
1282    fn append(&mut self, other: &mut Vec<Marker>) {
1283        if self.markers.is_empty() {
1284            swap(&mut self.markers, other);
1285        } else {
1286            self.markers.append(other);
1287        }
1288    }
1289}
1290
1291struct Queue {
1292    /// Records [Span] and [Event] markers.
1293    blocks: std::sync::Mutex<Blocks>,
1294
1295    /// Records [LongSpan] markers.
1296    ///
1297    /// These are recorded separately because they are not accounted the same
1298    /// way and because they need to be garbage collected.
1299    long_spans: std::sync::Mutex<LongSpans>,
1300}
1301
1302impl Queue {
1303    fn new() -> Arc<Self> {
1304        let queue = Arc::new(Self {
1305            blocks: Default::default(),
1306            long_spans: Default::default(),
1307        });
1308        ALL_THREAD_MARKERS
1309            .lock()
1310            .unwrap()
1311            .push(ThreadMarkers::new(queue.clone()));
1312        queue
1313    }
1314
1315    /// Adds `marker` if there's room with the limit.
1316    fn push(&self, marker: Marker) {
1317        self.blocks.lock().unwrap().push(marker);
1318    }
1319
1320    /// Adds `marker` to the collection of long spans.
1321    fn push_long_span(&self, marker: Marker) {
1322        self.long_spans.lock().unwrap().push(marker);
1323    }
1324
1325    fn take_blocks(&self) -> Blocks {
1326        std::mem::take(&mut *self.blocks.lock().unwrap())
1327    }
1328
1329    fn take_long_spans(&self) -> Vec<Marker> {
1330        let old_long_spans = std::mem::take(&mut *self.long_spans.lock().unwrap()).markers;
1331
1332        // Requeue the long spans that we removed that should stay in place.
1333        let mut new_long_spans = Vec::with_capacity(old_long_spans.capacity());
1334        for marker in &old_long_spans {
1335            if marker.end.should_keep(false) {
1336                new_long_spans.push(marker.clone());
1337            }
1338        }
1339        if !new_long_spans.is_empty() {
1340            self.long_spans.lock().unwrap().append(&mut new_long_spans);
1341        }
1342
1343        old_long_spans
1344    }
1345}
1346
1347thread_local! {
1348    static QUEUE: Arc<Queue> = Queue::new();
1349}