flareapp-core 0.1.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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
//! The entry point of a report, log or trace: the web request, command or job
//! that started the work.
//!
//! Flare groups and filters by entry point, and only accepts three kinds: web
//! requests, commands and queued jobs. [`EntryPoint`] turns one of them into the
//! `flare.entry_point.*` attributes.
//!
//! The docs of [`EntryPoint`] list the four places that an entry point comes
//! from, and their order. [`resolve_entry_point`] applies that order, and all code
//! that resolves an entry point calls [`resolve_entry_point`]. The `tracing` integration stores the entry
//! point of a span as a [`SpanEntryPoint`].

use tracing_subscriber::Registry;
use tracing_subscriber::registry::LookupSpan;

use crate::process::executable_name;
use crate::scope::{app_entry_point, nested_entry_point};

/// The handler type of the process entry point, for a binary without a handler
/// of its own. Flare's protocol uses `php_script` for the same case in PHP.
const BINARY_HANDLER_TYPE: &str = "rust_binary";

/// The handler type of a command that has a handler identifier of its own.
pub(crate) const COMMAND_HANDLER_TYPE: &str = "rust_command";

/// What started the work that a report, log or trace belongs to: a web request, a
/// command, or a queued job. Flare requires an entry point, and groups and
/// filters by it.
///
/// # Where the entry point comes from
///
/// The Flare client looks for the entry point of a piece of work in four places,
/// in this order. The first place that has an entry point wins.
///
/// 1. The innermost nested scope that has an entry point. A nested scope is the
///    scope that [`with_scope`](crate::with_scope) or
///    [`ScopeFutureExt::with_flare_scope`](crate::ScopeFutureExt::with_flare_scope)
///    adds for one piece of work. Set the entry point there with
///    [`Scope::set_entry_point`](crate::Scope::set_entry_point). The web
///    integrations do this for each request.
/// 2. The closest `tracing` span around the work that has an entry point: the
///    `server` span of a request, the `consumer` span of a job, or a span with
///    `flare.span_type = "command"`. The `tracing` integration reads the entry
///    point from the fields of the span.
/// 3. The app-wide scope, set with [`configure_scope`](crate::configure_scope)
///    outside a nested scope.
/// 4. The command line of the process, from [`EntryPoint::current_process`].
///
/// The app-wide scope comes after the spans on purpose. A worker command can set
/// its own entry point in the app-wide scope. Each job that the worker runs still
/// gets the entry point of its job span.
#[derive(Debug, Clone, PartialEq, Eq)]
#[must_use]
pub struct EntryPoint {
    kind: EntryPointKind,
    value: String,
    handler_identifier: Option<String>,
    handler_name: Option<String>,
    handler_type: Option<String>,
}

/// The kinds of entry point Flare accepts.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum EntryPointKind {
    Web,
    Cli,
    Queue,
}

impl EntryPointKind {
    /// Returns the name that Flare uses for the kind, like `web`.
    fn as_str(self) -> &'static str {
        match self {
            Self::Web => "web",
            Self::Cli => "cli",
            Self::Queue => "queue",
        }
    }
}

impl EntryPoint {
    /// Creates a web request entry point. `url` is the full URL of the request.
    pub fn web<S: Into<String>>(url: S) -> Self {
        Self::new(EntryPointKind::Web, url.into())
    }

    /// Creates a command entry point. `command_line` is the command with its
    /// arguments.
    pub fn cli<S: Into<String>>(command_line: S) -> Self {
        Self::new(EntryPointKind::Cli, command_line.into())
    }

    /// Creates a queued job entry point. `job` is the name of the job.
    pub fn queue<S: Into<String>>(job: S) -> Self {
        Self::new(EntryPointKind::Queue, job.into())
    }

    /// Creates a command entry point with the command line of this process. The
    /// Flare client uses this entry point for work outside a request, job or
    /// command.
    ///
    /// # Examples
    ///
    /// When your app cannot use a command span, name the command on the app-wide
    /// scope, for example after it reads the name of a subcommand:
    ///
    /// ```
    /// use flareapp_core::EntryPoint;
    ///
    /// flareapp_core::configure_scope(|scope| {
    ///     scope.set_entry_point(EntryPoint::current_process().handler_identifier("import"));
    /// });
    /// ```
    pub fn current_process() -> Self {
        Self::cli(crate::command_line())
    }

    fn new(kind: EntryPointKind, value: String) -> Self {
        Self {
            kind,
            value,
            handler_identifier: None,
            handler_name: None,
            handler_type: None,
        }
    }

    /// Sets the identifier Flare groups by, like the route `GET /users/{id}`, a
    /// command name, or a job name.
    pub fn handler_identifier<S: Into<String>>(mut self, identifier: S) -> Self {
        self.handler_identifier = Some(identifier.into());

        self
    }

