Skip to main content

micromegas_tracing/
property_set.rs

1//! Interned collection of PropertySet instances. Each PropertySet contains properties where the names and the values are statically allocated.
2//! The user is expected to manage the cardinality: this holds for `key = static expr` values
3//! too, since every distinct combination is interned and never freed.
4use crate::{dyn_deps::static_ref_str, static_string_ref::StaticStringRef};
5use internment::Intern;
6use micromegas_transit::{HeterogeneousQueue, StaticStringDependency, UserDefinedType, prelude::*};
7use rustc_hash::FxHashSet;
8use std::{
9    borrow::Cow,
10    hash::Hash,
11    sync::{Arc, OnceLock},
12};
13
14lazy_static::lazy_static! {
15    pub static ref PROPERTY_SET_DEP_TYPE_NAME: Arc<String> = Arc::new("PropertySetDependency".into());
16}
17
18#[derive(Debug, Eq, PartialEq, Hash, Clone, TransitReflect)]
19pub struct Property {
20    pub name: StaticStringRef,
21    pub value: StaticStringRef,
22}
23
24impl Property {
25    pub fn new(name: &'static str, value: &'static str) -> Self {
26        Self {
27            name: name.into(),
28            value: value.into(),
29        }
30    }
31}
32
33/// A property whose value is not `'static`. The name is either `'static` (`new`, referenced by
34/// address) or block-scoped (`with_dyn_name`, copied into the block like a dynamic value).
35/// Names from outside Rust, or otherwise unbounded, belong in `with_dyn_name`.
36///
37/// For `log!` and metric macros, analytics treats some names as column overrides:
38/// `level`/`target` (logs) and `target`/`name`/`unit` (metrics). The macros reject those names
39/// as keys, so an override arrives through a `..set` spread, a slice of `DynProperty` built at
40/// runtime, or the `imetric_dyn!`/`fmetric_dyn!` macros, which set `name` and `unit`. A dynamic
41/// `level` must be a valid level name or the block fails to parse. Interop logs (the `tracing`
42/// layer) keep their level and target unchanged.
43#[derive(Debug, Clone, Copy)]
44pub struct DynProperty<'a> {
45    name: &'a str,
46    value: &'a str,
47    // Private: a `true` flag on a non-`'static` name would make `static_ref_str` read freed memory.
48    static_name: bool,
49}
50
51impl<'a> DynProperty<'a> {
52    pub const fn new(name: &'static str, value: &'a str) -> Self {
53        Self {
54            name,
55            value,
56            static_name: true,
57        }
58    }
59
60    pub const fn with_dyn_name(name: &'a str, value: &'a str) -> Self {
61        Self {
62            name,
63            value,
64            static_name: false,
65        }
66    }
67
68    pub fn name(&self) -> &'a str {
69        self.name
70    }
71
72    pub fn value(&self) -> &'a str {
73        self.value
74    }
75
76    #[doc(hidden)]
77    pub fn is_static_name(&self) -> bool {
78        self.static_name
79    }
80}
81
82/// Interns the literal properties of one macro callsite on first use. `cell` is a `static`
83/// emitted by the macro, so each callsite pays one atomic load afterwards.
84///
85/// Duplicate names are resolved the way `merge_properties` does: case-insensitive, last wins.
86pub fn callsite_set(
87    cell: &'static OnceLock<&'static PropertySet>,
88    pairs: &'static [(&'static str, &'static str)],
89) -> &'static PropertySet {
90    cell.get_or_init(|| {
91        let mut properties: Vec<Property> = Vec::with_capacity(pairs.len());
92        apply_pairs(&mut properties, pairs.iter().copied());
93        PropertySet::find_or_create(properties)
94    })
95}
96
97/// Adds `pairs` in order, each one replacing an earlier property of the same name
98/// (case-insensitive), so the last one wins.
99pub fn apply_pairs(
100    properties: &mut Vec<Property>,
101    pairs: impl IntoIterator<Item = (&'static str, &'static str)>,
102) {
103    for (name, value) in pairs {
104        properties.retain(|p| !p.name.as_str().eq_ignore_ascii_case(name));
105        properties.push(Property::new(name, value));
106    }
107}
108
109/// Identity, but only accepts a `&'static str`: a borrowed value passed to a `key = static expr`
110/// property is a lifetime error at the call site.
111#[inline(always)]
112pub fn static_value(v: &'static str) -> &'static str {
113    v
114}
115
116pub fn dyn_property_get<'a>(properties: &[DynProperty<'a>], name: &str) -> Option<&'a str> {
117    properties
118        .iter()
119        .find(|p| p.name.eq_ignore_ascii_case(name))
120        .map(|p| p.value)
121}
122
123pub fn property_get<'a>(properties: &'a [Property], name: &str) -> Option<&'a str> {
124    properties.iter().find_map(|p| {
125        if p.name.as_str().eq_ignore_ascii_case(name) {
126            Some(p.value.as_str())
127        } else {
128            None
129        }
130    })
131}
132
133#[derive(Debug, Clone)]
134pub struct PropertySet {
135    pub(crate) properties: Vec<Property>,
136    // Same order as `properties`. Lets sinks get a slice without a per-call allocation.
137    dyn_view: Box<[DynProperty<'static>]>,
138}
139
140// Identity is the properties alone, so the cached view never affects interning.
141impl PartialEq for PropertySet {
142    fn eq(&self, other: &Self) -> bool {
143        self.properties == other.properties
144    }
145}
146
147impl Eq for PropertySet {}
148
149impl Hash for PropertySet {
150    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
151        self.properties.hash(state);
152    }
153}
154
155/// Canonical property order, so that equal sets hash equally.
156pub(crate) fn sort_properties(properties: &mut [Property]) {
157    properties.sort_by(|a, b| b.name.as_str().cmp(a.name.as_str()));
158}
159
160/// Same order as `sort_properties`, so a merged list matches the dynamic set built from it.
161#[doc(hidden)]
162pub fn cmp_dyn_properties(a: &DynProperty<'_>, b: &DynProperty<'_>) -> std::cmp::Ordering {
163    b.name.cmp(a.name)
164}
165
166impl PropertySet {
167    pub fn find_or_create(mut properties: Vec<Property>) -> &'static Self {
168        sort_properties(&mut properties);
169        // SAFETY: the refs were built from `&'static str` by `Property::new`, and they don't
170        // point into the set, so moving it into `Intern` keeps them valid.
171        let dyn_view = properties
172            .iter()
173            .map(|p| unsafe { DynProperty::new(static_ref_str(&p.name), static_ref_str(&p.value)) })
174            .collect();
175        let set = PropertySet {
176            properties,
177            dyn_view,
178        };
179        Intern::<PropertySet>::new(set).as_ref()
180    }
181
182    /// The interned set with no properties, for calls that only carry dynamic ones.
183    pub fn empty() -> &'static Self {
184        lazy_static::lazy_static! {
185            static ref EMPTY: &'static PropertySet = PropertySet::find_or_create(vec![]);
186        }
187        *EMPTY
188    }
189
190    pub fn get_properties(&self) -> &[Property] {
191        &self.properties
192    }
193
194    pub fn dyn_properties(&'static self) -> &'static [DynProperty<'static>] {
195        &self.dyn_view
196    }
197}
198
199/// Identifies a property set within one block's events: the address of an interned set, or
200/// the id of a record in the block's dynamic dependency queue.
201#[derive(Debug, Clone, Copy, PartialEq, Eq)]
202#[repr(transparent)]
203pub struct PropertySetId(pub(crate) u64);
204
205// Dynamic set ids have bit 0 set, which is how they are told apart from interned addresses.
206const _: () = assert!(std::mem::align_of::<PropertySet>() >= 2);
207
208impl PropertySetId {
209    pub fn interned(set: &'static PropertySet) -> Self {
210        Self(set as *const PropertySet as u64)
211    }
212
213    /// `None` for the id of a dynamic set, which only its block's `DynDeps` can resolve.
214    pub fn as_interned(self) -> Option<&'static PropertySet> {
215        if self.0 & 1 != 0 {
216            return None;
217        }
218        // SAFETY: ids with bit 0 clear are only built by `interned`.
219        Some(unsafe { &*(self.0 as *const PropertySet) })
220    }
221}
222
223/// A dependency queue that can receive string records.
224pub trait StringDepsQueue: HeterogeneousQueue {
225    fn push_string(&mut self, dep: StaticStringDependency);
226}
227
228/// A dependency queue that can receive the records of a property set.
229pub trait PropertyDepsQueue: StringDepsQueue {
230    fn push_set(&mut self, dep: PropertySetDependency);
231}
232
233#[derive(Debug)]
234pub struct PropertySetDependency {
235    pub id: u64,
236    pub properties: Cow<'static, [Property]>,
237}
238
239/// Emits the dependencies of an interned property set once per block.
240pub(crate) fn record_properties<D: PropertyDepsQueue>(
241    set: &'static PropertySet,
242    recorded_deps: &mut FxHashSet<u64>,
243    deps: &mut D,
244) {
245    let id = PropertySetId::interned(set).0;
246    if recorded_deps.insert(id) {
247        for prop in set.get_properties() {
248            if recorded_deps.insert(prop.name.id()) {
249                deps.push_string(prop.name.into_dependency());
250            }
251            if recorded_deps.insert(prop.value.id()) {
252                deps.push_string(prop.value.into_dependency());
253            }
254        }
255        deps.push_set(PropertySetDependency {
256            id,
257            properties: Cow::Borrowed(set.get_properties()),
258        });
259    }
260}
261
262impl Reflect for PropertySetDependency {
263    fn reflect() -> UserDefinedType {
264        UserDefinedType {
265            name: PROPERTY_SET_DEP_TYPE_NAME.clone(),
266            size: 0,
267            members: vec![],
268            is_reference: false,
269            secondary_udts: vec![Property::reflect()],
270        }
271    }
272}
273
274impl InProcSerialize for PropertySetDependency {
275    const IN_PROC_SIZE: InProcSize = InProcSize::Dynamic;
276
277    fn get_value_size(&self) -> Option<u32> {
278        let header_size: u32 = std::mem::size_of::<u64>() as u32 + // id
279			std::mem::size_of::<u32>() as u32; // number of properties
280        let container_size: u32 =
281            self.properties.len() as u32 * std::mem::size_of::<Property>() as u32;
282        let size = header_size + container_size;
283        Some(size)
284    }
285
286    fn write_value(&self, buffer: &mut Vec<u8>) {
287        write_any(buffer, &self.id);
288        let nb_properties: u32 = self.properties.len() as u32;
289        write_any(buffer, &nb_properties);
290        for prop in self.properties.iter() {
291            write_any(buffer, prop);
292        }
293    }
294
295    unsafe fn read_value(mut _window: &[u8]) -> Self {
296        // dependencies don't need to be read in the instrumented process
297        unimplemented!();
298    }
299}