flareapp-core 0.3.0

The core of the Flare client: config, the client, and the worker thread that sends data.
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
//! The Flare rules for spans: the limits, the span type, and the entry point of a
//! trace.
//!
//! The `tracing` integration and the OpenTelemetry bridge both build OTLP spans.
//! Both call these functions, so a span gets the same Flare attributes from either
//! integration.

use std::borrow::Cow;

use flareapp_otlp::{AnyValue, KeyValue, Span, SpanKind, StatusCode, find_attribute};

use crate::entry_point::{EntryPoint, WebRequest, web_entry_point};

/// The most spans a trace keeps, the same as the PHP and JS clients.
pub const MAX_SPANS_PER_TRACE: usize = 1024;

/// The most attributes a span keeps.
pub const MAX_ATTRIBUTES: usize = 128;

/// The most events a span keeps.
pub const MAX_EVENTS: usize = 128;

/// The W3C flag that says the trace is sampled. The flag is bit 0 of the flags in a
/// `traceparent` header, and of the OTLP span `flags`.
const FLAG_SAMPLED: u32 = 0x01;

/// Bit 8 of the OTLP span `flags`. This bit says that bit 9 has a value. Without
/// bit 8, a receiver reads bit 9 as unknown.
const FLAG_HAS_IS_REMOTE: u32 = 0x100;

/// Bit 9 of the OTLP span `flags`. This bit says that the parent span is in
/// another process, like the service that sent an incoming request. Flare reads
/// the bit to tell the first span of a service apart from a child span.
const FLAG_IS_REMOTE: u32 = 0x200;

/// Returns the OTLP span `flags` of a sampled span. `parent_is_remote` is `true`
/// when the parent span is in another process.
pub fn sampled_span_flags(parent_is_remote: bool) -> u32 {
    let flags = FLAG_SAMPLED | FLAG_HAS_IS_REMOTE;

    if parent_is_remote {
        flags | FLAG_IS_REMOTE
    } else {
        flags
    }
}

/// Returns `true` when `span` is the first span of its trace in this process: the
/// span has no parent, or the parent span is in another process.
///
/// The function reads the parent from the `flags` of the span, which
/// [`sampled_span_flags`] sets. The OpenTelemetry bridge has the same check on
/// the `SpanData` of the SDK, before the bridge sets the flags.
pub fn is_local_root(span: &Span) -> bool {
    let remote_parent = FLAG_HAS_IS_REMOTE | FLAG_IS_REMOTE;

    span.parent_span_id.is_none() || span.flags & remote_parent == remote_parent
}

/// Sets an attribute on `span`, or replaces the attribute when the span already
/// has one with that key.
///
/// Above [`MAX_ATTRIBUTES`], a new attribute is dropped and counted in
/// `dropped_attributes_count`.
pub fn set_span_attribute<K, V>(span: &mut Span, key: K, value: V)
where
    K: Into<Cow<'static, str>>,
    V: Into<AnyValue>,
{
    let attribute = KeyValue::new(key, value);

    if let Some(existing) = span
        .attributes
        .iter_mut()
        .find(|existing| existing.key == attribute.key)
    {
        existing.value = attribute.value;
    } else if span.attributes.len() < MAX_ATTRIBUTES {
        span.attributes.push(attribute);
    } else {
        span.dropped_attributes_count += 1;
    }
}

/// Adds the Flare attributes to a span that ended, right before the span is sent.
///
/// - The span gets a Flare span type in `flare.span_type`, like `request` or
///   `query`, unless the span already has one.
/// - The first span of the trace in this process gets the `flare.entry_point.*`
///   attributes of `entry_point`. Entry point attributes that the span set itself
///   win.
/// - A `command` span gets `process.command`, the attribute that Flare groups
///   commands by.
/// - A span without the error status loses its status message, as
///   [`clear_status_message_unless_error`] describes.
///
/// Pass `entry_point` only for the first span of the trace in this process.
pub fn finish_span(span: &mut Span, is_local_root: bool, entry_point: Option<&EntryPoint>) {
    if !has_attribute(span, "flare.span_type")
        && let Some(span_type) = mapped_span_type(span, is_local_root)
    {
        set_span_attribute(span, "flare.span_type", span_type);
    }
    if let Some(entry_point) = entry_point {
        for (key, value) in entry_point.attributes() {
            if !has_attribute(span, key) {
                set_span_attribute(span, key, value);
            }
        }
    }
    // The PHP client sends the name of the Artisan command in `process.command`,
    // so the Rust client sends the span name, like `import`.
    if string_attribute(span, "flare.span_type") == Some("command")
        && !has_attribute(span, "process.command")
    {
        let name = span.name.to_string();
        set_span_attribute(span, "process.command", name);
    }
    clear_status_message_unless_error(span);
}

