Skip to main content

servers/http/
jaeger.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15pub mod v3;
16
17use std::collections::{BTreeMap, HashMap};
18use std::fmt;
19use std::str::FromStr;
20use std::sync::Arc;
21
22use axum::Extension;
23use axum::extract::{Path, Query, State};
24use axum::http::{HeaderMap, StatusCode as HttpStatusCode};
25use axum::response::IntoResponse;
26use axum_extra::TypedHeader;
27use common_catalog::consts::{PARENT_SPAN_ID_COLUMN, TRACE_TABLE_NAME};
28use common_error::ext::ErrorExt;
29use common_error::status_code::StatusCode;
30use common_query::{Output, OutputData};
31use common_recordbatch::util;
32use common_telemetry::{debug, error, tracing, warn};
33use headers::UserAgent;
34use serde::{Deserialize, Deserializer, Serialize, de};
35use serde_json::Value as JsonValue;
36use session::context::{Channel, QueryContext};
37use snafu::{OptionExt, ResultExt};
38
39use crate::error::{
40    CollectRecordbatchSnafu, Error, InvalidJaegerQuerySnafu, Result, status_code_to_http_status,
41};
42use crate::http::HttpRecordsOutput;
43use crate::http::extractor::TraceTableName;
44use crate::metrics::METRIC_JAEGER_QUERY_ELAPSED;
45use crate::otlp::trace::{
46    DURATION_NANO_COLUMN, KEY_OTEL_SCOPE_NAME, KEY_OTEL_SCOPE_VERSION, KEY_OTEL_STATUS_CODE,
47    KEY_OTEL_STATUS_ERROR_KEY, KEY_OTEL_STATUS_MESSAGE, KEY_OTEL_TRACE_STATE, KEY_SERVICE_NAME,
48    KEY_SPAN_KIND, RESOURCE_ATTRIBUTES_COLUMN, SCOPE_NAME_COLUMN, SCOPE_VERSION_COLUMN,
49    SERVICE_NAME_COLUMN, SPAN_ATTRIBUTES_COLUMN, SPAN_EVENTS_COLUMN, SPAN_ID_COLUMN,
50    SPAN_KIND_COLUMN, SPAN_KIND_PREFIX, SPAN_LINKS_COLUMN, SPAN_NAME_COLUMN, SPAN_STATUS_CODE,
51    SPAN_STATUS_ERROR, SPAN_STATUS_MESSAGE_COLUMN, SPAN_STATUS_PREFIX, SPAN_STATUS_UNSET,
52    TIMESTAMP_COLUMN, TRACE_ID_COLUMN, TRACE_STATE_COLUMN,
53};
54use crate::query_handler::JaegerQueryHandlerRef;
55
56pub const JAEGER_QUERY_TABLE_NAME_KEY: &str = "jaeger_query_table_name";
57
58const REF_TYPE_CHILD_OF: &str = "CHILD_OF";
59const SPAN_KIND_TIME_FMTS: [&str; 2] = ["%Y-%m-%d %H:%M:%S%.6f%z", "%Y-%m-%d %H:%M:%S%.9f%z"];
60
61const TRACE_NOT_FOUND_ERROR_CODE: i32 = 404;
62const TRACE_NOT_FOUND_ERROR_MSG: &str = "trace not found";
63
64/// JaegerAPIResponse is the response of Jaeger HTTP API.
65/// The original version is `structuredResponse` which is defined in https://github.com/jaegertracing/jaeger/blob/main/cmd/query/app/http_handler.go.
66#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
67pub struct JaegerAPIResponse {
68    pub data: Option<JaegerData>,
69    pub total: usize,
70    pub limit: usize,
71    pub offset: usize,
72    pub errors: Vec<JaegerAPIError>,
73}
74
75impl JaegerAPIResponse {
76    pub fn trace_not_found() -> Self {
77        Self {
78            data: None,
79            total: 0,
80            limit: 0,
81            offset: 0,
82            errors: vec![JaegerAPIError {
83                code: TRACE_NOT_FOUND_ERROR_CODE,
84                msg: TRACE_NOT_FOUND_ERROR_MSG.to_string(),
85                trace_id: None,
86            }],
87        }
88    }
89}
90
91/// JaegerData is the query result of Jaeger HTTP API.
92#[derive(Debug, Serialize, Deserialize, PartialEq)]
93#[serde(untagged)]
94pub enum JaegerData {
95    ServiceNames(Vec<String>),
96    OperationsNames(Vec<String>),
97    Operations(Vec<Operation>),
98    Traces(Vec<Trace>),
99}
100
101/// JaegerAPIError is the error of Jaeger HTTP API.
102#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
103#[serde(rename_all = "camelCase")]
104pub struct JaegerAPIError {
105    pub code: i32,
106    pub msg: String,
107    #[serde(skip_serializing_if = "Option::is_none")]
108    pub trace_id: Option<String>,
109}
110
111/// Operation is an operation in a service.
112#[derive(Debug, Default, Serialize, Deserialize, PartialEq)]
113#[serde(rename_all = "camelCase")]
114pub struct Operation {
115    pub name: String,
116    #[serde(skip_serializing_if = "Option::is_none")]
117    pub span_kind: Option<String>,
118}
119
120/// Trace is a collection of spans.
121#[derive(Debug, Default, Serialize, Deserialize, PartialEq)]
122#[serde(rename_all = "camelCase")]
123pub struct Trace {
124    #[serde(rename = "traceID")]
125    pub trace_id: String,
126    pub spans: Vec<Span>,
127
128    #[serde(skip_serializing_if = "HashMap::is_empty")]
129    pub processes: HashMap<String, Process>,
130
131    #[serde(skip_serializing_if = "Vec::is_empty")]
132    pub warnings: Vec<String>,
133}
134
135/// Span is a single operation within a trace.
136#[derive(Debug, Default, Serialize, Deserialize, PartialEq)]
137#[serde(rename_all = "camelCase")]
138pub struct Span {
139    #[serde(rename = "traceID")]
140    pub trace_id: String,
141
142    #[serde(rename = "spanID")]
143    pub span_id: String,
144
145    #[serde(rename = "parentSpanID")]
146    #[serde(skip_serializing_if = "String::is_empty")]
147    pub parent_span_id: String,
148
149    #[serde(skip_serializing_if = "Option::is_none")]
150    pub flags: Option<u32>,
151
152    pub operation_name: String,
153    pub references: Vec<Reference>,
154    pub start_time: u64, // microseconds since unix epoch
155    pub duration: u64,   // microseconds
156    pub tags: Vec<KeyValue>,
157    pub logs: Vec<Log>,
158
159    #[serde(rename = "processID")]
160    #[serde(skip_serializing_if = "String::is_empty")]
161    pub process_id: String,
162
163    #[serde(skip_serializing_if = "Option::is_none")]
164    pub process: Option<Process>,
165
166    #[serde(skip_serializing_if = "Vec::is_empty")]
167    pub warnings: Vec<String>,
168}
169
170/// Reference is a reference from one span to another.
171#[derive(Debug, Serialize, Deserialize, PartialEq)]
172#[serde(rename_all = "camelCase")]
173pub struct Reference {
174    #[serde(rename = "traceID")]
175    pub trace_id: String,
176    #[serde(rename = "spanID")]
177    pub span_id: String,
178    pub ref_type: String,
179}
180
181/// Process is the process emitting a set of spans.
182#[derive(Debug, Serialize, Deserialize, PartialEq)]
183#[serde(rename_all = "camelCase")]
184pub struct Process {
185    pub service_name: String,
186    pub tags: Vec<KeyValue>,
187}
188
189/// Log is a log emitted in a span.
190#[derive(Debug, Serialize, Deserialize, PartialEq)]
191#[serde(rename_all = "camelCase")]
192pub struct Log {
193    pub timestamp: u64,
194    pub fields: Vec<KeyValue>,
195}
196
197/// KeyValue is a key-value pair with typed value.
198#[derive(Debug, Serialize, Deserialize, PartialEq)]
199#[serde(rename_all = "camelCase")]
200pub struct KeyValue {
201    pub key: String,
202    #[serde(rename = "type")]
203    pub value_type: ValueType,
204    pub value: Value,
205}
206
207/// Value is the value of a key-value pair in Jaeger Span attributes.
208#[derive(Debug, Serialize, Deserialize, PartialEq)]
209#[serde(untagged)]
210#[serde(rename_all = "camelCase")]
211pub enum Value {
212    String(String),
213    Int64(i64),
214    Float64(f64),
215    Boolean(bool),
216    Binary(Vec<u8>),
217}
218
219/// ValueType is the type of a value stored in KeyValue struct.
220#[derive(Debug, Serialize, Deserialize, PartialEq)]
221#[serde(rename_all = "lowercase")]
222pub enum ValueType {
223    String,
224    Int64,
225    Float64,
226    Boolean,
227    Binary,
228}
229
230/// JaegerQueryParams is the query parameters of Jaeger HTTP API.
231#[derive(Default, Debug, Serialize, Deserialize)]
232#[serde(rename_all = "camelCase")]
233pub struct JaegerQueryParams {
234    /// Service name of the trace.
235    #[serde(rename = "service")]
236    pub service_name: Option<String>,
237
238    /// Operation name of the trace.
239    #[serde(rename = "operation")]
240    pub operation_name: Option<String>,
241
242    /// Limit the return data.
243    #[serde(default, deserialize_with = "empty_string_as_none")]
244    pub limit: Option<usize>,
245
246    /// Start time of the trace in microseconds since unix epoch.
247    pub start: Option<i64>,
248
249    /// End time of the trace in microseconds since unix epoch.
250    pub end: Option<i64>,
251
252    /// Max duration string value of the trace. Units can be `ns`, `us` (or `µs`), `ms`, `s`, `m`, `h`.
253    #[serde(default, deserialize_with = "empty_string_as_none")]
254    pub max_duration: Option<String>,
255
256    /// Min duration string value of the trace. Units can be `ns`, `us` (or `µs`), `ms`, `s`, `m`, `h`.
257    #[serde(default, deserialize_with = "empty_string_as_none")]
258    pub min_duration: Option<String>,
259
260    /// Tags of the trace in JSON format. It will be URL encoded in the raw query.
261    /// The decoded format is like: tags="{\"http.status_code\":\"200\",\"latency\":\"11.234\",\"error\":\"false\",\"http.method\":\"GET\",\"http.path\":\"/api/v1/users\"}".
262    /// The key and value of the map are both strings. The key and value is the attribute name and value of the span. The value will be converted to the corresponding type when querying.
263    pub tags: Option<String>,
264
265    /// The span kind of the trace.
266    pub span_kind: Option<String>,
267}
268
269/// Serde deserialization decorator to map empty Strings to None.
270fn empty_string_as_none<'de, D, T>(de: D) -> Result<Option<T>, D::Error>
271where
272    D: Deserializer<'de>,
273    T: FromStr,
274    T::Err: fmt::Display,
275{
276    let opt = Option::<String>::deserialize(de)?;
277    match opt.as_deref() {
278        None | Some("") => Ok(None),
279        Some(s) => FromStr::from_str(s).map_err(de::Error::custom).map(Some),
280    }
281}
282
283fn update_query_context(query_ctx: &mut QueryContext, table_name: Option<String>) {
284    // db should be already handled by middlewares
285    query_ctx.set_channel(Channel::Jaeger);
286    if let Some(table) = table_name {
287        query_ctx.set_extension(JAEGER_QUERY_TABLE_NAME_KEY, table);
288    }
289}
290
291impl QueryTraceParams {
292    fn from_jaeger_query_params(query_params: JaegerQueryParams) -> Result<Self> {
293        let mut internal_query_params: QueryTraceParams = QueryTraceParams {
294            service_name: Some(query_params.service_name.context(InvalidJaegerQuerySnafu {
295                reason: "service_name is required".to_string(),
296            })?),
297            operation_name: query_params.operation_name,
298            // Convert start time from microseconds to nanoseconds.
299            start_time: query_params.start.map(|start| start * 1000),
300            end_time: query_params.end.map(|end| end * 1000),
301            ..Default::default()
302        };
303
304        if let Some(max_duration) = query_params.max_duration {
305            let duration = humantime::parse_duration(&max_duration).map_err(|e| {
306                InvalidJaegerQuerySnafu {
307                    reason: format!("parse maxDuration '{}' failed: {}", max_duration, e),
308                }
309                .build()
310            })?;
311            internal_query_params.max_duration = Some(duration.as_nanos() as u64);
312        }
313
314        if let Some(min_duration) = query_params.min_duration {
315            let duration = humantime::parse_duration(&min_duration).map_err(|e| {
316                InvalidJaegerQuerySnafu {
317                    reason: format!("parse minDuration '{}' failed: {}", min_duration, e),
318                }
319                .build()
320            })?;
321            internal_query_params.min_duration = Some(duration.as_nanos() as u64);
322        }
323
324        if let Some(tags) = query_params.tags {
325            // Serialize the tags to a JSON map.
326            let mut tags_map: HashMap<String, JsonValue> =
327                serde_json::from_str(&tags).map_err(|e| {
328                    InvalidJaegerQuerySnafu {
329                        reason: format!("parse tags '{}' failed: {}", tags, e),
330                    }
331                    .build()
332                })?;
333            for v in tags_map.values_mut() {
334                if let Some(number) = convert_string_to_number(v) {
335                    *v = number;
336                }
337                if let Some(boolean) = convert_string_to_boolean(v) {
338                    *v = boolean;
339                }
340            }
341            internal_query_params.tags = Some(tags_map);
342        }
343
344        internal_query_params.limit = query_params.limit;
345
346        Ok(internal_query_params)
347    }
348}
349
350#[derive(Debug, Default, PartialEq)]
351pub struct QueryTraceParams {
352    pub service_name: Option<String>,
353    pub operation_name: Option<String>,
354
355    // The limit of the number of traces to return.
356    pub limit: Option<usize>,
357
358    // Select the traces with the given tags(span attributes).
359    pub tags: Option<HashMap<String, JsonValue>>,
360
361    // The unit of the following time related parameters is nanoseconds.
362    pub start_time: Option<i64>,
363    pub end_time: Option<i64>,
364    pub min_duration: Option<u64>,
365    pub max_duration: Option<u64>,
366
367    /// Fetch all spans of matching traces, including spans outside the search window.
368    pub fetch_full_trace: bool,
369
370    // The user agent of the trace query, mainly find traces
371    pub user_agent: TraceUserAgent,
372}
373
374#[derive(Debug, Default, PartialEq, Eq)]
375pub enum TraceUserAgent {
376    Grafana,
377    // Jaeger-UI does not actually send user agent
378    // But it's a jaeger API, so let's treat it as jaeger
379    #[default]
380    Jaeger,
381}
382
383impl From<UserAgent> for TraceUserAgent {
384    fn from(value: UserAgent) -> Self {
385        let ua_str = value.as_str().to_lowercase();
386        debug!("received user agent: {}", ua_str);
387        if ua_str.contains("grafana") {
388            Self::Grafana
389        } else {
390            Self::Jaeger
391        }
392    }
393}
394
395/// Handle the GET `/api/services` request.
396#[axum_macros::debug_handler]
397#[tracing::instrument(skip_all, fields(protocol = "jaeger", request_type = "get_services"))]
398pub async fn handle_get_services(
399    State(handler): State<JaegerQueryHandlerRef>,
400    Query(query_params): Query<JaegerQueryParams>,
401    Extension(mut query_ctx): Extension<QueryContext>,
402    TraceTableName(table_name): TraceTableName,
403) -> impl IntoResponse {
404    debug!(
405        "Received Jaeger '/api/services' request, query_params: {:?}, query_ctx: {:?}",
406        query_params, query_ctx
407    );
408
409    query_ctx.set_channel(Channel::Jaeger);
410    if let Some(table) = table_name {
411        query_ctx.set_extension(JAEGER_QUERY_TABLE_NAME_KEY, table);
412    }
413
414    let query_ctx = Arc::new(query_ctx);
415    let db = query_ctx.get_db_string();
416
417    // Record the query time histogram.
418    let _timer = METRIC_JAEGER_QUERY_ELAPSED
419        .with_label_values(&[db.as_str(), "/api/services"])
420        .start_timer();
421
422    match handler.get_services(query_ctx).await {
423        Ok(output) => match covert_to_records(output).await {
424            Ok(Some(records)) => match services_from_records(records) {
425                Ok(services) => {
426                    let services_num = services.len();
427                    (
428                        HttpStatusCode::OK,
429                        axum::Json(JaegerAPIResponse {
430                            data: Some(JaegerData::ServiceNames(services)),
431                            total: services_num,
432                            ..Default::default()
433                        }),
434                    )
435                }
436                Err(err) => {
437                    error!("Failed to get services: {:?}", err);
438                    error_response(err)
439                }
440            },
441            Ok(None) => (HttpStatusCode::OK, axum::Json(JaegerAPIResponse::default())),
442            Err(err) => {
443                error!("Failed to get services: {:?}", err);
444                error_response(err)
445            }
446        },
447        Err(err) => handle_query_error(err, "Failed to get services", &db),
448    }
449}
450
451/// Handle the GET `/api/traces/{trace_id}` request.
452#[axum_macros::debug_handler]
453#[tracing::instrument(skip_all, fields(protocol = "jaeger", request_type = "get_trace"))]
454pub async fn handle_get_trace(
455    State(handler): State<JaegerQueryHandlerRef>,
456    Path(trace_id): Path<String>,
457    Query(query_params): Query<JaegerQueryParams>,
458    Extension(mut query_ctx): Extension<QueryContext>,
459    TraceTableName(table_name): TraceTableName,
460) -> impl IntoResponse {
461    debug!(
462        "Received Jaeger '/api/traces/{}' request, query_params: {:?}, query_ctx: {:?}",
463        trace_id, query_params, query_ctx
464    );
465
466    update_query_context(&mut query_ctx, table_name);
467    let query_ctx = Arc::new(query_ctx);
468    let db = query_ctx.get_db_string();
469
470    // Record the query time histogram.
471    let _timer = METRIC_JAEGER_QUERY_ELAPSED
472        .with_label_values(&[db.as_str(), "/api/traces"])
473        .start_timer();
474
475    // Convert start time and end time from microseconds to nanoseconds.
476    let start_time_ns = query_params.start.map(|start_us| start_us * 1000);
477    let end_time_ns = query_params.end.map(|end_us| end_us * 1000);
478
479    let output = match handler
480        .get_trace(
481            query_ctx,
482            &trace_id,
483            start_time_ns,
484            end_time_ns,
485            query_params.limit,
486        )
487        .await
488    {
489        Ok(output) => output,
490        Err(err) => {
491            return handle_query_error(
492                err,
493                &format!("Failed to get trace for '{}'", trace_id),
494                &db,
495            );
496        }
497    };
498
499    match covert_to_records(output).await {
500        Ok(Some(records)) => match traces_from_records(records) {
501            Ok(traces) if traces.is_empty() => (
502                HttpStatusCode::NOT_FOUND,
503                axum::Json(JaegerAPIResponse::trace_not_found()),
504            ),
505            Ok(traces) => (
506                HttpStatusCode::OK,
507                axum::Json(JaegerAPIResponse {
508                    data: Some(JaegerData::Traces(traces)),
509                    ..Default::default()
510                }),
511            ),
512            Err(err) => {
513                error!("Failed to get trace '{}': {:?}", trace_id, err);
514                error_response(err)
515            }
516        },
517        Ok(None) => (
518            HttpStatusCode::NOT_FOUND,
519            axum::Json(JaegerAPIResponse::trace_not_found()),
520        ),
521        Err(err) => {
522            error!("Failed to get trace '{}': {:?}", trace_id, err);
523            error_response(err)
524        }
525    }
526}
527
528/// Handle the GET `/api/traces` request.
529#[axum_macros::debug_handler]
530#[tracing::instrument(skip_all, fields(protocol = "jaeger", request_type = "find_traces"))]
531pub async fn handle_find_traces(
532    State(handler): State<JaegerQueryHandlerRef>,
533    Query(query_params): Query<JaegerQueryParams>,
534    Extension(mut query_ctx): Extension<QueryContext>,
535    TraceTableName(table_name): TraceTableName,
536    optional_user_agent: Option<TypedHeader<UserAgent>>,
537) -> impl IntoResponse {
538    debug!(
539        "Received Jaeger '/api/traces' request, query_params: {:?}, query_ctx: {:?}",
540        query_params, query_ctx
541    );
542
543    update_query_context(&mut query_ctx, table_name);
544    let query_ctx = Arc::new(query_ctx);
545    let db = query_ctx.get_db_string();
546
547    // Record the query time histogram.
548    let _timer = METRIC_JAEGER_QUERY_ELAPSED
549        .with_label_values(&[db.as_str(), "/api/traces"])
550        .start_timer();
551
552    match QueryTraceParams::from_jaeger_query_params(query_params) {
553        Ok(mut query_params) => {
554            if let Some(TypedHeader(user_agent)) = optional_user_agent {
555                query_params.user_agent = user_agent.into();
556            }
557            let output = handler.find_traces(query_ctx, query_params).await;
558            match output {
559                Ok(output) => match covert_to_records(output).await {
560                    Ok(Some(records)) => match traces_from_records(records) {
561                        Ok(traces) => (
562                            HttpStatusCode::OK,
563                            axum::Json(JaegerAPIResponse {
564                                data: Some(JaegerData::Traces(traces)),
565                                ..Default::default()
566                            }),
567                        ),
568                        Err(err) => {
569                            error!("Failed to find traces: {:?}", err);
570                            error_response(err)
571                        }
572                    },
573                    Ok(None) => (HttpStatusCode::OK, axum::Json(JaegerAPIResponse::default())),
574                    Err(err) => error_response(err),
575                },
576                Err(err) => handle_query_error(err, "Failed to find traces", &db),
577            }
578        }
579        Err(e) => error_response(e),
580    }
581}
582
583/// Handle the GET `/api/operations` request.
584#[axum_macros::debug_handler]
585#[tracing::instrument(skip_all, fields(protocol = "jaeger", request_type = "get_operations"))]
586pub async fn handle_get_operations(
587    State(handler): State<JaegerQueryHandlerRef>,
588    Query(query_params): Query<JaegerQueryParams>,
589    Extension(mut query_ctx): Extension<QueryContext>,
590    TraceTableName(table_name): TraceTableName,
591    headers: HeaderMap,
592) -> impl IntoResponse {
593    debug!(
594        "Received Jaeger '/api/operations' request, query_params: {:?}, query_ctx: {:?}, headers: {:?}",
595        query_params, query_ctx, headers
596    );
597
598    if let Some(service_name) = &query_params.service_name {
599        update_query_context(&mut query_ctx, table_name);
600        let query_ctx = Arc::new(query_ctx);
601        let db = query_ctx.get_db_string();
602
603        // Record the query time histogram.
604        let _timer = METRIC_JAEGER_QUERY_ELAPSED
605            .with_label_values(&[db.as_str(), "/api/operations"])
606            .start_timer();
607
608        match handler
609            .get_operations(query_ctx, service_name, query_params.span_kind.as_deref())
610            .await
611        {
612            Ok(output) => match covert_to_records(output).await {
613                Ok(Some(records)) => match operations_from_records(records, true) {
614                    Ok(operations) => {
615                        let total = operations.len();
616                        (
617                            HttpStatusCode::OK,
618                            axum::Json(JaegerAPIResponse {
619                                data: Some(JaegerData::Operations(operations)),
620                                total,
621                                ..Default::default()
622                            }),
623                        )
624                    }
625                    Err(err) => {
626                        error!("Failed to get operations: {:?}", err);
627                        error_response(err)
628                    }
629                },
630                Ok(None) => (HttpStatusCode::OK, axum::Json(JaegerAPIResponse::default())),
631                Err(err) => error_response(err),
632            },
633            Err(err) => handle_query_error(
634                err,
635                &format!("Failed to get operations for service '{}'", service_name),
636                &db,
637            ),
638        }
639    } else {
640        (
641            HttpStatusCode::BAD_REQUEST,
642            axum::Json(JaegerAPIResponse {
643                errors: vec![JaegerAPIError {
644                    code: 400,
645                    msg: "parameter 'service' is required".to_string(),
646                    trace_id: None,
647                }],
648                ..Default::default()
649            }),
650        )
651    }
652}
653
654/// Handle the GET `/api/services/{service_name}/operations` request.
655#[axum_macros::debug_handler]
656#[tracing::instrument(
657    skip_all,
658    fields(protocol = "jaeger", request_type = "get_operations_by_service")
659)]
660pub async fn handle_get_operations_by_service(
661    State(handler): State<JaegerQueryHandlerRef>,
662    Path(service_name): Path<String>,
663    Query(query_params): Query<JaegerQueryParams>,
664    Extension(mut query_ctx): Extension<QueryContext>,
665    TraceTableName(table_name): TraceTableName,
666    headers: HeaderMap,
667) -> impl IntoResponse {
668    debug!(
669        "Received Jaeger '/api/services/{}/operations' request, query_params: {:?}, query_ctx: {:?}, headers: {:?}",
670        service_name, query_params, query_ctx, headers
671    );
672
673    update_query_context(&mut query_ctx, table_name);
674    let query_ctx = Arc::new(query_ctx);
675    let db = query_ctx.get_db_string();
676
677    // Record the query time histogram.
678    let _timer = METRIC_JAEGER_QUERY_ELAPSED
679        .with_label_values(&[db.as_str(), "/api/services"])
680        .start_timer();
681
682    match handler.get_operations(query_ctx, &service_name, None).await {
683        Ok(output) => match covert_to_records(output).await {
684            Ok(Some(records)) => match operations_from_records(records, false) {
685                Ok(operations) => {
686                    let operations: Vec<String> =
687                        operations.into_iter().map(|op| op.name).collect();
688                    let total = operations.len();
689                    (
690                        HttpStatusCode::OK,
691                        axum::Json(JaegerAPIResponse {
692                            data: Some(JaegerData::OperationsNames(operations)),
693                            total,
694                            ..Default::default()
695                        }),
696                    )
697                }
698                Err(err) => {
699                    error!(
700                        "Failed to get operations for service '{}': {:?}",
701                        service_name, err
702                    );
703                    error_response(err)
704                }
705            },
706            Ok(None) => (HttpStatusCode::OK, axum::Json(JaegerAPIResponse::default())),
707            Err(err) => error_response(err),
708        },
709        Err(err) => handle_query_error(
710            err,
711            &format!("Failed to get operations for service '{}'", service_name),
712            &db,
713        ),
714    }
715}
716
717async fn covert_to_records(output: Output) -> Result<Option<HttpRecordsOutput>> {
718    match output.data {
719        OutputData::Stream(stream) => {
720            let records = HttpRecordsOutput::try_new(
721                stream.schema().clone(),
722                util::collect(stream)
723                    .await
724                    .context(CollectRecordbatchSnafu)?,
725            )?;
726            debug!(
727                "The query records: {}",
728                serde_json::to_string(&records).unwrap()
729            );
730            Ok(Some(records))
731        }
732        // It's unlikely to happen. However, if the output is not a stream, return None.
733        _ => Ok(None),
734    }
735}
736
737fn handle_query_error(
738    err: Error,
739    prompt: &str,
740    db: &str,
741) -> (HttpStatusCode, axum::Json<JaegerAPIResponse>) {
742    // To compatible with the Jaeger API, if the trace table is not found, return an empty response instead of an error.
743    if err.status_code() == StatusCode::TableNotFound {
744        warn!(
745            "No trace table '{}' found in database '{}'",
746            TRACE_TABLE_NAME, db
747        );
748        (HttpStatusCode::OK, axum::Json(JaegerAPIResponse::default()))
749    } else {
750        error!("{}: {:?}", prompt, err);
751        error_response(err)
752    }
753}
754
755fn error_response(err: Error) -> (HttpStatusCode, axum::Json<JaegerAPIResponse>) {
756    (
757        status_code_to_http_status(&err.status_code()),
758        axum::Json(JaegerAPIResponse {
759            errors: vec![JaegerAPIError {
760                code: err.status_code() as i32,
761                msg: err.to_string(),
762                ..Default::default()
763            }],
764            ..Default::default()
765        }),
766    )
767}
768
769fn traces_from_records(records: HttpRecordsOutput) -> Result<Vec<Trace>> {
770    // maintain the mapping: trace_id -> (process_id -> service_name).
771    let mut trace_id_to_processes: HashMap<String, HashMap<String, String>> = HashMap::new();
772    // maintain the mapping: trace_id -> spans.
773    // use BTreeMap to retain order
774    let mut trace_id_to_spans: BTreeMap<String, Vec<Span>> = BTreeMap::new();
775    // maintain the mapping: (trace_id, service.name) -> resource.attributes.
776    let mut service_to_resource_attributes: HashMap<(String, String), Vec<KeyValue>> =
777        HashMap::new();
778
779    let is_span_attributes_flatten = !records
780        .schema
781        .column_schemas
782        .iter()
783        .any(|c| c.name == SPAN_ATTRIBUTES_COLUMN);
784
785    for row in records.rows.into_iter() {
786        let mut span = Span::default();
787        let mut service_name = None;
788        let mut parent_span_id = None;
789        let mut resource_tags = vec![];
790
791        for (idx, cell) in row.into_iter().enumerate() {
792            // safe to use index here
793            let column_name = &records.schema.column_schemas[idx].name;
794
795            match column_name.as_str() {
796                TRACE_ID_COLUMN => {
797                    if let JsonValue::String(trace_id) = cell {
798                        span.trace_id = trace_id.clone();
799                        trace_id_to_processes.entry(trace_id).or_default();
800                    }
801                }
802                TIMESTAMP_COLUMN => {
803                    span.start_time = cell.as_u64().context(InvalidJaegerQuerySnafu {
804                        reason: "Failed to convert timestamp to u64".to_string(),
805                    })? / 1000;
806                }
807                DURATION_NANO_COLUMN => {
808                    span.duration = cell.as_u64().context(InvalidJaegerQuerySnafu {
809                        reason: "Failed to convert duration to u64".to_string(),
810                    })? / 1000;
811                }
812                SERVICE_NAME_COLUMN => {
813                    if let JsonValue::String(name) = cell {
814                        service_name = Some(name);
815                    }
816                }
817                SPAN_NAME_COLUMN => {
818                    if let JsonValue::String(span_name) = cell {
819                        span.operation_name = span_name;
820                    }
821                }
822                SPAN_ID_COLUMN => {
823                    if let JsonValue::String(span_id) = cell {
824                        span.span_id = span_id;
825                    }
826                }
827                SPAN_ATTRIBUTES_COLUMN => {
828                    // For v0 and v2, span_attributes are nested as a JSON
829                    // data structure
830                    if let JsonValue::Object(span_attrs) = cell {
831                        span.tags.extend(object_to_tags(span_attrs));
832                    }
833                }
834                RESOURCE_ATTRIBUTES_COLUMN => {
835                    // For v0 and v2, resource_attributes are nested as a JSON
836                    // data structure
837
838                    if let JsonValue::Object(mut resource_attrs) = cell {
839                        resource_attrs.remove(KEY_SERVICE_NAME);
840                        resource_tags = object_to_tags(resource_attrs);
841                    }
842                }
843                PARENT_SPAN_ID_COLUMN => {
844                    if let JsonValue::String(id) = cell
845                        && !id.is_empty()
846                    {
847                        parent_span_id = Some(id);
848                    }
849                }
850                SPAN_LINKS_COLUMN => {
851                    if let JsonValue::Array(links) = cell {
852                        for link in links {
853                            if let (Some(trace_id), Some(span_id)) = (
854                                link.get("trace_id").and_then(JsonValue::as_str),
855                                link.get("span_id").and_then(JsonValue::as_str),
856                            ) {
857                                span.references.push(Reference {
858                                    trace_id: trace_id.to_string(),
859                                    span_id: span_id.to_string(),
860                                    ref_type: "FOLLOWS_FROM".to_string(),
861                                });
862                            }
863                        }
864                    }
865                }
866                SPAN_EVENTS_COLUMN => {
867                    if let JsonValue::Array(events) = cell {
868                        for event in events {
869                            if let JsonValue::Object(mut obj) = event {
870                                let Some(action) = obj.get("name").and_then(|v| v.as_str()) else {
871                                    continue;
872                                };
873
874                                let Some(t) =
875                                    obj.get("time").and_then(|t| t.as_str()).and_then(|s| {
876                                        SPAN_KIND_TIME_FMTS
877                                            .iter()
878                                            .find_map(|fmt| {
879                                                chrono::DateTime::parse_from_str(s, fmt).ok()
880                                            })
881                                            .map(|dt| dt.timestamp_micros() as u64)
882                                    })
883                                else {
884                                    continue;
885                                };
886
887                                let mut fields = vec![KeyValue {
888                                    key: "event".to_string(),
889                                    value_type: ValueType::String,
890                                    value: Value::String(action.to_string()),
891                                }];
892
893                                // Add event attributes as fields
894                                if let Some(JsonValue::Object(attrs)) = obj.remove("attributes") {
895                                    fields.extend(object_to_tags(attrs));
896                                }
897
898                                span.logs.push(Log {
899                                    timestamp: t,
900                                    fields,
901                                });
902                            }
903                        }
904                    }
905                }
906                SCOPE_NAME_COLUMN => {
907                    if let JsonValue::String(scope_name) = cell
908                        && !scope_name.is_empty()
909                    {
910                        span.tags.push(KeyValue {
911                            key: KEY_OTEL_SCOPE_NAME.to_string(),
912                            value_type: ValueType::String,
913                            value: Value::String(scope_name),
914                        });
915                    }
916                }
917                SCOPE_VERSION_COLUMN => {
918                    if let JsonValue::String(scope_version) = cell
919                        && !scope_version.is_empty()
920                    {
921                        span.tags.push(KeyValue {
922                            key: KEY_OTEL_SCOPE_VERSION.to_string(),
923                            value_type: ValueType::String,
924                            value: Value::String(scope_version),
925                        });
926                    }
927                }
928                SPAN_KIND_COLUMN => {
929                    if let JsonValue::String(span_kind) = cell
930                        && !span_kind.is_empty()
931                    {
932                        span.tags.push(KeyValue {
933                            key: KEY_SPAN_KIND.to_string(),
934                            value_type: ValueType::String,
935                            value: Value::String(normalize_span_kind(&span_kind)),
936                        });
937                    }
938                }
939                SPAN_STATUS_CODE => {
940                    if let JsonValue::String(span_status) = cell
941                        && span_status != SPAN_STATUS_UNSET
942                        && !span_status.is_empty()
943                    {
944                        span.tags.push(KeyValue {
945                            key: KEY_OTEL_STATUS_CODE.to_string(),
946                            value_type: ValueType::String,
947                            value: Value::String(normalize_status_code(&span_status)),
948                        });
949                        // set error to comply with the Jaeger API
950                        if span_status == SPAN_STATUS_ERROR {
951                            span.tags.push(KeyValue {
952                                key: KEY_OTEL_STATUS_ERROR_KEY.to_string(),
953                                value_type: ValueType::Boolean,
954                                value: Value::Boolean(true),
955                            });
956                        }
957                    }
958                }
959
960                SPAN_STATUS_MESSAGE_COLUMN => {
961                    if let JsonValue::String(span_status_message) = cell
962                        && !span_status_message.is_empty()
963                    {
964                        span.tags.push(KeyValue {
965                            key: KEY_OTEL_STATUS_MESSAGE.to_string(),
966                            value_type: ValueType::String,
967                            value: Value::String(span_status_message),
968                        });
969                    }
970                }
971
972                TRACE_STATE_COLUMN => {
973                    if let JsonValue::String(trace_state) = cell
974                        && !trace_state.is_empty()
975                    {
976                        span.tags.push(KeyValue {
977                            key: KEY_OTEL_TRACE_STATE.to_string(),
978                            value_type: ValueType::String,
979                            value: Value::String(trace_state),
980                        });
981                    }
982                }
983
984                _ => {
985                    // this this v1 data model
986                    if is_span_attributes_flatten {
987                        const SPAN_ATTR_PREFIX: &str = "span_attributes.";
988                        const RESOURCE_ATTR_PREFIX: &str = "resource_attributes.";
989                        // a span attributes column
990                        if column_name.starts_with(SPAN_ATTR_PREFIX) {
991                            if let Some(keyvalue) = to_keyvalue(
992                                column_name
993                                    .strip_prefix(SPAN_ATTR_PREFIX)
994                                    .unwrap_or_default()
995                                    .to_string(),
996                                cell,
997                            ) {
998                                span.tags.push(keyvalue);
999                            }
1000                        } else if column_name.starts_with(RESOURCE_ATTR_PREFIX)
1001                            && let Some(keyvalue) = to_keyvalue(
1002                                column_name
1003                                    .strip_prefix(RESOURCE_ATTR_PREFIX)
1004                                    .unwrap_or_default()
1005                                    .to_string(),
1006                                cell,
1007                            )
1008                        {
1009                            resource_tags.push(keyvalue);
1010                        }
1011                    }
1012                }
1013            }
1014        }
1015
1016        if let Some(parent_span_id) = parent_span_id {
1017            span.references.insert(
1018                0,
1019                Reference {
1020                    trace_id: span.trace_id.clone(),
1021                    span_id: parent_span_id,
1022                    ref_type: REF_TYPE_CHILD_OF.to_string(),
1023                },
1024            );
1025        }
1026
1027        if let Some(service_name) = service_name {
1028            service_to_resource_attributes
1029                .entry((span.trace_id.clone(), service_name.clone()))
1030                .or_insert(resource_tags);
1031
1032            if let Some(process) = trace_id_to_processes.get_mut(&span.trace_id) {
1033                if let Some(process_id) = process.get(&service_name) {
1034                    span.process_id = process_id.clone();
1035                } else {
1036                    // Allocate a new process id.
1037                    let process_id = format!("p{}", process.len() + 1);
1038                    process.insert(service_name, process_id.clone());
1039                    span.process_id = process_id;
1040                }
1041            }
1042        }
1043
1044        // ensure span tags order
1045        span.tags.sort_by(|a, b| a.key.cmp(&b.key));
1046
1047        if let Some(spans) = trace_id_to_spans.get_mut(&span.trace_id) {
1048            spans.push(span);
1049        } else {
1050            trace_id_to_spans.insert(span.trace_id.clone(), vec![span]);
1051        }
1052    }
1053
1054    let mut traces = Vec::new();
1055    for (trace_id, spans) in trace_id_to_spans {
1056        let mut trace = Trace {
1057            trace_id,
1058            spans,
1059            ..Default::default()
1060        };
1061
1062        if let Some(processes) = trace_id_to_processes.remove(&trace.trace_id) {
1063            let mut process_id_to_process = HashMap::new();
1064            for (service_name, process_id) in processes.into_iter() {
1065                let tags = service_to_resource_attributes
1066                    .remove(&(trace.trace_id.clone(), service_name.clone()))
1067                    .unwrap_or_default();
1068                process_id_to_process.insert(process_id, Process { service_name, tags });
1069            }
1070            trace.processes = process_id_to_process;
1071        }
1072        traces.push(trace);
1073    }
1074
1075    Ok(traces)
1076}
1077
1078fn to_keyvalue(key: String, value: JsonValue) -> Option<KeyValue> {
1079    match value {
1080        JsonValue::String(value) => Some(KeyValue {
1081            key,
1082            value_type: ValueType::String,
1083            value: Value::String(value.clone()),
1084        }),
1085        JsonValue::Number(value) => {
1086            if value.is_i64() {
1087                Some(KeyValue {
1088                    key,
1089                    value_type: ValueType::Int64,
1090                    value: Value::Int64(value.as_i64()?),
1091                })
1092            } else {
1093                Some(KeyValue {
1094                    key,
1095                    value_type: ValueType::Float64,
1096                    value: Value::Float64(value.as_f64()?),
1097                })
1098            }
1099        }
1100        JsonValue::Bool(value) => Some(KeyValue {
1101            key,
1102            value_type: ValueType::Boolean,
1103            value: Value::Boolean(value),
1104        }),
1105        JsonValue::Array(value) => Some(KeyValue {
1106            key,
1107            value_type: ValueType::String,
1108            value: Value::String(serde_json::to_string(&value).unwrap()),
1109        }),
1110        JsonValue::Object(value) => Some(KeyValue {
1111            key,
1112            value_type: ValueType::String,
1113            value: Value::String(serde_json::to_string(&value).unwrap()),
1114        }),
1115        JsonValue::Null => None,
1116    }
1117}
1118
1119fn object_to_tags(object: serde_json::map::Map<String, JsonValue>) -> Vec<KeyValue> {
1120    object
1121        .into_iter()
1122        .filter_map(|(key, value)| to_keyvalue(key, value))
1123        .collect()
1124}
1125
1126fn services_from_records(records: HttpRecordsOutput) -> Result<Vec<String>> {
1127    let expected_schema = vec![(SERVICE_NAME_COLUMN, "String")];
1128    check_schema(&records, &expected_schema)?;
1129
1130    let mut services = Vec::with_capacity(records.total_rows);
1131    for row in records.rows.into_iter() {
1132        for value in row.into_iter() {
1133            if let JsonValue::String(service_name) = value {
1134                services.push(service_name);
1135            }
1136        }
1137    }
1138    Ok(services)
1139}
1140
1141// Construct Jaeger operations from records.
1142fn operations_from_records(
1143    records: HttpRecordsOutput,
1144    contain_span_kind: bool,
1145) -> Result<Vec<Operation>> {
1146    let expected_schema = vec![(SPAN_NAME_COLUMN, "String"), (SPAN_KIND_COLUMN, "String")];
1147    check_schema(&records, &expected_schema)?;
1148
1149    let mut operations = Vec::with_capacity(records.total_rows);
1150    for row in records.rows.into_iter() {
1151        let mut row_iter = row.into_iter();
1152        if let Some(JsonValue::String(operation)) = row_iter.next() {
1153            let mut operation = Operation {
1154                name: operation,
1155                span_kind: None,
1156            };
1157            if contain_span_kind {
1158                if let Some(JsonValue::String(span_kind)) = row_iter.next() {
1159                    operation.span_kind = Some(normalize_span_kind(&span_kind));
1160                }
1161            } else {
1162                // skip span kind.
1163                row_iter.next();
1164            }
1165            operations.push(operation);
1166        }
1167    }
1168
1169    Ok(operations)
1170}
1171
1172// Check whether the schema of the records is correct.
1173fn check_schema(records: &HttpRecordsOutput, expected_schema: &[(&str, &str)]) -> Result<()> {
1174    for (i, column) in records.schema.column_schemas.iter().enumerate() {
1175        if column.name != expected_schema[i].0 || column.data_type != expected_schema[i].1 {
1176            InvalidJaegerQuerySnafu {
1177                reason: "query result schema is not correct".to_string(),
1178            }
1179            .fail()?
1180        }
1181    }
1182    Ok(())
1183}
1184
1185// By default, the span kind is stored as `SPAN_KIND_<kind>` in GreptimeDB.
1186// However, in Jaeger API, the span kind is returned as `<kind>` which is the lowercase of the span kind and without the `SPAN_KIND_` prefix.
1187fn normalize_span_kind(span_kind: &str) -> String {
1188    // If the span_kind starts with `SPAN_KIND_` prefix, remove it and convert to lowercase.
1189    if let Some(stripped) = span_kind.strip_prefix(SPAN_KIND_PREFIX) {
1190        stripped.to_lowercase()
1191    } else {
1192        // It's unlikely to happen. However, we still convert it to lowercase for consistency.
1193        span_kind.to_lowercase()
1194    }
1195}
1196
1197// By default, the status code is stored as `STATUS_CODE_<code>` in GreptimeDB.
1198// However, in Jaeger API, the status code is returned as `<code>` without the `STATUS_CODE_` prefix.
1199fn normalize_status_code(status_code: &str) -> String {
1200    // If the span_kind starts with `SPAN_KIND_` prefix, remove it and convert to lowercase.
1201    if let Some(stripped) = status_code.strip_prefix(SPAN_STATUS_PREFIX) {
1202        stripped.to_string()
1203    } else {
1204        // It's unlikely to happen
1205        status_code.to_string()
1206    }
1207}
1208
1209fn convert_string_to_number(input: &serde_json::Value) -> Option<serde_json::Value> {
1210    if let Some(data) = input.as_str() {
1211        if let Ok(number) = data.parse::<i64>() {
1212            return Some(serde_json::Value::Number(serde_json::Number::from(number)));
1213        }
1214        if let Ok(number) = data.parse::<f64>()
1215            && let Some(number) = serde_json::Number::from_f64(number)
1216        {
1217            return Some(serde_json::Value::Number(number));
1218        }
1219    }
1220
1221    None
1222}
1223
1224fn convert_string_to_boolean(input: &serde_json::Value) -> Option<serde_json::Value> {
1225    if let Some(data) = input.as_str() {
1226        if data == "true" {
1227            return Some(serde_json::Value::Bool(true));
1228        }
1229        if data == "false" {
1230            return Some(serde_json::Value::Bool(false));
1231        }
1232    }
1233
1234    None
1235}
1236
1237#[cfg(test)]
1238mod tests {
1239    use serde_json::{Number, Value as JsonValue, json};
1240
1241    use super::*;
1242    use crate::http::{ColumnSchema, HttpRecordsOutput, OutputSchema};
1243
1244    #[test]
1245    fn test_numeric_tag_types() {
1246        for (input, value_type, value) in [
1247            (json!(42), ValueType::Int64, Value::Int64(42)),
1248            (json!(1.5), ValueType::Float64, Value::Float64(1.5)),
1249        ] {
1250            assert_eq!(
1251                to_keyvalue("tag".to_string(), input),
1252                Some(KeyValue {
1253                    key: "tag".to_string(),
1254                    value_type,
1255                    value,
1256                })
1257            );
1258        }
1259    }
1260
1261    #[test]
1262    fn test_services_from_records() {
1263        // The tests is the tuple of `(test_records, expected)`.
1264        let tests = vec![(
1265            HttpRecordsOutput {
1266                schema: OutputSchema {
1267                    column_schemas: vec![ColumnSchema {
1268                        name: "service_name".to_string(),
1269                        data_type: "String".to_string(),
1270                    }],
1271                },
1272                rows: vec![
1273                    vec![JsonValue::String("test-service-0".to_string())],
1274                    vec![JsonValue::String("test-service-1".to_string())],
1275                ],
1276                total_rows: 2,
1277                metrics: HashMap::new(),
1278            },
1279            vec!["test-service-0".to_string(), "test-service-1".to_string()],
1280        )];
1281
1282        for (records, expected) in tests {
1283            let services = services_from_records(records).unwrap();
1284            assert_eq!(services, expected);
1285        }
1286    }
1287
1288    #[test]
1289    fn test_operations_from_records() {
1290        // The tests is the tuple of `(test_records, contain_span_kind, expected)`.
1291        let tests = vec![
1292            (
1293                HttpRecordsOutput {
1294                    schema: OutputSchema {
1295                        column_schemas: vec![
1296                            ColumnSchema {
1297                                name: "span_name".to_string(),
1298                                data_type: "String".to_string(),
1299                            },
1300                            ColumnSchema {
1301                                name: "span_kind".to_string(),
1302                                data_type: "String".to_string(),
1303                            },
1304                        ],
1305                    },
1306                    rows: vec![
1307                        vec![
1308                            JsonValue::String("access-mysql".to_string()),
1309                            JsonValue::String("SPAN_KIND_SERVER".to_string()),
1310                        ],
1311                        vec![
1312                            JsonValue::String("access-redis".to_string()),
1313                            JsonValue::String("SPAN_KIND_CLIENT".to_string()),
1314                        ],
1315                    ],
1316                    total_rows: 2,
1317                    metrics: HashMap::new(),
1318                },
1319                false,
1320                vec![
1321                    Operation {
1322                        name: "access-mysql".to_string(),
1323                        span_kind: None,
1324                    },
1325                    Operation {
1326                        name: "access-redis".to_string(),
1327                        span_kind: None,
1328                    },
1329                ],
1330            ),
1331            (
1332                HttpRecordsOutput {
1333                    schema: OutputSchema {
1334                        column_schemas: vec![
1335                            ColumnSchema {
1336                                name: "span_name".to_string(),
1337                                data_type: "String".to_string(),
1338                            },
1339                            ColumnSchema {
1340                                name: "span_kind".to_string(),
1341                                data_type: "String".to_string(),
1342                            },
1343                        ],
1344                    },
1345                    rows: vec![
1346                        vec![
1347                            JsonValue::String("access-mysql".to_string()),
1348                            JsonValue::String("SPAN_KIND_SERVER".to_string()),
1349                        ],
1350                        vec![
1351                            JsonValue::String("access-redis".to_string()),
1352                            JsonValue::String("SPAN_KIND_CLIENT".to_string()),
1353                        ],
1354                    ],
1355                    total_rows: 2,
1356                    metrics: HashMap::new(),
1357                },
1358                true,
1359                vec![
1360                    Operation {
1361                        name: "access-mysql".to_string(),
1362                        span_kind: Some("server".to_string()),
1363                    },
1364                    Operation {
1365                        name: "access-redis".to_string(),
1366                        span_kind: Some("client".to_string()),
1367                    },
1368                ],
1369            ),
1370        ];
1371
1372        for (records, contain_span_kind, expected) in tests {
1373            let operations = operations_from_records(records, contain_span_kind).unwrap();
1374            assert_eq!(operations, expected);
1375        }
1376    }
1377
1378    #[test]
1379    fn test_traces_from_records() {
1380        // The tests is the tuple of `(test_records, expected)`.
1381        let tests = vec![(
1382            HttpRecordsOutput {
1383                schema: OutputSchema {
1384                    column_schemas: vec![
1385                        ColumnSchema {
1386                            name: "trace_id".to_string(),
1387                            data_type: "String".to_string(),
1388                        },
1389                        ColumnSchema {
1390                            name: "timestamp".to_string(),
1391                            data_type: "TimestampNanosecond".to_string(),
1392                        },
1393                        ColumnSchema {
1394                            name: "duration_nano".to_string(),
1395                            data_type: "UInt64".to_string(),
1396                        },
1397                        ColumnSchema {
1398                            name: "service_name".to_string(),
1399                            data_type: "String".to_string(),
1400                        },
1401                        ColumnSchema {
1402                            name: "span_name".to_string(),
1403                            data_type: "String".to_string(),
1404                        },
1405                        ColumnSchema {
1406                            name: "span_id".to_string(),
1407                            data_type: "String".to_string(),
1408                        },
1409                        ColumnSchema {
1410                            name: "span_attributes".to_string(),
1411                            data_type: "Json".to_string(),
1412                        },
1413                    ],
1414                },
1415                rows: vec![
1416                    vec![
1417                        JsonValue::String("5611dce1bc9ebed65352d99a027b08ea".to_string()),
1418                        JsonValue::Number(Number::from_u128(1738726754492422000).unwrap()),
1419                        JsonValue::Number(Number::from_u128(100000000).unwrap()),
1420                        JsonValue::String("test-service-0".to_string()),
1421                        JsonValue::String("access-mysql".to_string()),
1422                        JsonValue::String("008421dbbd33a3e9".to_string()),
1423                        JsonValue::Object(
1424                            json!({
1425                                "operation.type": "access-mysql",
1426                            })
1427                            .as_object()
1428                            .unwrap()
1429                            .clone(),
1430                        ),
1431                    ],
1432                    vec![
1433                        JsonValue::String("5611dce1bc9ebed65352d99a027b08ea".to_string()),
1434                        JsonValue::Number(Number::from_u128(1738726754642422000).unwrap()),
1435                        JsonValue::Number(Number::from_u128(100000000).unwrap()),
1436                        JsonValue::String("test-service-0".to_string()),
1437                        JsonValue::String("access-redis".to_string()),
1438                        JsonValue::String("ffa03416a7b9ea48".to_string()),
1439                        JsonValue::Object(
1440                            json!({
1441                                "operation.type": "access-redis",
1442                            })
1443                            .as_object()
1444                            .unwrap()
1445                            .clone(),
1446                        ),
1447                    ],
1448                ],
1449                total_rows: 2,
1450                metrics: HashMap::new(),
1451            },
1452            vec![Trace {
1453                trace_id: "5611dce1bc9ebed65352d99a027b08ea".to_string(),
1454                spans: vec![
1455                    Span {
1456                        trace_id: "5611dce1bc9ebed65352d99a027b08ea".to_string(),
1457                        span_id: "008421dbbd33a3e9".to_string(),
1458                        operation_name: "access-mysql".to_string(),
1459                        start_time: 1738726754492422,
1460                        duration: 100000,
1461                        tags: vec![KeyValue {
1462                            key: "operation.type".to_string(),
1463                            value_type: ValueType::String,
1464                            value: Value::String("access-mysql".to_string()),
1465                        }],
1466                        process_id: "p1".to_string(),
1467                        ..Default::default()
1468                    },
1469                    Span {
1470                        trace_id: "5611dce1bc9ebed65352d99a027b08ea".to_string(),
1471                        span_id: "ffa03416a7b9ea48".to_string(),
1472                        operation_name: "access-redis".to_string(),
1473                        start_time: 1738726754642422,
1474                        duration: 100000,
1475                        tags: vec![KeyValue {
1476                            key: "operation.type".to_string(),
1477                            value_type: ValueType::String,
1478                            value: Value::String("access-redis".to_string()),
1479                        }],
1480                        process_id: "p1".to_string(),
1481                        ..Default::default()
1482                    },
1483                ],
1484                processes: HashMap::from([(
1485                    "p1".to_string(),
1486                    Process {
1487                        service_name: "test-service-0".to_string(),
1488                        tags: vec![],
1489                    },
1490                )]),
1491                ..Default::default()
1492            }],
1493        )];
1494
1495        for (records, expected) in tests {
1496            let traces = traces_from_records(records).unwrap();
1497            assert_eq!(traces, expected);
1498        }
1499    }
1500
1501    #[test]
1502    fn test_traces_from_v1_records() {
1503        // The tests is the tuple of `(test_records, expected)`.
1504        let tests = vec![(
1505            HttpRecordsOutput {
1506                schema: OutputSchema {
1507                    column_schemas: vec![
1508                        ColumnSchema {
1509                            name: "trace_id".to_string(),
1510                            data_type: "String".to_string(),
1511                        },
1512                        ColumnSchema {
1513                            name: "timestamp".to_string(),
1514                            data_type: "TimestampNanosecond".to_string(),
1515                        },
1516                        ColumnSchema {
1517                            name: "duration_nano".to_string(),
1518                            data_type: "UInt64".to_string(),
1519                        },
1520                        ColumnSchema {
1521                            name: "service_name".to_string(),
1522                            data_type: "String".to_string(),
1523                        },
1524                        ColumnSchema {
1525                            name: "span_name".to_string(),
1526                            data_type: "String".to_string(),
1527                        },
1528                        ColumnSchema {
1529                            name: "span_id".to_string(),
1530                            data_type: "String".to_string(),
1531                        },
1532                        ColumnSchema {
1533                            name: "span_attributes.http.request.method".to_string(),
1534                            data_type: "String".to_string(),
1535                        },
1536                        ColumnSchema {
1537                            name: "span_attributes.http.request.url".to_string(),
1538                            data_type: "String".to_string(),
1539                        },
1540                        ColumnSchema {
1541                            name: "span_attributes.http.status_code".to_string(),
1542                            data_type: "UInt64".to_string(),
1543                        },
1544                    ],
1545                },
1546                rows: vec![
1547                    vec![
1548                        JsonValue::String("5611dce1bc9ebed65352d99a027b08ea".to_string()),
1549                        JsonValue::Number(Number::from_u128(1738726754492422000).unwrap()),
1550                        JsonValue::Number(Number::from_u128(100000000).unwrap()),
1551                        JsonValue::String("test-service-0".to_string()),
1552                        JsonValue::String("access-mysql".to_string()),
1553                        JsonValue::String("008421dbbd33a3e9".to_string()),
1554                        JsonValue::String("GET".to_string()),
1555                        JsonValue::String("/data".to_string()),
1556                        JsonValue::Number(Number::from_u128(200).unwrap()),
1557                    ],
1558                    vec![
1559                        JsonValue::String("5611dce1bc9ebed65352d99a027b08ea".to_string()),
1560                        JsonValue::Number(Number::from_u128(1738726754642422000).unwrap()),
1561                        JsonValue::Number(Number::from_u128(100000000).unwrap()),
1562                        JsonValue::String("test-service-0".to_string()),
1563                        JsonValue::String("access-redis".to_string()),
1564                        JsonValue::String("ffa03416a7b9ea48".to_string()),
1565                        JsonValue::String("POST".to_string()),
1566                        JsonValue::String("/create".to_string()),
1567                        JsonValue::Number(Number::from_u128(400).unwrap()),
1568                    ],
1569                ],
1570                total_rows: 2,
1571                metrics: HashMap::new(),
1572            },
1573            vec![Trace {
1574                trace_id: "5611dce1bc9ebed65352d99a027b08ea".to_string(),
1575                spans: vec![
1576                    Span {
1577                        trace_id: "5611dce1bc9ebed65352d99a027b08ea".to_string(),
1578                        span_id: "008421dbbd33a3e9".to_string(),
1579                        operation_name: "access-mysql".to_string(),
1580                        start_time: 1738726754492422,
1581                        duration: 100000,
1582                        tags: vec![
1583                            KeyValue {
1584                                key: "http.request.method".to_string(),
1585                                value_type: ValueType::String,
1586                                value: Value::String("GET".to_string()),
1587                            },
1588                            KeyValue {
1589                                key: "http.request.url".to_string(),
1590                                value_type: ValueType::String,
1591                                value: Value::String("/data".to_string()),
1592                            },
1593                            KeyValue {
1594                                key: "http.status_code".to_string(),
1595                                value_type: ValueType::Int64,
1596                                value: Value::Int64(200),
1597                            },
1598                        ],
1599                        process_id: "p1".to_string(),
1600                        ..Default::default()
1601                    },
1602                    Span {
1603                        trace_id: "5611dce1bc9ebed65352d99a027b08ea".to_string(),
1604                        span_id: "ffa03416a7b9ea48".to_string(),
1605                        operation_name: "access-redis".to_string(),
1606                        start_time: 1738726754642422,
1607                        duration: 100000,
1608                        tags: vec![
1609                            KeyValue {
1610                                key: "http.request.method".to_string(),
1611                                value_type: ValueType::String,
1612                                value: Value::String("POST".to_string()),
1613                            },
1614                            KeyValue {
1615                                key: "http.request.url".to_string(),
1616                                value_type: ValueType::String,
1617                                value: Value::String("/create".to_string()),
1618                            },
1619                            KeyValue {
1620                                key: "http.status_code".to_string(),
1621                                value_type: ValueType::Int64,
1622                                value: Value::Int64(400),
1623                            },
1624                        ],
1625                        process_id: "p1".to_string(),
1626                        ..Default::default()
1627                    },
1628                ],
1629                processes: HashMap::from([(
1630                    "p1".to_string(),
1631                    Process {
1632                        service_name: "test-service-0".to_string(),
1633                        tags: vec![],
1634                    },
1635                )]),
1636                ..Default::default()
1637            }],
1638        )];
1639
1640        for (records, expected) in tests {
1641            let traces = traces_from_records(records).unwrap();
1642            assert_eq!(traces, expected);
1643        }
1644    }
1645
1646    #[test]
1647    fn test_each_trace_gets_its_own_process_tags() {
1648        let column = |name: &str| ColumnSchema {
1649            name: name.to_string(),
1650            data_type: "String".to_string(),
1651        };
1652        let row = |trace_id: &str, host: &str| {
1653            vec![
1654                JsonValue::String(trace_id.to_string()),
1655                JsonValue::String("test-service".to_string()),
1656                JsonValue::String(host.to_string()),
1657            ]
1658        };
1659        let records = HttpRecordsOutput {
1660            schema: OutputSchema {
1661                column_schemas: vec![
1662                    column("trace_id"),
1663                    column("service_name"),
1664                    column("resource_attributes.host.name"),
1665                ],
1666            },
1667            rows: vec![row("trace-1", "host-1"), row("trace-2", "host-2")],
1668            total_rows: 2,
1669            metrics: HashMap::new(),
1670        };
1671
1672        let traces = traces_from_records(records).unwrap();
1673        assert_eq!(traces.len(), 2);
1674        for (trace, host) in traces.iter().zip(["host-1", "host-2"]) {
1675            assert_eq!(
1676                trace.processes["p1"].tags,
1677                vec![KeyValue {
1678                    key: "host.name".to_string(),
1679                    value_type: ValueType::String,
1680                    value: Value::String(host.to_string()),
1681                }]
1682            );
1683        }
1684    }
1685
1686    #[test]
1687    fn test_from_jaeger_query_params() {
1688        // The tests is the tuple of `(test_query_params, expected)`.
1689        let tests = vec![
1690            (
1691                JaegerQueryParams {
1692                    service_name: Some("test-service-0".to_string()),
1693                    ..Default::default()
1694                },
1695                QueryTraceParams {
1696                    service_name: Some("test-service-0".to_string()),
1697                    ..Default::default()
1698                },
1699            ),
1700            (
1701                JaegerQueryParams {
1702                    service_name: Some("test-service-0".to_string()),
1703                    operation_name: Some("access-mysql".to_string()),
1704                    start: Some(1738726754492422),
1705                    end: Some(1738726754642422),
1706                    max_duration: Some("100ms".to_string()),
1707                    min_duration: Some("50ms".to_string()),
1708                    limit: Some(10),
1709                    tags: Some("{\"http.status_code\":\"200\",\"latency\":\"11.234\",\"error\":\"false\",\"http.method\":\"GET\",\"http.path\":\"/api/v1/users\"}".to_string()),
1710                    ..Default::default()
1711                },
1712                QueryTraceParams {
1713                    service_name: Some("test-service-0".to_string()),
1714                    operation_name: Some("access-mysql".to_string()),
1715                    start_time: Some(1738726754492422000),
1716                    end_time: Some(1738726754642422000),
1717                    min_duration: Some(50000000),
1718                    max_duration: Some(100000000),
1719                    limit: Some(10),
1720                    tags: Some(HashMap::from([
1721                        ("http.status_code".to_string(), JsonValue::Number(Number::from(200))),
1722                        ("latency".to_string(), JsonValue::Number(Number::from_f64(11.234).unwrap())),
1723                        ("error".to_string(), JsonValue::Bool(false)),
1724                        ("http.method".to_string(), JsonValue::String("GET".to_string())),
1725                        ("http.path".to_string(), JsonValue::String("/api/v1/users".to_string())),
1726                    ])),
1727                    user_agent: TraceUserAgent::Jaeger,
1728                    fetch_full_trace: false,
1729                },
1730            ),
1731        ];
1732
1733        for (query_params, expected) in tests {
1734            let query_params = QueryTraceParams::from_jaeger_query_params(query_params).unwrap();
1735            assert_eq!(query_params, expected);
1736        }
1737    }
1738
1739    #[test]
1740    fn test_check_schema() {
1741        // The tests is the tuple of `(test_records, expected_schema, is_ok)`.
1742        let tests = vec![(
1743            HttpRecordsOutput {
1744                schema: OutputSchema {
1745                    column_schemas: vec![
1746                        ColumnSchema {
1747                            name: "trace_id".to_string(),
1748                            data_type: "String".to_string(),
1749                        },
1750                        ColumnSchema {
1751                            name: "timestamp".to_string(),
1752                            data_type: "TimestampNanosecond".to_string(),
1753                        },
1754                        ColumnSchema {
1755                            name: "duration_nano".to_string(),
1756                            data_type: "UInt64".to_string(),
1757                        },
1758                        ColumnSchema {
1759                            name: "service_name".to_string(),
1760                            data_type: "String".to_string(),
1761                        },
1762                        ColumnSchema {
1763                            name: "span_name".to_string(),
1764                            data_type: "String".to_string(),
1765                        },
1766                        ColumnSchema {
1767                            name: "span_id".to_string(),
1768                            data_type: "String".to_string(),
1769                        },
1770                        ColumnSchema {
1771                            name: "span_attributes".to_string(),
1772                            data_type: "Json".to_string(),
1773                        },
1774                    ],
1775                },
1776                rows: vec![],
1777                total_rows: 0,
1778                metrics: HashMap::new(),
1779            },
1780            vec![
1781                (TRACE_ID_COLUMN, "String"),
1782                (TIMESTAMP_COLUMN, "TimestampNanosecond"),
1783                (DURATION_NANO_COLUMN, "UInt64"),
1784                (SERVICE_NAME_COLUMN, "String"),
1785                (SPAN_NAME_COLUMN, "String"),
1786                (SPAN_ID_COLUMN, "String"),
1787                (SPAN_ATTRIBUTES_COLUMN, "Json"),
1788            ],
1789            true,
1790        )];
1791
1792        for (records, expected_schema, is_ok) in tests {
1793            let result = check_schema(&records, &expected_schema);
1794            assert_eq!(result.is_ok(), is_ok);
1795        }
1796    }
1797
1798    #[test]
1799    fn test_normalize_span_kind() {
1800        let tests = vec![
1801            ("SPAN_KIND_SERVER".to_string(), "server".to_string()),
1802            ("SPAN_KIND_CLIENT".to_string(), "client".to_string()),
1803        ];
1804
1805        for (input, expected) in tests {
1806            let result = normalize_span_kind(&input);
1807            assert_eq!(result, expected);
1808        }
1809    }
1810
1811    #[test]
1812    fn test_convert_string_to_number() {
1813        let tests = vec![
1814            (
1815                JsonValue::String("123".to_string()),
1816                Some(JsonValue::Number(Number::from(123))),
1817            ),
1818            (
1819                JsonValue::String("123.456".to_string()),
1820                Some(JsonValue::Number(Number::from_f64(123.456).unwrap())),
1821            ),
1822        ];
1823
1824        for (input, expected) in tests {
1825            let result = convert_string_to_number(&input);
1826            assert_eq!(result, expected);
1827        }
1828    }
1829
1830    #[test]
1831    fn test_convert_string_to_boolean() {
1832        let tests = vec![
1833            (
1834                JsonValue::String("true".to_string()),
1835                Some(JsonValue::Bool(true)),
1836            ),
1837            (
1838                JsonValue::String("false".to_string()),
1839                Some(JsonValue::Bool(false)),
1840            ),
1841        ];
1842
1843        for (input, expected) in tests {
1844            let result = convert_string_to_boolean(&input);
1845            assert_eq!(result, expected);
1846        }
1847    }
1848}