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