/// Removes the status message of a span without the error status, because
/// OpenTelemetry allows a status message only with the error status.
///
/// [`finish_span`] calls this function. Call this function yourself for a span
/// that gets no Flare attributes, so that the span still follows this rule.
pub fn clear_status_message_unless_error(span: &mut Span) {
    if span.status.code != StatusCode::Error {
        span.status.message = None;
    }
}

/// Picks the Flare span type from the kind and the attributes of a span.
///
/// The types are Flare's generic types, and the rules follow the order Flare uses
/// for spans without a type. An `internal` root span becomes an `operation`,
/// which Flare lists under Operations. Other spans that match nothing get no
/// type, and Flare picks one itself: for example a job for a root span of kind
/// `consumer`.
fn mapped_span_type(span: &Span, is_local_root: bool) -> Option<&'static str> {
    let has_method = has_attribute(span, "http.request.method");

    if has_attribute(span, "db.system.name")
        || has_attribute(span, "db.query.text")
        || has_attribute(span, "db.statement")
    {
        Some("query")
    } else if span.kind == SpanKind::Server && has_method {
        Some("request")
    } else if span.kind == SpanKind::Client && has_method {
        Some("http_client")
    } else if is_local_root && span.kind == SpanKind::Internal {
        Some("operation")
    } else {
        None
    }
}

fn has_attribute(span: &Span, key: &str) -> bool {
    find_attribute(&span.attributes, key).is_some()
}

fn string_attribute<'a>(span: &'a Span, key: &str) -> Option<&'a str> {
    find_attribute(&span.attributes, key)?.as_str()
}

/// Parses a span kind in any case, like `server` or `Consumer`. This is the
/// format of the `otel.kind` field of `tracing-opentelemetry`.
pub fn parse_kind(kind: &str) -> Option<SpanKind> {
    const KINDS: [(&str, SpanKind); 5] = [
        ("internal", SpanKind::Internal),
        ("server", SpanKind::Server),
        ("client", SpanKind::Client),
        ("producer", SpanKind::Producer),
        ("consumer", SpanKind::Consumer),
    ];

    KINDS
        .iter()
        .find(|(name, _)| name.eq_ignore_ascii_case(kind))
        .map(|&(_, span_kind)| span_kind)
}

/// The fields of a span that decide its entry point.
///
/// A span has an entry point when the span follows the OpenTelemetry conventions
/// for one: a `server` span for a web request, or a `consumer` span for a job.
/// OpenTelemetry has no span kind for a command, so a span with
/// `flare.span_type = "command"` is a command. A `server` span with neither
/// `url.full` nor `url.path`, like a gRPC span, is not a web request and has no
/// entry point.
///
/// The Flare integrations use this type. It is not part of the public API.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct EntryFields {
    /// The name of the span, like `handle_order_message` for an `#[instrument]`
    /// function.
    name: Cow<'static, str>,
    /// `otel.name`, which replaces the name of the span.
    otel_name: Option<String>,
    /// `otel.kind`, like `server` or `consumer`.
    kind: Option<String>,
    /// `flare.span_type`, like `command`.
    span_type: Option<String>,
    /// `http.request.method`, like `GET`.
    method: Option<String>,
    /// `http.route`, like `/users/{id}`.
    route: Option<String>,
    /// `url.full`, like `https://shop.test/users/7`.
    url: Option<String>,
    /// `url.path`, like `/users/7`.
    path: Option<String>,
    /// `flare.framework.name`, like `axum`.
    framework: Option<String>,
    /// `messaging.destination.name`, the queue or topic of a job, like `orders`.
    destination: Option<String>,
}

