liminal-rs 0.2.0

A conversation-based messaging bus built on beamr
Documentation
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
use std::cell::Cell;
use std::error::Error;
use std::fmt::{Display, Formatter, Result as FmtResult};
use std::ptr;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicPtr, Ordering};
use std::time::{Duration, Instant};

use crate::tracing::TraceContext;

static SPAN_COLLECTOR_MARKER: AtomicPtr<()> = AtomicPtr::new(ptr::null_mut());
static SPAN_COLLECTOR_TOKEN: () = ();
static GLOBAL_SPAN_COLLECTOR: OnceLock<Box<dyn SpanCollector>> = OnceLock::new();

thread_local! {
    static ACTIVE_TRACE_CONTEXT: Cell<Option<TraceContext>> = const { Cell::new(None) };
}

#[derive(Debug)]
pub struct Span {
    name: String,
    context: TraceContext,
    parent: Option<TraceContext>,
    start: Instant,
}

impl Span {
    #[must_use]
    pub fn new(
        name: impl Into<String>,
        context: TraceContext,
        parent: Option<TraceContext>,
    ) -> Self {
        Self {
            name: name.into(),
            context,
            parent,
            start: Instant::now(),
        }
    }

    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    #[must_use]
    pub const fn context(&self) -> TraceContext {
        self.context
    }

    #[must_use]
    pub const fn parent(&self) -> Option<TraceContext> {
        self.parent
    }

    #[must_use]
    pub const fn start(&self) -> Instant {
        self.start
    }

    #[must_use]
    pub fn finish(self) -> FinishedSpan {
        let duration = self.start.elapsed();
        let finished = FinishedSpan::new(self.name, self.context, self.parent, duration);

        if let Some(collector) = global_span_collector() {
            collector.on_span(finished.clone());
        }

        finished
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FinishedSpan {
    name: String,
    context: TraceContext,
    parent: Option<TraceContext>,
    duration: Duration,
}

impl FinishedSpan {
    const fn new(
        name: String,
        context: TraceContext,
        parent: Option<TraceContext>,
        duration: Duration,
    ) -> Self {
        Self {
            name,
            context,
            parent,
            duration,
        }
    }

    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    #[must_use]
    pub const fn context(&self) -> TraceContext {
        self.context
    }

    #[must_use]
    pub const fn parent(&self) -> Option<TraceContext> {
        self.parent
    }

    #[must_use]
    pub const fn duration(&self) -> Duration {
        self.duration
    }
}

#[derive(Debug)]
pub struct ConversationSpan {
    span: Span,
}

impl ConversationSpan {
    #[must_use]
    pub fn new(conversation_id: impl Into<String>) -> Self {
        Self::root(conversation_id)
    }

    #[must_use]
    pub fn root(conversation_id: impl Into<String>) -> Self {
        Self {
            span: Span::new(conversation_id, TraceContext::new_root(), None),
        }
    }

    #[must_use]
    pub fn child(&self, conversation_id: impl Into<String>) -> Self {
        Self::with_parent(conversation_id, self.context())
    }

    #[must_use]
    pub fn with_parent(conversation_id: impl Into<String>, parent: TraceContext) -> Self {
        Self {
            span: Span::new(conversation_id, parent.child(), Some(parent)),
        }
    }

    #[must_use]
    pub fn name(&self) -> &str {
        self.span.name()
    }

    #[must_use]
    pub const fn context(&self) -> TraceContext {
        self.span.context()
    }

    #[must_use]
    pub const fn parent(&self) -> Option<TraceContext> {
        self.span.parent()
    }

    #[must_use]
    pub const fn message_context(&self) -> TraceContext {
        self.context()
    }

    #[must_use]
    pub fn finish(self) -> FinishedSpan {
        self.span.finish()
    }
}

#[derive(Debug)]
pub struct SpanGuard {
    span: Option<ConversationSpan>,
    name: String,
    context: TraceContext,
    parent: Option<TraceContext>,
    previous_context: Option<TraceContext>,
    context_restored: bool,
}

impl SpanGuard {
    #[must_use]
    pub fn start_conversation(conversation_id: impl Into<String>) -> Self {
        Self::new(conversation_id)
    }

    #[must_use]
    pub fn new(conversation_id: impl Into<String>) -> Self {
        Self::from_conversation(ConversationSpan::root(conversation_id))
    }

    #[must_use]
    pub fn child_conversation(&self, conversation_id: impl Into<String>) -> Self {
        Self::from_conversation(ConversationSpan::with_parent(conversation_id, self.context))
    }

    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    #[must_use]
    pub const fn context(&self) -> TraceContext {
        self.context
    }

    #[must_use]
    pub const fn parent(&self) -> Option<TraceContext> {
        self.parent
    }

    #[must_use]
    pub const fn message_context(&self) -> TraceContext {
        self.context
    }

    #[must_use]
    pub fn finish(mut self) -> FinishedSpan {
        let finished = self.finish_active_span();
        self.restore_context();
        finished
    }

    fn from_conversation(conversation: ConversationSpan) -> Self {
        let name = conversation.name().to_owned();
        let context = conversation.context();
        let parent = conversation.parent();
        let previous_context = replace_current_trace_context(Some(context));

        Self {
            span: Some(conversation),
            name,
            context,
            parent,
            previous_context,
            context_restored: false,
        }
    }

    fn finish_active_span(&mut self) -> FinishedSpan {
        match self.span.take() {
            Some(span) => span.finish(),
            None => Span::new(self.name.clone(), self.context, self.parent).finish(),
        }
    }

    fn restore_context(&mut self) {
        if !self.context_restored {
            replace_current_trace_context(self.previous_context);
            self.context_restored = true;
        }
    }
}

impl Drop for SpanGuard {
    fn drop(&mut self) {
        if self.span.is_some() {
            drop(self.finish_active_span());
        }
        self.restore_context();
    }
}

pub trait SpanCollector: std::fmt::Debug + Send + Sync + 'static {
    fn on_span(&self, span: FinishedSpan);
}

#[derive(Debug, Clone, Copy, Default)]
pub struct NoopCollector;

impl SpanCollector for NoopCollector {
    fn on_span(&self, span: FinishedSpan) {
        drop(span);
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SpanCollectorInstallError {
    AlreadyInstalled,
}

impl Display for SpanCollectorInstallError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
        match self {
            Self::AlreadyInstalled => {
                formatter.write_str("global span collector is already installed")
            }
        }
    }
}

impl Error for SpanCollectorInstallError {}

/// # Errors
///
/// Returns an error when a global span collector has already been installed.
pub fn install_span_collector<Collector>(
    collector: Collector,
) -> Result<(), SpanCollectorInstallError>
where
    Collector: SpanCollector,
{
    install_boxed_span_collector(Box::new(collector))
}

/// # Errors
///
/// Returns an error when a global span collector has already been installed.
pub fn install_boxed_span_collector(
    collector: Box<dyn SpanCollector>,
) -> Result<(), SpanCollectorInstallError> {
    match GLOBAL_SPAN_COLLECTOR.set(collector) {
        Ok(()) => {
            SPAN_COLLECTOR_MARKER.store(
                ptr::addr_of!(SPAN_COLLECTOR_TOKEN).cast_mut(),
                Ordering::Release,
            );
            Ok(())
        }
        Err(_collector) => Err(SpanCollectorInstallError::AlreadyInstalled),
    }
}

#[must_use]
pub fn span_collector_enabled() -> bool {
    !SPAN_COLLECTOR_MARKER.load(Ordering::Acquire).is_null()
}

#[must_use]
pub fn global_span_collector() -> Option<&'static dyn SpanCollector> {
    if span_collector_enabled() {
        GLOBAL_SPAN_COLLECTOR.get().map(Box::as_ref)
    } else {
        None
    }
}

