1#![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#[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 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 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#[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 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 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 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
268pub struct Span(Option<SpanInner>);
280
281impl Span {
282 pub const BYTES: usize = std::mem::size_of::<Marker>();
285
286 #[must_use]
298 pub fn new(name: &'static str) -> Self {
299 Self(Capture::is_active().then(|| SpanInner::new(name)))
300 }
301
302 #[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 #[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 #[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 pub fn in_scope<F, T>(self, f: F) -> T
347 where
348 F: FnOnce() -> T,
349 {
350 f()
351 }
352
353 pub fn record(self) {
355 }
357
358 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
372pub struct LongSpanBuilder(SpanInner);
374
375impl LongSpanBuilder {
376 #[must_use]
383 pub fn new(name: &'static str) -> Self {
384 Self(SpanInner::new(name))
385 }
386
387 #[must_use]
394 pub fn with_category(mut self, category: &'static str) -> Self {
395 self.0.category = category;
396 self
397 }
398
399 #[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 #[must_use]
414 pub fn with_start(mut self, start: Instant) -> Self {
415 self.0.start = start.into();
416 self
417 }
418
419 #[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
430pub struct LongSpan(Arc<AtomicOptionTimestamp>);
440
441impl LongSpan {
442 pub fn complete(self) {
446 }
448}
449
450impl Drop for LongSpan {
451 fn drop(&mut self) {
452 self.0.store(Some(Timestamp::now()));
453 }
454}
455
456pub struct Event(Option<SpanInner>);
468
469impl Event {
470 #[must_use]
479 pub fn new(name: &'static str) -> Self {
480 Self(Capture::is_active().then(|| SpanInner::new(name)))
481 }
482
483 #[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 #[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 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#[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 pub fn new() -> Self {
543 Self::default()
544 }
545
546 pub fn with_memory_limit(self, memory_limit: Option<usize>) -> Self {
553 Self {
554 memory_limit,
555 ..self
556 }
557 }
558
559 pub fn with_record_rss(self, record_rss: bool) -> Self {
564 Self { record_rss, ..self }
565 }
566
567 pub async fn start(self) -> Capture {
574 Capture::new(self, CAPTURE_MUTEX.lock().await)
575 }
576
577 pub fn blocking_start(self) -> Capture {
588 Capture::new(self, CAPTURE_MUTEX.blocking_lock())
589 }
590
591 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
608pub 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 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 pub fn abort(self) {
737 tracing::info!("aborting profile annotation capture");
738 }
739
740 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 CAPTURING.store(false, Ordering::Release);
772 }
773}
774
775#[derive(thiserror::Error, Debug)]
777pub enum Error {
778 #[error("Error decompressing profile ")]
780 GzDecoderError(#[from] std::io::Error),
781
782 #[error("Error parsing profile")]
784 SerdeError(#[from] serde_json_path_to_error::Error),
785}
786
787#[derive(Default, Clone, Debug)]
789pub struct AnnotationOptions {
790 product: Option<String>,
791 os_cpu: Option<String>,
792}
793
794impl AnnotationOptions {
795 pub fn new() -> Self {
797 Self::default()
798 }
799
800 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 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
825pub 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 pub fn apply(&self, profile: &[u8], options: AnnotationOptions) -> Result<Vec<u8>, Error> {
845 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 let mut profile = serde_json_path_to_error::from_slice::<Profile>(json)?;
858
859 #[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 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 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 #[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
1150static CAPTURING: AtomicBool = AtomicBool::new(false);
1152
1153#[derive(Clone, Debug)]
1155enum MarkerEnd {
1156 At(Timestamp),
1158
1159 Long(Arc<AtomicOptionTimestamp>),
1162}
1163
1164impl MarkerEnd {
1165 fn should_keep(&self, capturing: bool) -> bool {
1172 if let MarkerEnd::Long(timestamp) = self {
1173 if timestamp.load().is_some() {
1174 capturing
1177 } else if Arc::strong_count(timestamp) > 1 {
1178 true
1180 } else {
1181 capturing
1188 }
1189 } else {
1190 false
1191 }
1192 }
1193
1194 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#[derive(Clone, Debug)]
1206struct Marker {
1207 start: Timestamp,
1209 end: MarkerEnd,
1211 category: &'static str,
1213 name: &'static str,
1215 tooltip: String,
1217}
1218
1219#[derive(Clone)]
1221struct ThreadMarkers {
1222 tid: usize,
1226
1227 name: Option<String>,
1232
1233 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
1255static ALL_THREAD_MARKERS: std::sync::Mutex<Vec<ThreadMarkers>> = std::sync::Mutex::new(Vec::new());
1257
1258static FREE_BLOCKS: AtomicI64 = AtomicI64::new(0);
1262
1263const MARKERS_PER_BLOCK: usize = 32;
1265
1266const BYTES_PER_BLOCK: usize = MARKERS_PER_BLOCK * Span::BYTES;
1268
1269static 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 if MARKERS_EXHAUSTED.load().is_none() => {
1308 MARKERS_EXHAUSTED.store(Some(Timestamp::now()));
1309 }
1310 _ => (),
1311 }
1312 }
1313 }
1314
1315 fn iter(&self) -> impl Iterator<Item = &Marker> {
1316 self.0.iter().flat_map(|block| block.0.iter())
1317 }
1318}
1319
1320#[derive(Debug, Default)]
1321struct LongSpans {
1322 markers: Vec<Marker>,
1323}
1324
1325impl LongSpans {
1326 fn push(&mut self, marker: Marker) {
1327 if self.markers.len() == self.markers.capacity() {
1328 let capturing = Capture::is_active();
1330 self.markers
1331 .retain(|marker| marker.end.should_keep(capturing));
1332 }
1333 self.markers.push(marker);
1334 }
1335
1336 fn append(&mut self, other: &mut Vec<Marker>) {
1337 if self.markers.is_empty() {
1338 swap(&mut self.markers, other);
1339 } else {
1340 self.markers.append(other);
1341 }
1342 }
1343}
1344
1345struct Queue {
1346 blocks: std::sync::Mutex<Blocks>,
1348
1349 long_spans: std::sync::Mutex<LongSpans>,
1354}
1355
1356impl Queue {
1357 fn new() -> Arc<Self> {
1358 let queue = Arc::new(Self {
1359 blocks: Default::default(),
1360 long_spans: Default::default(),
1361 });
1362 ALL_THREAD_MARKERS
1363 .lock()
1364 .unwrap()
1365 .push(ThreadMarkers::new(queue.clone()));
1366 queue
1367 }
1368
1369 fn push(&self, marker: Marker) {
1371 self.blocks.lock().unwrap().push(marker);
1372 }
1373
1374 fn push_long_span(&self, marker: Marker) {
1376 self.long_spans.lock().unwrap().push(marker);
1377 }
1378
1379 fn take_blocks(&self) -> Blocks {
1380 std::mem::take(&mut *self.blocks.lock().unwrap())
1381 }
1382
1383 fn take_long_spans(&self) -> Vec<Marker> {
1384 let old_long_spans = std::mem::take(&mut *self.long_spans.lock().unwrap()).markers;
1385
1386 let mut new_long_spans = Vec::with_capacity(old_long_spans.capacity());
1388 for marker in &old_long_spans {
1389 if marker.end.should_keep(false) {
1390 new_long_spans.push(marker.clone());
1391 }
1392 }
1393 if !new_long_spans.is_empty() {
1394 self.long_spans.lock().unwrap().append(&mut new_long_spans);
1395 }
1396
1397 old_long_spans
1398 }
1399}
1400
1401thread_local! {
1402 static QUEUE: Arc<Queue> = Queue::new();
1403}