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 fn new(value: Option<Timestamp>) -> Self {
86 Self(AtomicI64::new(
87 value.map_or(i64::MIN, |timestamp| timestamp.0),
88 ))
89 }
90
91 fn load(&self) -> Option<Timestamp> {
92 let value = self.0.load(Ordering::Relaxed);
93 (value != i64::MIN).then_some(Timestamp(value))
94 }
95
96 fn store(&self, value: Option<Timestamp>) {
97 self.0.store(
98 value.map_or(i64::MIN, |timestamp| timestamp.0),
99 Ordering::Relaxed,
100 )
101 }
102}
103
104#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
105#[repr(transparent)]
106struct Timestamp(
107 i64,
116);
117
118#[cfg(target_os = "macos")]
119fn mach_absolute_time_nanos() -> i64 {
120 use mach2::mach_time::{mach_absolute_time, mach_timebase_info, mach_timebase_info_data_t};
121 use std::sync::OnceLock;
122
123 static NANOS_PER_TICK: OnceLock<(u32, u32)> = OnceLock::new();
124 let (numer, denom) = *NANOS_PER_TICK.get_or_init(|| {
125 let mut info = mach_timebase_info_data_t { numer: 0, denom: 0 };
126 unsafe {
127 mach_timebase_info(&mut info);
128 }
129 if info.denom == 0 {
130 (1, 1)
131 } else {
132 (info.numer, info.denom)
133 }
134 });
135 let ticks = unsafe { mach_absolute_time() };
136 (ticks * u64::from(numer) / u64::from(denom)) as i64
137}
138
139impl Timestamp {
140 fn now() -> Self {
141 #[cfg(target_os = "macos")]
142 {
143 Self(mach_absolute_time_nanos())
144 }
145
146 #[cfg(not(target_os = "macos"))]
147 {
148 let now = clock_gettime(ClockId::CLOCK_MONOTONIC).unwrap();
149 Self(now.tv_sec() as i64 * 1_000_000_000 + now.tv_nsec() as i64)
150 }
151 }
152}
153
154#[cfg(target_os = "macos")]
156fn unix_epoch_nanos() -> i64 {
157 SystemTime::now()
158 .duration_since(UNIX_EPOCH)
159 .expect("system clock is before Unix epoch")
160 .as_nanos() as i64
161}
162
163impl From<Instant> for Timestamp {
164 fn from(value: Instant) -> Self {
165 let zero = unsafe { std::mem::zeroed::<Instant>() };
178 Self((value - zero).as_nanos() as i64)
179 }
180}
181
182impl Display for Timestamp {
183 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
184 write!(f, "{}", self.0)
185 }
186}
187
188impl Serialize for Timestamp {
189 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
193 where
194 S: serde::Serializer,
195 {
196 let milliseconds = self.0 as f64 / 1_000_000.0;
197 milliseconds.serialize(serializer)
198 }
199}
200
201impl<'de> Deserialize<'de> for Timestamp {
202 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
206 where
207 D: serde::Deserializer<'de>,
208 {
209 let milliseconds = f64::deserialize(deserializer)?;
210 Ok(Self((milliseconds * 1_000_000.0) as i64))
211 }
212}
213
214impl Debug for Span {
215 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
216 write!(f, "Span")?;
217 if let Some(inner) = &self.0 {
218 write!(f, "({})", &inner.name)?;
219 }
220 Ok(())
221 }
222}
223
224struct SpanInner {
225 start: Timestamp,
226 category: &'static str,
227 name: &'static str,
228 tooltip: String,
229}
230
231impl SpanInner {
232 #[cold]
233 fn new(name: &'static str) -> Self {
234 Self {
235 start: Timestamp::now(),
236 category: "Other",
237 name,
238 tooltip: String::new(),
239 }
240 }
241
242 fn into_marker(self, end: MarkerEnd) -> Marker {
243 Marker {
244 start: self.start,
245 end,
246 category: self.category,
247 name: self.name,
248 tooltip: self.tooltip,
249 }
250 }
251
252 #[cold]
253 fn record(self, end: MarkerEnd) {
254 QUEUE.with(|queue| queue.push(self.into_marker(end)));
255 }
256}
257
258pub struct Span(Option<SpanInner>);
270
271impl Span {
272 pub const BYTES: usize = std::mem::size_of::<Marker>();
275
276 #[must_use]
288 pub fn new(name: &'static str) -> Self {
289 Self(Capture::is_active().then(|| SpanInner::new(name)))
290 }
291
292 #[must_use]
299 pub fn with_category(mut self, category: &'static str) -> Self {
300 if let Some(inner) = &mut self.0 {
301 inner.category = category;
302 }
303 self
304 }
305
306 #[must_use]
314 pub fn with_tooltip<F>(mut self, tooltip: F) -> Self
315 where
316 F: FnOnce() -> String,
317 {
318 if let Some(inner) = &mut self.0 {
319 inner.tooltip = tooltip();
320 }
321 self
322 }
323
324 #[must_use]
328 pub fn with_start(mut self, start: Instant) -> Self {
329 if let Some(inner) = &mut self.0 {
330 inner.start = start.into();
331 }
332 self
333 }
334
335 pub fn in_scope<F, T>(self, f: F) -> T
337 where
338 F: FnOnce() -> T,
339 {
340 f()
341 }
342
343 pub fn record(self) {
345 }
347
348 pub fn cancel(mut self) {
350 let _ = self.0.take();
351 }
352}
353
354impl Drop for Span {
355 fn drop(&mut self) {
356 if let Some(inner) = self.0.take() {
357 inner.record(MarkerEnd::At(Timestamp::now()))
358 }
359 }
360}
361
362pub struct LongSpanBuilder(SpanInner);
364
365impl LongSpanBuilder {
366 #[must_use]
373 pub fn new(name: &'static str) -> Self {
374 Self(SpanInner::new(name))
375 }
376
377 #[must_use]
384 pub fn with_category(mut self, category: &'static str) -> Self {
385 self.0.category = category;
386 self
387 }
388
389 #[must_use]
395 pub fn with_tooltip(mut self, tooltip: impl Into<String>) -> Self {
396 self.0.tooltip = tooltip.into();
397 self
398 }
399
400 #[must_use]
404 pub fn with_start(mut self, start: Instant) -> Self {
405 self.0.start = start.into();
406 self
407 }
408
409 #[must_use]
411 pub fn build(self) -> LongSpan {
412 let timestamp = Arc::new(AtomicOptionTimestamp::default());
413 QUEUE.with(|queue| {
414 queue.push_long_span(self.0.into_marker(MarkerEnd::Long(timestamp.clone())))
415 });
416 LongSpan(timestamp)
417 }
418}
419
420pub struct LongSpan(Arc<AtomicOptionTimestamp>);
430
431impl LongSpan {
432 pub fn complete(self) {
436 }
438}
439
440impl Drop for LongSpan {
441 fn drop(&mut self) {
442 self.0.store(Some(Timestamp::now()));
443 }
444}
445
446pub struct Event(Option<SpanInner>);
458
459impl Event {
460 #[must_use]
469 pub fn new(name: &'static str) -> Self {
470 Self(Capture::is_active().then(|| SpanInner::new(name)))
471 }
472
473 #[must_use]
480 pub fn with_category(mut self, category: &'static str) -> Self {
481 if let Some(inner) = &mut self.0 {
482 inner.category = category;
483 }
484 self
485 }
486
487 #[must_use]
495 pub fn with_tooltip<F>(mut self, tooltip: F) -> Self
496 where
497 F: FnOnce() -> String,
498 {
499 if let Some(inner) = &mut self.0 {
500 inner.tooltip = tooltip();
501 }
502 self
503 }
504
505 pub fn record(self) {
507 if let Some(inner) = self.0 {
508 let end = MarkerEnd::At(inner.start);
509 inner.record(end);
510 }
511 }
512}
513
514#[derive(Clone, Debug)]
516pub struct CaptureOptions {
517 memory_limit: Option<usize>,
518 record_rss: bool,
519}
520
521impl Default for CaptureOptions {
522 fn default() -> Self {
523 Self {
524 memory_limit: None,
525 record_rss: true,
526 }
527 }
528}
529
530impl CaptureOptions {
531 pub fn new() -> Self {
533 Self::default()
534 }
535
536 pub fn with_memory_limit(self, memory_limit: Option<usize>) -> Self {
543 Self {
544 memory_limit,
545 ..self
546 }
547 }
548
549 pub fn with_record_rss(self, record_rss: bool) -> Self {
554 Self { record_rss, ..self }
555 }
556
557 pub async fn start(self) -> Capture {
564 Capture::new(self, CAPTURE_MUTEX.lock().await)
565 }
566
567 pub fn blocking_start(self) -> Capture {
578 Capture::new(self, CAPTURE_MUTEX.blocking_lock())
579 }
580
581 pub fn try_start(self) -> Result<Capture, Self> {
588 let guard = match CAPTURE_MUTEX.try_lock() {
589 Ok(guard) => guard,
590 Err(_) => return Err(self),
591 };
592 Ok(Capture::new(self, guard))
593 }
594}
595
596static CAPTURE_MUTEX: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
597
598pub struct Capture {
605 _guard: tokio::sync::MutexGuard<'static, ()>,
606 memory: Option<JoinHandle<Vec<(Timestamp, usize)>>>,
607 unparker: Unparker,
608 request_exit: Arc<AtomicBool>,
609 block_limit: i64,
610 #[cfg(target_os = "macos")]
611 anchor: (Timestamp, i64),
612}
613
614impl Capture {
615 fn new(params: CaptureOptions, guard: tokio::sync::MutexGuard<'static, ()>) -> Self {
616 if let Some(memory_limit) = params.memory_limit {
617 tracing::info!(
618 "marker capture limited to {}",
619 HumanBytes::from(memory_limit)
620 );
621 }
622 let block_limit = params.memory_limit.map_or(i64::MAX, |memory_limit| {
623 (memory_limit / BYTES_PER_BLOCK) as i64
624 });
625 let parker = Parker::new();
626 let unparker = parker.unparker().clone();
627 let request_exit = Arc::new(AtomicBool::new(false));
628 let memory = params.record_rss.then(|| {
629 std::thread::Builder::new()
630 .name(String::from("capture-rss"))
631 .spawn({
632 let request_exit = request_exit.clone();
633 move || {
634 let mut memory = Vec::new();
635 while !request_exit.load(Ordering::Acquire) {
636 if let Some(memory_stats) = memory_stats() {
637 memory.push((Timestamp::now(), memory_stats.physical_mem));
638 }
639 parker.park_timeout(Duration::from_millis(100));
640 }
641 memory
642 }
643 })
644 .expect("should be able to start a capture thread")
645 });
646 FREE_BLOCKS.store(block_limit, Ordering::Relaxed);
647 CAPTURING.store(true, Ordering::Release);
648 Self {
649 block_limit,
650 memory,
651 unparker,
652 request_exit,
653 #[cfg(target_os = "macos")]
654 anchor: (Timestamp::now(), unix_epoch_nanos()),
655 _guard: guard,
656 }
657 }
658
659 pub fn finish(mut self) -> Annotations {
661 let end_time = Timestamp::now();
662 CAPTURING.store(false, Ordering::Release);
663 let remaining_blocks = FREE_BLOCKS.load(Ordering::Relaxed);
664 if remaining_blocks <= 0 {
665 tracing::info!("marker capture exceeded the limit");
666 } else {
667 let used_bytes = (self.block_limit - remaining_blocks) as usize * BYTES_PER_BLOCK;
668 tracing::info!("marker capture used {}", HumanBytes::from(used_bytes));
669 }
670
671 let markers = self
672 .all_threads()
673 .into_iter()
674 .map(|thread| {
675 let mut blocks = thread.queue.take_blocks();
676
677 let long_spans = thread.queue.take_long_spans();
678 if !long_spans.is_empty() {
679 blocks.0.push(Block(long_spans));
680 }
681
682 (thread.tid, (thread.name, blocks))
683 })
684 .collect();
685
686 Annotations {
687 end_time,
688 markers,
689 memory: self.take_memory(),
690 #[cfg(target_os = "macos")]
691 anchor: self.anchor,
692 }
693 }
694
695 pub fn abort(self) {
699 tracing::info!("aborting profile annotation capture");
700 }
701
702 pub fn is_active() -> bool {
709 CAPTURING.load(Ordering::Acquire)
710 }
711
712 fn all_threads(&mut self) -> Vec<ThreadMarkers> {
713 ALL_THREAD_MARKERS.lock().unwrap().clone()
714 }
715
716 fn take_memory(&mut self) -> Vec<(Timestamp, usize)> {
717 if let Some(memory) = self.memory.take() {
718 self.request_exit.store(true, Ordering::Release);
719 self.unparker.unpark();
720 memory.join().unwrap_or_default()
721 } else {
722 Default::default()
723 }
724 }
725}
726
727impl Drop for Capture {
728 fn drop(&mut self) {
729 self.take_memory();
730
731 CAPTURING.store(false, Ordering::Release);
734 }
735}
736
737#[derive(thiserror::Error, Debug)]
739pub enum Error {
740 #[error("Error decompressing profile ")]
742 GzDecoderError(#[from] std::io::Error),
743
744 #[error("Error parsing profile")]
746 SerdeError(#[from] serde_json_path_to_error::Error),
747}
748
749#[derive(Default, Clone, Debug)]
751pub struct AnnotationOptions {
752 product: Option<String>,
753 os_cpu: Option<String>,
754}
755
756impl AnnotationOptions {
757 pub fn new() -> Self {
759 Self::default()
760 }
761
762 pub fn with_product(self, product: Option<impl Into<String>>) -> Self {
768 Self {
769 product: product.map(|s| s.into()),
770 ..self
771 }
772 }
773
774 pub fn with_os_cpu(self, os_cpu: Option<impl Into<String>>) -> Self {
780 Self {
781 os_cpu: os_cpu.map(|s| s.into()),
782 ..self
783 }
784 }
785}
786
787pub struct Annotations {
791 end_time: Timestamp,
792 markers: HashMap<usize, (Option<String>, Blocks)>,
793 memory: Vec<(Timestamp, usize)>,
794 #[cfg(target_os = "macos")]
795 anchor: (Timestamp, i64),
796}
797
798impl Annotations {
799 pub fn apply(&self, profile: &[u8], options: AnnotationOptions) -> Result<Vec<u8>, Error> {
806 let mut buffer = Vec::new();
809 let json = if profile.starts_with(&[0x1f, 0x8b]) {
810 GzDecoder::new(profile).read_to_end(&mut buffer)?;
811 &buffer
812 } else {
813 profile
814 };
815 let gzip = !buffer.is_empty();
816
817 let mut profile = serde_json_path_to_error::from_slice::<Profile>(json)?;
819
820 #[cfg(target_os = "macos")]
841 let to_profile_time = {
842 let profile_start_time_ms = profile.meta.start_time;
843 let (anchor_monotonic_ns, anchor_wall_clock_ns) = self.anchor;
844 let profile_start_wall_clock_ns = (profile_start_time_ms * 1_000_000.0) as i64;
845 let adjustment_ns = anchor_wall_clock_ns - profile_start_wall_clock_ns;
846 move |timestamp: Timestamp| {
847 Timestamp(timestamp.0 - anchor_monotonic_ns.0 + adjustment_ns)
848 }
849 };
850 #[cfg(not(target_os = "macos"))]
851 let to_profile_time = |timestamp: Timestamp| timestamp;
852
853 if let Some(product) = options.product {
854 profile.meta.product = product;
855 }
856 if let Some(os_cpu) = options.os_cpu {
857 profile.meta.os_cpu = os_cpu;
858 }
859 profile.meta.marker_schema.push(json!({
860 "name": "FelderaMarker",
861 "display": [
862 "marker-chart",
863 "marker-table"
864 ],
865 "chartLabel": "{marker.data.name}",
866 "tooltipLabel": "{marker.data.name}",
867 "tableLabel": "{marker.data.name}",
868 "description": "Marker generated by Feldera.",
869 "fields": [
870 {
871 "key": "name",
872 "label": "Name",
873 "format": "unique-string"
874 }
875 ]
876 }));
877 static CATEGORY_COLORS: [&str; 12] = [
880 "purple",
881 "green",
882 "orange",
883 "yellow",
884 "lightblue",
885 "blue",
886 "brown",
887 "magenta",
888 "red",
889 "lightred",
890 "darkgrey",
891 "grey",
892 ];
893 let mut categories = profile
894 .meta
895 .categories
896 .iter()
897 .enumerate()
898 .map(|(index, category)| (category.name.clone(), index))
899 .collect::<HashMap<_, _>>();
900 for (category, color) in self
901 .markers
902 .values()
903 .flat_map(|(_, markers)| markers.iter())
904 .map(|marker| marker.category)
905 .collect::<HashSet<_>>()
906 .into_iter()
907 .zip(CATEGORY_COLORS.iter().cycle())
908 {
909 categories.insert(category.into(), profile.meta.categories.len());
910 profile.meta.categories.push(Category {
911 color: (*color).into(),
912 name: category.into(),
913 other: [(String::from("subcategories"), json!(["Other"]))]
914 .into_iter()
915 .collect(),
916 });
917 }
918 for thread in &mut profile.threads {
919 if let Some(tid) = &thread.tid
920 && let Ok(tid) = tid.parse::<usize>()
921 && let Some((name, markers)) = self.markers.get(&tid)
922 {
923 if let Some(name) = name {
924 thread.name = Some(name.clone());
925 }
926 for marker in markers.iter() {
927 thread.markers.length += 1;
928 thread.markers.category.push(categories[marker.category]);
929 thread.markers.data.push(ProfileMarkerData {
930 type_: Cow::from("FelderaMarker"),
931 name: profile.shared.add_name(&marker.tooltip),
932 });
933 thread
934 .markers
935 .start_time
936 .push(to_profile_time(marker.start));
937 thread.markers.end_time.push(to_profile_time(
938 marker.end.timestamp().unwrap_or(self.end_time),
939 ));
940 thread
941 .markers
942 .name
943 .push(profile.shared.add_name(marker.name));
944 thread.markers.phase.push(1);
945 }
946 }
947 }
948
949 if !self.memory.is_empty() {
950 profile.counters.push(RawCounter {
951 name: String::from("RSS"),
952 category: String::from("Memory"),
953 description: String::from("RSS in bytes"),
954 pid: profile.threads.first().unwrap().pid.clone(),
955 main_thread_index: 0,
956 samples: {
957 RawCounterSamplesTable {
958 time: self
959 .memory
960 .iter()
961 .map(|(time, _rss)| to_profile_time(*time))
962 .collect(),
963 time_deltas: Vec::new(),
964 number: repeat_n(0, self.memory.len()).collect(),
965 count: once(self.memory[0].1 as i64)
966 .chain(
967 self.memory
968 .iter()
969 .map(|(_time, rss)| *rss as i64)
970 .tuple_windows()
971 .map(|(prev, next)| next - prev),
972 )
973 .collect(),
974 length: self.memory.len(),
975 other: Default::default(),
976 }
977 },
978 other: Default::default(),
979 });
980 }
981
982 let output = serde_json::to_vec(&profile).unwrap();
984 let output = if gzip {
985 let mut gzipped_output = Vec::new();
986 GzEncoder::new(Cursor::new(output), Compression::fast())
987 .read_to_end(&mut gzipped_output)
988 .unwrap();
989 gzipped_output
990 } else {
991 output
992 };
993
994 return Ok(output);
995
996 #[derive(Debug, Serialize, Deserialize)]
1000 #[serde(rename_all = "camelCase")]
1001 struct Profile {
1002 meta: Meta,
1003 threads: Vec<Thread>,
1004 #[serde(default)]
1005 counters: Vec<RawCounter>,
1006 shared: Shared,
1007 #[serde(flatten)]
1008 other: HashMap<String, Value>,
1009 }
1010
1011 #[derive(Debug, Serialize, Deserialize)]
1012 #[serde(rename_all = "camelCase")]
1013 struct Meta {
1014 product: String,
1015 #[serde(rename = "oscpu")]
1016 os_cpu: String,
1017 start_time: f64,
1018 categories: Vec<Category>,
1019 marker_schema: Vec<Value>,
1020 #[serde(flatten)]
1021 other: HashMap<String, Value>,
1022 }
1023
1024 #[derive(Debug, Serialize, Deserialize)]
1025 #[serde(rename_all = "camelCase")]
1026 struct Category {
1027 color: String,
1028 name: String,
1029 #[serde(flatten)]
1030 other: HashMap<String, Value>,
1031 }
1032
1033 #[derive(Debug, Serialize, Deserialize)]
1034 #[serde(rename_all = "camelCase")]
1035 struct Thread {
1036 name: Option<String>,
1037 #[serde(default)]
1038 markers: ProfileMarkers,
1039 tid: Option<String>,
1040 pid: String,
1041 #[serde(flatten)]
1042 other: HashMap<String, Value>,
1043 }
1044
1045 #[derive(Default, Debug, Serialize, Deserialize)]
1046 #[serde(rename_all = "camelCase")]
1047 struct ProfileMarkers {
1048 length: usize,
1049 category: Vec<usize>,
1050 data: Vec<ProfileMarkerData>,
1051 start_time: Vec<Timestamp>,
1052 end_time: Vec<Timestamp>,
1053 name: Vec<usize>,
1054 phase: Vec<usize>,
1055 }
1056
1057 #[derive(Default, Debug, Serialize, Deserialize)]
1058 #[serde(rename_all = "camelCase")]
1059 struct ProfileMarkerData {
1060 #[serde(rename = "type")]
1061 type_: Cow<'static, str>,
1062 name: usize,
1063 }
1064
1065 #[derive(Debug, Serialize, Deserialize)]
1066 #[serde(rename_all = "camelCase")]
1067 struct Shared {
1068 string_array: Vec<String>,
1069 #[serde(flatten)]
1070 other: HashMap<String, Value>,
1071 }
1072
1073 impl Shared {
1074 fn add_name(&mut self, name: &str) -> usize {
1075 let index = self.string_array.len();
1076 self.string_array.push(name.into());
1077 index
1078 }
1079 }
1080
1081 #[derive(Default, Debug, Serialize, Deserialize)]
1082 #[serde(rename_all = "camelCase")]
1083 struct RawCounter {
1084 name: String,
1085 category: String,
1086 description: String,
1087 pid: String,
1088 main_thread_index: usize,
1089 samples: RawCounterSamplesTable,
1090 #[serde(flatten)]
1091 other: HashMap<String, Value>,
1092 }
1093
1094 #[derive(Default, Debug, Serialize, Deserialize)]
1095 #[serde(rename_all = "camelCase")]
1096 struct RawCounterSamplesTable {
1097 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1098 time: Vec<Timestamp>,
1099 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1100 time_deltas: Vec<Timestamp>,
1101 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1102 number: Vec<usize>,
1103 count: Vec<i64>,
1104 length: usize,
1105 #[serde(flatten)]
1106 other: HashMap<String, Value>,
1107 }
1108 }
1109}
1110
1111static CAPTURING: AtomicBool = AtomicBool::new(false);
1113
1114#[derive(Clone, Debug)]
1116enum MarkerEnd {
1117 At(Timestamp),
1119
1120 Long(Arc<AtomicOptionTimestamp>),
1123}
1124
1125impl MarkerEnd {
1126 fn should_keep(&self, capturing: bool) -> bool {
1133 if let MarkerEnd::Long(timestamp) = self {
1134 if timestamp.load().is_some() {
1135 capturing
1138 } else if Arc::strong_count(timestamp) > 1 {
1139 true
1141 } else {
1142 capturing
1149 }
1150 } else {
1151 false
1152 }
1153 }
1154
1155 fn timestamp(&self) -> Option<Timestamp> {
1158 match self {
1159 MarkerEnd::At(timestamp) => Some(*timestamp),
1160 MarkerEnd::Long(timestamp) => timestamp.load(),
1161 }
1162 }
1163}
1164
1165#[derive(Clone, Debug)]
1167struct Marker {
1168 start: Timestamp,
1170 end: MarkerEnd,
1172 category: &'static str,
1174 name: &'static str,
1176 tooltip: String,
1178}
1179
1180#[derive(Clone)]
1182struct ThreadMarkers {
1183 tid: usize,
1187
1188 name: Option<String>,
1193
1194 queue: Arc<Queue>,
1199}
1200
1201impl ThreadMarkers {
1202 fn new(queue: Arc<Queue>) -> Self {
1203 #[cfg(target_os = "linux")]
1204 let tid = nix::unistd::gettid().as_raw() as usize;
1205 #[cfg(not(target_os = "linux"))]
1206 let tid = thread_id::get();
1207
1208 Self {
1209 tid,
1210 name: std::thread::current().name().map(|s| s.into()),
1211 queue,
1212 }
1213 }
1214}
1215
1216static ALL_THREAD_MARKERS: std::sync::Mutex<Vec<ThreadMarkers>> = std::sync::Mutex::new(Vec::new());
1218
1219static FREE_BLOCKS: AtomicI64 = AtomicI64::new(0);
1220const MARKERS_PER_BLOCK: usize = 32;
1221const BYTES_PER_BLOCK: usize = MARKERS_PER_BLOCK * Span::BYTES;
1222
1223struct Block(Vec<Marker>);
1224impl Block {
1225 fn new(marker: Marker) -> Self {
1226 let mut markers = Vec::with_capacity(MARKERS_PER_BLOCK);
1227 markers.push(marker);
1228 Self(markers)
1229 }
1230 fn is_full(&self) -> bool {
1231 self.0.len() >= self.0.capacity()
1232 }
1233 fn push(&mut self, marker: Marker) {
1234 self.0.push(marker);
1235 }
1236}
1237
1238struct Blocks(Vec<Block>);
1239
1240impl Default for Blocks {
1241 fn default() -> Self {
1242 Self(Vec::with_capacity(32))
1243 }
1244}
1245
1246impl Blocks {
1247 fn push(&mut self, marker: Marker) {
1248 if let Some(block) = self.0.last_mut()
1249 && !block.is_full()
1250 {
1251 block.push(marker);
1252 } else {
1253 match FREE_BLOCKS.fetch_sub(1, Ordering::Relaxed) {
1254 1.. => self.0.push(Block::new(marker)),
1255 0 => warn!("marker capture space exhausted"),
1256 _ => (),
1257 }
1258 }
1259 }
1260
1261 fn iter(&self) -> impl Iterator<Item = &Marker> {
1262 self.0.iter().flat_map(|block| block.0.iter())
1263 }
1264}
1265
1266#[derive(Debug, Default)]
1267struct LongSpans {
1268 markers: Vec<Marker>,
1269}
1270
1271impl LongSpans {
1272 fn push(&mut self, marker: Marker) {
1273 if self.markers.len() == self.markers.capacity() {
1274 let capturing = Capture::is_active();
1276 self.markers
1277 .retain(|marker| marker.end.should_keep(capturing));
1278 }
1279 self.markers.push(marker);
1280 }
1281
1282 fn append(&mut self, other: &mut Vec<Marker>) {
1283 if self.markers.is_empty() {
1284 swap(&mut self.markers, other);
1285 } else {
1286 self.markers.append(other);
1287 }
1288 }
1289}
1290
1291struct Queue {
1292 blocks: std::sync::Mutex<Blocks>,
1294
1295 long_spans: std::sync::Mutex<LongSpans>,
1300}
1301
1302impl Queue {
1303 fn new() -> Arc<Self> {
1304 let queue = Arc::new(Self {
1305 blocks: Default::default(),
1306 long_spans: Default::default(),
1307 });
1308 ALL_THREAD_MARKERS
1309 .lock()
1310 .unwrap()
1311 .push(ThreadMarkers::new(queue.clone()));
1312 queue
1313 }
1314
1315 fn push(&self, marker: Marker) {
1317 self.blocks.lock().unwrap().push(marker);
1318 }
1319
1320 fn push_long_span(&self, marker: Marker) {
1322 self.long_spans.lock().unwrap().push(marker);
1323 }
1324
1325 fn take_blocks(&self) -> Blocks {
1326 std::mem::take(&mut *self.blocks.lock().unwrap())
1327 }
1328
1329 fn take_long_spans(&self) -> Vec<Marker> {
1330 let old_long_spans = std::mem::take(&mut *self.long_spans.lock().unwrap()).markers;
1331
1332 let mut new_long_spans = Vec::with_capacity(old_long_spans.capacity());
1334 for marker in &old_long_spans {
1335 if marker.end.should_keep(false) {
1336 new_long_spans.push(marker.clone());
1337 }
1338 }
1339 if !new_long_spans.is_empty() {
1340 self.long_spans.lock().unwrap().append(&mut new_long_spans);
1341 }
1342
1343 old_long_spans
1344 }
1345}
1346
1347thread_local! {
1348 static QUEUE: Arc<Queue> = Queue::new();
1349}