grow-apache-skywalking 0.2.0

Rust SDK for Apache SkyWalking by Grow Codes
Documentation
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
// Generated by sdk-kit 0.3.0 — do not edit; change sdk-kit and run "sdk-kit sync"
//! Trace query model and its normalized JSON form (`spec/schemas/telemetry.schema.json`).

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

use serde::{Deserialize, Deserializer, Serialize};

use super::{AttrValue, Attributes};
use crate::core::{Error, Result};

/// Span kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SpanKind {
    /// Internal operation (default).
    #[default]
    Internal,
    /// Server side of a request.
    Server,
    /// Client side of a request.
    Client,
    /// Message producer.
    Producer,
    /// Message consumer.
    Consumer,
    /// Unknown kind.
    Unspecified,
}

impl SpanKind {
    /// Parses vendor spellings (`SPAN_KIND_SERVER`, `server`, `2`, …); unknown → `Unspecified`.
    pub fn parse(s: &str) -> SpanKind {
        let t = s.trim().to_ascii_lowercase();
        let t = t.strip_prefix("span_kind_").unwrap_or(&t);
        match t {
            "internal" | "1" => SpanKind::Internal,
            "server" | "2" => SpanKind::Server,
            "client" | "3" => SpanKind::Client,
            "producer" | "4" => SpanKind::Producer,
            "consumer" | "5" => SpanKind::Consumer,
            _ => SpanKind::Unspecified,
        }
    }
}

impl From<&opentelemetry::trace::SpanKind> for SpanKind {
    fn from(k: &opentelemetry::trace::SpanKind) -> Self {
        use opentelemetry::trace::SpanKind as K;
        match k {
            K::Internal => SpanKind::Internal,
            K::Server => SpanKind::Server,
            K::Client => SpanKind::Client,
            K::Producer => SpanKind::Producer,
            K::Consumer => SpanKind::Consumer,
        }
    }
}

/// Span status code.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum StatusCode {
    /// Not set (default).
    #[default]
    Unset,
    /// Explicitly OK.
    Ok,
    /// Error.
    Error,
}

/// Span status (`{code, message?}` in JSON).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SpanStatus {
    /// Code.
    pub code: StatusCode,
    /// Error description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
}

/// Span event.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SpanEvent {
    /// Event name.
    pub name: String,
    /// Microseconds since the epoch.
    pub time_micros: u64,
    /// Attributes.
    #[serde(default)]
    pub attributes: Attributes,
}

/// Link to another span.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SpanLink {
    /// Linked trace id.
    pub trace_id: String,
    /// Linked span id.
    pub span_id: String,
    /// Attributes.
    #[serde(default)]
    pub attributes: Attributes,
}

/// A span as returned by a query API (SPEC §5 `Span`; JSON per `trace.schema.json`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Span {
    /// Trace id (32 lower-case hex).
    pub trace_id: String,
    /// Span id (16 lower-case hex).
    pub span_id: String,
    /// Parent span id.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parent_span_id: Option<String>,
    /// Operation name.
    pub name: String,
    /// Kind.
    #[serde(default, deserialize_with = "de_kind")]
    pub kind: SpanKind,
    /// Reporting service.
    pub service_name: String,
    /// Start, microseconds since the epoch.
    pub start_micros: u64,
    /// End, microseconds since the epoch.
    pub end_micros: u64,
    /// Duration in microseconds.
    pub duration_micros: u64,
    /// Status.
    #[serde(default, deserialize_with = "de_status")]
    pub status: SpanStatus,
    /// Attributes.
    #[serde(default)]
    pub attributes: Attributes,
    /// Events.
    #[serde(default)]
    pub events: Vec<SpanEvent>,
    /// Links.
    #[serde(default)]
    pub links: Vec<SpanLink>,
}