impl EntryFields {
    /// Creates the fields of a span with the name `name`, and no other field.
    pub fn new<N: Into<Cow<'static, str>>>(name: N) -> Self {
        Self {
            name: name.into(),
            ..Self::default()
        }
    }

    /// Returns every field next to the name of the span field that the field
    /// reads. `set` and `merge` both use this list, so a new field only needs a line
    /// here.
    fn slots(&mut self) -> [(&'static str, &mut Option<String>); 9] {
        [
            ("otel.name", &mut self.otel_name),
            ("otel.kind", &mut self.kind),
            ("flare.span_type", &mut self.span_type),
            ("http.request.method", &mut self.method),
            ("http.route", &mut self.route),
            ("url.full", &mut self.url),
            ("url.path", &mut self.path),
            ("flare.framework.name", &mut self.framework),
            ("messaging.destination.name", &mut self.destination),
        ]
    }

    /// Stores the value of the span field `field` when the field decides the
    /// entry point. `value` only runs for those fields, so other fields are not
    /// formatted.
    pub fn set<F: FnOnce() -> String>(&mut self, field: &str, value: F) {
        if let Some((_, slot)) = self.slots().into_iter().find(|(name, _)| *name == field) {
            *slot = Some(value());
        }
    }

    /// Returns `true` when no field was set. The name does not count.
    pub fn is_empty(&self) -> bool {
        let empty = Self {
            name: self.name.clone(),
            ..Self::default()
        };

        *self == empty
    }

    /// Copies the fields that `other` has set over the fields of this value. The
    /// name of `other` does not count.
    pub fn merge(&mut self, mut other: Self) {
        for ((_, slot), (_, value)) in self.slots().into_iter().zip(other.slots()) {
            if value.is_some() {
                *slot = value.take();
            }
        }
    }

    /// Returns the entry point of the span, or `None` when the span is not a
    /// command, `server` or `consumer` span.
    pub fn entry_point(&self) -> Option<EntryPoint> {
        if self.span_type.as_deref() == Some("command") {
            return Some(self.command());
        }

        match parse_kind(self.kind.as_deref()?)? {
            SpanKind::Server => self.web(),
            SpanKind::Consumer => Some(self.queue()),
            _ => None,
        }
    }

    /// Returns a command entry point. Flare lists the entry point under the span
    /// name, like `import`. The value of the entry point is the command line of the
    /// process.
    fn command(&self) -> EntryPoint {
        EntryPoint::current_process().handler_identifier(self.span_name())
    }

    /// Returns a web entry point. Flare lists the entry point under the method and
    /// the route, like `GET /users/{id}`. Without a route, Flare lists the entry
    /// point under the method and the path, as Flare's protocol does for apps
    /// without a router. Returns `None` when the span has neither `url.full` nor
    /// `url.path`, because the span is not a web request.
    fn web(&self) -> Option<EntryPoint> {
        let url = self.url.as_deref().or(self.path.as_deref())?;

        Some(web_entry_point(&WebRequest {
            url,
            method: self.method.as_deref(),
            route: self.route.as_deref(),
            path: self.path.as_deref(),
            framework: self.framework.as_deref(),
        }))
    }

    /// Returns a job entry point. Flare lists the entry point under the span name,
    /// like `handle_order_message`. The value of the entry point is the queue name
    /// from `messaging.destination.name`, or the span name when the span has no
    /// queue name.
    fn queue(&self) -> EntryPoint {
        let name = self.span_name();
        let queue = self.destination.as_deref().unwrap_or(name);

        EntryPoint::queue(queue).handler_identifier(name)
    }

    /// Returns `otel.name` when the span sets it, and the name of the span
    /// otherwise.
    fn span_name(&self) -> &str {
        self.otel_name.as_deref().unwrap_or(&self.name)
    }
}

#[cfg(test)]
mod tests {
    use flareapp_otlp::{SpanId, TraceId};

    use super::*;

    fn span(kind: SpanKind) -> Span {
        Span::new(TraceId::random(), SpanId::random(), "checkout", kind)
    }

    fn span_type(span: &Span) -> Option<&str> {
        string_attribute(span, "flare.span_type")
    }

    #[test]
    fn parses_kinds_in_any_case() {
        assert_eq!(parse_kind("server"), Some(SpanKind::Server));
        assert_eq!(parse_kind("CLIENT"), Some(SpanKind::Client));
    }

    #[test]
    fn ignores_unknown_kinds() {
        assert_eq!(parse_kind("sideways"), None);
    }

    #[test]
    fn a_span_without_a_parent_is_a_local_root() {
        assert!(is_local_root(&span(SpanKind::Internal)));
    }

    #[test]
    fn a_span_with_a_remote_parent_is_a_local_root() {
        let span = Span {
            parent_span_id: Some(SpanId::random()),
            flags: sampled_span_flags(true),
            ..span(SpanKind::Server)
        };

        assert!(is_local_root(&span));
    }

