use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
use anyhow::{bail, Result};
use colored::Colorize;
use futures::future::join_all;
use tokio::sync::OnceCell;
use crate::api_client::CxClient;
use crate::config::ResolvedConfig;
use crate::identity;
pub struct ExecutionTarget {
pub profile_name: String,
pub cfg: ResolvedConfig,
pub client: CxClient,
console_base: OnceCell<Option<String>>,
no_console_link: bool,
}
impl ExecutionTarget {
pub fn new(cfg: ResolvedConfig) -> Result<Self> {
Self::with_timeout(cfg, None)
}
pub fn with_timeout(cfg: ResolvedConfig, timeout: Option<Duration>) -> Result<Self> {
let client = CxClient::with_timeout(&cfg.endpoint, &cfg.api_key, timeout)?;
let profile_name = cfg.profile_name.clone();
Ok(Self {
profile_name,
cfg,
client,
console_base: OnceCell::new(),
no_console_link: false,
})
}
pub async fn console_base(&self) -> Option<String> {
if self.no_console_link {
return None;
}
self.console_base
.get_or_init(|| async {
if !self.cfg.credentials_overridden {
if let Some(url) = &self.cfg.console_url {
return Some(url.clone());
}
if let Some(url) = crate::config::load_cached_console_url(&self.profile_name) {
return Some(url);
}
}
let resolved = identity::resolve_team_url(&self.client).await;
if !self.cfg.credentials_overridden {
if let Some(url) = &resolved {
crate::config::cache_console_url(&self.profile_name, url);
}
}
resolved
})
.await
.clone()
}
pub async fn emit_console_link(&self, build: impl FnOnce(&str) -> String) -> Option<String> {
let base = self.console_base().await?;
let url = build(&base);
crate::render::print_console_link(&url);
Some(url)
}
}
pub async fn emit_console_link_for_profile(
targets: &[Arc<ExecutionTarget>],
profile: &str,
build: impl FnOnce(&str) -> String,
) -> Option<String> {
find_target(targets, profile)?
.emit_console_link(build)
.await
}
pub fn build_targets(
configs: Vec<ResolvedConfig>,
no_console_link: bool,
timeout: Option<Duration>,
) -> Result<Vec<Arc<ExecutionTarget>>> {
configs
.into_iter()
.map(|cfg| {
let mut target = ExecutionTarget::with_timeout(cfg, timeout)?;
target.no_console_link = no_console_link;
Ok(Arc::new(target))
})
.collect()
}
pub fn find_target<'a>(
targets: &'a [Arc<ExecutionTarget>],
profile: &str,
) -> Option<&'a Arc<ExecutionTarget>> {
targets.iter().find(|t| t.profile_name == profile)
}
pub async fn fan_out<T, F, Fut>(targets: &[Arc<ExecutionTarget>], f: F) -> Vec<(String, Result<T>)>
where
F: Fn(Arc<ExecutionTarget>) -> Fut,
Fut: Future<Output = Result<T>>,
{
let futures = targets.iter().map(|t| {
let profile_name = t.profile_name.clone();
let fut = f(Arc::clone(t));
async move { (profile_name, fut.await) }
});
join_all(futures).await
}
pub fn report_errors_and_collect_successes<T>(
per_profile: Vec<(String, Result<T>)>,
) -> Result<Vec<(String, T)>> {
let target_count = per_profile.len();
let mut successes = Vec::with_capacity(target_count);
let mut errors: Vec<(String, anyhow::Error)> = Vec::new();
for (profile, result) in per_profile {
match result {
Ok(v) => successes.push((profile, v)),
Err(e) => errors.push((profile, e)),
}
}
if successes.is_empty() && target_count > 0 {
if let [_] = errors.as_slice() {
let (profile, e) = errors.into_iter().next().expect("one error present");
return Err(e.context(format!("profile '{profile}' failed")));
}
for (profile, e) in &errors {
eprintln!("{}", format!("error from profile '{profile}': {e:#}").red());
}
bail!("all {target_count} profiles returned errors");
}
for (profile, e) in errors {
eprintln!("{}", format!("error from profile '{profile}': {e:#}").red());
}
Ok(successes)
}
#[cfg(test)]
mod tests {
use super::*;
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
fn test_cfg(endpoint: &str, console_url: Option<&str>) -> ResolvedConfig {
ResolvedConfig {
profile_name: "test-profile".to_string(),
api_key: "test-key".to_string(),
auth_kind: crate::config::AuthKind::ApiKey,
endpoint: endpoint.to_string(),
default_tier: crate::Tier::Archive,
console_url: console_url.map(str::to_string),
credentials_overridden: false,
}
}
fn install_rustls_provider() {
rustls::crypto::ring::default_provider()
.install_default()
.ok();
}
#[test]
fn find_target_locates_by_profile_name() {
install_rustls_provider();
let a = Arc::new(ExecutionTarget::new(test_cfg("http://127.0.0.1:1", None)).unwrap());
let targets = vec![a.clone()];
assert!(find_target(&targets, "test-profile").is_some());
assert!(find_target(&targets, "missing-profile").is_none());
}
#[tokio::test]
async fn console_base_prefers_explicit_console_url() {
install_rustls_provider();
let target = ExecutionTarget::new(test_cfg(
"http://127.0.0.1:1",
Some("https://c4c.example.com/"),
))
.unwrap();
assert_eq!(
target.console_base().await,
Some("https://c4c.example.com/".to_string())
);
}
#[tokio::test]
async fn console_base_uses_team_url_from_whoami_by_default() {
install_rustls_provider();
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/identity/whoami"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"team_id": 1,
"team_name": "C4C",
"team_url": "https://c4c.app.eu2.coralogix.com"
})))
.mount(&server)
.await;
let target = ExecutionTarget::new(test_cfg(&server.uri(), None)).unwrap();
assert_eq!(
target.console_base().await,
Some("https://c4c.app.eu2.coralogix.com".to_string())
);
}
#[tokio::test]
async fn console_base_none_when_whoami_omits_team_url() {
install_rustls_provider();
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/identity/whoami"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"team_id": 1,
"team_name": "C4C"
})))
.mount(&server)
.await;
let target = ExecutionTarget::new(test_cfg(&server.uri(), None)).unwrap();
assert_eq!(target.console_base().await, None);
}
#[tokio::test]
async fn console_base_none_when_whoami_fails() {
install_rustls_provider();
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/identity/whoami"))
.respond_with(ResponseTemplate::new(500))
.mount(&server)
.await;
let target = ExecutionTarget::new(test_cfg(&server.uri(), None)).unwrap();
assert_eq!(target.console_base().await, None);
}
#[tokio::test]
async fn console_base_explicit_console_url_takes_precedence_over_whoami() {
install_rustls_provider();
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/identity/whoami"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"team_id": 1,
"team_name": "Totally Different Name",
"team_url": "https://totally-different.app.eu2.coralogix.com"
})))
.expect(0)
.mount(&server)
.await;
let target = ExecutionTarget::new(test_cfg(
&server.uri(),
Some("https://c4c.app.eu2.coralogix.com"),
))
.unwrap();
assert_eq!(
target.console_base().await,
Some("https://c4c.app.eu2.coralogix.com".to_string())
);
}
#[tokio::test]
async fn console_base_is_cached_after_first_resolution() {
install_rustls_provider();
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/identity/whoami"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"team_id": 1,
"team_name": "C4C",
"team_url": "https://c4c.app.eu2.coralogix.com"
})))
.expect(1)
.mount(&server)
.await;
let target = ExecutionTarget::new(test_cfg(&server.uri(), None)).unwrap();
let first = target.console_base().await;
let second = target.console_base().await;
assert_eq!(first, second);
assert_eq!(first, Some("https://c4c.app.eu2.coralogix.com".to_string()));
}
#[tokio::test]
async fn console_base_none_when_no_console_link_set_even_with_explicit_console_url() {
install_rustls_provider();
let mut target = ExecutionTarget::new(test_cfg(
"http://127.0.0.1:1",
Some("https://c4c.example.com/"),
))
.unwrap();
target.no_console_link = true;
assert_eq!(target.console_base().await, None);
}
#[test]
fn build_targets_propagates_no_console_link_to_every_target() {
install_rustls_provider();
let configs = vec![
test_cfg("http://127.0.0.1:1", Some("https://c4c.example.com/")),
test_cfg("http://127.0.0.1:2", Some("https://other.example.com/")),
];
let targets = build_targets(configs, true, None).unwrap();
assert_eq!(targets.len(), 2);
for target in &targets {
assert!(target.no_console_link);
}
}
#[test]
fn collect_successes_returns_all_when_none_fail() {
let per_profile: Vec<(String, Result<i32>)> =
vec![("prod".to_string(), Ok(1)), ("staging".to_string(), Ok(2))];
let successes = report_errors_and_collect_successes(per_profile).expect("should not bail");
assert_eq!(
successes,
vec![("prod".to_string(), 1), ("staging".to_string(), 2)]
);
}
#[test]
fn collect_successes_skips_errored_profiles_on_partial_failure() {
let per_profile: Vec<(String, Result<i32>)> = vec![
("good".to_string(), Ok(1)),
("bad".to_string(), Err(anyhow::anyhow!("simulated error"))),
("also-good".to_string(), Ok(2)),
];
let successes = report_errors_and_collect_successes(per_profile)
.expect("partial failure should not bail");
assert_eq!(
successes,
vec![("good".to_string(), 1), ("also-good".to_string(), 2)]
);
}
#[test]
fn collect_successes_bails_when_every_target_fails() {
let per_profile: Vec<(String, Result<i32>)> = vec![
("a".to_string(), Err(anyhow::anyhow!("boom"))),
("b".to_string(), Err(anyhow::anyhow!("boom"))),
];
let result = report_errors_and_collect_successes(per_profile);
assert!(
result.is_err(),
"a total failure must surface as an error, not a silent empty result"
);
}
#[test]
fn collect_successes_does_not_bail_on_empty_input() {
let per_profile: Vec<(String, Result<i32>)> = vec![];
let successes = report_errors_and_collect_successes(per_profile)
.expect("empty fan-out is not a failure");
assert!(successes.is_empty());
}
}