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
use hyper::{Body, Method, Request};

use hyper::client::connect::HttpConnector;
use rmp::encode;
use serde::Serialize;
use tokio::sync::mpsc;

use std::collections::HashMap;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

#[derive(Debug, Clone)]
pub struct Client {
    env: Option<String>,
    endpoint: String,
    service: String,
    http_client: hyper::Client<HttpConnector>,
    buffer_sender: mpsc::Sender<Trace>,
    buffer_size: usize,
    buffer_flush_min_interval: Duration,
}

/// Configuration settings for the client.
#[derive(Debug)]
pub struct Config {
    /// Datadog apm service name
    pub service: String,
    /// Datadog apm environment
    pub env: Option<String>,
    /// Datadog agent host/ip, defaults to `localhost`.
    pub host: String,
    /// Datadog agent port, defaults to `8196`.
    pub port: String,
    /// Client buffer queue capacity, defaults to `std::u16::MAX`.
    /// It is used for limit the amount of traces being queued in memory before drop. The client should handle send all the traces before the queue is full, you usually don't need to change this value.
    pub buffer_queue_capacity: u16,
    /// The buffer size, defaults to 200. It's the amount of traces send in a single request to datadog agent.
    pub buffer_size: u16,
    /// The buffer flush minimal interval, defaults to 200 ms. It's the minimum amount of time between buffer flushes that is the time we wait to buffer the traces before send if the buffer does not reach the buffer_size.
    pub buffer_flush_min_interval: Duration,
}

impl Default for Config {
    fn default() -> Self {
        Config {
            env: None,
            host: "localhost".to_string(),
            port: "8126".to_string(),
            service: "".to_string(),
            buffer_queue_capacity: std::u16::MAX,
            buffer_size: 200,
            buffer_flush_min_interval: Duration::from_millis(200),
        }
    }
}

impl Client {
    pub fn new(config: Config) -> Client {
        let (buffer_sender, buffer_receiver) = mpsc::channel(config.buffer_queue_capacity as usize);

        let client = Client {
            env: config.env,
            service: config.service,
            endpoint: format!("http://{}:{}/v0.3/traces", config.host, config.port),
            http_client: hyper::Client::new(),
            buffer_sender: buffer_sender,
            buffer_size: config.buffer_size as usize,
            buffer_flush_min_interval: config.buffer_flush_min_interval,
        };

        spawn_consume_buffer_task(buffer_receiver, client.clone());

        client
    }

    pub fn send_trace(mut self, trace: Trace) {
        match self.buffer_sender.try_send(trace) {
            Ok(_) => trace!("trace enqueued"),
            Err(err) => warn!("could not enqueue trace: {:?}", err),
        };
    }

    async fn send_traces(self, traces: Vec<Trace>) {
        let traces = traces
            .iter()
            .map(|trace| map_to_raw_spans(trace, self.env.clone(), self.service.clone()))
            .collect::<Vec<Vec<RawSpan>>>();

        let trace_count = traces.len();
        let payload = serialize_as_msgpack(traces);

        let req = Request::builder()
            .method(Method::POST)
            .uri(self.endpoint)
            .header("content-type", "application/msgpack")
            .header("content-length", payload.len())
            .header("X-Datadog-Trace-Count", trace_count)
            .body(Body::from(payload))
            .unwrap();

        match self.http_client.request(req).await {
            Ok(resp) => {
                if resp.status().is_success() {
                    trace!("{} traces sent to datadog", trace_count)
                } else {
                    error!("error sending traces to datadog: {:?}", resp)
                }
            }
            Err(err) => error!("error sending traces to datadog: {:?}", err),
        }
    }
}

#[derive(Debug, Clone)]
pub struct Trace {
    pub id: u64,
    pub spans: Vec<Span>,
    pub priority: u32,
}

#[derive(Debug, Clone)]
pub struct Span {
    pub id: u64,
    pub name: String,
    pub resource: String,
    pub parent_id: Option<u64>,
    pub start: SystemTime,
    pub duration: Duration,
    pub error: Option<ErrorInfo>,
    pub http: Option<HttpInfo>,
    pub sql: Option<SqlInfo>,
    pub r#type: String,
    pub tags: HashMap<String, String>,
}

