1use std::io::Read;
10use std::time::Duration;
11
12use serde::{Deserialize, Serialize};
13use serde_json::Value;
14
15use crate::runtime::environment::{Credentials, Environment};
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
19pub enum Status {
20 Up,
21 Down,
22 OutOfService,
23 Unknown,
24}
25
26impl Status {
27 fn parse(text: &str) -> Self {
28 match text {
29 "UP" => Status::Up,
30 "DOWN" => Status::Down,
31 "OUT_OF_SERVICE" => Status::OutOfService,
32 _ => Status::Unknown,
33 }
34 }
35}
36
37#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39pub struct Component {
40 pub name: String,
41 pub status: Status,
42 pub details: Vec<(String, String)>,
44}
45
46#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
48pub struct Info {
49 pub environment: Option<String>,
50 pub laravel: Option<String>,
51 pub git_branch: Option<String>,
52 pub git_commit: Option<String>,
53 pub php_version: Option<String>,
54 pub php_sapi: Option<String>,
55 pub memory_usage: Option<i64>,
57 pub memory_peak: Option<i64>,
58 pub memory_limit: Option<i64>,
59}
60
61#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
63pub struct Route {
64 pub methods: Vec<String>,
65 pub uri: String,
67 pub name: Option<String>,
68 pub action: String,
70 pub middleware: Vec<String>,
71}
72
73#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
75pub struct Task {
76 pub target: String,
78 pub expression: Option<String>,
80 pub interval_ms: Option<u64>,
82 pub timezone: Option<String>,
83 pub next: Option<String>,
85 #[serde(default)]
88 pub module: Option<String>,
89}
90
91#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
93pub struct Runtime {
94 pub status: Status,
95 pub components: Option<Vec<Component>>,
97 pub exposed: Vec<String>,
99 pub info: Option<Info>,
101 pub routes: Option<Vec<Route>>,
103 pub tasks: Option<Vec<Task>>,
105}
106
107impl Runtime {
108 pub fn exposes(&self, endpoint: &str) -> bool {
110 self.exposed.iter().any(|exposed| exposed == endpoint)
111 }
112
113 pub fn not_exposed(&self) -> Vec<&'static str> {
115 ["info", "mappings", "scheduledtasks"]
116 .into_iter()
117 .filter(|endpoint| !self.exposes(endpoint))
118 .collect()
119 }
120}
121
122#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
125pub enum Answer {
126 NoAnswer {
128 url: String,
129 message: String,
130 },
131 NotAuthorized {
133 url: String,
134 status: u16,
135 },
136 Unexpected {
138 url: String,
139 status: u16,
140 location: Option<String>,
142 },
143 Answered(Box<Runtime>),
144}
145
146pub type Secret = Option<String>;
148
149pub const METRICS_BODY_LIMIT: u64 = 16 * 1024 * 1024;
151
152#[derive(Debug, Clone, PartialEq, Eq)]
154pub enum NoMetrics {
155 Off,
157 Unavailable {
159 url: String,
160 line: String,
161 },
162 TooLarge {
164 url: String,
165 limit: u64,
166 },
167 NoAnswer {
168 url: String,
169 message: String,
170 },
171 NotAuthorized {
172 url: String,
173 status: u16,
174 },
175 Unexpected {
176 url: String,
177 status: u16,
178 location: Option<String>,
179 },
180}
181
182struct Reply {
184 status: u16,
185 body: String,
186 too_large: bool,
188 location: Option<String>,
189}
190
191struct Client<'a> {
193 agent: ureq::Agent,
194 environment: &'a Environment,
195 secret: &'a Secret,
196}
197
198impl<'a> Client<'a> {
199 fn new(environment: &'a Environment, secret: &'a Secret) -> Self {
200 let config = ureq::Agent::config_builder()
201 .timeout_global(Some(TIMEOUT))
202 .http_status_as_error(false)
204 .max_redirects(0)
208 .tls_config(
211 ureq::tls::TlsConfig::builder()
212 .root_certs(ureq::tls::RootCerts::PlatformVerifier)
213 .build(),
214 )
215 .build();
216 Self {
217 agent: ureq::Agent::new_with_config(config),
218 environment,
219 secret,
220 }
221 }
222
223 fn get(&self, url: &str, limit: Option<u64>) -> Result<Reply, ureq::Error> {
227 let mut request = self.agent.get(url).header("Accept", "application/json");
229 let secret = self.secret.as_deref().unwrap_or_default();
230 match &self.environment.credentials {
231 Credentials::None => {}
232 Credentials::Bearer => {
233 request = request.header("Authorization", format!("Bearer {secret}"));
234 }
235 Credentials::Basic { user } => {
236 let pair = base64(format!("{user}:{secret}").as_bytes());
237 request = request.header("Authorization", format!("Basic {pair}"));
238 }
239 Credentials::Header { name } => request = request.header(name.as_str(), secret),
240 }
241 let mut response = request.call()?;
242 let status = response.status().as_u16();
243 let location = response
244 .headers()
245 .get("location")
246 .and_then(|value| value.to_str().ok())
247 .map(|location| resolve(url, location));
248 let (body, too_large) = match limit {
249 None => (
250 response.body_mut().read_to_string().unwrap_or_default(),
251 false,
252 ),
253 Some(_) if !matches!(status, 200 | 503) => (String::new(), false),
254 Some(limit) => {
255 let mut bytes = Vec::new();
258 response
259 .body_mut()
260 .with_config()
261 .reader()
262 .take(limit.saturating_add(1))
263 .read_to_end(&mut bytes)
264 .map_err(ureq::Error::from)?;
265 if bytes.len() as u64 > limit {
266 (String::new(), true)
267 } else {
268 (String::from_utf8_lossy(&bytes).into_owned(), false)
269 }
270 }
271 };
272 Ok(Reply {
273 status,
274 body,
275 too_large,
276 location,
277 })
278 }
279
280 fn fetch(&self, endpoint: &str) -> Result<Value, Answer> {
282 let url = self.environment.url(endpoint);
283 let reply = match self.get(&url, None) {
284 Ok(reply) => reply,
285 Err(error) => {
286 return Err(Answer::NoAnswer {
287 url,
288 message: reason(&error),
289 });
290 }
291 };
292 match reply.status {
293 200 | 503 => Ok(serde_json::from_str(&reply.body).unwrap_or(Value::Null)),
295 status @ (401 | 403) => Err(Answer::NotAuthorized { url, status }),
296 status => Err(Answer::Unexpected {
297 url,
298 status,
299 location: reply.location.filter(|_| (300..400).contains(&status)),
300 }),
301 }
302 }
303
304 fn metrics(&self) -> Result<String, NoMetrics> {
306 let url = self.environment.url("prometheus");
307 let reply = match self.get(&url, Some(METRICS_BODY_LIMIT)) {
308 Ok(reply) => reply,
309 Err(error) => {
310 return Err(NoMetrics::NoAnswer {
311 url,
312 message: reason(&error),
313 });
314 }
315 };
316 match reply.status {
317 200 | 503 if reply.too_large => Err(NoMetrics::TooLarge {
318 url,
319 limit: METRICS_BODY_LIMIT,
320 }),
321 200 if reply.body.trim().is_empty() => Err(NoMetrics::Off),
322 200 => Ok(reply.body),
323 503 => Err(NoMetrics::Unavailable {
325 url,
326 line: reply
327 .body
328 .lines()
329 .next()
330 .unwrap_or_default()
331 .chars()
332 .take(200)
333 .collect(),
334 }),
335 status @ (401 | 403) => Err(NoMetrics::NotAuthorized { url, status }),
336 status => Err(NoMetrics::Unexpected {
337 url,
338 status,
339 location: reply.location.filter(|_| (300..400).contains(&status)),
340 }),
341 }
342 }
343
344 fn health(&self) -> Result<(Status, Option<Vec<Component>>), Answer> {
346 let health = self.fetch("health")?;
347 let status = |value: &Value| {
348 value
349 .get("status")
350 .and_then(Value::as_str)
351 .map_or(Status::Unknown, Status::parse)
352 };
353 let components = health
354 .get("components")
355 .and_then(Value::as_object)
356 .map(|components| {
357 components
358 .iter()
359 .map(|(name, component)| Component {
360 name: name.clone(),
361 status: status(component),
362 details: component
363 .get("details")
364 .and_then(Value::as_object)
365 .map(|details| {
366 details
367 .iter()
368 .map(|(key, value)| (key.clone(), plain(value)))
369 .collect()
370 })
371 .unwrap_or_default(),
372 })
373 .collect()
374 });
375 Ok((status(&health), components))
376 }
377
378 fn everything(&self) -> Result<Runtime, Answer> {
379 let exposed: Vec<String> = self
382 .fetch("")?
383 .get("_links")
384 .and_then(Value::as_object)
385 .map(|links| {
386 links
387 .keys()
388 .filter(|key| *key != "self" && !key.contains('-'))
389 .cloned()
390 .collect()
391 })
392 .unwrap_or_default();
393 let (status, components) = self.health()?;
394 let mut runtime = Runtime {
395 status,
396 components,
397 exposed,
398 info: None,
399 routes: None,
400 tasks: None,
401 };
402 if runtime.exposes("info") {
403 runtime.info = Some(read_info(&self.fetch("info")?));
404 }
405 if runtime.exposes("mappings") {
406 runtime.routes = Some(read_routes(&self.fetch("mappings")?));
407 }
408 if runtime.exposes("scheduledtasks") {
409 runtime.tasks = Some(read_tasks(&self.fetch("scheduledtasks")?));
410 }
411 Ok(runtime)
412 }
413}
414
415fn resolve(url: &str, location: &str) -> String {
417 let Some((scheme, rest)) = url.split_once("://") else {
418 return location.to_owned();
419 };
420 let host = rest.split('/').next().unwrap_or_default();
421 if location.starts_with("//") {
422 format!("{scheme}:{location}")
423 } else if location.starts_with('/') {
424 format!("{scheme}://{host}{location}")
425 } else {
426 location.to_owned()
428 }
429}
430
431const TIMEOUT: Duration = Duration::from_secs(10);
433
434fn reason(error: &ureq::Error) -> String {
436 use std::io::ErrorKind;
437 let timeout = || format!("no answer in {} s", TIMEOUT.as_secs());
438 let text = match error {
439 ureq::Error::Timeout(_) => return timeout(),
440 ureq::Error::HostNotFound => return "the host was not found".to_owned(),
441 ureq::Error::ConnectionFailed => return "connection failed".to_owned(),
442 ureq::Error::BadUri(_) => return "the URL is not valid".to_owned(),
443 ureq::Error::Io(error) => match error.kind() {
444 ErrorKind::ConnectionRefused => return "connection refused".to_owned(),
445 ErrorKind::ConnectionReset | ErrorKind::ConnectionAborted => {
446 return "the connection was closed".to_owned();
447 }
448 ErrorKind::TimedOut => return timeout(),
449 #[cfg(windows)]
451 _ if matches!(error.raw_os_error(), Some(11001 | 11004)) => {
452 return "the host was not found".to_owned();
453 }
454 _ => error.to_string(),
455 },
456 other => other.to_string(),
457 };
458 if text.contains("lookup address") {
460 "the host was not found".to_owned()
461 } else if text.contains("invalid peer certificate") {
462 "the certificate is not trusted on this computer".to_owned()
463 } else {
464 text
465 }
466}
467
468pub fn ask(environment: &Environment, secret: &Secret) -> Answer {
473 match Client::new(environment, secret).everything() {
474 Ok(runtime) => Answer::Answered(Box::new(runtime)),
475 Err(answer) => answer,
476 }
477}
478
479pub fn ask_status(environment: &Environment, secret: &Secret, earlier: &Runtime) -> Answer {
482 match Client::new(environment, secret).health() {
483 Ok((status, components)) => Answer::Answered(Box::new(Runtime {
484 status,
485 components,
486 ..earlier.clone()
487 })),
488 Err(answer) => answer,
489 }
490}
491
492pub fn ask_metrics(environment: &Environment, secret: &Secret) -> Result<String, NoMetrics> {
497 Client::new(environment, secret).metrics()
498}
499
500fn plain(value: &Value) -> String {
502 match value {
503 Value::String(text) => text.clone(),
504 other if other.to_string().starts_with("invalid peer certificate") => {
506 "the certificate is not trusted on this computer".to_owned()
507 }
508 other => other.to_string(),
509 }
510}
511
512fn text(value: &Value, path: &[&str]) -> Option<String> {
513 path.iter()
514 .try_fold(value, |value, key| value.get(key))?
515 .as_str()
516 .map(str::to_owned)
517}
518
519fn number(value: &Value, path: &[&str]) -> Option<i64> {
520 path.iter()
521 .try_fold(value, |value, key| value.get(key))?
522 .as_i64()
523}
524
525fn read_info(info: &Value) -> Info {
526 Info {
527 environment: text(info, &["app", "environment"]),
528 laravel: text(info, &["app", "laravel"]),
529 git_branch: text(info, &["git", "branch"]),
530 git_commit: text(info, &["git", "commit", "id"]),
531 php_version: text(info, &["php", "version"]),
532 php_sapi: text(info, &["php", "sapi"]),
533 memory_usage: number(info, &["process", "memory", "usage"]),
534 memory_peak: number(info, &["process", "memory", "peak"]),
535 memory_limit: number(info, &["process", "memory", "limit"]),
536 }
537}
538
539fn strings(value: Option<&Value>) -> Vec<String> {
540 value
541 .and_then(Value::as_array)
542 .map(|items| {
543 items
544 .iter()
545 .filter_map(Value::as_str)
546 .map(str::to_owned)
547 .collect()
548 })
549 .unwrap_or_default()
550}
551
552fn read_routes(mappings: &Value) -> Vec<Route> {
553 mappings
554 .get("routes")
555 .and_then(Value::as_array)
556 .map(|routes| {
557 routes
558 .iter()
559 .map(|route| Route {
560 methods: strings(route.get("methods")),
561 uri: text(route, &["uri"]).unwrap_or_default(),
562 name: text(route, &["name"]),
563 action: text(route, &["action"]).unwrap_or_default(),
564 middleware: strings(route.get("middleware")),
565 })
566 .collect()
567 })
568 .unwrap_or_default()
569}
570
571fn read_tasks(tasks: &Value) -> Vec<Task> {
572 let list = |key: &str| {
573 tasks
574 .get(key)
575 .and_then(Value::as_array)
576 .cloned()
577 .unwrap_or_default()
578 };
579 let cron = list("cron").into_iter().map(|task| Task {
580 target: text(&task, &["runnable", "target"]).unwrap_or_default(),
581 expression: text(&task, &["expression"]),
582 interval_ms: None,
583 timezone: text(&task, &["timezone"]),
584 next: text(&task, &["nextExecution", "time"]),
585 module: text(&task, &["tags", "module"]),
586 });
587 let fixed = list("fixedRate").into_iter().map(|task| Task {
588 target: text(&task, &["runnable", "target"]).unwrap_or_default(),
589 expression: None,
590 interval_ms: task.get("interval").and_then(Value::as_u64),
591 timezone: None,
592 next: None,
593 module: text(&task, &["tags", "module"]),
594 });
595 cron.chain(fixed).collect()
596}
597
598fn base64(bytes: &[u8]) -> String {
600 const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
601 let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
602 for chunk in bytes.chunks(3) {
603 let group = u32::from(chunk[0]) << 16
604 | u32::from(*chunk.get(1).unwrap_or(&0)) << 8
605 | u32::from(*chunk.get(2).unwrap_or(&0));
606 for i in 0..4 {
607 if i <= chunk.len() {
608 out.push(ALPHABET[(group >> (18 - 6 * i) & 63) as usize] as char);
609 } else {
610 out.push('=');
611 }
612 }
613 }
614 out
615}
616
617#[cfg(test)]
618mod tests {
619 use super::*;
620
621 #[test]
622 fn base64_matches_known_values() {
623 assert_eq!(base64(b""), "");
624 assert_eq!(base64(b"f"), "Zg==");
625 assert_eq!(base64(b"fo"), "Zm8=");
626 assert_eq!(base64(b"foo"), "Zm9v");
627 assert_eq!(base64(b"mortise:secret"), "bW9ydGlzZTpzZWNyZXQ=");
628 }
629}