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
#[macro_use]
extern crate serde_json;
#[allow(unused_imports)]
#[macro_use]
extern crate lazy_static;
extern crate failure;
#[allow(unused_imports)]
#[macro_use]
extern crate observer_attribute;
#[macro_use]
extern crate serde_derive;

pub mod backends;
pub mod context;
#[cfg(feature = "mysql")]
pub mod mysql;
pub mod observe;
pub mod observe_fields;
#[cfg(feature = "postgres")]
pub mod pg;
pub mod span;
mod sql_parse;

pub use crate::context::Context;
pub use crate::observe::Observe;
pub use crate::observe_fields::*;
pub use crate::span::{Span, SpanItem};

#[macro_use]
extern crate log;

#[cfg(test)]
mod tests;

pub type Result<T> = std::result::Result<T, failure::Error>;

pub trait Backend: Send + Sync {
    fn app_started(&self) {}
    fn app_ended(&self) {}
    fn context_created(&self, _id: &str) {}
    fn context_ended(&self, _ctx: &crate::Context) {}
    fn span_created(&self, _id: &str) {}
    fn span_data(&self, _key: &str, _value: &str) {}
    fn span_ended(&self, _span: Option<&crate::span::Span>) {}
}

pub struct Observer {
    backends: Vec<Box<dyn Backend>>,
}

lazy_static! {
    static ref OBSERVER: std::sync::Arc<antidote::RwLock<Option<Observer>>> =
        std::sync::Arc::new(antidote::RwLock::new(None));
}

thread_local! {
    static CONTEXT: std::cell::RefCell<Option<Context>> = std::cell::RefCell::new(None);
}

pub fn builder(backend: Box<dyn Backend>) -> Observer {
    Observer::builder(backend)
}

pub fn create_context(context_id: &str) {
    let obj = OBSERVER.as_ref().read();
    if let Some(obj) = obj.as_ref() {
        obj.create_context(context_id);
    }
}

pub fn end_context() -> Option<impl serde::Serialize> {
    let obj = OBSERVER.as_ref().read();
    if let Some(obj) = obj.as_ref() {
        Some(obj.end_context())
    } else {
        None
    }
}

pub fn printed_context() -> Option<String> {
    use backends::logger::print_context;
    CONTEXT.with(|context| {
        if let Some(ctx) = context.borrow().as_ref() {
            Some(print_context(ctx))
        } else {
            None
        }
    })
}

pub fn shape_hash() -> String {
    use sha2::Digest;

    let trace_without_data = shape_trace().unwrap_or_else(|| "".to_string());
    format!("{:x}", sha2::Sha256::digest(trace_without_data.as_bytes()))
}

pub fn shape_trace() -> Option<String> {
    CONTEXT.with(|context| {
        if let Some(ctx) = context.borrow().as_ref() {
            Some(ctx.trace_without_data(false))
        } else {
            None
        }
    })
}

pub fn test_trace() -> Option<String> {
    CONTEXT.with(|context| {
        if let Some(ctx) = context.borrow().as_ref() {
            Some(ctx.trace_without_data(true))
        } else {
            None
        }
    })
}

pub fn trace() -> Option<String> {
    CONTEXT.with(|context| {
        if let Some(ctx) = context.borrow().as_ref() {
            Some(ctx.trace_without_data(true))
        } else {
            None
        }
    })
}

pub fn log(value: &'static str) {
    let obj = OBSERVER.as_ref().read();
    if let Some(obj) = obj.as_ref() {
        obj.span_log(value);
    }
}

pub(crate) fn start_span(id: &str) {
    let obj = OBSERVER.as_ref().read();
    if let Some(obj) = obj.as_ref() {
        obj.create_span(id);
    }
}

pub(crate) fn end_span(is_critical: bool, err: Option<String>) {
    let obj = OBSERVER.as_ref().read();
    if let Some(obj) = obj.as_ref() {
        obj.end_span(is_critical, err);
    }
}

pub(crate) fn field(key: &'static str, value: serde_json::Value) {
    CONTEXT.with(|context| {
        if let Some(ctx) = context.borrow().as_ref() {
            ctx.observe_span_field(key, value);
        }
    });
}

pub(crate) fn transient_field(key: &'static str, value: serde_json::Value) {
    CONTEXT.with(|context| {
        if let Some(ctx) = context.borrow().as_ref() {
            ctx.observe_span_transient_field(key, value);
        }
    });
}

#[allow(dead_code)]
pub(crate) fn observe_query(
    query: String,
    bind: Option<String>,
    result: std::result::Result<usize, String>,
) {
    CONTEXT.with(|context| {
        if let Some(ctx) = context.borrow().as_ref() {
            ctx.observe_query(query, bind, result);
        }
    });
}

pub(crate) fn observe_result(result: impl serde::Serialize) {
    CONTEXT.with(|ctx| {
        if let Some(ctx) = ctx.borrow().as_ref() {
            ctx.observe_span_result(result);
        }
    });
}

#[allow(dead_code)]
pub fn observe_span_id(id: &str) {
    CONTEXT.with(|context| {
        if let Some(ctx) = context.borrow().as_ref() {
            ctx.observe_span_id(id);
        }
    });
}

impl Observer {
    /// Initialized Observer with different backends(NewRelic, StatsD, Sentry, Jaeger, etc...)
    /// and call their app started method

    pub fn builder(backend: Box<dyn Backend>) -> Self {
        Observer {
            backends: vec![backend],
        }
    }

    pub fn add_backend(mut self, backend: Box<dyn Backend>) -> Self {
        self.backends.push(backend);
        self
    }

    pub fn init(self) {
        for backend in self.backends.iter() {
            backend.app_started()
        }

        let mut obj = OBSERVER.as_ref().write();
        obj.replace(self);
    }

    /// It will iterate through all backends and call their context_created method.
    pub(crate) fn create_context(&self, context_id: &str) {
        CONTEXT.with(|obj| {
            let mut context = obj.borrow_mut();
            if context.is_none() {
                context.replace(Context::new(context_id.to_string()));
            }
            for backend in self.backends.iter() {
                backend.context_created(context_id);
            }
        });
    }

    /// It will end context object and drop things if needed.
    pub(crate) fn end_context(&self) -> impl serde::Serialize {
        CONTEXT.with(|ctx| {
            let mut ctx = ctx.borrow_mut();
            match ctx.as_ref() {
                Some(ctx) => {
                    ctx.finalise();
                    for backend in self.backends.iter() {
                        backend.context_ended(&ctx);
                    }
                }
                None => {
                    unreachable!("this is bug");
                }
            };
            ctx.take()
        })
    }

    pub(crate) fn create_span(&self, id: &str) {
        CONTEXT.with(|ctx| {
            if let Some(ctx) = ctx.borrow().as_ref() {
                ctx.start_span(id);
                for backend in self.backends.iter() {
                    backend.span_created(id);
                }
            }
        });
    }

    pub(crate) fn end_span(&self, is_critical: bool, err: Option<String>) {
        CONTEXT.with(|ctx| {
            if let Some(ctx) = ctx.borrow().as_ref() {
                ctx.end_span(is_critical, err);
                for backend in self.backends.iter() {
                    backend.span_ended(ctx.span_stack.borrow().last());
                }
            }
        });
    }

    pub(crate) fn span_log(&self, value: &'static str) {
        CONTEXT.with(|ctx| {
            if let Some(ctx) = ctx.borrow().as_ref() {
                ctx.span_log(value);
            }
        });
    }
}