    /// Sets the code that handles the work, like a controller or a job type.
    pub fn handler_name<S: Into<String>>(mut self, name: S) -> Self {
        self.handler_name = Some(name.into());

        self
    }

    /// Sets the kind of handler, prefixed with the framework, like `axum_route`.
    pub fn handler_type<S: Into<String>>(mut self, handler_type: S) -> Self {
        self.handler_type = Some(handler_type.into());

        self
    }

    /// Returns the `flare.entry_point.*` attributes.
    ///
    /// Flare lists work under its handler identifier, so an entry point without
    /// one gets the default of Flare's protocol: the path for a web request, the
    /// executable name for a command, and the job name for a job.
    ///
    /// Used by the Flare integrations. Not part of the public API.
    #[doc(hidden)]
    pub fn attributes(&self) -> Vec<(&'static str, String)> {
        self.clone().into_attributes()
    }

    /// Returns the `flare.entry_point.*` attributes, like
    /// [`EntryPoint::attributes`]. This function moves the strings of the entry
    /// point into the attributes instead of copying them.
    pub(crate) fn into_attributes(mut self) -> Vec<(&'static str, String)> {
        // The default handler type checks the handler identifier, so it comes first.
        let handler_type = self
            .handler_type
            .take()
            .or_else(|| self.default_handler_type());
        let handler_identifier = self
            .handler_identifier
            .take()
            .or_else(|| self.default_handler_identifier());

        let mut attributes = vec![
            ("flare.entry_point.type", self.kind.as_str().to_owned()),
            ("flare.entry_point.value", self.value),
        ];
        let handler = [
            ("flare.entry_point.handler.identifier", handler_identifier),
            ("flare.entry_point.handler.name", self.handler_name),
            ("flare.entry_point.handler.type", handler_type),
        ];
        attributes.extend(
            handler
                .into_iter()
                .filter_map(|(key, value)| value.map(|value| (key, value))),
        );

        attributes
    }

    fn default_handler_identifier(&self) -> Option<String> {
        match self.kind {
            EntryPointKind::Web => Some(url_path(&self.value).to_owned()),
            EntryPointKind::Cli => executable_name().map(str::to_owned),
            EntryPointKind::Queue => Some(self.value.clone()),
        }
    }

    /// Returns the handler type of a command without one. A command with its own
    /// identifier is a `rust_command`, and a command that falls back to the
    /// executable name is a `rust_binary`.
    fn default_handler_type(&self) -> Option<String> {
        if self.kind != EntryPointKind::Cli {
            return None;
        }
        if self.handler_identifier.is_some() {
            return Some(COMMAND_HANDLER_TYPE.to_owned());
        }

        executable_name().map(|_| BINARY_HANDLER_TYPE.to_owned())
    }
}

/// The parts of a web request that decide its entry point. See
/// [`web_entry_point`].
///
/// Used by the Flare integrations. Not part of the public API.
#[doc(hidden)]
#[derive(Debug, Clone, Copy)]
pub struct WebRequest<'a> {
    /// The URL of the request, like `https://shop.test/users/7`. It is the value
    /// of the entry point.
    pub url: &'a str,
    /// The HTTP method, like `GET`.
    pub method: Option<&'a str>,
    /// The route pattern that matched, like `/users/{id}`.
    pub route: Option<&'a str>,
    /// The path, like `/users/7`.
    pub path: Option<&'a str>,
    /// The framework that handles the request, like `axum`.
    pub framework: Option<&'a str>,
}

/// Creates the entry point of a web request, for the web integrations.
///
/// `url` is the value of the entry point. The handler identifier is
/// `METHOD route` when there is a `route`. Otherwise it is `METHOD path`, where
/// `path` is the given path, or else the path of `url`. Without a `method`, the
/// identifier is only the route or the path.
///
/// The handler type is `<framework>_route`, like `axum_route`, but only when both
/// the route and the framework are known.
///
/// Used by the Flare integrations. Not part of the public API.
#[doc(hidden)]
pub fn web_entry_point(request: &WebRequest<'_>) -> EntryPoint {
    let target = request
        .route
        .or(request.path)
        .unwrap_or_else(|| url_path(request.url));
    let identifier = match request.method {
        Some(method) => format!("{method} {target}"),
        None => target.to_owned(),
    };

    let entry_point = EntryPoint::web(request.url).handler_identifier(identifier);

    match (request.route, request.framework) {
        (Some(_), Some(framework)) => entry_point.handler_type(format!("{framework}_route")),
        _ => entry_point,
    }
}

