#![allow(clippy::expect_used)]
mod common;
use std::collections::BTreeSet;
use std::error::Error;
use std::net::SocketAddr;
use std::time::Duration;
use common::{Events, LISTENER, get_with};
use prometheus_parse::{Sample, Scrape, Value};
use redup_abstractions::DependencyRole;
use redup_bootstrap::{
Builder, Context, CustomProbe, Level, LoadKind, Module, ModuleError, Service, Template, Unit,
async_trait,
};
use redup_config::Config;
type TestResult<T> = std::result::Result<T, Box<dyn Error>>;
#[derive(Debug, Clone, Default, PartialEq, Config)]
struct JobSettings {
tick: Duration,
api_secret: Option<String>,
}
struct Job;
#[async_trait]
impl Module for Job {
const NAME: &'static str = "Job";
type Config = JobSettings;
type Args = ();
async fn create(
settings: JobSettings,
(): (),
ctx: &mut Context<'_>,
) -> Result<Self, ModuleError> {
let processed =
ctx.meter()
.counter("job_processed", Unit::Count, "Обработанные задачи.")?;
let neighbour = ctx
.dependency("neighbour")
.probe(CustomProbe::new(|_| async move { Ok(true) }))
.start()?;
let health = ctx.health();
health.track(&neighbour, DependencyRole::Critical);
health.set(redup_abstractions::Phase::Serving);
if !settings.tick.is_zero() {
let load = ctx.load();
let work = load.clone();
let token = ctx.token();
let processed = processed.clone();
let tick = settings.tick;
tokio::spawn(async move {
loop {
tokio::select! {
_ = token.cancelled() => return,
_ = tokio::time::sleep(tick) => {}
}
let _work = work.work(LoadKind::Worker);
tokio::time::sleep(tick / 2).await;
processed.increment(1);
}
});
}
Ok(Self)
}
fn details(&self) -> Vec<(String, String)> {
vec![("queue".to_owned(), "0".to_owned())]
}
}
async fn start(tick: &str, bootstrap: &str) -> TestResult<redup_bootstrap::Instance> {
let (_directory, source) = Events::source(&format!(
"{LISTENER}{bootstrap}jobSettings:\n tick: {tick}\n apiSecret: s3cret-value\n"
))?;
let service = Service::new("trial", "0.1.0");
let mut builder = Builder::new(&source, service)?;
builder.add::<Job>(()).await?;
let mut instance = builder.build();
instance.start().await?;
Ok(instance)
}
async fn get(
address: SocketAddr,
path: &str,
headers: &[(&str, &str)],
) -> TestResult<(u16, String, String)> {
let reply = get_with(address, path, headers).await?;
Ok((reply.status, reply.content_type, reply.body))
}
fn scrape(body: &str) -> Scrape {
Scrape::parse(
body.lines()
.map(|line| Ok::<String, std::io::Error>(line.to_owned())),
)
.expect("the exposition text is parsed by prometheus-parse")
}
fn series<'a>(scrape: &'a Scrape, metric: &str, labels: &[(&str, &str)]) -> Vec<&'a Sample> {
scrape
.samples
.iter()
.filter(|sample| {
sample.metric == metric
&& labels.iter().all(|(name, value)| {
sample
.labels
.get(name)
.is_some_and(|found| *found == **value)
})
})
.collect()
}
fn number(scrape: &Scrape, metric: &str, labels: &[(&str, &str)]) -> f64 {
let found = series(scrape, metric, labels);
assert_eq!(found.len(), 1, "expected one series of {metric}");
match found[0].value {
Value::Counter(value) | Value::Gauge(value) | Value::Untyped(value) => value,
_ => unreachable!("{metric} is not a number"),
}
}
fn families(scrape: &Scrape) -> BTreeSet<String> {
scrape
.samples
.iter()
.map(|sample| {
let name = sample.metric.as_str();
let name = name.strip_suffix("_bucket").unwrap_or(name);
let name = name.strip_suffix("_sum").unwrap_or(name);
let name = name.strip_suffix("_count").unwrap_or(name);
name.to_owned()
})
.collect()
}
fn contract() -> BTreeSet<String> {
let path = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../contracts/metrics/prometheus.txt"
);
let text = std::fs::read_to_string(path).expect("the reference file of metrics");
text.lines()
.filter_map(|line| line.strip_prefix("# TYPE "))
.filter_map(|line| line.split_whitespace().next())
.map(str::to_owned)
.collect()
}
#[tokio::test]
async fn metrics_follow_the_contract() -> TestResult<()> {
let mut instance = start("20ms", "").await?;
let address = instance.address().ok_or("the listener is not started")?;
assert_eq!(get(address, "/readyz", &[]).await?.0, 200);
tokio::time::sleep(Duration::from_millis(120)).await;
let (status, content_type, body) = get(address, "/metrics", &[]).await?;
instance.stop().await;
assert_eq!(status, 200);
assert!(
content_type.starts_with("text/plain; version=0.0.4"),
"{content_type}"
);
let scrape = scrape(&body);
let build = [("version", "0.1.0"), ("bootstrap_version", "0.3.3")];
assert_eq!(number(&scrape, "build_info", &build), 1.0);
let target = [("service_name", "trial"), ("service_version", "0.1.0")];
assert_eq!(number(&scrape, "target_info", &target), 1.0);
let dependency = [("module", "Job"), ("dependency", "neighbour")];
assert_eq!(number(&scrape, "dependency_state", &dependency), 2.0);
assert_eq!(number(&scrape, "dependency_up", &dependency), 1.0);
assert!(
number(&scrape, "trial_job_processed_total", &[]) >= 1.0,
"{body}"
);
let worker = number(&scrape, "worker_load_total", &[]);
assert!(worker > 0.0, "{body}");
assert_eq!(number(&scrape, "incoming_load_total", &[]), 0.0);
assert_eq!(number(&scrape, "outgoing_load_total", &[]), 0.0);
assert_eq!(number(&scrape, "load_total", &[]), worker);
assert_eq!(number(&scrape, "service_load_total", &[]), worker);
assert!(number(&scrape, "mem_working_set_bytes", &[]) > 0.0);
assert!(number(&scrape, "process_resident_memory_bytes", &[]) > 0.0);
assert!(number(&scrape, "process_cpu_seconds_total", &[]) >= 0.0);
assert!(number(&scrape, "process_start_time_seconds", &[]) > 1.7e9);
assert!(number(&scrape, "process_threads", &[]) >= 1.0);
assert!(number(&scrape, "process_open_fds", &[]) >= 1.0);
assert!(number(&scrape, "process_max_fds", &[]) > 0.0);
let http = [
("http_request_method", "GET"),
("http_response_status_code", "200"),
("http_route", "/readyz"),
("network_protocol_version", "1.1"),
("url_scheme", "http"),
];
assert_eq!(
series(&scrape, "http_server_request_duration_seconds_count", &http).len(),
1,
"{body}"
);
assert_eq!(number(&scrape, "rest_call_count", &[]), 1.0);
let expected: BTreeSet<String> = contract()
.into_iter()
.filter(|name| !name.starts_with("grpc_server_") && name != "load_average_optimal")
.collect();
let present = families(&scrape);
let missing: Vec<&String> = expected.difference(&present).collect();
assert!(missing.is_empty(), "missing: {missing:?}\n{body}");
Ok(())
}
#[tokio::test]
async fn metrics_follow_the_configuration() -> TestResult<()> {
let mut instance = start(
"20ms",
" metrics:\n optimalAverageLoad: 0.7\n load:\n denominator: 2\n",
)
.await?;
let address = instance.address().ok_or("the listener is not started")?;
tokio::time::sleep(Duration::from_millis(120)).await;
let body = get(address, "/metrics", &[]).await?.2;
instance.stop().await;
let scrape = scrape(&body);
assert_eq!(number(&scrape, "load_average_optimal", &[]), 0.7);
let worker = number(&scrape, "worker_load_total", &[]);
assert!(worker >= 2.0, "{body}");
assert_eq!(number(&scrape, "load_total", &[]), (worker / 2.0).floor());
Ok(())
}
#[tokio::test]
async fn pages_show_the_instance_modules_and_configurations() -> TestResult<()> {
let mut instance = start("0s", "").await?;
let address = instance.address().ok_or("the listener is not started")?;
let (status, content_type, body) = get(address, "/info", &[]).await?;
assert_eq!(
(status, content_type.as_str()),
(200, "text/html; charset=utf-8")
);
assert!(body.starts_with("<!DOCTYPE html>"), "{body}");
for text in [
"trial",
"0.1.0",
"/info/Job",
"/readyz/Job",
"/config/JobSettings",
] {
assert!(body.contains(text), "/info lacks {text}:\n{body}");
}
let (status, _, body) = get(address, "/info/Job", &[]).await?;
assert_eq!(status, 200);
for text in [
"Модуль Job",
"neighbour",
"Up",
"queue",
"/config/JobSettings",
] {
assert!(body.contains(text), "/info/Job lacks {text}:\n{body}");
}
let (status, content_type, body) = get(address, "/config", &[]).await?;
assert_eq!(
(status, content_type.as_str()),
(200, "text/html; charset=utf-8")
);
assert!(
body.contains("/config/JobSettings") && body.contains("/config/Bootstrap"),
"{body}"
);
let (status, _, body) = get(address, "/config/JobSettings", &[]).await?;
assert_eq!(status, 200);
assert!(
body.contains("Tick") && body.contains("ApiSecret") && body.contains("*****"),
"{body}"
);
assert!(
!body.contains("s3cret-value"),
"the secret is shown:\n{body}"
);
for path in ["/info/Nobody", "/config/Nobody"] {
let (status, content_type, body) = get(address, path, &[]).await?;
assert_eq!(
(status, content_type.as_str()),
(404, "text/plain; charset=utf-8")
);
assert_eq!(body, "Not found");
}
instance.stop().await;
Ok(())
}
#[tokio::test]
async fn journal_is_controlled_by_its_handle() -> TestResult<()> {
let (_directory, source) = Events::none()?;
let service = Service::new("trial", "0.1.0");
let mut builder = Builder::new(&source, service)?;
builder.add::<Job>(()).await?;
let instance = builder.build();
let logging = instance.logging();
assert_eq!(logging.level(), Level::Info);
assert_eq!(logging.template(), Template::Auto);
let mut capture = logging.capture(Level::Trace);
tracing::info!("captured message");
tracing::debug!("too detailed");
let first = capture.next().await.ok_or("no message is captured")?;
assert_eq!(
(first.level(), first.message()),
(Level::Info, "captured message")
);
logging.set_level(Level::Trace);
tracing::debug!("now detailed");
let second = capture
.next()
.await
.ok_or("the debug message is not captured")?;
assert_eq!(
(second.level(), second.message()),
(Level::Debug, "now detailed")
);
logging.set_level(Level::Off);
tracing::error!("silenced");
assert!(
tokio::time::timeout(Duration::from_millis(50), capture.next())
.await
.is_err()
);
Ok(())
}
#[cfg(not(feature = "otlp"))]
#[tokio::test]
async fn collector_needs_the_export_feature() -> TestResult<()> {
let (_directory, source) = Events::source(&format!(
"{LISTENER} tracing:\n collector: 127.0.0.1:4317\n"
))?;
let error = Builder::new(&source, Service::new("trial", "0.1.0"))
.err()
.ok_or("the collector is accepted without the trace export")?;
let text = error.to_string();
assert!(
text.contains("127.0.0.1:4317") && text.contains("trace export"),
"{text}"
);
Ok(())
}
#[tokio::test]
async fn request_context_reaches_the_journal() -> TestResult<()> {
let mut instance = start("0s", "").await?;
let address = instance.address().ok_or("the listener is not started")?;
let logging = instance.logging();
logging.set_level(Level::Trace);
let mut capture = logging.capture(Level::Debug);
let correlation = "6f107bf6-289b-4421-acee-40e1b9f5b4c9";
let headers = [
("X-Correlation-ID", correlation),
(
"traceparent",
"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
),
];
assert_eq!(get(address, "/readyz", &headers).await?.0, 200);
let found = tokio::time::timeout(Duration::from_secs(5), async {
while let Some(message) = capture.next().await {
if message.message() == "request handled" {
return message;
}
}
unreachable!("the journal outlives the instance")
})
.await;
instance.stop().await;
let message = found.map_err(|_| "the request event did not reach the journal in time")?;
assert_eq!(message.level(), Level::Debug);
assert_eq!(message.correlation_id(), Some(correlation));
Ok(())
}