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
use crate::context::ResolveId;
use crate::extensions::{Extension, ResolveInfo};
use crate::QueryPathSegment;
use parking_lot::Mutex;
use std::collections::BTreeMap;
use tracing::{span, Id, Level};

#[derive(Default)]
struct Inner {
    root_id: Option<Id>,
    fields: BTreeMap<usize, Id>,
}

/// Tracing extension
///
/// # References
///
/// https://crates.io/crates/tracing
pub struct Tracing {
    inner: Mutex<Inner>,
}

impl Default for Tracing {
    fn default() -> Self {
        Self {
            inner: Default::default(),
        }
    }
}

impl Extension for Tracing {
    fn parse_start(&self, query_source: &str) {
        let root_span = span!(target: "async-graphql", parent:None, Level::INFO, "query", source = query_source);
        if let Some(id) = root_span.id() {
            tracing::dispatcher::get_default(|d| d.enter(&id));
            self.inner.lock().root_id.replace(id);
        }
    }

    fn execution_end(&self) {
        if let Some(id) = self.inner.lock().root_id.take() {
            tracing::dispatcher::get_default(|d| d.exit(&id));
        }
    }

    fn resolve_field_start(&self, info: &ResolveInfo<'_>) {
        let mut inner = self.inner.lock();
        let parent_span = info
            .resolve_id
            .parent
            .and_then(|id| inner.fields.get(&id))
            .cloned();
        let span = match &info.path_node.segment {
            QueryPathSegment::Index(idx) => span!(
                target: "async-graphql",
                parent: parent_span,
                Level::INFO,
                "field",
                index = *idx,
                parent_type = info.parent_type,
                return_type = info.return_type
            ),
            QueryPathSegment::Name(name) => span!(
                target: "async-graphql",
                parent: parent_span,
                Level::INFO,
                "field",
                name = name,
                parent_type = info.parent_type,
                return_type = info.return_type
            ),
        };
        if let Some(id) = span.id() {
            tracing::dispatcher::get_default(|d| d.enter(&id));
            inner.fields.insert(info.resolve_id.current, id);
        }
    }

    fn resolve_field_end(&self, resolve_id: ResolveId) {
        if let Some(id) = self.inner.lock().fields.remove(&resolve_id.current) {
            tracing::dispatcher::get_default(|d| d.exit(&id));
        }
    }
}