#[derive(Debug, Clone)]
pub struct ErrorInfo {
    pub r#type: String,
    pub msg: String,
    pub stack: String,
}

#[derive(Debug, Clone)]
pub struct HttpInfo {
    pub url: String,
    pub status_code: String,
    pub method: String,
}

#[derive(Debug, Clone)]
pub struct SqlInfo {
    pub query: String,
    pub rows: String,
    pub db: String,
}

#[derive(Debug, Serialize, Clone, PartialEq)]
struct RawSpan {
    service: String,
    name: String,
    resource: String,
    trace_id: u64,
    span_id: u64,
    parent_id: Option<u64>,
    start: u64,
    duration: u64,
    error: i32,
    meta: HashMap<String, String>,
    metrics: HashMap<String, f64>,
    r#type: String,
}

fn spawn_consume_buffer_task(mut buffer_receiver: mpsc::Receiver<Trace>, client: Client) {
    tokio::spawn(async move {
        let mut buffer = Vec::with_capacity(client.buffer_size);
        let mut last_flushed_at = SystemTime::now();
        loop {
            let client = client.clone();

            match buffer_receiver.try_recv() {
                Ok(trace) => {
                    buffer.push(trace);
                }
                Err(_) => {
                    tokio::time::delay_for(Duration::from_secs(1)).await;
                }
            }

            if buffer.len() == client.buffer_size
                || flush_min_interval_has_passed(&buffer, &client, last_flushed_at)
            {
                client.send_traces(buffer.drain(..).collect()).await;
                last_flushed_at = SystemTime::now();
            }
        }

        fn flush_min_interval_has_passed<T>(
            buffer: &Vec<T>,
            client: &Client,
            last_flushed_at: SystemTime,
        ) -> bool {
            buffer.len() > 0
                && SystemTime::now().duration_since(last_flushed_at).unwrap()
                    > client.buffer_flush_min_interval
        }
    });
}

fn serialize_as_msgpack(traces: Vec<Vec<RawSpan>>) -> Vec<u8> {
    // this function uses a hack over rpm_serde library,
    // because the lib does not work when the struct is wrapped in a array,
    // so it manually encode the array, and then serialize each entity in a loop

    let mut buf = Vec::new();

    encode::write_array_len(&mut buf, traces.len() as u32).unwrap();
    for spans in traces {
        encode::write_array_len(&mut buf, spans.len() as u32).unwrap();
        for span in spans {
            let mut se = rmps::Serializer::new(&mut buf).with_struct_map();
            span.serialize(&mut se).unwrap();
        }
    }
    buf
}

