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
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#[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 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 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 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 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
209pub struct Span(Option<SpanInner>);
221
222impl Span {
223 pub const BYTES: usize = std::mem::size_of::<Marker>();
226
227 #[must_use]
239 pub fn new(name: &'static str) -> Self {
240 Self(Capture::is_active().then(|| SpanInner::new(name)))
241 }
242
243 #[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 #[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 #[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 pub fn in_scope<F, T>(self, f: F) -> T
288 where
289 F: FnOnce() -> T,
290 {
291 f()
292 }
293
294 pub fn record(self) {
296 }
298
299 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
313pub struct LongSpanBuilder(SpanInner);
315
316impl LongSpanBuilder {
317 #[must_use]
324 pub fn new(name: &'static str) -> Self {
325 Self(SpanInner::new(name))
326 }
327
328 #[must_use]
335 pub fn with_category(mut self, category: &'static str) -> Self {
336 self.0.category = category;
337 self
338 }
339
340 #[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 #[must_use]
355 pub fn with_start(mut self, start: Instant) -> Self {
356 self.0.start = start.into();
357 self
358 }
359
360 #[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
371pub struct LongSpan(Arc<AtomicOptionTimestamp>);
381
382impl LongSpan {
383 pub fn complete(self) {
387 }
389}
390
391impl Drop for LongSpan {
392 fn drop(&mut self) {
393 self.0.store(Some(Timestamp::now()));
394 }
395}
396
397pub struct Event(Option<SpanInner>);
409
410impl Event {
411 #[must_use]
420 pub fn new(name: &'static str) -> Self {
421 Self(Capture::is_active().then(|| SpanInner::new(name)))
422 }
423
424 #[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 #[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 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#[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 pub fn new() -> Self {
484 Self::default()
485 }
486
487 pub fn with_memory_limit(self, memory_limit: Option<usize>) -> Self {
494 Self {
495 memory_limit,
496 ..self
497 }
498 }
499
500 pub fn with_record_rss(self, record_rss: bool) -> Self {
505 Self { record_rss, ..self }
506 }
507
508 pub async fn start(self) -> Capture {
515 Capture::new(self, CAPTURE_MUTEX.lock().await)
516 }
517
518 pub fn blocking_start(self) -> Capture {
529 Capture::new(self, CAPTURE_MUTEX.blocking_lock())
530 }
531
532 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
549pub 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 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 pub fn abort(self) {
644 tracing::info!("aborting profile annotation capture");
645 }
646
647 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 CAPTURING.store(false, Ordering::Release);
679 }
680}
681
682#[derive(thiserror::Error, Debug)]
684pub enum Error {
685 #[error("Error decompressing profile ")]
687 GzDecoderError(#[from] std::io::Error),
688
689 #[error("Error parsing profile")]
691 SerdeError(#[from] serde_json_path_to_error::Error),
692}
693
694#[derive(Default, Clone, Debug)]
696pub struct AnnotationOptions {
697 product: Option<String>,
698 os_cpu: Option<String>,
699}
700
701impl AnnotationOptions {
702 pub fn new() -> Self {
704 Self::default()
705 }
706
707 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 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
732pub struct Annotations {
736 end_time: Timestamp,
737 markers: HashMap<usize, (Option<String>, Blocks)>,
738 memory: Vec<(Timestamp, usize)>,
739}
740
741impl Annotations {
742 pub fn apply(&self, profile: &[u8], options: AnnotationOptions) -> Result<Vec<u8>, Error> {
749 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 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 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 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 #[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
1018static CAPTURING: AtomicBool = AtomicBool::new(false);
1020
1021#[derive(Clone, Debug)]
1023enum MarkerEnd {
1024 At(Timestamp),
1026
1027 Long(Arc<AtomicOptionTimestamp>),
1030}
1031
1032impl MarkerEnd {
1033 fn should_keep(&self, capturing: bool) -> bool {
1040 if let MarkerEnd::Long(timestamp) = self {
1041 if timestamp.load().is_some() {
1042 capturing
1045 } else if Arc::strong_count(timestamp) > 1 {
1046 true
1048 } else {
1049 capturing
1056 }
1057 } else {
1058 false
1059 }
1060 }
1061
1062 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#[derive(Clone, Debug)]
1074struct Marker {
1075 start: Timestamp,
1077 end: MarkerEnd,
1079 category: &'static str,
1081 name: &'static str,
1083 tooltip: String,
1085}
1086
1087#[derive(Clone)]
1089struct ThreadMarkers {
1090 tid: usize,
1094
1095 name: Option<String>,
1100
1101 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
1123static 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 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 blocks: std::sync::Mutex<Blocks>,
1201
1202 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 fn push(&self, marker: Marker) {
1224 self.blocks.lock().unwrap().push(marker);
1225 }
1226
1227 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 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}