Skip to main content

flareapp_core/
entry_point.rs

1//! The entry point of a report, log or trace: the web request, command or job
2//! that started the work.
3//!
4//! Flare groups and filters by entry point, and only accepts three kinds: web
5//! requests, commands and queued jobs. [`EntryPoint`] turns one of them into the
6//! `flare.entry_point.*` attributes.
7//!
8//! The docs of [`EntryPoint`] list the four places that an entry point comes
9//! from, and their order. [`resolve_entry_point`] applies that order, and all code
10//! that resolves an entry point calls [`resolve_entry_point`]. The `tracing` integration stores the entry
11//! point of a span as a [`SpanEntryPoint`].
12
13use tracing_subscriber::Registry;
14use tracing_subscriber::registry::LookupSpan;
15
16use crate::process::executable_name;
17use crate::scope::{app_entry_point, nested_entry_point};
18
19/// The handler type of the process entry point, for a binary without a handler
20/// of its own. Flare's protocol uses `php_script` for the same case in PHP.
21const BINARY_HANDLER_TYPE: &str = "rust_binary";
22
23/// The handler type of a command that has a handler identifier of its own.
24pub(crate) const COMMAND_HANDLER_TYPE: &str = "rust_command";
25
26/// What started the work that a report, log or trace belongs to: a web request, a
27/// command, or a queued job. Flare requires an entry point, and groups and
28/// filters by it.
29///
30/// # Where the entry point comes from
31///
32/// The Flare client looks for the entry point of a piece of work in four places,
33/// in this order. The first place that has an entry point wins.
34///
35/// 1. The innermost nested scope that has an entry point. A nested scope is the
36///    scope that [`with_scope`](crate::with_scope) or
37///    [`ScopeFutureExt::with_flare_scope`](crate::ScopeFutureExt::with_flare_scope)
38///    adds for one piece of work. Set the entry point there with
39///    [`Scope::set_entry_point`](crate::Scope::set_entry_point). The web
40///    integrations do this for each request.
41/// 2. The closest `tracing` span around the work that has an entry point: the
42///    `server` span of a request, the `consumer` span of a job, or a span with
43///    `flare.span_type = "command"`. The `tracing` integration reads the entry
44///    point from the fields of the span.
45/// 3. The app-wide scope, set with [`configure_scope`](crate::configure_scope)
46///    outside a nested scope.
47/// 4. The command line of the process, from [`EntryPoint::current_process`].
48///
49/// The app-wide scope comes after the spans on purpose. A worker command can set
50/// its own entry point in the app-wide scope. Each job that the worker runs still
51/// gets the entry point of its job span.
52#[derive(Debug, Clone, PartialEq, Eq)]
53#[must_use]
54pub struct EntryPoint {
55    kind: EntryPointKind,
56    value: String,
57    handler_identifier: Option<String>,
58    handler_name: Option<String>,
59    handler_type: Option<String>,
60}
61
62/// The kinds of entry point Flare accepts.
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64enum EntryPointKind {
65    Web,
66    Cli,
67    Queue,
68}
69
70impl EntryPointKind {
71    /// Returns the name that Flare uses for the kind, like `web`.
72    fn as_str(self) -> &'static str {
73        match self {
74            Self::Web => "web",
75            Self::Cli => "cli",
76            Self::Queue => "queue",
77        }
78    }
79}
80
81impl EntryPoint {
82    /// Creates a web request entry point. `url` is the full URL of the request.
83    pub fn web<S: Into<String>>(url: S) -> Self {
84        Self::new(EntryPointKind::Web, url.into())
85    }
86
87    /// Creates a command entry point. `command_line` is the command with its
88    /// arguments.
89    pub fn cli<S: Into<String>>(command_line: S) -> Self {
90        Self::new(EntryPointKind::Cli, command_line.into())
91    }
92
93    /// Creates a queued job entry point. `job` is the name of the job.
94    pub fn queue<S: Into<String>>(job: S) -> Self {
95        Self::new(EntryPointKind::Queue, job.into())
96    }
97
98    /// Creates a command entry point with the command line of this process. The
99    /// Flare client uses this entry point for work outside a request, job or
100    /// command.
101    ///
102    /// # Examples
103    ///
104    /// When your app cannot use a command span, name the command on the app-wide
105    /// scope, for example after it reads the name of a subcommand:
106    ///
107    /// ```
108    /// use flareapp_core::EntryPoint;
109    ///
110    /// flareapp_core::configure_scope(|scope| {
111    ///     scope.set_entry_point(EntryPoint::current_process().handler_identifier("import"));
112    /// });
113    /// ```
114    pub fn current_process() -> Self {
115        Self::cli(crate::command_line())
116    }
117
118    fn new(kind: EntryPointKind, value: String) -> Self {
119        Self {
120            kind,
121            value,
122            handler_identifier: None,
123            handler_name: None,
124            handler_type: None,
125        }
126    }
127
128    /// Sets the identifier Flare groups by, like the route `GET /users/{id}`, a
129    /// command name, or a job name.
130    pub fn handler_identifier<S: Into<String>>(mut self, identifier: S) -> Self {
131        self.handler_identifier = Some(identifier.into());
132
133        self
134    }
135
136    /// Sets the code that handles the work, like a controller or a job type.
137    pub fn handler_name<S: Into<String>>(mut self, name: S) -> Self {
138        self.handler_name = Some(name.into());
139
140        self
141    }
142
143    /// Sets the kind of handler, prefixed with the framework, like `axum_route`.
144    pub fn handler_type<S: Into<String>>(mut self, handler_type: S) -> Self {
145        self.handler_type = Some(handler_type.into());
146
147        self
148    }
149
150    /// Returns the `flare.entry_point.*` attributes.
151    ///
152    /// Flare lists work under its handler identifier, so an entry point without
153    /// one gets the default of Flare's protocol: the path for a web request, the
154    /// executable name for a command, and the job name for a job.
155    ///
156    /// Used by the Flare integrations. Not part of the public API.
157    #[doc(hidden)]
158    pub fn attributes(&self) -> Vec<(&'static str, String)> {
159        self.clone().into_attributes()
160    }
161
162    /// Returns the `flare.entry_point.*` attributes, like
163    /// [`EntryPoint::attributes`]. This function moves the strings of the entry
164    /// point into the attributes instead of copying them.
165    pub(crate) fn into_attributes(mut self) -> Vec<(&'static str, String)> {
166        // The default handler type checks the handler identifier, so it comes first.
167        let handler_type = self
168            .handler_type
169            .take()
170            .or_else(|| self.default_handler_type());
171        let handler_identifier = self
172            .handler_identifier
173            .take()
174            .or_else(|| self.default_handler_identifier());
175
176        let mut attributes = vec![
177            ("flare.entry_point.type", self.kind.as_str().to_owned()),
178            ("flare.entry_point.value", self.value),
179        ];
180        let handler = [
181            ("flare.entry_point.handler.identifier", handler_identifier),
182            ("flare.entry_point.handler.name", self.handler_name),
183            ("flare.entry_point.handler.type", handler_type),
184        ];
185        attributes.extend(
186            handler
187                .into_iter()
188                .filter_map(|(key, value)| value.map(|value| (key, value))),
189        );
190
191        attributes
192    }
193
194    fn default_handler_identifier(&self) -> Option<String> {
195        match self.kind {
196            EntryPointKind::Web => Some(url_path(&self.value).to_owned()),
197            EntryPointKind::Cli => executable_name().map(str::to_owned),
198            EntryPointKind::Queue => Some(self.value.clone()),
199        }
200    }
201
202    /// Returns the handler type of a command without one. A command with its own
203    /// identifier is a `rust_command`, and a command that falls back to the
204    /// executable name is a `rust_binary`.
205    fn default_handler_type(&self) -> Option<String> {
206        if self.kind != EntryPointKind::Cli {
207            return None;
208        }
209        if self.handler_identifier.is_some() {
210            return Some(COMMAND_HANDLER_TYPE.to_owned());
211        }
212
213        executable_name().map(|_| BINARY_HANDLER_TYPE.to_owned())
214    }
215}
216
217/// The parts of a web request that decide its entry point. See
218/// [`web_entry_point`].
219///
220/// Used by the Flare integrations. Not part of the public API.
221#[doc(hidden)]
222#[derive(Debug, Clone, Copy)]
223pub struct WebRequest<'a> {
224    /// The URL of the request, like `https://shop.test/users/7`. It is the value
225    /// of the entry point.
226    pub url: &'a str,
227    /// The HTTP method, like `GET`.
228    pub method: Option<&'a str>,
229    /// The route pattern that matched, like `/users/{id}`.
230    pub route: Option<&'a str>,
231    /// The path, like `/users/7`.
232    pub path: Option<&'a str>,
233    /// The framework that handles the request, like `axum`.
234    pub framework: Option<&'a str>,
235}
236
237/// Creates the entry point of a web request, for the web integrations.
238///
239/// `url` is the value of the entry point. The handler identifier is
240/// `METHOD route` when there is a `route`. Otherwise it is `METHOD path`, where
241/// `path` is the given path, or else the path of `url`. Without a `method`, the
242/// identifier is only the route or the path.
243///
244/// The handler type is `<framework>_route`, like `axum_route`, but only when both
245/// the route and the framework are known.
246///
247/// Used by the Flare integrations. Not part of the public API.
248#[doc(hidden)]
249pub fn web_entry_point(request: &WebRequest<'_>) -> EntryPoint {
250    let target = request
251        .route
252        .or(request.path)
253        .unwrap_or_else(|| url_path(request.url));
254    let identifier = match request.method {
255        Some(method) => format!("{method} {target}"),
256        None => target.to_owned(),
257    };
258
259    let entry_point = EntryPoint::web(request.url).handler_identifier(identifier);
260
261    match (request.route, request.framework) {
262        (Some(_), Some(framework)) => entry_point.handler_type(format!("{framework}_route")),
263        _ => entry_point,
264    }
265}
266
267/// Returns the path of a URL, without the query and fragment: `/users/7` for
268/// `https://shop.test/users/7?tab=orders`.
269fn url_path(url: &str) -> &str {
270    let path = match url.split_once("://") {
271        Some((_, rest)) => rest.find('/').and_then(|start| rest.get(start..)),
272        None => Some(url),
273    };
274    let path = path.unwrap_or("/");
275
276    path.split(['?', '#']).next().unwrap_or(path)
277}
278
279/// The entry point of a `tracing` span, stored in the extensions of the span.
280///
281/// The `tracing` integration stores this value on the spans that start a piece of
282/// work: the `server` span of a request, the `consumer` span of a job, or a
283/// command span. Reports, logs and the root spans of traces inside the span get
284/// this entry point, unless a nested scope has an entry point of its own.
285///
286/// The Flare integrations use this type. It is not part of the public API.
287#[derive(Debug, Clone, PartialEq, Eq)]
288pub struct SpanEntryPoint(pub EntryPoint);
289
290/// Returns the entry point of the closest span around the current code that has
291/// an entry point. Returns `None` when no span around the code has one.
292///
293/// The spans live in the subscriber, so this function asks the subscriber of the
294/// current span for its `Registry`. That works with every subscriber built on
295/// `tracing_subscriber::registry()`.
296///
297/// The Flare integrations use this function. It is not part of the public API.
298pub fn current_span_entry_point() -> Option<EntryPoint> {
299    tracing::Span::current()
300        .with_subscriber(|(id, dispatch)| {
301            let registry = dispatch.downcast_ref::<Registry>()?;
302
303            registry.span(id)?.scope().find_map(|span| {
304                span.extensions()
305                    .get::<SpanEntryPoint>()
306                    .map(|entry_point| entry_point.0.clone())
307            })
308        })
309        .flatten()
310}
311
312/// Returns the entry point of the current work, in the order of the
313/// [`EntryPoint`] docs: the innermost nested scope, the closest `tracing` span,
314/// the app-wide scope, and else the command line of the process.
315///
316/// `search_spans` returns the entry point of the closest `tracing` span that has
317/// one. This function only calls `search_spans` when no nested scope has an entry
318/// point, because a nested scope wins over every span.
319///
320/// Call this function on the thread that made the work, because the nested scopes
321/// belong to that thread. The Flare integrations use this function. The function
322/// is not part of the public API.
323pub fn resolve_entry_point<F>(search_spans: F) -> EntryPoint
324where
325    F: FnOnce() -> Option<EntryPoint>,
326{
327    nested_entry_point()
328        .or_else(search_spans)
329        .or_else(app_entry_point)
330        .unwrap_or_else(EntryPoint::current_process)
331}
332
333#[cfg(test)]
334mod tests {
335    use super::*;
336    use crate::scope::with_scope;
337    use crate::test_support::{global_entry_point, serial};
338
339    fn attribute(entry_point: &EntryPoint, key: &str) -> Option<String> {
340        entry_point
341            .attributes()
342            .into_iter()
343            .find(|(name, _)| *name == key)
344            .map(|(_, value)| value)
345    }
346
347    #[test]
348    fn a_set_identifier_wins() {
349        let entry_point = EntryPoint::cli("my-app import").handler_identifier("import");
350
351        assert_eq!(
352            attribute(&entry_point, "flare.entry_point.handler.identifier").as_deref(),
353            Some("import")
354        );
355    }
356
357    #[test]
358    fn commands_with_an_identifier_are_rust_commands() {
359        let entry_point = EntryPoint::cli("my-app import").handler_identifier("import");
360
361        assert_eq!(
362            attribute(&entry_point, "flare.entry_point.handler.type").as_deref(),
363            Some("rust_command")
364        );
365    }
366
367    #[test]
368    fn a_set_handler_type_wins_for_commands() {
369        let entry_point = EntryPoint::cli("my-app import")
370            .handler_identifier("import")
371            .handler_type("clap_command");
372
373        assert_eq!(
374            attribute(&entry_point, "flare.entry_point.handler.type").as_deref(),
375            Some("clap_command")
376        );
377    }
378
379    #[test]
380    fn jobs_with_an_identifier_have_no_handler_type() {
381        let entry_point = EntryPoint::queue("send-invoice").handler_identifier("invoices");
382
383        assert_eq!(
384            attribute(&entry_point, "flare.entry_point.handler.type"),
385            None
386        );
387    }
388
389    #[test]
390    fn commands_default_to_the_executable_name() {
391        let entry_point = EntryPoint::cli("my-app import");
392
393        assert_eq!(
394            attribute(&entry_point, "flare.entry_point.handler.identifier").as_deref(),
395            executable_name()
396        );
397    }
398
399    #[test]
400    fn commands_without_an_identifier_are_rust_binaries() {
401        let entry_point = EntryPoint::cli("my-app import");
402
403        assert_eq!(
404            attribute(&entry_point, "flare.entry_point.handler.type").as_deref(),
405            Some("rust_binary")
406        );
407    }
408
409    #[test]
410    fn jobs_default_to_the_job_name() {
411        let entry_point = EntryPoint::queue("send-invoice");
412
413        assert_eq!(
414            attribute(&entry_point, "flare.entry_point.handler.identifier").as_deref(),
415            Some("send-invoice")
416        );
417    }
418
419    #[test]
420    fn web_requests_default_to_the_path() {
421        let entry_point = EntryPoint::web("https://shop.test/users/7?tab=orders");
422
423        assert_eq!(
424            attribute(&entry_point, "flare.entry_point.handler.identifier").as_deref(),
425            Some("/users/7")
426        );
427    }
428
429    #[test]
430    fn the_path_of_a_url_has_no_query_or_fragment() {
431        assert_eq!(
432            url_path("https://shop.test/users/7?tab=orders#top"),
433            "/users/7"
434        );
435    }
436
437    #[test]
438    fn the_path_of_a_url_without_a_path_is_the_root() {
439        assert_eq!(url_path("https://shop.test"), "/");
440    }
441
442    #[test]
443    fn the_path_of_a_path_is_the_path() {
444        assert_eq!(url_path("/users/7?tab=orders"), "/users/7");
445    }
446
447    fn nested() -> EntryPoint {
448        EntryPoint::web("https://shop.test/users/7")
449    }
450
451    fn span() -> EntryPoint {
452        EntryPoint::queue("send-invoice")
453    }
454
455    fn global() -> EntryPoint {
456        EntryPoint::cli("my-app worker")
457    }
458
459    #[test]
460    fn a_nested_scope_wins_over_a_span() {
461        let _serial = serial();
462        let _global = global_entry_point(global());
463
464        let resolved = with_scope(
465            |scope| scope.set_entry_point(nested()),
466            || resolve_entry_point(|| Some(span())),
467        );
468
469        assert_eq!(resolved, nested());
470    }
471
472    #[test]
473    fn a_nested_scope_skips_the_span_search() {
474        let searched = with_scope(
475            |scope| scope.set_entry_point(nested()),
476            || {
477                let mut searched = false;
478                let _ = resolve_entry_point(|| {
479                    searched = true;
480
481                    None
482                });
483
484                searched
485            },
486        );
487
488        assert!(!searched);
489    }
490
491    #[test]
492    fn a_span_wins_over_the_global_scope() {
493        let _serial = serial();
494        let _global = global_entry_point(global());
495
496        assert_eq!(resolve_entry_point(|| Some(span())), span());
497    }
498
499    #[test]
500    fn the_global_scope_wins_over_the_process() {
501        let _serial = serial();
502        let _global = global_entry_point(global());
503
504        assert_eq!(resolve_entry_point(|| None), global());
505    }
506
507    #[test]
508    fn the_process_is_the_fallback() {
509        let _serial = serial();
510
511        assert_eq!(resolve_entry_point(|| None), EntryPoint::current_process());
512    }
513
514    #[test]
515    fn a_web_entry_point_with_a_route_and_framework_has_a_route_handler() {
516        let entry_point = web_entry_point(&WebRequest {
517            url: "https://shop.test/users/7",
518            method: Some("GET"),
519            route: Some("/users/{id}"),
520            path: Some("/users/7"),
521            framework: Some("axum"),
522        });
523
524        assert_eq!(
525            entry_point,
526            EntryPoint::web("https://shop.test/users/7")
527                .handler_identifier("GET /users/{id}")
528                .handler_type("axum_route")
529        );
530    }
531
532    #[test]
533    fn a_web_entry_point_with_a_route_but_no_framework_has_no_handler_type() {
534        let entry_point = web_entry_point(&WebRequest {
535            url: "https://shop.test/users/7",
536            method: Some("GET"),
537            route: Some("/users/{id}"),
538            path: Some("/users/7"),
539            framework: None,
540        });
541
542        assert_eq!(
543            entry_point,
544            EntryPoint::web("https://shop.test/users/7").handler_identifier("GET /users/{id}")
545        );
546    }
547
548    #[test]
549    fn a_web_entry_point_without_a_route_uses_the_given_path() {
550        let entry_point = web_entry_point(&WebRequest {
551            url: "https://shop.test/users/7?tab=orders",
552            method: Some("GET"),
553            route: None,
554            path: Some("/users/7"),
555            framework: Some("axum"),
556        });
557
558        assert_eq!(
559            entry_point,
560            EntryPoint::web("https://shop.test/users/7?tab=orders")
561                .handler_identifier("GET /users/7")
562        );
563    }
564
565    #[test]
566    fn a_web_entry_point_with_only_a_url_uses_the_path_of_the_url() {
567        let entry_point = web_entry_point(&WebRequest {
568            url: "https://shop.test/users/7?tab=orders",
569            method: Some("GET"),
570            route: None,
571            path: None,
572            framework: None,
573        });
574
575        assert_eq!(
576            entry_point,
577            EntryPoint::web("https://shop.test/users/7?tab=orders")
578                .handler_identifier("GET /users/7")
579        );
580    }
581
582    #[test]
583    fn a_web_entry_point_without_a_method_has_only_the_path() {
584        let entry_point = web_entry_point(&WebRequest {
585            url: "https://shop.test/users/7",
586            method: None,
587            route: None,
588            path: None,
589            framework: None,
590        });
591
592        assert_eq!(
593            entry_point,
594            EntryPoint::web("https://shop.test/users/7").handler_identifier("/users/7")
595        );
596    }
597}