    #[test]
    fn a_span_with_a_parent_in_this_process_is_not_a_local_root() {
        let span = Span {
            parent_span_id: Some(SpanId::random()),
            flags: sampled_span_flags(false),
            ..span(SpanKind::Internal)
        };

        assert!(!is_local_root(&span));
    }

    #[test]
    fn counts_the_attributes_above_the_limit() {
        let mut span = span(SpanKind::Internal);

        for index in 0..MAX_ATTRIBUTES + 2 {
            set_span_attribute(&mut span, format!("field_{index}"), 1_i64);
        }

        assert_eq!(
            (span.attributes.len(), span.dropped_attributes_count),
            (MAX_ATTRIBUTES, 2)
        );
    }

    #[test]
    fn replacing_an_attribute_keeps_room_for_others() {
        let mut span = span(SpanKind::Internal);

        set_span_attribute(&mut span, "status", 200_i64);
        set_span_attribute(&mut span, "status", 500_i64);

        assert_eq!(span.attributes.len(), 1);
    }

    #[test]
    fn an_internal_root_span_is_an_operation() {
        let mut span = span(SpanKind::Internal);

        finish_span(&mut span, true, None);

        assert_eq!(span_type(&span), Some("operation"));
    }

    #[test]
    fn an_internal_child_span_gets_no_type() {
        let mut span = span(SpanKind::Internal);

        finish_span(&mut span, false, None);

        assert_eq!(span_type(&span), None);
    }

    #[test]
    fn a_span_with_a_query_is_a_query() {
        let mut span = span(SpanKind::Client);
        set_span_attribute(&mut span, "db.query.text", "select 1");

        finish_span(&mut span, false, None);

        assert_eq!(span_type(&span), Some("query"));
    }

    #[test]
    fn a_span_type_of_the_span_wins() {
        let mut span = span(SpanKind::Internal);
        set_span_attribute(&mut span, "flare.span_type", "job");

        finish_span(&mut span, true, None);

        assert_eq!(span_type(&span), Some("job"));
    }

    #[test]
    fn a_command_span_gets_its_name_as_the_process_command() {
        let mut span = span(SpanKind::Internal);
        set_span_attribute(&mut span, "flare.span_type", "command");

        finish_span(&mut span, true, None);

        assert_eq!(string_attribute(&span, "process.command"), Some("checkout"));
    }

    #[test]
    fn only_an_error_status_keeps_its_message() {
        let mut span = span(SpanKind::Internal);
        span.status.message = Some("it went fine".to_owned());

        finish_span(&mut span, true, None);

        assert_eq!(span.status.message, None);
    }

    #[test]
    fn entry_point_attributes_of_the_span_win() {
        let mut span = span(SpanKind::Internal);
        set_span_attribute(&mut span, "flare.entry_point.type", "queue");

        finish_span(&mut span, true, Some(&EntryPoint::cli("app import")));

        assert_eq!(
            string_attribute(&span, "flare.entry_point.type"),
            Some("queue")
        );
    }

    #[test]
    fn a_server_span_with_a_path_is_a_web_entry_point() {
        let mut fields = EntryFields::new("request");
        fields.set("otel.kind", || "server".to_owned());
        fields.set("http.request.method", || "GET".to_owned());
        fields.set("url.path", || "/users/7".to_owned());

        let attributes = fields.entry_point().map(|entry| entry.attributes());

        assert!(attributes.is_some_and(|attributes| {
            attributes.contains(&("flare.entry_point.type", "web".to_owned()))
                && attributes.contains(&(
                    "flare.entry_point.handler.identifier",
                    "GET /users/7".to_owned(),
                ))
        }));
    }

    #[test]
    fn a_server_span_without_a_url_has_no_entry_point() {
        let mut fields = EntryFields::new("grpc");
        fields.set("otel.kind", || "server".to_owned());

        assert_eq!(fields.entry_point(), None);
    }

    #[test]
    fn merging_keeps_the_fields_that_the_other_value_did_not_set() {
        let mut fields = EntryFields::new("job");
        fields.set("otel.kind", || "consumer".to_owned());
        let mut later = EntryFields::default();
        later.set("messaging.destination.name", || "orders".to_owned());

        fields.merge(later);

        assert_eq!(fields.kind.as_deref(), Some("consumer"));
        assert_eq!(fields.destination.as_deref(), Some("orders"));
    }
}