/// Returns the path of a URL, without the query and fragment: `/users/7` for
/// `https://shop.test/users/7?tab=orders`.
fn url_path(url: &str) -> &str {
    let path = match url.split_once("://") {
        Some((_, rest)) => rest.find('/').and_then(|start| rest.get(start..)),
        None => Some(url),
    };
    let path = path.unwrap_or("/");

    path.split(['?', '#']).next().unwrap_or(path)
}

/// The entry point of a `tracing` span, stored in the extensions of the span.
///
/// The `tracing` integration stores this value on the spans that start a piece of
/// work: the `server` span of a request, the `consumer` span of a job, or a
/// command span. Reports, logs and the root spans of traces inside the span get
/// this entry point, unless a nested scope has an entry point of its own.
///
/// The Flare integrations use this type. It is not part of the public API.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SpanEntryPoint(pub EntryPoint);

/// Returns the entry point of the closest span around the current code that has
/// an entry point. Returns `None` when no span around the code has one.
///
/// The spans live in the subscriber, so this function asks the subscriber of the
/// current span for its `Registry`. That works with every subscriber built on
/// `tracing_subscriber::registry()`.
///
/// The Flare integrations use this function. It is not part of the public API.
pub fn current_span_entry_point() -> Option<EntryPoint> {
    tracing::Span::current()
        .with_subscriber(|(id, dispatch)| {
            let registry = dispatch.downcast_ref::<Registry>()?;

            registry.span(id)?.scope().find_map(|span| {
                span.extensions()
                    .get::<SpanEntryPoint>()
                    .map(|entry_point| entry_point.0.clone())
            })
        })
        .flatten()
}