/// A trace: spans sorted by start time, then span id (also after deserialisation).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", from = "TraceWire")]
pub struct Trace {
    /// Trace id.
    pub trace_id: String,
    /// Spans.
    pub spans: Vec<Span>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct TraceWire {
    trace_id: String,
    #[serde(default)]
    spans: Vec<Span>,
}

impl From<TraceWire> for Trace {
    fn from(w: TraceWire) -> Self {
        Trace::new(w.trace_id, w.spans)
    }
}

/// Search hit (SPEC §5 `TraceSummary`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TraceSummary {
    /// Trace id.
    pub trace_id: String,
    /// Service of the root span.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub root_service_name: Option<String>,
    /// Name of the root span.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub root_name: Option<String>,
    /// Earliest span start, microseconds since the epoch.
    pub start_micros: u64,
    /// Trace duration in microseconds.
    pub duration_micros: u64,
    /// Number of spans.
    pub span_count: usize,
}

/// Search filter (SPEC §5 `TraceSearchQuery`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TraceSearchQuery {
    /// Service name.
    pub service: Option<String>,
    /// Operation (span name).
    pub operation: Option<String>,
    /// Attribute equality filters.
    pub tags: BTreeMap<String, String>,
    /// Minimum trace duration.
    pub min_duration: Option<Duration>,
    /// Maximum trace duration.
    pub max_duration: Option<Duration>,
    /// Earliest start.
    pub start: Option<SystemTime>,
    /// Latest start.
    pub end: Option<SystemTime>,
    /// Maximum results (default 20).
    pub limit: usize,
}

impl Default for TraceSearchQuery {
    fn default() -> Self {
        TraceSearchQuery {
            service: None,
            operation: None,
            tags: BTreeMap::new(),
            min_duration: None,
            max_duration: None,
            start: None,
            end: None,
            limit: 20,
        }
    }
}

impl TraceSearchQuery {
    /// Query for a service.
    pub fn service(service: impl Into<String>) -> Self {
        TraceSearchQuery {
            service: Some(service.into()),
            ..Default::default()
        }
    }
    /// Sets the operation.
    pub fn operation(mut self, op: impl Into<String>) -> Self {
        self.operation = Some(op.into());
        self
    }
    /// Adds a tag filter.
    pub fn tag(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.tags.insert(key.into(), value.into());
        self
    }
    /// Sets the limit.
    pub fn limit(mut self, limit: usize) -> Self {
        self.limit = limit;
        self
    }

    /// Whether a trace matches every filter of this query (for in-memory implementations).
    pub fn matches(&self, trace: &Trace) -> bool {
        let summary = trace.summary();
        let start = UNIX_EPOCH + Duration::from_micros(summary.start_micros);
        let dur = Duration::from_micros(summary.duration_micros);
        let span_ok = |s: &Span| {
            self.service.as_ref().is_none_or(|v| &s.service_name == v)
                && self.operation.as_ref().is_none_or(|v| &s.name == v)
                && self.tags.iter().all(|(k, v)| match s.attributes.get(k) {
                    Some(AttrValue::String(x)) => x == v,
                    Some(other) => &other.to_string() == v,
                    None => false,
                })
        };
        trace.spans.iter().any(span_ok)
            && self.min_duration.is_none_or(|d| dur >= d)
            && self.max_duration.is_none_or(|d| dur <= d)
            && self.start.is_none_or(|t| start >= t)
            && self.end.is_none_or(|t| start <= t)
    }
}

/// Service dependency edge (SPEC §5 `DependencyLink`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DependencyLink {
    /// Calling service.
    pub parent: String,
    /// Called service.
    pub child: String,
    /// Number of calls.
    pub call_count: u64,
}

/// A span with its children (see [`build_tree`]).
#[derive(Debug, Clone, PartialEq)]
pub struct SpanNode {
    /// The span.
    pub span: Span,
    /// Child nodes, sorted like [`sort_spans`].
    pub children: Vec<SpanNode>,
}

fn normalize_hex(id: &str, len: usize, what: &str) -> Result<String> {
    let t = id.trim();
    let t = t
        .strip_prefix("0x")
        .or_else(|| t.strip_prefix("0X"))
        .unwrap_or(t);
    if t.is_empty() || t.len() > len || !t.bytes().all(|b| b.is_ascii_hexdigit()) {
        return Err(Error::validation(format!("invalid {what} {id:?}")));
    }
    let out = format!("{:0>len$}", t.to_ascii_lowercase());
    if out.bytes().all(|b| b == b'0') {
        return Err(Error::validation(format!("invalid {what}: all zeros")));
    }
    Ok(out)
}

