1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
//! Types to carry tracing events over the WASM client-host boundary.

use serde::{Deserialize, Serialize};
use tracing_core::{Level, Metadata};

use core::hash::Hash;

use crate::{
    alloc::{Cow, String, Vec},
    TracedValues,
};

/// ID of a tracing [`Metadata`] record as used in [`TracingEvent`]s.
pub type MetadataId = u64;
/// ID of a tracing span as used in [`TracingEvent`]s.
pub type RawSpanId = u64;

/// Tracing level defined in [`CallSiteData`].
///
/// This corresponds to [`Level`] from the `tracing-core` library, but is (de)serializable.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TracingLevel {
    /// "ERROR" level.
    Error,
    /// "WARN" level.
    Warn,
    /// "INFO" level.
    Info,
    /// "DEBUG" level.
    Debug,
    /// "TRACE" level.
    Trace,
}

impl From<Level> for TracingLevel {
    fn from(level: Level) -> Self {
        match level {
            Level::ERROR => Self::Error,
            Level::WARN => Self::Warn,
            Level::INFO => Self::Info,
            Level::DEBUG => Self::Debug,
            Level::TRACE => Self::Trace,
        }
    }
}

/// Kind of [`CallSiteData`] location: either a span, or an event.
#[derive(Debug, Clone, Copy, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CallSiteKind {
    /// Call site is a span.
    Span,
    /// Call site is an event.
    Event,
}

/// Data for a single tracing call site: either a span definition, or an event definition.
///
/// This corresponds to [`Metadata`] from the `tracing-core` library, but is (de)serializable.
#[derive(Debug, Clone, Hash, Serialize, Deserialize)]
pub struct CallSiteData {
    /// Kind of the call site.
    pub kind: CallSiteKind,
    /// Name of the call site.
    pub name: Cow<'static, str>,
    /// Tracing target.
    pub target: Cow<'static, str>,
    /// Tracing level.
    pub level: TracingLevel,
    /// Path to the module where this call site is defined.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub module_path: Option<Cow<'static, str>>,
    /// Path to the file where this call site is defined.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub file: Option<Cow<'static, str>>,
    /// Line number for this call site.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub line: Option<u32>,
    /// Fields defined by this call site.
    pub fields: Vec<Cow<'static, str>>,
}

impl From<&Metadata<'static>> for CallSiteData {
    fn from(metadata: &Metadata<'static>) -> Self {
        let kind = if metadata.is_span() {
            CallSiteKind::Span
        } else {
            debug_assert!(metadata.is_event());
            CallSiteKind::Event
        };
        let fields = metadata
            .fields()
            .iter()
            .map(|field| Cow::Borrowed(field.name()));

        Self {
            kind,
            name: Cow::Borrowed(metadata.name()),
            target: Cow::Borrowed(metadata.target()),
            level: TracingLevel::from(*metadata.level()),
            module_path: metadata.module_path().map(Cow::Borrowed),
            file: metadata.file().map(Cow::Borrowed),
            line: metadata.line(),
            fields: fields.collect(),
        }
    }
}

/// Event produced during tracing.
///
/// These events are emitted by a [`TracingEventSender`] and then consumed
/// by a [`TracingEventReceiver`] to pass tracing info across an API boundary.
///
/// [`TracingEventSender`]: crate::TracingEventSender
/// [`TracingEventReceiver`]: crate::TracingEventReceiver
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum TracingEvent {
    /// New call site.
    NewCallSite {
        /// Unique ID of the call site that will be used to refer to it in the following events.
        id: MetadataId,
        /// Information about the call site.
        #[serde(flatten)]
        data: CallSiteData,
    },

    /// New tracing span.
    NewSpan {
        /// Unique ID of the span that will be used to refer to it in the following events.
        id: RawSpanId,
        /// Parent span ID. `None` means using the contextual parent (i.e., the current span).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        parent_id: Option<RawSpanId>,
        /// ID of the span metadata.
        metadata_id: MetadataId,
        /// Values associated with the span.
        values: TracedValues<String>,
    },
    /// New "follows from" relation between spans.
    FollowsFrom {
        /// ID of the follower span.
        id: RawSpanId,
        /// ID of the source span.
        follows_from: RawSpanId,
    },
    /// Span was entered.
    SpanEntered {
        /// ID of the span.
        id: RawSpanId,
    },
    /// Span was exited.
    SpanExited {
        /// ID of the span.
        id: RawSpanId,
    },
    /// Span was cloned.
    SpanCloned {
        /// ID of the span.
        id: RawSpanId,
    },
    /// Span was dropped (aka closed).
    SpanDropped {
        /// ID of the span.
        id: RawSpanId,
    },
    /// New values recorded for a span.
    ValuesRecorded {
        /// ID of the span.
        id: RawSpanId,
        /// Recorded values.
        values: TracedValues<String>,
    },

    /// New event.
    NewEvent {
        /// ID of the event metadata.
        metadata_id: MetadataId,
        /// Parent span ID. `None` means using the contextual parent (i.e., the current span).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        parent: Option<RawSpanId>,
        /// Values associated with the event.
        values: TracedValues<String>,
    },
}