/// Returns the entry point of the current work, in the order of the
/// [`EntryPoint`] docs: the innermost nested scope, the closest `tracing` span,
/// the app-wide scope, and else the command line of the process.
///
/// `search_spans` returns the entry point of the closest `tracing` span that has
/// one. This function only calls `search_spans` when no nested scope has an entry
/// point, because a nested scope wins over every span.
///
/// Call this function on the thread that made the work, because the nested scopes
/// belong to that thread. The Flare integrations use this function. The function
/// is not part of the public API.
pub fn resolve_entry_point<F>(search_spans: F) -> EntryPoint
where
    F: FnOnce() -> Option<EntryPoint>,
{
    nested_entry_point()
        .or_else(search_spans)
        .or_else(app_entry_point)
        .unwrap_or_else(EntryPoint::current_process)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::scope::with_scope;
    use crate::test_support::{global_entry_point, serial};

    fn attribute(entry_point: &EntryPoint, key: &str) -> Option<String> {
        entry_point
            .attributes()
            .into_iter()
            .find(|(name, _)| *name == key)
            .map(|(_, value)| value)
    }

    #[test]
    fn a_set_identifier_wins() {
        let entry_point = EntryPoint::cli("my-app import").handler_identifier("import");

        assert_eq!(
            attribute(&entry_point, "flare.entry_point.handler.identifier").as_deref(),
            Some("import")
        );
    }

    #[test]
    fn commands_with_an_identifier_are_rust_commands() {
        let entry_point = EntryPoint::cli("my-app import").handler_identifier("import");

        assert_eq!(
            attribute(&entry_point, "flare.entry_point.handler.type").as_deref(),
            Some("rust_command")
        );
    }

    #[test]
    fn a_set_handler_type_wins_for_commands() {
        let entry_point = EntryPoint::cli("my-app import")
            .handler_identifier("import")
            .handler_type("clap_command");

        assert_eq!(
            attribute(&entry_point, "flare.entry_point.handler.type").as_deref(),
            Some("clap_command")
        );
    }

    #[test]
    fn jobs_with_an_identifier_have_no_handler_type() {
        let entry_point = EntryPoint::queue("send-invoice").handler_identifier("invoices");

        assert_eq!(
            attribute(&entry_point, "flare.entry_point.handler.type"),
            None
        );
    }

    #[test]
    fn commands_default_to_the_executable_name() {
        let entry_point = EntryPoint::cli("my-app import");

        assert_eq!(
            attribute(&entry_point, "flare.entry_point.handler.identifier").as_deref(),
            executable_name()
        );
    }

    #[test]
    fn commands_without_an_identifier_are_rust_binaries() {
        let entry_point = EntryPoint::cli("my-app import");

        assert_eq!(
            attribute(&entry_point, "flare.entry_point.handler.type").as_deref(),
            Some("rust_binary")
        );
    }

    #[test]
    fn jobs_default_to_the_job_name() {
        let entry_point = EntryPoint::queue("send-invoice");

        assert_eq!(
            attribute(&entry_point, "flare.entry_point.handler.identifier").as_deref(),
            Some("send-invoice")
        );
    }

    #[test]
    fn web_requests_default_to_the_path() {
        let entry_point = EntryPoint::web("https://shop.test/users/7?tab=orders");

        assert_eq!(
            attribute(&entry_point, "flare.entry_point.handler.identifier").as_deref(),
            Some("/users/7")
        );
    }

    #[test]
    fn the_path_of_a_url_has_no_query_or_fragment() {
        assert_eq!(
            url_path("https://shop.test/users/7?tab=orders#top"),
            "/users/7"
        );
    }

    #[test]
    fn the_path_of_a_url_without_a_path_is_the_root() {
        assert_eq!(url_path("https://shop.test"), "/");
    }

    #[test]
    fn the_path_of_a_path_is_the_path() {
        assert_eq!(url_path("/users/7?tab=orders"), "/users/7");
    }

    fn nested() -> EntryPoint {
        EntryPoint::web("https://shop.test/users/7")
    }

    fn span() -> EntryPoint {
        EntryPoint::queue("send-invoice")
    }

    fn global() -> EntryPoint {
        EntryPoint::cli("my-app worker")
    }

    #[test]
    fn a_nested_scope_wins_over_a_span() {
        let _serial = serial();
        let _global = global_entry_point(global());

        let resolved = with_scope(
            |scope| scope.set_entry_point(nested()),
            || resolve_entry_point(|| Some(span())),
        );

        assert_eq!(resolved, nested());
    }

    #[test]
    fn a_nested_scope_skips_the_span_search() {
        let searched = with_scope(
            |scope| scope.set_entry_point(nested()),
            || {
                let mut searched = false;
                let _ = resolve_entry_point(|| {
                    searched = true;

                    None
                });

                searched
            },
        );

        assert!(!searched);
    }

    #[test]
    fn a_span_wins_over_the_global_scope() {
        let _serial = serial();
        let _global = global_entry_point(global());

        assert_eq!(resolve_entry_point(|| Some(span())), span());
    }

    #[test]
    fn the_global_scope_wins_over_the_process() {
        let _serial = serial();
        let _global = global_entry_point(global());

        assert_eq!(resolve_entry_point(|| None), global());
    }

    #[test]
    fn the_process_is_the_fallback() {
        let _serial = serial();

        assert_eq!(resolve_entry_point(|| None), EntryPoint::current_process());
    }

    #[test]
    fn a_web_entry_point_with_a_route_and_framework_has_a_route_handler() {
        let entry_point = web_entry_point(&WebRequest {
            url: "https://shop.test/users/7",
            method: Some("GET"),
            route: Some("/users/{id}"),
            path: Some("/users/7"),
            framework: Some("axum"),
        });

        assert_eq!(
            entry_point,
            EntryPoint::web("https://shop.test/users/7")
                .handler_identifier("GET /users/{id}")
                .handler_type("axum_route")
        );
    }

    #[test]
    fn a_web_entry_point_with_a_route_but_no_framework_has_no_handler_type() {
        let entry_point = web_entry_point(&WebRequest {
            url: "https://shop.test/users/7",
            method: Some("GET"),
            route: Some("/users/{id}"),
            path: Some("/users/7"),
            framework: None,
        });

        assert_eq!(
            entry_point,
            EntryPoint::web("https://shop.test/users/7").handler_identifier("GET /users/{id}")
        );
    }

    #[test]
    fn a_web_entry_point_without_a_route_uses_the_given_path() {
        let entry_point = web_entry_point(&WebRequest {
            url: "https://shop.test/users/7?tab=orders",
            method: Some("GET"),
            route: None,
            path: Some("/users/7"),
            framework: Some("axum"),
        });

        assert_eq!(
            entry_point,
            EntryPoint::web("https://shop.test/users/7?tab=orders")
                .handler_identifier("GET /users/7")
        );
    }

    #[test]
    fn a_web_entry_point_with_only_a_url_uses_the_path_of_the_url() {
        let entry_point = web_entry_point(&WebRequest {
            url: "https://shop.test/users/7?tab=orders",
            method: Some("GET"),
            route: None,
            path: None,
            framework: None,
        });

        assert_eq!(
            entry_point,
            EntryPoint::web("https://shop.test/users/7?tab=orders")
                .handler_identifier("GET /users/7")
        );
    }

    #[test]
    fn a_web_entry_point_without_a_method_has_only_the_path() {
        let entry_point = web_entry_point(&WebRequest {
            url: "https://shop.test/users/7",
            method: None,
            route: None,
            path: None,
            framework: None,
        });

        assert_eq!(
            entry_point,
            EntryPoint::web("https://shop.test/users/7").handler_identifier("/users/7")
        );
    }
}