/// Lower-cases and left-pads a trace id to 32 hex characters (64-bit ids from Zipkin/Datadog).
pub fn normalize_trace_id(id: &str) -> Result<String> {
    normalize_hex(id, 32, "trace id")
}

/// [`normalize_trace_id`] for hex ids; any other non-empty id (a native id such as a
/// SkyWalking segment/trace id) is returned trimmed and unchanged. Use it where a backend's own
/// ids must not be rejected.
pub fn normalize_trace_id_or_native(id: &str) -> Result<String> {
    native_or(id, 32, "trace id")
}

/// [`normalize_span_id`] for hex ids; any other non-empty id is returned trimmed and unchanged.
pub fn normalize_span_id_or_native(id: &str) -> Result<String> {
    native_or(id, 16, "span id")
}

fn native_or(id: &str, len: usize, what: &str) -> Result<String> {
    let t = id.trim();
    if t.is_empty() {
        return Err(Error::validation(format!("invalid {what}: empty")));
    }
    let hex = t
        .strip_prefix("0x")
        .or_else(|| t.strip_prefix("0X"))
        .unwrap_or(t);
    if hex.len() <= len && !hex.is_empty() && hex.bytes().all(|b| b.is_ascii_hexdigit()) {
        return normalize_hex(t, len, what);
    }
    Ok(t.to_string())
}

/// Lower-cases and left-pads a span id to 16 hex characters.
pub fn normalize_span_id(id: &str) -> Result<String> {
    normalize_hex(id, 16, "span id")
}

/// Sorts spans by start time, then span id.
pub fn sort_spans(spans: &mut [Span]) {
    spans.sort_by(|a, b| {
        a.start_micros
            .cmp(&b.start_micros)
            .then_with(|| a.span_id.cmp(&b.span_id))
    });
}

/// Builds the span forest: roots are spans without a parent or whose parent is not present.
pub fn build_tree(spans: &[Span]) -> Vec<SpanNode> {
    let mut sorted = spans.to_vec();
    sort_spans(&mut sorted);
    let ids: std::collections::HashSet<&str> = sorted.iter().map(|s| s.span_id.as_str()).collect();
    let mut children: BTreeMap<String, Vec<Span>> = BTreeMap::new();
    let mut roots = Vec::new();
    for s in &sorted {
        match &s.parent_span_id {
            Some(p) if ids.contains(p.as_str()) && p != &s.span_id => {
                children.entry(p.clone()).or_default().push(s.clone())
            }
            _ => roots.push(s.clone()),
        }
    }
    fn attach(span: Span, children: &mut BTreeMap<String, Vec<Span>>) -> SpanNode {
        let kids = children.remove(&span.span_id).unwrap_or_default();
        SpanNode {
            children: kids.into_iter().map(|k| attach(k, children)).collect(),
            span,
        }
    }
    roots
        .into_iter()
        .map(|r| attach(r, &mut children))
        .collect()
}

fn micros(t: SystemTime) -> u64 {
    t.duration_since(UNIX_EPOCH)
        .map(|d| d.as_micros() as u64)
        .unwrap_or(0)
}

fn kv_attributes(kvs: &[opentelemetry::KeyValue]) -> Attributes {
    kvs.iter()
        .map(|kv| (kv.key.to_string(), attr_value(&kv.value)))
        .collect()
}

fn attr_value(v: &opentelemetry::Value) -> AttrValue {
    use opentelemetry::{Array, Value};
    match v {
        Value::Bool(b) => (*b).into(),
        Value::I64(i) => (*i).into(),
        Value::F64(f) => (*f).into(),
        Value::String(s) => s.as_str().into(),
        Value::Array(Array::Bool(a)) => a.clone().into(),
        Value::Array(Array::I64(a)) => a.clone().into(),
        Value::Array(Array::F64(a)) => a.clone().into(),
        Value::Array(Array::String(a)) => a
            .iter()
            .map(|s| s.as_str().to_string())
            .collect::<Vec<_>>()
            .into(),
        other => other.to_string().into(),
    }
}

