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