1use std::sync::Mutex;
6use std::time::SystemTime;
7
8use serde::{Deserialize, Serialize};
9use serde_json::{json, Value};
10
11use crate::config::SkyWalkingConfig;
12use crate::core::redact::truncate;
13use crate::core::transport::MAX_VENDOR_MESSAGE;
14use crate::core::{Error, HttpTransport, Response, Result};
15use crate::duration::{
16 parse_timezone, resolve_range, to_graphql_duration, GraphQLDuration, TimeRange,
17};
18
19#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
21pub struct GraphQLErrorInfo {
22 pub message: String,
24 pub path: Vec<Value>,
26 pub classification: Option<String>,
28}
29
30#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
32pub struct GraphQLResponse {
33 pub data: Option<Value>,
35 pub errors: Vec<GraphQLErrorInfo>,
37}
38
39impl GraphQLResponse {
40 pub fn field(&self, field: &str) -> Option<&Value> {
42 self.data
43 .as_ref()
44 .and_then(|d| d.get(field))
45 .filter(|v| !v.is_null())
46 }
47}
48
49#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
52pub struct SkyWalkingCapabilities {
53 pub query_traces_v2: bool,
55 pub logs_by_keywords: bool,
57}
58
59#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
61pub struct TimeInfo {
62 pub timezone: String,
64 pub current_timestamp: i64,
66}
67
68pub fn graphql_errors(body: &Value) -> Vec<GraphQLErrorInfo> {
70 body.get("errors")
71 .and_then(Value::as_array)
72 .map(|errors| {
73 errors
74 .iter()
75 .filter(|e| e.is_object())
76 .map(|e| GraphQLErrorInfo {
77 message: e
78 .get("message")
79 .and_then(Value::as_str)
80 .unwrap_or("")
81 .to_owned(),
82 path: e
83 .get("path")
84 .and_then(Value::as_array)
85 .cloned()
86 .unwrap_or_default(),
87 classification: e
88 .get("extensions")
89 .and_then(|x| x.get("classification"))
90 .and_then(Value::as_str)
91 .map(str::to_owned),
92 })
93 .collect()
94 })
95 .unwrap_or_default()
96}
97
98pub fn graphql_error(
102 operation: &str,
103 errors: &[GraphQLErrorInfo],
104 redact: impl Fn(&str) -> String,
105) -> Error {
106 let raw = errors
107 .iter()
108 .map(|e| e.message.as_str())
109 .find(|m| !m.is_empty())
110 .unwrap_or("GraphQL error");
111 let collapsed = raw.split_whitespace().collect::<Vec<_>>().join(" ");
112 let text = truncate(&redact(&collapsed), MAX_VENDOR_MESSAGE);
113 if raw.contains("UnsupportedOperationException") {
114 Error::unsupported(format!("{operation}: {text}"))
115 } else {
116 Error::validation(format!("{operation}: {text}"))
117 }
118}
119
120fn is_mutation(query: &str) -> bool {
121 let t = query.trim_start();
122 t.starts_with("mutation")
123 && !t[8..]
124 .chars()
125 .next()
126 .is_some_and(|c| c.is_alphanumeric() || c == '_')
127}
128
129#[derive(Debug)]
131pub(crate) struct Api {
132 pub(crate) transport: HttpTransport,
133 pub(crate) config: SkyWalkingConfig,
134 offset: Mutex<Option<i32>>,
135 capabilities: Mutex<Option<SkyWalkingCapabilities>>,
136}
137
138impl Api {
139 pub(crate) fn new(config: SkyWalkingConfig) -> Result<Self> {
140 let transport = HttpTransport::new(config.common())?;
141 for secret in config.known_secrets() {
142 transport.add_known_secret(&secret);
143 }
144 Ok(Api {
145 transport,
146 config,
147 offset: Mutex::new(None),
148 capabilities: Mutex::new(None),
149 })
150 }
151
152 pub(crate) async fn graphql(
156 &self,
157 query: &str,
158 variables: Value,
159 operation: &str,
160 ) -> Result<GraphQLResponse> {
161 if query.trim().is_empty() {
162 return Err(Error::validation(format!("{operation}: query is required")));
163 }
164 let variables = if variables.is_null() {
165 json!({})
166 } else {
167 variables
168 };
169 let resp = self
170 .transport
171 .post(self.config.graphql_path())
172 .operation(operation)
173 .idempotent(!is_mutation(query))
174 .json(&json!({ "query": query, "variables": variables }))
175 .send()
176 .await?;
177 let body: Value = resp.json().map_err(|_| {
178 Error::validation(format!("{operation}: the response is not GraphQL JSON"))
179 })?;
180 Ok(GraphQLResponse {
181 data: body.get("data").filter(|d| d.is_object()).cloned(),
182 errors: graphql_errors(&body),
183 })
184 }
185
186 pub(crate) async fn field(
188 &self,
189 query: &str,
190 variables: Value,
191 field: &str,
192 operation: &str,
193 ) -> Result<Value> {
194 let res = self.graphql(query, variables, operation).await?;
195 if !res.errors.is_empty() {
196 return Err(graphql_error(operation, &res.errors, |t| {
197 self.transport.redact(t)
198 }));
199 }
200 Ok(res.field(field).cloned().unwrap_or(Value::Null))
201 }
202
203 pub(crate) async fn time_info(&self, operation: &str) -> Result<TimeInfo> {
205 let info = self
206 .field(
207 "{getTimeInfo{timezone currentTimestamp}}",
208 Value::Null,
209 "getTimeInfo",
210 operation,
211 )
212 .await?;
213 let timezone = info
214 .get("timezone")
215 .and_then(Value::as_str)
216 .unwrap_or("+0000")
217 .to_owned();
218 let current_timestamp = info
219 .get("currentTimestamp")
220 .and_then(Value::as_i64)
221 .unwrap_or_else(|| crate::duration::epoch_ms(SystemTime::now()));
222 let mut offset = self.offset.lock().unwrap_or_else(|e| e.into_inner());
223 if offset.is_none() {
224 *offset = Some(parse_timezone(&timezone));
225 }
226 Ok(TimeInfo {
227 timezone,
228 current_timestamp,
229 })
230 }
231
232 pub(crate) async fn offset_minutes(&self, operation: &str) -> Result<i32> {
234 if let Some(v) = *self.offset.lock().unwrap_or_else(|e| e.into_inner()) {
235 return Ok(v);
236 }
237 let info = self.time_info(operation).await?;
238 Ok(parse_timezone(&info.timezone))
239 }
240
241 pub(crate) async fn duration(
243 &self,
244 range: &TimeRange,
245 operation: &str,
246 ) -> Result<GraphQLDuration> {
247 let resolved = resolve_range(range, SystemTime::now(), operation)?;
248 Ok(to_graphql_duration(
249 &resolved,
250 self.offset_minutes(operation).await?,
251 ))
252 }
253
254 pub(crate) async fn capabilities(&self, operation: &str) -> Result<SkyWalkingCapabilities> {
256 if let Some(c) = *self.capabilities.lock().unwrap_or_else(|e| e.into_inner()) {
257 return Ok(c);
258 }
259 let res = self
260 .graphql(
261 "{hasQueryTracesV2Support supportQueryLogsByKeywords}",
262 Value::Null,
263 operation,
264 )
265 .await?;
266 let caps = SkyWalkingCapabilities {
267 query_traces_v2: res.field("hasQueryTracesV2Support") == Some(&Value::Bool(true)),
268 logs_by_keywords: res.field("supportQueryLogsByKeywords") == Some(&Value::Bool(true)),
269 };
270 *self.capabilities.lock().unwrap_or_else(|e| e.into_inner()) = Some(caps);
271 Ok(caps)
272 }
273
274 pub(crate) async fn zipkin_get(
276 &self,
277 path: &str,
278 operation: &str,
279 query: &[(&str, String)],
280 ok_404: bool,
281 ) -> Result<Response> {
282 let mut req = self
283 .transport
284 .get(&format!("{}{path}", self.config.zipkin_url()))
285 .operation(operation);
286 for (k, v) in query {
287 req = req.query(*k, v.clone());
288 }
289 if ok_404 {
290 req = req.ok_status(404);
291 }
292 req.send().await
293 }
294}
295
296#[cfg(test)]
297mod tests {
298 use super::is_mutation;
299
300 #[test]
301 fn mutation_detection() {
302 assert!(is_mutation("mutation { x }"));
303 assert!(is_mutation(" mutation($a:Int){x}"));
304 assert!(!is_mutation("mutations"));
305 assert!(!is_mutation("query{version}"));
306 assert!(!is_mutation("{version}"));
307 }
308}