#![cfg(all(feature = "conformance", feature = "internal-auth", feature = "client"))]
use std::{path::PathBuf, time::Duration};
use openadr::conformance::{Credential, Outcome, RunMeta, Runner, Severity, Target};
use testcontainers::{
ContainerAsync, GenericImage, ImageExt,
core::{CmdWaitFor, ExecCommand, IntoContainerPort},
runners::AsyncRunner,
};
use testcontainers_modules::postgres::Postgres;
const PEER_IMAGE_VAR: &str = "OPENADR_PEER_IMAGE";
const JSON_VAR: &str = "OPENADR_INTEROP_JSON";
const POSTGRES_TAG: &str = "17-alpine";
const DB: &str = "openadr";
const SECRET: &str = "interop-secret";
const BL: &str = "interop-bl";
const VEN: &str = "interop-ven";
struct Peer {
image: String,
tag: String,
}
impl Peer {
fn from_env() -> Self {
let image = std::env::var(PEER_IMAGE_VAR)
.unwrap_or_else(|_| "ghcr.io/openleadr/openleadr-rs:latest".to_string());
match image.rsplit_once(':') {
Some((name, tag)) if !tag.contains('/') => Self {
image: name.to_string(),
tag: tag.to_string(),
},
_ => Self {
image,
tag: "latest".to_string(),
},
}
}
fn bootstrap(hash: &str) -> String {
format!(
r#"
INSERT INTO "user" (id, reference, description, created, modified, scopes) VALUES
('{BL}','{BL}','conformance', now(), now(),
ARRAY['read_all','write_programs','write_events','write_subscriptions_bl','write_vens_bl','write_reports_bl']::scope[]),
('{VEN}','{VEN}','conformance', now(), now(),
ARRAY['read_targets','read_ven_objects','write_reports_ven','write_subscriptions_ven','write_vens_ven']::scope[])
ON CONFLICT (id) DO NOTHING;
INSERT INTO user_credentials (user_id, client_id, client_secret) VALUES
('{BL}','{BL}','{hash}'), ('{VEN}','{VEN}','{hash}')
ON CONFLICT (client_id) DO UPDATE SET client_secret = EXCLUDED.client_secret;
"#
)
}
}
fn free_port() -> u16 {
std::net::TcpListener::bind("127.0.0.1:0")
.and_then(|l| l.local_addr())
.map(|a| a.port())
.expect("a free port")
}
async fn wait_until_serving(base: &str) -> bool {
openadr::install_crypto_provider().unwrap();
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(5))
.build()
.expect("an HTTP client");
for _ in 0..120 {
if client
.get(format!("{base}/auth/server"))
.send()
.await
.is_ok_and(|r| r.status().is_success())
{
return true;
}
tokio::time::sleep(Duration::from_millis(500)).await;
}
false
}
async fn start(
peer: &Peer,
) -> (
ContainerAsync<Postgres>,
ContainerAsync<GenericImage>,
String,
) {
let network = format!("oadr-interop-{}", uuid::Uuid::now_v7());
let pg_host = format!("{network}-pg");
let postgres = Postgres::default()
.with_user(DB)
.with_password(DB)
.with_db_name(DB)
.with_tag(POSTGRES_TAG)
.with_network(&network)
.with_container_name(&pg_host)
.start()
.await
.expect("interop measurement requires a running PostgreSQL container");
let port = free_port();
let vtn = GenericImage::new(&peer.image, &peer.tag)
.with_mapped_port(port, 3000.tcp())
.with_network(&network)
.with_platform("linux/amd64")
.with_env_var(
"DATABASE_URL",
format!("postgres://{DB}:{DB}@{pg_host}:5432/{DB}"),
)
.with_env_var(
"OAUTH_TOKEN_URL",
format!("http://localhost:{port}/auth/token"),
)
.with_startup_timeout(Duration::from_secs(300))
.start()
.await
.expect("interop measurement requires the peer VTN container to start");
let base = format!("http://127.0.0.1:{port}");
assert!(
wait_until_serving(&base).await,
"peer never became ready at {base}/auth/server"
);
(postgres, vtn, base)
}
#[tokio::test]
#[ignore = "a measurement against somebody else's VTN: run with --ignored --nocapture"]
async fn the_suite_runs_against_a_peer() {
let peer = Peer::from_env();
let (postgres, _vtn, base) = start(&peer).await;
let hash = openadr::vtn::auth::InternalAuth::hash_secret(SECRET).expect("a PHC string");
postgres
.exec(
ExecCommand::new([
"psql",
"-v",
"ON_ERROR_STOP=1",
"-qtU",
DB,
"-d",
DB,
"-c",
&Peer::bootstrap(&hash),
])
.with_cmd_ready_condition(CmdWaitFor::exit_code(0)),
)
.await
.expect("peer database bootstrap must succeed before measuring");
let credential = |id: &str| Credential::ClientCredentials {
id: id.to_string(),
secret: SECRET.to_string(),
};
let target = Target::new(&base)
.with_business_logic(credential(BL))
.with_ven(credential(VEN), VEN);
let mut report = Runner::new(target)
.expect("the base URL parses")
.run()
.await;
let (passed, failed, skipped) = report.tally(Severity::Required);
println!("required: {passed} passed, {failed} failed, {skipped} skipped");
let unreachable: Vec<&str> = report
.findings
.iter()
.filter(|f| match &f.outcome {
Outcome::Skipped(why) => why.contains("could not be reached"),
_ => false,
})
.map(|f| f.check.id)
.collect();
assert!(
unreachable.is_empty(),
"{} check(s) never reached {}:{} — that is this harness's fault, not the peer's: {unreachable:?}",
unreachable.len(),
peer.image,
peer.tag
);
assert!(
passed + failed >= 20,
"only {} required checks were attempted — the suite did not run",
passed + failed
);
report.target = format!("{}:{}", peer.image, peer.tag);
if let Some(path) = std::env::var_os(JSON_VAR).map(PathBuf::from) {
assert_eq!(
path.extension().and_then(|ext| ext.to_str()),
Some("json"),
"{JSON_VAR} must name a .json file"
);
let meta = RunMeta {
generated: openadr::model::Timestamp::now().to_string(),
suite_version: env!("CARGO_PKG_VERSION").into(),
spec_version: openadr::SPEC_VERSION.into(),
};
let mut json = report.to_json();
json["generated"] = meta.generated.clone().into();
json["suiteVersion"] = meta.suite_version.clone().into();
json["specVersion"] = meta.spec_version.clone().into();
let html = path.with_extension("html");
std::fs::write(&html, report.to_html(&meta)).expect("write HTML interop report");
std::fs::write(&path, serde_json::to_vec_pretty(&json).unwrap())
.expect("write JSON interop report");
println!("reports: {} and {}", path.display(), html.display());
} else {
println!("{report}");
}
}