fn fill_meta(span: &Span, env: Option<String>) -> HashMap<String, String> {
    let mut meta = HashMap::new();
    if let Some(env) = env {
        meta.insert("env".to_string(), env);
    }

    if let Some(http) = &span.http {
        meta.insert("http.status_code".to_string(), http.status_code.clone());
        meta.insert("http.method".to_string(), http.method.clone());
        meta.insert("http.url".to_string(), http.url.clone());
    }
    if let Some(error) = &span.error {
        meta.insert("error.type".to_string(), error.r#type.clone());
        meta.insert("error.msg".to_string(), error.msg.clone());
        meta.insert("error.stack".to_string(), error.stack.clone());
    }
    if let Some(sql) = &span.sql {
        meta.insert("sql.query".to_string(), sql.query.clone());
        meta.insert("sql.rows".to_string(), sql.rows.clone());
        meta.insert("sql.db".to_string(), sql.db.clone());
    }
    for (key, value) in &span.tags {
        meta.insert(key.to_string(), value.to_string());
    }
    meta
}

fn fill_metrics(priority: u32) -> HashMap<String, f64> {
    let mut metrics = HashMap::new();
    metrics.insert("_sampling_priority_v1".to_string(), f64::from(priority));
    metrics
}

fn map_to_raw_spans(trace: &Trace, env: Option<String>, service: String) -> Vec<RawSpan> {
    let mut traces = Vec::new();
    for span in &trace.spans {
        traces.push(RawSpan {
            service: service.clone(),
            trace_id: trace.id,
            span_id: span.id,
            name: span.name.clone(),
            resource: span.resource.clone(),
            parent_id: span.parent_id,
            start: duration_to_nanos(span.start.duration_since(UNIX_EPOCH).unwrap()),
            duration: duration_to_nanos(span.duration),
            error: if span.error.is_some() { 1 } else { 0 },
            r#type: span.r#type.clone(),
            meta: fill_meta(&span, env.clone()),
            metrics: fill_metrics(trace.priority),
        });
    }
    traces
}

fn duration_to_nanos(duration: Duration) -> u64 {
    duration.as_secs() * 1_000_000_000 + duration.subsec_nanos() as u64
}

#[cfg(test)]
mod tests {
    extern crate rand;

    use super::*;

    use rand::Rng;
    use serde_json::json;

    #[tokio::test]
    #[ignore]
    async fn test_send_trace() {
        let config = Config {
            service: String::from("service_name"),
            ..Default::default()
        };
        let client = Client::new(config);
        let trace = a_trace();
        client.send_trace(trace);
    }

    #[tokio::test]
    async fn test_map_to_raw_spans() {
        let config = Config {
            service: String::from("service_name"),
            env: Some(String::from("staging")),
            ..Default::default()
        };
        let trace = a_trace();

        let mut expected = Vec::new();
        for span in &trace.spans {
            let mut meta: HashMap<String, String> = HashMap::new();
            meta.insert("env".to_string(), config.env.clone().unwrap());
            if let Some(http) = &span.http {
                meta.insert("http.url".to_string(), http.url.clone());
                meta.insert("http.method".to_string(), http.method.clone());
                meta.insert("http.status_code".to_string(), http.status_code.clone());
            }

            let mut metrics = HashMap::new();
            metrics.insert(
                "_sampling_priority_v1".to_string(),
                f64::from(trace.priority),
            );

            expected.push(RawSpan {
                trace_id: trace.id,
                span_id: span.id,
                parent_id: span.parent_id,
                name: span.name.clone(),
                resource: span.resource.clone(),
                service: config.service.clone(),
                r#type: span.r#type.clone(),
                start: duration_to_nanos(span.start.duration_since(UNIX_EPOCH).unwrap()),
                duration: duration_to_nanos(span.duration),
                error: 0,
                meta: meta,
                metrics: metrics,
            });
        }
        let raw_spans = map_to_raw_spans(&trace, config.env, config.service);

        assert_eq!(raw_spans, expected);
    }

    #[tokio::test]
    async fn test_message_pack_serialization() {
        let generate_span = || {
            let mut rng = rand::thread_rng();
            let now = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs();
            RawSpan {
                trace_id: rng.gen::<u64>(),
                span_id: rng.gen::<u64>(),
                parent_id: None,
                name: String::from("request"),
                resource: String::from("/home"),
                service: String::from("service_name"),
                r#type: String::from("web"),
                start: now * 1_000_000_000,
                duration: 4853472865,
                error: 0,
                meta: std::collections::HashMap::new(),
                metrics: std::collections::HashMap::new(),
            }
        };

        let traces = (0..3).map(|_| vec![generate_span()]).collect::<Vec<_>>();
        let result = serialize_as_msgpack(traces.clone());

        let msgpack_as_json: serde_json::Value = rmp_serde::from_read_ref(&result).unwrap();

        // debugging utility:
        //serde_json::to_writer_pretty(std::io::stdout(), &msgpack_as_json).unwrap();

        assert_eq!(msgpack_as_json, json!(traces));
    }

    fn a_trace() -> Trace {
        let mut rng = rand::thread_rng();
        Trace {
            id: rng.gen::<u64>(),
            priority: 1,
            spans: vec![Span {
                id: rng.gen::<u64>(),
                name: String::from("request"),
                resource: String::from("/home/v3"),
                r#type: String::from("web"),
                start: SystemTime::now(),
                duration: Duration::from_secs(2),
                parent_id: None,
                http: Some(HttpInfo {
                    url: String::from("/home/v3/2?trace=true"),
                    method: String::from("GET"),
                    status_code: String::from("200"),
                }),
                error: None,
                sql: None,
                tags: HashMap::new(),
            }],
        }
    }
}