impl Span {
    /// Converts finished SDK span data (as received by a `SpanExporter`).
    pub fn from_span_data(data: &opentelemetry_sdk::trace::SpanData, service_name: &str) -> Span {
        use opentelemetry::trace::{SpanId, Status};
        let start = micros(data.start_time);
        let end = micros(data.end_time).max(start);
        let status = match &data.status {
            Status::Unset => SpanStatus::default(),
            Status::Ok => SpanStatus {
                code: StatusCode::Ok,
                message: None,
            },
            Status::Error { description } => SpanStatus {
                code: StatusCode::Error,
                message: Some(description.to_string()).filter(|d| !d.is_empty()),
            },
        };
        Span {
            trace_id: data.span_context.trace_id().to_string(),
            span_id: data.span_context.span_id().to_string(),
            parent_span_id: (data.parent_span_id != SpanId::INVALID)
                .then(|| data.parent_span_id.to_string()),
            name: data.name.to_string(),
            kind: SpanKind::from(&data.span_kind),
            service_name: service_name.to_string(),
            start_micros: start,
            end_micros: end,
            duration_micros: end - start,
            status,
            attributes: kv_attributes(&data.attributes),
            events: data
                .events
                .iter()
                .map(|e| SpanEvent {
                    name: e.name.to_string(),
                    time_micros: micros(e.timestamp),
                    attributes: kv_attributes(&e.attributes),
                })
                .collect(),
            links: data
                .links
                .iter()
                .map(|l| SpanLink {
                    trace_id: l.span_context.trace_id().to_string(),
                    span_id: l.span_context.span_id().to_string(),
                    attributes: kv_attributes(&l.attributes),
                })
                .collect(),
        }
    }
}

impl Trace {
    /// A trace with spans sorted.
    pub fn new(trace_id: impl Into<String>, mut spans: Vec<Span>) -> Self {
        sort_spans(&mut spans);
        Trace {
            trace_id: trace_id.into(),
            spans,
        }
    }

    /// The span tree.
    pub fn tree(&self) -> Vec<SpanNode> {
        build_tree(&self.spans)
    }

    /// Names of the direct children of every span named `parent_name`.
    pub fn children_of(&self, parent_name: &str) -> Vec<String> {
        let parents: Vec<&str> = self
            .spans
            .iter()
            .filter(|s| s.name == parent_name)
            .map(|s| s.span_id.as_str())
            .collect();
        self.spans
            .iter()
            .filter(|s| {
                s.parent_span_id
                    .as_deref()
                    .is_some_and(|p| parents.contains(&p))
            })
            .map(|s| s.name.clone())
            .collect()
    }

    /// Summary: root = first span without a present parent.
    pub fn summary(&self) -> TraceSummary {
        let roots = self.tree();
        let root = roots.first().map(|n| &n.span);
        let start = self.spans.iter().map(|s| s.start_micros).min().unwrap_or(0);
        let end = self
            .spans
            .iter()
            .map(|s| s.end_micros)
            .max()
            .unwrap_or(start);
        TraceSummary {
            trace_id: self.trace_id.clone(),
            root_service_name: root.map(|s| s.service_name.clone()),
            root_name: root.map(|s| s.name.clone()),
            start_micros: start,
            duration_micros: end.saturating_sub(start),
            span_count: self.spans.len(),
        }
    }
}

/// Accepts `status` as `{code, message?}` (wire form) or a bare code string.
fn de_status<'de, D: Deserializer<'de>>(d: D) -> std::result::Result<SpanStatus, D::Error> {
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum Wire {
        Code(StatusCode),
        Object {
            code: StatusCode,
            #[serde(default)]
            message: Option<String>,
        },
    }
    Ok(match Wire::deserialize(d)? {
        Wire::Code(code) => SpanStatus {
            code,
            message: None,
        },
        Wire::Object { code, message } => SpanStatus { code, message },
    })
}

/// Accepts vendor kind spellings on input.
fn de_kind<'de, D: Deserializer<'de>>(d: D) -> std::result::Result<SpanKind, D::Error> {
    Ok(SpanKind::parse(&String::deserialize(d)?))
}