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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
pub use tracing_serde_modality_ingest::TimelineId;
pub use tracing_serde_wire::Packet;
use std::{fmt::Debug, thread, thread_local, time::Instant};
use anyhow::Context as _;
use once_cell::sync::Lazy;
use parking_lot::RwLock;
use tokio::runtime::Runtime;
use tracing_core::{
field::Visit,
span::{Attributes, Id, Record},
Field, Subscriber,
};
use tracing_subscriber::{
layer::{Context, Layer},
prelude::*,
registry::{LookupSpan, Registry},
};
use uuid::Uuid;
use tracing_serde_modality_ingest::{options::Options, ConnectError, TracingModality};
use tracing_serde_structured::{AsSerde, CowString, RecordMap, SerializeValue};
use tracing_serde_wire::TracingWire;
static START: Lazy<Instant> = Lazy::new(Instant::now);
static GLOBAL_OPTIONS: RwLock<Option<Options>> = RwLock::new(None);
thread_local! {
static HANDLER: LocalHandler = LocalHandler::new();
}
struct LocalHandler(RwLock<Option<Result<TSHandler, ConnectError>>>);
impl LocalHandler {
const fn new() -> Self {
LocalHandler(RwLock::new(None))
}
fn manual_init(&self, new_handler: TSHandler) {
let mut handler = self.0.write();
*handler = Some(Ok(new_handler));
}
fn with_read<R, F: FnOnce(&TSHandler) -> R>(&self, f: F) -> Option<R> {
let mut handler = self.0.write();
if handler.is_none() {
*handler = Some(TSHandler::new());
}
if let Some(Ok(ref handler)) = *handler {
Some(f(handler))
} else {
None
}
}
fn with_write<R, F: FnOnce(&mut TSHandler) -> R>(&self, f: F) -> Option<R> {
let mut handler = self.0.write();
if handler.is_none() {
*handler = Some(TSHandler::new());
}
if let Some(Ok(ref mut handler)) = *handler {
Some(f(handler))
} else {
None
}
}
}
impl LocalHandler {
fn handle_message(&self, msg: TracingWire<'_>) {
self.with_write(|h| h.handle_message(msg));
}
fn timeline_id(&self) -> TimelineId {
self.with_read(|t| t.tracer.timeline_id())
.unwrap_or_else(TimelineId::zero)
}
}
pub fn timeline_id() -> TimelineId {
HANDLER.with(|h| h.timeline_id())
}
pub struct TSHandler {
tracer: TracingModality,
rt: Runtime,
}
impl TSHandler {
fn new() -> Result<Self, ConnectError> {
let mut local_opts = GLOBAL_OPTIONS
.read()
.as_ref()
.context("global options not initialized, but global logger was set to us somehow")?
.clone();
let cur = thread::current();
let name = cur
.name()
.map(str::to_string)
.unwrap_or_else(|| format!("Thread#{:?}", cur.id()));
local_opts.set_name(name);
let rt = Runtime::new().context("create local tokio runtime for sdk")?;
let tracing_result = {
let handle = rt.handle();
handle.block_on(async { TracingModality::connect_with_options(local_opts).await })
};
match tracing_result {
Ok(tracer) => Ok(TSHandler { rt, tracer }),
Err(e) => Err(e),
}
}
fn handle_message(&mut self, message: TracingWire<'_>) {
let packet = Packet {
message,
tick: START.elapsed().as_micros() as u64,
};
self.rt
.handle()
.block_on(async { self.tracer.handle_packet(packet).await })
.unwrap();
}
}
pub struct TSSubscriber {
_no_external_construct: (),
}
impl TSSubscriber {
#[allow(clippy::new_ret_no_self)]
pub fn new() -> impl Subscriber {
Self::new_with_options(Default::default())
}
pub fn new_with_options(opts: Options) -> impl Subscriber {
Registry::default().with(TSLayer::new_with_options(opts))
}
pub fn connect() -> Result<(), ConnectError> {
let first_local_handler = TSHandler::new()?;
HANDLER.with(|h| h.manual_init(first_local_handler));
Ok(())
}
}
pub struct TSLayer {
_no_external_construct: (),
}
impl TSLayer {
pub fn new() -> Self {
Self::new_with_options(Default::default())
}
pub fn new_with_options(mut opts: Options) -> Self {
let run_id = Uuid::new_v4();
opts.add_metadata("run_id", run_id.to_string());
{
let mut global_opts = GLOBAL_OPTIONS.write();
*global_opts = Some(opts);
}
TSLayer {
_no_external_construct: (),
}
}
pub fn connect(&self) -> Result<(), ConnectError> {
let first_local_handler = TSHandler::new()?;
HANDLER.with(|h| h.manual_init(first_local_handler));
Ok(())
}
pub fn connect_or_panic(&self) {
if let Err(e) = self.connect() {
panic!("Cannot connect to to modality: {e}")
}
}
}
impl Default for TSLayer {
fn default() -> Self {
Self::new()
}
}
impl<S> Layer<S> for TSLayer
where
S: Subscriber + for<'a> LookupSpan<'a>,
{
fn enabled(&self, _metadata: &tracing_core::Metadata<'_>, _ctx: Context<'_, S>) -> bool {
true
}
fn on_new_span(&self, attrs: &Attributes<'_>, id: &Id, _ctx: Context<'_, S>) {
let mut visitor = RecordMapBuilder::new();
attrs.record(&mut visitor);
let msg = TracingWire::NewSpan {
id: id.as_serde(),
attrs: attrs.as_serde(),
values: visitor.values().into(),
};
HANDLER.with(move |h| h.handle_message(msg));
}
fn on_record(&self, span: &Id, values: &Record<'_>, _ctx: Context<'_, S>) {
let msg = TracingWire::Record {
span: span.as_serde(),
values: values.as_serde().to_owned(),
};
HANDLER.with(move |h| h.handle_message(msg));
}
fn on_follows_from(&self, span: &Id, follows: &Id, _ctx: Context<'_, S>) {
let msg = TracingWire::RecordFollowsFrom {
span: span.as_serde(),
follows: follows.as_serde().to_owned(),
};
HANDLER.with(move |h| h.handle_message(msg));
}
fn on_event(&self, event: &tracing_core::Event<'_>, _ctx: Context<'_, S>) {
let msg = TracingWire::Event(event.as_serde().to_owned());
HANDLER.with(move |h| h.handle_message(msg));
}
fn on_enter(&self, span: &Id, _ctx: Context<'_, S>) {
let msg = TracingWire::Enter(span.as_serde());
HANDLER.with(move |h| h.handle_message(msg));
}
fn on_exit(&self, span: &Id, _ctx: Context<'_, S>) {
let msg = TracingWire::Exit(span.as_serde());
HANDLER.with(move |h| h.handle_message(msg));
}
fn on_id_change(&self, old: &Id, new: &Id, _ctx: Context<'_, S>) {
let msg = TracingWire::IdClone {
old: old.as_serde(),
new: new.as_serde(),
};
HANDLER.with(move |h| h.handle_message(msg));
}
fn on_close(&self, span: Id, _ctx: Context<'_, S>) {
let msg = TracingWire::Close(span.as_serde());
HANDLER.with(move |h| h.handle_message(msg));
}
}
struct RecordMapBuilder<'a> {
record_map: RecordMap<'a>,
}
impl<'a> RecordMapBuilder<'a> {
fn values(self) -> RecordMap<'a> {
self.record_map
}
}
impl<'a> RecordMapBuilder<'a> {
fn new() -> RecordMapBuilder<'a> {
RecordMapBuilder {
record_map: RecordMap::new(),
}
}
}
impl<'a> Visit for RecordMapBuilder<'a> {
fn record_debug(&mut self, field: &Field, value: &dyn Debug) {
self.record_map.insert(
CowString::Borrowed(field.name()),
SerializeValue::Debug(CowString::Owned(format!("{:?}", value)).into()),
);
}
fn record_f64(&mut self, field: &Field, value: f64) {
self.record_map.insert(
CowString::Borrowed(field.name()),
SerializeValue::F64(value),
);
}
fn record_i64(&mut self, field: &Field, value: i64) {
self.record_map.insert(
CowString::Borrowed(field.name()),
SerializeValue::I64(value),
);
}
fn record_u64(&mut self, field: &Field, value: u64) {
self.record_map.insert(
CowString::Borrowed(field.name()),
SerializeValue::U64(value),
);
}
fn record_bool(&mut self, field: &Field, value: bool) {
self.record_map.insert(
CowString::Borrowed(field.name()),
SerializeValue::Bool(value),
);
}
fn record_str(&mut self, field: &Field, value: &str) {
self.record_map.insert(
CowString::Borrowed(field.name()),
SerializeValue::Str(CowString::Borrowed(value).to_owned()),
);
}
}