1use 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#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
22#[serde(rename_all = "camelCase")]
23pub struct SkyWalkingService {
24 pub id: String,
26 pub name: String,
28 pub group: String,
30 pub short_name: String,
32 pub layers: Vec<String>,
34 pub normal: bool,
36}
37
38#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
40pub struct SkyWalkingEndpoint {
41 pub id: String,
43 pub name: String,
45}
46
47#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
49pub struct InstanceAttribute {
50 pub name: String,
52 pub value: String,
54}
55
56#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
58#[serde(rename_all = "camelCase")]
59pub struct SkyWalkingInstance {
60 pub id: String,
62 pub name: String,
64 pub language: String,
66 #[serde(rename = "instanceUUID")]
68 pub instance_uuid: String,
69 pub attributes: Vec<InstanceAttribute>,
71}
72
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub struct Paging {
76 pub page_num: usize,
78 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
117pub enum TraceState {
118 #[default]
120 All,
121 Success,
123 Error,
125}
126
127impl TraceState {
128 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
140pub enum TraceOrder {
141 #[default]
143 ByStartTime,
144 ByDuration,
146}
147
148impl TraceOrder {
149 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
160pub enum LogOrder {
161 #[default]
163 Des,
164 Asc,
166}
167
168impl LogOrder {
169 pub fn as_str(self) -> &'static str {
171 match self {
172 LogOrder::Des => "DES",
173 LogOrder::Asc => "ASC",
174 }
175 }
176}
177
178#[derive(Debug, Clone, Default, PartialEq)]
180pub struct QueryTracesOptions {
181 pub service: Option<String>,
183 pub instance: Option<String>,
185 pub endpoint: Option<String>,
187 pub trace_id: Option<String>,
189 pub trace_state: TraceState,
191 pub min_duration_ms: Option<u64>,
193 pub max_duration_ms: Option<u64>,
195 pub tags: BTreeMap<String, String>,
197 pub range: Option<TimeRange>,
199 pub paging: Paging,
201 pub order: TraceOrder,
203}
204
205impl QueryTracesOptions {
206 pub fn service(service: impl Into<String>) -> Self {
208 QueryTracesOptions {
209 service: Some(service.into()),
210 ..Default::default()
211 }
212 }
213 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 pub fn range(mut self, range: TimeRange) -> Self {
220 self.range = Some(range);
221 self
222 }
223 pub fn trace_state(mut self, state: TraceState) -> Self {
225 self.trace_state = state;
226 self
227 }
228}
229
230#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
232#[serde(rename_all = "camelCase")]
233pub struct QueryTracesResult {
234 pub traces: Vec<NativeTrace>,
236 pub retrieved_time_range: Option<(i64, i64)>,
238}
239
240#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
242#[serde(rename_all = "camelCase")]
243pub struct NativeLog {
244 pub service_name: String,
246 pub service_id: String,
248 pub service_instance_name: String,
250 pub endpoint_name: String,
252 pub trace_id: String,
254 pub timestamp: i64,
256 pub content_type: String,
258 pub content: String,
260 pub tags: Vec<KeyValue>,
262}
263
264impl NativeLog {
265 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#[derive(Debug, Clone, Default, PartialEq)]
276pub struct QueryLogsOptions {
277 pub service: Option<String>,
279 pub instance: Option<String>,
281 pub endpoint: Option<String>,
283 pub trace_id: Option<String>,
285 pub segment_id: Option<String>,
287 pub span_id: Option<i64>,
289 pub keywords: Vec<String>,
293 pub excluding_keywords: Vec<String>,
295 pub tags: BTreeMap<String, String>,
297 pub range: Option<TimeRange>,
299 pub paging: Paging,
301 pub order: LogOrder,
303}
304
305impl QueryLogsOptions {
306 pub fn service(service: impl Into<String>) -> Self {
308 QueryLogsOptions {
309 service: Some(service.into()),
310 ..Default::default()
311 }
312 }
313 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 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 pub fn range(mut self, range: TimeRange) -> Self {
327 self.range = Some(range);
328 self
329 }
330}
331
332#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
334#[serde(rename_all = "camelCase")]
335pub struct QueryLogsResult {
336 pub logs: Vec<NativeLog>,
338 pub error_reason: Option<String>,
340}
341
342#[derive(Debug, Clone, Default, PartialEq, Eq)]
344pub struct TopologyOptions {
345 pub service: Option<String>,
347 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
366pub 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#[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 pub async fn graphql(&self, query: &str, variables: Value) -> Result<GraphQLResponse> {
453 self.api.graphql(query, variables, "graphql").await
454 }
455
456 pub async fn time_info(&self) -> Result<TimeInfo> {
458 self.api.time_info("query.timeInfo").await
459 }
460
461 pub async fn capabilities(&self) -> Result<SkyWalkingCapabilities> {
463 self.api.capabilities("query.capabilities").await
464 }
465
466 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 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 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 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 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 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 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 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 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}