#[must_use]
pub fn current_trace_context() -> Option<TraceContext> {
    ACTIVE_TRACE_CONTEXT.with(Cell::get)
}

fn replace_current_trace_context(context: Option<TraceContext>) -> Option<TraceContext> {
    ACTIVE_TRACE_CONTEXT.with(|active| active.replace(context))
}

#[cfg(test)]
mod tests {
    use std::time::{Duration, Instant};

    use super::{
        ConversationSpan, NoopCollector, Span, SpanCollector, SpanGuard, current_trace_context,
    };
    use crate::tracing::TraceContext;

    #[test]
    fn span_finish_returns_finished_span() {
        let context = TraceContext::new_root();
        let parent = Some(TraceContext::new_root());
        let outer_start = Instant::now();
        let span = Span::new("conversation-1", context, parent);

        let finished = span.finish();
        let outer_elapsed = outer_start.elapsed();

        assert_eq!(finished.name(), "conversation-1");
        assert_eq!(finished.context(), context);
        assert_eq!(finished.parent(), parent);
        assert!(finished.duration() <= outer_elapsed);
    }

    #[test]
    fn conversation_span_creates_root_and_child_contexts() {
        let parent = ConversationSpan::new("parent");
        let child = parent.child("child");

        assert_eq!(parent.name(), "parent");
        assert_eq!(parent.parent(), None);
        assert_eq!(parent.message_context(), parent.context());
        assert_eq!(child.parent(), Some(parent.context()));
        assert_eq!(child.context().trace_id(), parent.context().trace_id());
        assert_ne!(child.context().span_id(), parent.context().span_id());
        assert_eq!(child.message_context(), child.context());
    }

    #[test]
    fn span_guard_sets_and_restores_current_context() {
        assert_eq!(current_trace_context(), None);

        let guard = SpanGuard::start_conversation("root");
        assert_eq!(current_trace_context(), Some(guard.context()));

        {
            let child = guard.child_conversation("child");
            assert_eq!(child.parent(), Some(guard.context()));
            assert_eq!(current_trace_context(), Some(child.context()));
        }

        assert_eq!(current_trace_context(), Some(guard.context()));
        drop(guard);
        assert_eq!(current_trace_context(), None);
    }

    #[test]
    fn noop_collector_discards_spans() {
        let collector = NoopCollector;
        let span = Span::new("discard", TraceContext::new_root(), None).finish();

        collector.on_span(span);
    }

    #[test]
    fn finished_span_is_clone_debug() {
        fn assert_clone_debug<T: Clone + std::fmt::Debug>() {}

        assert_clone_debug::<super::FinishedSpan>();
    }

    #[test]
    fn span_start_is_now() {
        let before = Instant::now();
        let span = Span::new("timed", TraceContext::new_root(), None);
        let after = Instant::now();

        assert!(span.start() >= before);
        assert!(span.start() <= after + Duration::from_millis(1));
    }
}