1use tracing_subscriber::Registry;
14use tracing_subscriber::registry::LookupSpan;
15
16use crate::process::executable_name;
17use crate::scope::{app_entry_point, nested_entry_point};
18
19const BINARY_HANDLER_TYPE: &str = "rust_binary";
22
23pub(crate) const COMMAND_HANDLER_TYPE: &str = "rust_command";
25
26#[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64enum EntryPointKind {
65 Web,
66 Cli,
67 Queue,
68}
69
70impl EntryPointKind {
71 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 pub fn web<S: Into<String>>(url: S) -> Self {
84 Self::new(EntryPointKind::Web, url.into())
85 }
86
87 pub fn cli<S: Into<String>>(command_line: S) -> Self {
90 Self::new(EntryPointKind::Cli, command_line.into())
91 }
92
93 pub fn queue<S: Into<String>>(job: S) -> Self {
95 Self::new(EntryPointKind::Queue, job.into())
96 }
97
98 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 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 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 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 #[doc(hidden)]
158 pub fn attributes(&self) -> Vec<(&'static str, String)> {
159 self.clone().into_attributes()
160 }
161
162 pub(crate) fn into_attributes(mut self) -> Vec<(&'static str, String)> {
166 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 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#[doc(hidden)]
222#[derive(Debug, Clone, Copy)]
223pub struct WebRequest<'a> {
224 pub url: &'a str,
227 pub method: Option<&'a str>,
229 pub route: Option<&'a str>,
231 pub path: Option<&'a str>,
233 pub framework: Option<&'a str>,
235}
236
237#[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
267fn 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#[derive(Debug, Clone, PartialEq, Eq)]
288pub struct SpanEntryPoint(pub EntryPoint);
289
290pub 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
312pub 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}