Skip to main content

grow_apache_skywalking/
query.rs

1// Service code (Apache SkyWalking): `SkyWalkingQueryClient`, the OAP GraphQL query API.
2//! `SkyWalkingQueryClient` — the OAP GraphQL query API (`POST /graphql` on port 12800):
3//! metadata, native traces, logs, topology and raw GraphQL. Services, instances and endpoints
4//! are named by their names; the SDK derives the ids (`base64(name).1`).
5
6use std::collections::BTreeMap;
7use std::sync::Arc;
8
9use serde::{Deserialize, Serialize};
10use serde_json::{json, Map, Value};
11
12use crate::api::{Api, GraphQLResponse, SkyWalkingCapabilities, TimeInfo};
13use crate::core::{Error, Result};
14use crate::duration::{endpoint_id, instance_id, service_id, TimeRange};
15use crate::native::{
16    decode_topology, i64_of, key_values, native_trace_from_spans, objects, str_of, strings,
17    KeyValue, NativeTrace, Topology, NATIVE_SPAN_FIELDS,
18};
19
20/// A service known to OAP (native agents, native logs, OTLP logs).
21#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
22#[serde(rename_all = "camelCase")]
23pub struct SkyWalkingService {
24    /// `base64(name) + ".1"` for real services.
25    pub id: String,
26    /// Name.
27    pub name: String,
28    /// Group.
29    pub group: String,
30    /// Short name.
31    pub short_name: String,
32    /// Layers (e.g. `GENERAL`).
33    pub layers: Vec<String>,
34    /// `false` for virtual (conjectured) services.
35    pub normal: bool,
36}
37
38/// An endpoint (operation) of a service.
39#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
40pub struct SkyWalkingEndpoint {
41    /// Endpoint id.
42    pub id: String,
43    /// Endpoint name.
44    pub name: String,
45}
46
47/// An attribute of a service instance.
48#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
49pub struct InstanceAttribute {
50    /// Name.
51    pub name: String,
52    /// Value.
53    pub value: String,
54}
55
56/// A service instance.
57#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
58#[serde(rename_all = "camelCase")]
59pub struct SkyWalkingInstance {
60    /// Instance id.
61    pub id: String,
62    /// Instance name.
63    pub name: String,
64    /// Language reported by the agent.
65    pub language: String,
66    /// Instance UUID.
67    #[serde(rename = "instanceUUID")]
68    pub instance_uuid: String,
69    /// Attributes.
70    pub attributes: Vec<InstanceAttribute>,
71}
72
73/// 1-based page selection.
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub struct Paging {
76    /// Page number (default 1).
77    pub page_num: usize,
78    /// Page size (default 20, at most 10000).
79    pub page_size: usize,
80}
81
82impl Default for Paging {
83    fn default() -> Self {
84        Paging {
85            page_num: 1,
86            page_size: 20,
87        }
88    }
89}
90
91impl Paging {
92    /// A page.
93    pub fn new(page_num: usize, page_size: usize) -> Self {
94        Paging {
95            page_num,
96            page_size,
97        }
98    }
99
100    fn to_json(self, operation: &str) -> Result<Value> {
101        if self.page_num < 1 {
102            return Err(Error::validation(format!(
103                "{operation}: pageNum must be a positive integer"
104            )));
105        }
106        if self.page_size < 1 || self.page_size > 10_000 {
107            return Err(Error::validation(format!(
108                "{operation}: pageSize must be 1..10000"
109            )));
110        }
111        Ok(json!({ "pageNum": self.page_num, "pageSize": self.page_size }))
112    }
113}
114
115/// Trace state filter of [`SkyWalkingQueryClient::query_traces`].
116#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
117pub enum TraceState {
118    /// Every trace (default).
119    #[default]
120    All,
121    /// Successful traces.
122    Success,
123    /// Traces with an error.
124    Error,
125}
126
127impl TraceState {
128    /// Wire value.
129    pub fn as_str(self) -> &'static str {
130        match self {
131            TraceState::All => "ALL",
132            TraceState::Success => "SUCCESS",
133            TraceState::Error => "ERROR",
134        }
135    }
136}
137
138/// Order of [`SkyWalkingQueryClient::query_traces`].
139#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
140pub enum TraceOrder {
141    /// Newest first (default).
142    #[default]
143    ByStartTime,
144    /// Longest first.
145    ByDuration,
146}
147
148impl TraceOrder {
149    /// Wire value.
150    pub fn as_str(self) -> &'static str {
151        match self {
152            TraceOrder::ByStartTime => "BY_START_TIME",
153            TraceOrder::ByDuration => "BY_DURATION",
154        }
155    }
156}
157
158/// Order of [`SkyWalkingQueryClient::query_logs`].
159#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
160pub enum LogOrder {
161    /// Newest first (default).
162    #[default]
163    Des,
164    /// Oldest first.
165    Asc,
166}
167
168impl LogOrder {
169    /// Wire value.
170    pub fn as_str(self) -> &'static str {
171        match self {
172            LogOrder::Des => "DES",
173            LogOrder::Asc => "ASC",
174        }
175    }
176}
177
178/// Filter of [`SkyWalkingQueryClient::query_traces`] (native traces).
179#[derive(Debug, Clone, Default, PartialEq)]
180pub struct QueryTracesOptions {
181    /// Service name.
182    pub service: Option<String>,
183    /// Instance name (needs `service`).
184    pub instance: Option<String>,
185    /// Endpoint name (needs `service`).
186    pub endpoint: Option<String>,
187    /// Native trace id.
188    pub trace_id: Option<String>,
189    /// Trace state (default `ALL`).
190    pub trace_state: TraceState,
191    /// Minimum trace duration in ms.
192    pub min_duration_ms: Option<u64>,
193    /// Maximum trace duration in ms.
194    pub max_duration_ms: Option<u64>,
195    /// Tag matches; only keys in the server's `SW_SEARCHABLE_TAG_KEYS` can match.
196    pub tags: BTreeMap<String, String>,
197    /// Window (default: last hour; omitted when only `trace_id` is given).
198    pub range: Option<TimeRange>,
199    /// Page (default 1 × 20).
200    pub paging: Paging,
201    /// Order (default `BY_START_TIME`).
202    pub order: TraceOrder,
203}
204
205impl QueryTracesOptions {
206    /// Filter on a service.
207    pub fn service(service: impl Into<String>) -> Self {
208        QueryTracesOptions {
209            service: Some(service.into()),
210            ..Default::default()
211        }
212    }
213    /// Adds a tag match.
214    pub fn tag(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
215        self.tags.insert(key.into(), value.into());
216        self
217    }
218    /// Sets the window.
219    pub fn range(mut self, range: TimeRange) -> Self {
220        self.range = Some(range);
221        self
222    }
223    /// Sets the trace state.
224    pub fn trace_state(mut self, state: TraceState) -> Self {
225        self.trace_state = state;
226        self
227    }
228}
229
230/// Result of [`SkyWalkingQueryClient::query_traces`].
231#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
232#[serde(rename_all = "camelCase")]
233pub struct QueryTracesResult {
234    /// Whole traces (every segment) that match.
235    pub traces: Vec<NativeTrace>,
236    /// Window the server searched, epoch ms `(start, end)`, when reported.
237    pub retrieved_time_range: Option<(i64, i64)>,
238}
239
240/// A log entry as stored by OAP.
241#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
242#[serde(rename_all = "camelCase")]
243pub struct NativeLog {
244    /// Service name.
245    pub service_name: String,
246    /// Service id.
247    pub service_id: String,
248    /// Instance name.
249    pub service_instance_name: String,
250    /// Endpoint name.
251    pub endpoint_name: String,
252    /// Native or hex trace id; `""` when the log has no trace context.
253    pub trace_id: String,
254    /// Epoch milliseconds.
255    pub timestamp: i64,
256    /// `TEXT`, `JSON` or `YAML`.
257    pub content_type: String,
258    /// Content.
259    pub content: String,
260    /// Tags.
261    pub tags: Vec<KeyValue>,
262}
263
264impl NativeLog {
265    /// Value of the first tag named `key`.
266    pub fn tag(&self, key: &str) -> Option<&str> {
267        self.tags
268            .iter()
269            .find(|t| t.key == key)
270            .map(|t| t.value.as_str())
271    }
272}
273
274/// Filter of [`SkyWalkingQueryClient::query_logs`].
275#[derive(Debug, Clone, Default, PartialEq)]
276pub struct QueryLogsOptions {
277    /// Service name.
278    pub service: Option<String>,
279    /// Instance name (needs `service`).
280    pub instance: Option<String>,
281    /// Endpoint name (needs `service`).
282    pub endpoint: Option<String>,
283    /// Logs related to this trace (native or hex id).
284    pub trace_id: Option<String>,
285    /// With `trace_id`: the segment.
286    pub segment_id: Option<String>,
287    /// With `segment_id`: the span.
288    pub span_id: Option<i64>,
289    /// Words the content must contain. Sent to the server when it supports keyword search
290    /// (Elasticsearch storage); on BanyanDB the returned page is filtered client side
291    /// (case-insensitive substring).
292    pub keywords: Vec<String>,
293    /// Words the content must not contain (same rules as `keywords`).
294    pub excluding_keywords: Vec<String>,
295    /// Tag matches; only keys in `SW_SEARCHABLE_LOGS_TAG_KEYS` can match.
296    pub tags: BTreeMap<String, String>,
297    /// Window (default last hour; omitted when only `trace_id` is given).
298    pub range: Option<TimeRange>,
299    /// Page (default 1 × 20).
300    pub paging: Paging,
301    /// Order (default `DES`, newest first).
302    pub order: LogOrder,
303}
304
305impl QueryLogsOptions {
306    /// Filter on a service.
307    pub fn service(service: impl Into<String>) -> Self {
308        QueryLogsOptions {
309            service: Some(service.into()),
310            ..Default::default()
311        }
312    }
313    /// Filter on a related trace.
314    pub fn trace_id(trace_id: impl Into<String>) -> Self {
315        QueryLogsOptions {
316            trace_id: Some(trace_id.into()),
317            ..Default::default()
318        }
319    }
320    /// Adds a tag match.
321    pub fn tag(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
322        self.tags.insert(key.into(), value.into());
323        self
324    }
325    /// Sets the window.
326    pub fn range(mut self, range: TimeRange) -> Self {
327        self.range = Some(range);
328        self
329    }
330}
331
332/// Result of [`SkyWalkingQueryClient::query_logs`].
333#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
334#[serde(rename_all = "camelCase")]
335pub struct QueryLogsResult {
336    /// Logs of the page (after client-side keyword filtering).
337    pub logs: Vec<NativeLog>,
338    /// Server-side explanation when the query could not run as asked.
339    pub error_reason: Option<String>,
340}
341
342/// Options of [`SkyWalkingQueryClient::topology`].
343#[derive(Debug, Clone, Default, PartialEq, Eq)]
344pub struct TopologyOptions {
345    /// Only this service's neighbourhood (`getServiceTopology`).
346    pub service: Option<String>,
347    /// Only this layer (global topology).
348    pub layer: Option<String>,
349}
350
351const SERVICE_FIELDS: &str = "id name group shortName layers normal";
352const LOG_FIELDS: &str = "serviceName serviceId serviceInstanceName endpointName traceId timestamp contentType content tags{key value}";
353const TOPOLOGY_FIELDS: &str = "nodes{id name type isReal layers} calls{id source target detectPoints sourceComponents targetComponents}";
354
355fn decode_service(s: &Value) -> SkyWalkingService {
356    SkyWalkingService {
357        id: str_of(s, "id"),
358        name: str_of(s, "name"),
359        group: str_of(s, "group"),
360        short_name: str_of(s, "shortName"),
361        layers: strings(s.get("layers")),
362        normal: s.get("normal") != Some(&Value::Bool(false)),
363    }
364}
365
366/// Decodes one native log.
367pub fn decode_native_log(l: &Value) -> NativeLog {
368    NativeLog {
369        service_name: str_of(l, "serviceName"),
370        service_id: str_of(l, "serviceId"),
371        service_instance_name: str_of(l, "serviceInstanceName"),
372        endpoint_name: str_of(l, "endpointName"),
373        trace_id: str_of(l, "traceId"),
374        timestamp: i64_of(l, "timestamp", 0),
375        content_type: str_of(l, "contentType"),
376        content: str_of(l, "content"),
377        tags: key_values(l.get("tags")),
378    }
379}
380
381fn required<'a>(value: &'a str, what: &str, operation: &str) -> Result<&'a str> {
382    if value.trim().is_empty() {
383        return Err(Error::validation(format!(
384            "{operation}: {what} is required"
385        )));
386    }
387    Ok(value)
388}
389
390fn tag_list(tags: &BTreeMap<String, String>) -> Option<Value> {
391    (!tags.is_empty()).then(|| {
392        Value::Array(
393            tags.iter()
394                .map(|(k, v)| json!({ "key": k, "value": v }))
395                .collect(),
396        )
397    })
398}
399
400fn scoped_ids(
401    service: Option<&str>,
402    instance: Option<&str>,
403    endpoint: Option<&str>,
404    operation: &str,
405    out: &mut Map<String, Value>,
406) -> Result<()> {
407    let Some(service) = service else {
408        if instance.is_some() || endpoint.is_some() {
409            return Err(Error::validation(format!(
410                "{operation}: instance and endpoint need service"
411            )));
412        }
413        return Ok(());
414    };
415    out.insert(
416        "serviceId".into(),
417        service_id(required(service, "service", operation)?).into(),
418    );
419    if let Some(i) = instance {
420        out.insert("serviceInstanceId".into(), instance_id(service, i).into());
421    }
422    if let Some(e) = endpoint {
423        out.insert("endpointId".into(), endpoint_id(service, e).into());
424    }
425    Ok(())
426}
427
428fn contains_all(text: &str, words: &[String]) -> bool {
429    let lower = text.to_lowercase();
430    words.iter().all(|w| lower.contains(&w.to_lowercase()))
431}
432
433fn contains_none(text: &str, words: &[String]) -> bool {
434    let lower = text.to_lowercase();
435    words.iter().all(|w| !lower.contains(&w.to_lowercase()))
436}
437
438/// The SkyWalking GraphQL query API (`POST /graphql` on port 12800). Obtain it from
439/// [`SkyWalkingClient::query`](crate::SkyWalkingClient::query). Cheap to clone.
440#[derive(Debug, Clone)]
441pub struct SkyWalkingQueryClient {
442    api: Arc<Api>,
443}
444
445impl SkyWalkingQueryClient {
446    pub(crate) fn new(api: Arc<Api>) -> Self {
447        SkyWalkingQueryClient { api }
448    }
449
450    /// Raw GraphQL: returns `{data, errors}` (partial data possible). HTTP 400 (syntax or
451    /// validation errors) fails with `VALIDATION`.
452    pub async fn graphql(&self, query: &str, variables: Value) -> Result<GraphQLResponse> {
453        self.api.graphql(query, variables, "graphql").await
454    }
455
456    /// OAP clock and timezone: `getTimeInfo`.
457    pub async fn time_info(&self) -> Result<TimeInfo> {
458        self.api.time_info("query.timeInfo").await
459    }
460
461    /// Server features (`hasQueryTracesV2Support`, `supportQueryLogsByKeywords`), cached.
462    pub async fn capabilities(&self) -> Result<SkyWalkingCapabilities> {
463        self.api.capabilities("query.capabilities").await
464    }
465
466    /// Services: `listServices(layer)`. `None` = all layers; an unknown layer → empty.
467    /// OAP has no time filter for services, so `range` is accepted for API symmetry and ignored.
468    /// Services that only sent OTLP **traces** are not listed (use the trace query client).
469    pub async fn list_services(
470        &self,
471        layer: Option<&str>,
472        range: Option<TimeRange>,
473    ) -> Result<Vec<SkyWalkingService>> {
474        let _ = range;
475        let rows = self
476            .api
477            .field(
478                &format!("query($l:String){{listServices(layer:$l){{{SERVICE_FIELDS}}}}}"),
479                json!({ "l": layer }),
480                "listServices",
481                "query.listServices",
482            )
483            .await?;
484        Ok(objects(Some(&rows)).map(decode_service).collect())
485    }
486
487    /// One service by name: `findService`; `None` when unknown.
488    pub async fn find_service(&self, name: &str) -> Result<Option<SkyWalkingService>> {
489        let operation = "query.findService";
490        let row = self
491            .api
492            .field(
493                &format!("query($n:String!){{findService(serviceName:$n){{{SERVICE_FIELDS}}}}}"),
494                json!({ "n": required(name, "name", operation)? }),
495                "findService",
496                operation,
497            )
498            .await?;
499        Ok(row.is_object().then(|| decode_service(&row)))
500    }
501
502    /// Endpoints of a service: `findEndpoint(keyword, serviceId, limit)` (default limit 100).
503    /// `keyword` is a tokenised match (`downstream` finds `/native/downstream`, `down` does
504    /// not). No duration is sent (OAP 10.4 + BanyanDB returns nothing with one).
505    pub async fn list_endpoints(
506        &self,
507        service: &str,
508        keyword: Option<&str>,
509        limit: Option<usize>,
510    ) -> Result<Vec<SkyWalkingEndpoint>> {
511        let operation = "query.listEndpoints";
512        let limit = limit.unwrap_or(100);
513        if limit < 1 {
514            return Err(Error::validation(format!(
515                "{operation}: limit must be a positive integer"
516            )));
517        }
518        let rows = self
519            .api
520            .field(
521                "query($k:String,$s:ID!,$l:Int!){findEndpoint(keyword:$k,serviceId:$s,limit:$l){id name}}",
522                json!({
523                    "k": keyword.filter(|k| !k.is_empty()),
524                    "s": service_id(required(service, "service", operation)?),
525                    "l": limit,
526                }),
527                "findEndpoint",
528                operation,
529            )
530            .await?;
531        Ok(objects(Some(&rows))
532            .map(|e| SkyWalkingEndpoint {
533                id: str_of(e, "id"),
534                name: str_of(e, "name"),
535            })
536            .collect())
537    }
538
539    /// Instances of a service active in `range` (default last hour): `listInstances`.
540    pub async fn list_instances(
541        &self,
542        service: &str,
543        range: Option<TimeRange>,
544    ) -> Result<Vec<SkyWalkingInstance>> {
545        let operation = "query.listInstances";
546        let id = service_id(required(service, "service", operation)?);
547        let duration = self
548            .api
549            .duration(&range.unwrap_or_default(), operation)
550            .await?;
551        let rows = self
552            .api
553            .field(
554                "query($s:ID!,$d:Duration!){listInstances(serviceId:$s,duration:$d){id name language instanceUUID attributes{name value}}}",
555                json!({ "s": id, "d": duration }),
556                "listInstances",
557                operation,
558            )
559            .await?;
560        Ok(objects(Some(&rows))
561            .map(|i| SkyWalkingInstance {
562                id: str_of(i, "id"),
563                name: str_of(i, "name"),
564                language: str_of(i, "language"),
565                instance_uuid: str_of(i, "instanceUUID"),
566                attributes: objects(i.get("attributes"))
567                    .map(|a| InstanceAttribute {
568                        name: str_of(a, "name"),
569                        value: str_of(a, "value"),
570                    })
571                    .collect(),
572            })
573            .collect())
574    }
575
576    /// Native traces: `queryTraces(condition)` (whole traces). Durations in ms; tags must be
577    /// searchable keys. The legacy `queryBasicTraces` is not used (unsupported on BanyanDB).
578    pub async fn query_traces(&self, opts: &QueryTracesOptions) -> Result<QueryTracesResult> {
579        let operation = "query.queryTraces";
580        let mut c = Map::new();
581        scoped_ids(
582            opts.service.as_deref(),
583            opts.instance.as_deref(),
584            opts.endpoint.as_deref(),
585            operation,
586            &mut c,
587        )?;
588        c.insert("traceState".into(), opts.trace_state.as_str().into());
589        c.insert("queryOrder".into(), opts.order.as_str().into());
590        c.insert("paging".into(), opts.paging.to_json(operation)?);
591        if let Some(v) = opts.min_duration_ms {
592            c.insert("minTraceDuration".into(), v.into());
593        }
594        if let Some(v) = opts.max_duration_ms {
595            c.insert("maxTraceDuration".into(), v.into());
596        }
597        if let Some(id) = &opts.trace_id {
598            c.insert("traceId".into(), required(id, "traceId", operation)?.into());
599        }
600        if let Some(tags) = tag_list(&opts.tags) {
601            c.insert("tags".into(), tags);
602        }
603        if opts.trace_id.is_none() || opts.range.is_some() {
604            let d = self
605                .api
606                .duration(&opts.range.unwrap_or_default(), operation)
607                .await?;
608            c.insert("queryDuration".into(), serde_json::to_value(d)?);
609        }
610        let res = self
611            .api
612            .field(
613                &format!("query($c:TraceQueryCondition){{queryTraces(condition:$c){{traces{{spans{{{NATIVE_SPAN_FIELDS}}}}} retrievedTimeRange{{startTime endTime}}}}}}"),
614                json!({ "c": c }),
615                "queryTraces",
616                operation,
617            )
618            .await?;
619        let traces = objects(res.get("traces"))
620            .filter_map(|t| native_trace_from_spans(t.get("spans")))
621            .collect();
622        let retrieved_time_range = res
623            .get("retrievedTimeRange")
624            .and_then(|r| Some((r.get("startTime")?.as_i64()?, r.get("endTime")?.as_i64()?)));
625        Ok(QueryTracesResult {
626            traces,
627            retrieved_time_range,
628        })
629    }
630
631    /// One native trace: `queryTrace(traceId)`; `None` when unknown (OTLP trace ids are never
632    /// native).
633    pub async fn get_trace(&self, trace_id: &str) -> Result<Option<NativeTrace>> {
634        let operation = "query.getTrace";
635        let res = self
636            .api
637            .field(
638                &format!(
639                    "query($id:ID!){{queryTrace(traceId:$id){{spans{{{NATIVE_SPAN_FIELDS}}}}}}}"
640                ),
641                json!({ "id": required(trace_id, "traceId", operation)? }),
642                "queryTrace",
643                operation,
644            )
645            .await?;
646        Ok(native_trace_from_spans(res.get("spans")))
647    }
648
649    /// Logs: `queryLogs(condition)`. Either a window (default last hour) or `trace_id` is sent;
650    /// see [`QueryLogsOptions::keywords`] for keyword handling on BanyanDB.
651    pub async fn query_logs(&self, opts: &QueryLogsOptions) -> Result<QueryLogsResult> {
652        let operation = "query.queryLogs";
653        let mut c = Map::new();
654        scoped_ids(
655            opts.service.as_deref(),
656            opts.instance.as_deref(),
657            opts.endpoint.as_deref(),
658            operation,
659            &mut c,
660        )?;
661        c.insert("paging".into(), opts.paging.to_json(operation)?);
662        c.insert("queryOrder".into(), opts.order.as_str().into());
663        if let Some(id) = &opts.trace_id {
664            let mut related = Map::new();
665            related.insert("traceId".into(), required(id, "traceId", operation)?.into());
666            if let Some(s) = &opts.segment_id {
667                related.insert("segmentId".into(), s.clone().into());
668            }
669            if let Some(s) = opts.span_id {
670                related.insert("spanId".into(), s.into());
671            }
672            c.insert("relatedTrace".into(), related.into());
673        }
674        if let Some(tags) = tag_list(&opts.tags) {
675            c.insert("tags".into(), tags);
676        }
677        let mut server_keywords = false;
678        if !opts.keywords.is_empty() || !opts.excluding_keywords.is_empty() {
679            server_keywords = self.api.capabilities(operation).await?.logs_by_keywords;
680            if server_keywords {
681                if !opts.keywords.is_empty() {
682                    c.insert("keywordsOfContent".into(), json!(opts.keywords));
683                }
684                if !opts.excluding_keywords.is_empty() {
685                    c.insert(
686                        "excludingKeywordsOfContent".into(),
687                        json!(opts.excluding_keywords),
688                    );
689                }
690            }
691        }
692        if opts.trace_id.is_none() || opts.range.is_some() {
693            let d = self
694                .api
695                .duration(&opts.range.unwrap_or_default(), operation)
696                .await?;
697            c.insert("queryDuration".into(), serde_json::to_value(d)?);
698        }
699        let res = self
700            .api
701            .field(
702                &format!("query($c:LogQueryCondition){{queryLogs(condition:$c){{errorReason logs{{{LOG_FIELDS}}}}}}}"),
703                json!({ "c": c }),
704                "queryLogs",
705                operation,
706            )
707            .await?;
708        let mut logs: Vec<NativeLog> = objects(res.get("logs")).map(decode_native_log).collect();
709        if !server_keywords {
710            logs.retain(|l| {
711                contains_all(&l.content, &opts.keywords)
712                    && contains_none(&l.content, &opts.excluding_keywords)
713            });
714        }
715        Ok(QueryLogsResult {
716            logs,
717            error_reason: res
718                .get("errorReason")
719                .and_then(Value::as_str)
720                .filter(|s| !s.is_empty())
721                .map(str::to_owned),
722        })
723    }
724
725    /// Log tag keys seen in `range` (default last hour): `queryLogTagAutocompleteKeys`, sorted.
726    pub async fn list_log_tag_keys(&self, range: Option<TimeRange>) -> Result<Vec<String>> {
727        let operation = "query.listLogTagKeys";
728        let d = self
729            .api
730            .duration(&range.unwrap_or_default(), operation)
731            .await?;
732        let keys = self
733            .api
734            .field(
735                "query($d:Duration!){queryLogTagAutocompleteKeys(duration:$d)}",
736                json!({ "d": d }),
737                "queryLogTagAutocompleteKeys",
738                operation,
739            )
740            .await?;
741        let mut out = strings(Some(&keys));
742        out.sort();
743        Ok(out)
744    }
745
746    /// Service topology in `range` (default last hour): `getGlobalTopology(duration, layer)`,
747    /// or `getServiceTopology` when `opts.service` is set. Native traffic only (OTLP spans
748    /// create no edges); includes the virtual `User` node.
749    pub async fn topology(
750        &self,
751        range: Option<TimeRange>,
752        opts: &TopologyOptions,
753    ) -> Result<Topology> {
754        let operation = "query.topology";
755        let d = self
756            .api
757            .duration(&range.unwrap_or_default(), operation)
758            .await?;
759        let res = match &opts.service {
760            Some(service) => {
761                self.api
762                    .field(
763                        &format!("query($s:ID!,$d:Duration!){{getServiceTopology(serviceId:$s,duration:$d){{{TOPOLOGY_FIELDS}}}}}"),
764                        json!({ "s": service_id(required(service, "service", operation)?), "d": d }),
765                        "getServiceTopology",
766                        operation,
767                    )
768                    .await?
769            }
770            None => {
771                self.api
772                    .field(
773                        &format!("query($d:Duration!,$l:String){{getGlobalTopology(duration:$d,layer:$l){{{TOPOLOGY_FIELDS}}}}}"),
774                        json!({ "d": d, "l": opts.layer }),
775                        "getGlobalTopology",
776                        operation,
777                    )
778                    .await?
779            }
780        };
781        Ok(decode_topology(&res))
782    }
783}