use std::io::Read;
use std::time::Duration;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::runtime::environment::{Credentials, Environment};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Status {
Up,
Down,
OutOfService,
Unknown,
}
impl Status {
fn parse(text: &str) -> Self {
match text {
"UP" => Status::Up,
"DOWN" => Status::Down,
"OUT_OF_SERVICE" => Status::OutOfService,
_ => Status::Unknown,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Component {
pub name: String,
pub status: Status,
pub details: Vec<(String, String)>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct Info {
pub environment: Option<String>,
pub laravel: Option<String>,
pub git_branch: Option<String>,
pub git_commit: Option<String>,
pub php_version: Option<String>,
pub php_sapi: Option<String>,
pub memory_usage: Option<i64>,
pub memory_peak: Option<i64>,
pub memory_limit: Option<i64>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Route {
pub methods: Vec<String>,
pub uri: String,
pub name: Option<String>,
pub action: String,
pub middleware: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Task {
pub target: String,
pub expression: Option<String>,
pub interval_ms: Option<u64>,
pub timezone: Option<String>,
pub next: Option<String>,
#[serde(default)]
pub module: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Runtime {
pub status: Status,
pub components: Option<Vec<Component>>,
pub exposed: Vec<String>,
pub info: Option<Info>,
pub routes: Option<Vec<Route>>,
pub tasks: Option<Vec<Task>>,
}
impl Runtime {
pub fn exposes(&self, endpoint: &str) -> bool {
self.exposed.iter().any(|exposed| exposed == endpoint)
}
pub fn not_exposed(&self) -> Vec<&'static str> {
["info", "mappings", "scheduledtasks"]
.into_iter()
.filter(|endpoint| !self.exposes(endpoint))
.collect()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum Answer {
NoAnswer {
url: String,
message: String,
},
NotAuthorized {
url: String,
status: u16,
},
Unexpected {
url: String,
status: u16,
location: Option<String>,
},
Answered(Box<Runtime>),
}
pub type Secret = Option<String>;
pub const METRICS_BODY_LIMIT: u64 = 16 * 1024 * 1024;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NoMetrics {
Off,
Unavailable {
url: String,
line: String,
},
TooLarge {
url: String,
limit: u64,
},
NoAnswer {
url: String,
message: String,
},
NotAuthorized {
url: String,
status: u16,
},
Unexpected {
url: String,
status: u16,
location: Option<String>,
},
}
struct Reply {
status: u16,
body: String,
too_large: bool,
location: Option<String>,
}
struct Client<'a> {
agent: ureq::Agent,
environment: &'a Environment,
secret: &'a Secret,
}
impl<'a> Client<'a> {
fn new(environment: &'a Environment, secret: &'a Secret) -> Self {
let config = ureq::Agent::config_builder()
.timeout_global(Some(TIMEOUT))
.http_status_as_error(false)
.max_redirects(0)
.tls_config(
ureq::tls::TlsConfig::builder()
.root_certs(ureq::tls::RootCerts::PlatformVerifier)
.build(),
)
.build();
Self {
agent: ureq::Agent::new_with_config(config),
environment,
secret,
}
}
fn get(&self, url: &str, limit: Option<u64>) -> Result<Reply, ureq::Error> {
let mut request = self.agent.get(url).header("Accept", "application/json");
let secret = self.secret.as_deref().unwrap_or_default();
match &self.environment.credentials {
Credentials::None => {}
Credentials::Bearer => {
request = request.header("Authorization", format!("Bearer {secret}"));
}
Credentials::Basic { user } => {
let pair = base64(format!("{user}:{secret}").as_bytes());
request = request.header("Authorization", format!("Basic {pair}"));
}
Credentials::Header { name } => request = request.header(name.as_str(), secret),
}
let mut response = request.call()?;
let status = response.status().as_u16();
let location = response
.headers()
.get("location")
.and_then(|value| value.to_str().ok())
.map(|location| resolve(url, location));
let (body, too_large) = match limit {
None => (
response.body_mut().read_to_string().unwrap_or_default(),
false,
),
Some(_) if !matches!(status, 200 | 503) => (String::new(), false),
Some(limit) => {
let mut bytes = Vec::new();
response
.body_mut()
.with_config()
.reader()
.take(limit.saturating_add(1))
.read_to_end(&mut bytes)
.map_err(ureq::Error::from)?;
if bytes.len() as u64 > limit {
(String::new(), true)
} else {
(String::from_utf8_lossy(&bytes).into_owned(), false)
}
}
};
Ok(Reply {
status,
body,
too_large,
location,
})
}
fn fetch(&self, endpoint: &str) -> Result<Value, Answer> {
let url = self.environment.url(endpoint);
let reply = match self.get(&url, None) {
Ok(reply) => reply,
Err(error) => {
return Err(Answer::NoAnswer {
url,
message: reason(&error),
});
}
};
match reply.status {
200 | 503 => Ok(serde_json::from_str(&reply.body).unwrap_or(Value::Null)),
status @ (401 | 403) => Err(Answer::NotAuthorized { url, status }),
status => Err(Answer::Unexpected {
url,
status,
location: reply.location.filter(|_| (300..400).contains(&status)),
}),
}
}
fn metrics(&self) -> Result<String, NoMetrics> {
let url = self.environment.url("prometheus");
let reply = match self.get(&url, Some(METRICS_BODY_LIMIT)) {
Ok(reply) => reply,
Err(error) => {
return Err(NoMetrics::NoAnswer {
url,
message: reason(&error),
});
}
};
match reply.status {
200 | 503 if reply.too_large => Err(NoMetrics::TooLarge {
url,
limit: METRICS_BODY_LIMIT,
}),
200 if reply.body.trim().is_empty() => Err(NoMetrics::Off),
200 => Ok(reply.body),
503 => Err(NoMetrics::Unavailable {
url,
line: reply
.body
.lines()
.next()
.unwrap_or_default()
.chars()
.take(200)
.collect(),
}),
status @ (401 | 403) => Err(NoMetrics::NotAuthorized { url, status }),
status => Err(NoMetrics::Unexpected {
url,
status,
location: reply.location.filter(|_| (300..400).contains(&status)),
}),
}
}
fn health(&self) -> Result<(Status, Option<Vec<Component>>), Answer> {
let health = self.fetch("health")?;
let status = |value: &Value| {
value
.get("status")
.and_then(Value::as_str)
.map_or(Status::Unknown, Status::parse)
};
let components = health
.get("components")
.and_then(Value::as_object)
.map(|components| {
components
.iter()
.map(|(name, component)| Component {
name: name.clone(),
status: status(component),
details: component
.get("details")
.and_then(Value::as_object)
.map(|details| {
details
.iter()
.map(|(key, value)| (key.clone(), plain(value)))
.collect()
})
.unwrap_or_default(),
})
.collect()
});
Ok((status(&health), components))
}
fn everything(&self) -> Result<Runtime, Answer> {
let exposed: Vec<String> = self
.fetch("")?
.get("_links")
.and_then(Value::as_object)
.map(|links| {
links
.keys()
.filter(|key| *key != "self" && !key.contains('-'))
.cloned()
.collect()
})
.unwrap_or_default();
let (status, components) = self.health()?;
let mut runtime = Runtime {
status,
components,
exposed,
info: None,
routes: None,
tasks: None,
};
if runtime.exposes("info") {
runtime.info = Some(read_info(&self.fetch("info")?));
}
if runtime.exposes("mappings") {
runtime.routes = Some(read_routes(&self.fetch("mappings")?));
}
if runtime.exposes("scheduledtasks") {
runtime.tasks = Some(read_tasks(&self.fetch("scheduledtasks")?));
}
Ok(runtime)
}
}
fn resolve(url: &str, location: &str) -> String {
let Some((scheme, rest)) = url.split_once("://") else {
return location.to_owned();
};
let host = rest.split('/').next().unwrap_or_default();
if location.starts_with("//") {
format!("{scheme}:{location}")
} else if location.starts_with('/') {
format!("{scheme}://{host}{location}")
} else {
location.to_owned()
}
}
const TIMEOUT: Duration = Duration::from_secs(10);
fn reason(error: &ureq::Error) -> String {
use std::io::ErrorKind;
let timeout = || format!("no answer in {} s", TIMEOUT.as_secs());
let text = match error {
ureq::Error::Timeout(_) => return timeout(),
ureq::Error::HostNotFound => return "the host was not found".to_owned(),
ureq::Error::ConnectionFailed => return "connection failed".to_owned(),
ureq::Error::BadUri(_) => return "the URL is not valid".to_owned(),
ureq::Error::Io(error) => match error.kind() {
ErrorKind::ConnectionRefused => return "connection refused".to_owned(),
ErrorKind::ConnectionReset | ErrorKind::ConnectionAborted => {
return "the connection was closed".to_owned();
}
ErrorKind::TimedOut => return timeout(),
#[cfg(windows)]
_ if matches!(error.raw_os_error(), Some(11001 | 11004)) => {
return "the host was not found".to_owned();
}
_ => error.to_string(),
},
other => other.to_string(),
};
if text.contains("lookup address") {
"the host was not found".to_owned()
} else if text.contains("invalid peer certificate") {
"the certificate is not trusted on this computer".to_owned()
} else {
text
}
}
pub fn ask(environment: &Environment, secret: &Secret) -> Answer {
match Client::new(environment, secret).everything() {
Ok(runtime) => Answer::Answered(Box::new(runtime)),
Err(answer) => answer,
}
}
pub fn ask_status(environment: &Environment, secret: &Secret, earlier: &Runtime) -> Answer {
match Client::new(environment, secret).health() {
Ok((status, components)) => Answer::Answered(Box::new(Runtime {
status,
components,
..earlier.clone()
})),
Err(answer) => answer,
}
}
pub fn ask_metrics(environment: &Environment, secret: &Secret) -> Result<String, NoMetrics> {
Client::new(environment, secret).metrics()
}
fn plain(value: &Value) -> String {
match value {
Value::String(text) => text.clone(),
other if other.to_string().starts_with("invalid peer certificate") => {
"the certificate is not trusted on this computer".to_owned()
}
other => other.to_string(),
}
}
fn text(value: &Value, path: &[&str]) -> Option<String> {
path.iter()
.try_fold(value, |value, key| value.get(key))?
.as_str()
.map(str::to_owned)
}
fn number(value: &Value, path: &[&str]) -> Option<i64> {
path.iter()
.try_fold(value, |value, key| value.get(key))?
.as_i64()
}
fn read_info(info: &Value) -> Info {
Info {
environment: text(info, &["app", "environment"]),
laravel: text(info, &["app", "laravel"]),
git_branch: text(info, &["git", "branch"]),
git_commit: text(info, &["git", "commit", "id"]),
php_version: text(info, &["php", "version"]),
php_sapi: text(info, &["php", "sapi"]),
memory_usage: number(info, &["process", "memory", "usage"]),
memory_peak: number(info, &["process", "memory", "peak"]),
memory_limit: number(info, &["process", "memory", "limit"]),
}
}
fn strings(value: Option<&Value>) -> Vec<String> {
value
.and_then(Value::as_array)
.map(|items| {
items
.iter()
.filter_map(Value::as_str)
.map(str::to_owned)
.collect()
})
.unwrap_or_default()
}
fn read_routes(mappings: &Value) -> Vec<Route> {
mappings
.get("routes")
.and_then(Value::as_array)
.map(|routes| {
routes
.iter()
.map(|route| Route {
methods: strings(route.get("methods")),
uri: text(route, &["uri"]).unwrap_or_default(),
name: text(route, &["name"]),
action: text(route, &["action"]).unwrap_or_default(),
middleware: strings(route.get("middleware")),
})
.collect()
})
.unwrap_or_default()
}
fn read_tasks(tasks: &Value) -> Vec<Task> {
let list = |key: &str| {
tasks
.get(key)
.and_then(Value::as_array)
.cloned()
.unwrap_or_default()
};
let cron = list("cron").into_iter().map(|task| Task {
target: text(&task, &["runnable", "target"]).unwrap_or_default(),
expression: text(&task, &["expression"]),
interval_ms: None,
timezone: text(&task, &["timezone"]),
next: text(&task, &["nextExecution", "time"]),
module: text(&task, &["tags", "module"]),
});
let fixed = list("fixedRate").into_iter().map(|task| Task {
target: text(&task, &["runnable", "target"]).unwrap_or_default(),
expression: None,
interval_ms: task.get("interval").and_then(Value::as_u64),
timezone: None,
next: None,
module: text(&task, &["tags", "module"]),
});
cron.chain(fixed).collect()
}
fn base64(bytes: &[u8]) -> String {
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
for chunk in bytes.chunks(3) {
let group = u32::from(chunk[0]) << 16
| u32::from(*chunk.get(1).unwrap_or(&0)) << 8
| u32::from(*chunk.get(2).unwrap_or(&0));
for i in 0..4 {
if i <= chunk.len() {
out.push(ALPHABET[(group >> (18 - 6 * i) & 63) as usize] as char);
} else {
out.push('=');
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn base64_matches_known_values() {
assert_eq!(base64(b""), "");
assert_eq!(base64(b"f"), "Zg==");
assert_eq!(base64(b"fo"), "Zm8=");
assert_eq!(base64(b"foo"), "Zm9v");
assert_eq!(base64(b"mortise:secret"), "bW9ydGlzZTpzZWNyZXQ=");
}
}