use std::sync::Arc;
use anyhow::{anyhow, bail, Context, Result};
use colored::Colorize;
use serde_json::{json, Value};
use toon_format::encode_default as toon_encode;
pub mod api;
mod legacy;
use api::{
BoolFilter, CategoryType, FieldMatch, Filter, FilterDescriptor, GetResourcesResponse,
HealthHistoryEntry, InfraApi, ListResourcesParams, Op, ResourceData, ResourceTypeMapping,
};
use crate::config::OutputFormat;
use crate::execution::{fan_out, report_errors_and_collect_successes, ExecutionTarget};
use crate::render;
const JSON_KEY_PROFILE: &str = "profile";
#[derive(Debug, Clone, Copy)]
pub struct PageWindow {
pub start_row: Option<i64>,
pub end_row: Option<i64>,
}
pub async fn run_types(targets: &[Arc<ExecutionTarget>], output: OutputFormat) -> Result<()> {
eprintln!("{}", "Fetching available resource types...".dimmed());
let include_profile = targets.len() > 1;
let per_profile = fan_out(targets, |target| async move {
let api = InfraApi::new(&target.client);
Ok(api.available_types().await?)
})
.await;
let mut merged: Vec<(String, ResourceTypeMapping)> = Vec::new();
for (profile, resp) in report_errors_and_collect_successes(per_profile)? {
for mapping in resp.resource_types {
merged.push((profile.clone(), mapping));
}
}
match output {
OutputFormat::Json | OutputFormat::Toon => {
let rows: Vec<Value> = merged
.iter()
.map(|(profile, m)| type_mapping_to_json(m, include_profile, profile))
.collect();
render_machine_rows(output, &rows)?;
}
OutputFormat::Text => {
if merged.is_empty() {
render::print_no_results("No resource types found.");
return Ok(());
}
let rows: Vec<Vec<String>> = merged
.iter()
.map(|(profile, m)| {
vec![
profile.clone(),
display_or_dash(
m.category_type.as_ref().and_then(|c| c.category.as_deref()),
),
display_or_dash(
m.category_type
.as_ref()
.and_then(|c| c.type_name.as_deref()),
),
display_or_dash(m.label.as_deref()),
]
})
.collect();
render::render_table(&["Category", "Type", "Label"], rows, include_profile);
}
}
Ok(())
}
pub async fn run_filters(
targets: &[Arc<ExecutionTarget>],
category: Option<&str>,
resource_type: Option<&str>,
output: OutputFormat,
) -> Result<()> {
let category = category
.map(|c| require_non_empty(c, "--category"))
.transpose()?;
let resource_type = resource_type
.map(|t| require_non_empty(t, "--type"))
.transpose()?;
eprintln!("{}", "Fetching filterable attributes...".dimmed());
let include_profile = targets.len() > 1;
let per_profile = fan_out(targets, |target| async move {
let api = InfraApi::new(&target.client);
Ok(api.filters(category, resource_type).await?)
})
.await;
let mut merged: Vec<(String, FilterDescriptor)> = Vec::new();
for (profile, resp) in report_errors_and_collect_successes(per_profile)? {
for descriptor in resp.filters {
merged.push((profile.clone(), descriptor));
}
}
match output {
OutputFormat::Json | OutputFormat::Toon => {
let rows: Vec<Value> = merged
.iter()
.map(|(profile, f)| filter_to_json(f, include_profile, profile))
.collect();
render_machine_rows(output, &rows)?;
}
OutputFormat::Text => {
if merged.is_empty() {
render::print_no_results("No filterable attributes found.");
return Ok(());
}
let rows: Vec<Vec<String>> = merged
.iter()
.map(|(profile, f)| {
vec![
profile.clone(),
display_or_dash(f.name.as_deref()),
display_or_dash(f.kind.as_deref()),
if f.wildcard { "yes" } else { "no" }.to_string(),
join_or_dash(&f.values),
join_or_dash(&format_type_pairs(&f.types)),
]
})
.collect();
render::render_table(
&["Attribute", "Kind", "Wildcard", "Values", "Types"],
rows,
include_profile,
);
}
}
Ok(())
}
pub async fn run_list(
targets: &[Arc<ExecutionTarget>],
category: Option<&str>,
resource_type: Option<&str>,
match_all: &[String],
match_any: &[String],
window: PageWindow,
output: OutputFormat,
) -> Result<()> {
let category = category
.map(|c| require_non_empty(c, "--category"))
.transpose()?;
let resource_type = resource_type
.map(|t| require_non_empty(t, "--type"))
.transpose()?;
let filter = build_filter(match_all, match_any)?;
if category.is_none() && resource_type.is_none() && filter.is_none() {
bail!(
"nothing to narrow by; pass at least one of --category, --type, \
--match-all or --match-any - `cx infra resources filters` lists \
the attributes this tenant can filter on"
);
}
window.validate()?;
eprintln!("{}", "Fetching resources...".dimmed());
let per_profile = fan_out(targets, |target| {
let category = category.map(String::from);
let resource_type = resource_type.map(String::from);
let filter = &filter;
async move {
let api = InfraApi::new(&target.client);
let params = ListResourcesParams {
category: category.as_deref(),
resource_type: resource_type.as_deref(),
filter: filter.as_ref(),
start_row: window.start_row,
end_row: window.end_row,
};
Ok(api.list(¶ms).await?)
}
})
.await;
render_resources(
per_profile,
targets.len() > 1,
resource_type.is_some(),
output,
)
}
pub async fn run_list_legacy(
targets: &[Arc<ExecutionTarget>],
category: Option<&str>,
resource_type: Option<&str>,
name_filter: Option<&str>,
scope: &[String],
window: PageWindow,
output: OutputFormat,
) -> Result<()> {
let (Some(category), Some(resource_type)) = (category, resource_type) else {
bail!("--name-filter and --scope require both --category and --type");
};
let category = require_non_empty(category, "--category")?;
let resource_type = require_non_empty(resource_type, "--type")?;
let name_filter = name_filter.map(str::trim).filter(|s| !s.is_empty());
let scope_filters = legacy::parse_scope_filters(scope)?;
window.validate()?;
eprintln!("{}", "Fetching resources...".dimmed());
let per_profile = fan_out(targets, |target| {
let category = category.to_string();
let resource_type = resource_type.to_string();
let name_filter = name_filter.map(String::from);
let scope_filters = scope_filters.clone();
async move {
let params = legacy::LegacyListParams {
category: &category,
resource_type: &resource_type,
name_filter: name_filter.as_deref(),
scope_filters: &scope_filters,
start_row: window.start_row,
end_row: window.end_row,
};
Ok(legacy::list(&target.client, ¶ms).await?)
}
})
.await;
render_resources(per_profile, targets.len() > 1, true, output)
}
fn render_resources(
per_profile: Vec<(String, Result<GetResourcesResponse>)>,
include_profile: bool,
type_pinned: bool,
output: OutputFormat,
) -> Result<()> {
let mut counts: Vec<ProfileCounts> = Vec::new();
let mut merged: Vec<(String, ResourceData)> = Vec::new();
for (profile, resp) in report_errors_and_collect_successes(per_profile)? {
counts.push(ProfileCounts {
profile: profile.clone(),
total_count: resp.total_count,
returned_count: resp.resources.len(),
});
for resource in resp.resources {
merged.push((profile.clone(), resource));
}
}
let total_count = aggregate_total(&counts);
match output {
OutputFormat::Json | OutputFormat::Toon => {
let rows: Vec<Value> = merged
.iter()
.map(|(profile, r)| resource_to_json(r, include_profile, profile))
.collect();
let envelope = build_list_envelope(total_count, rows, &counts, include_profile);
render_machine_envelope(output, &envelope)?;
}
OutputFormat::Text => {
if merged.is_empty() {
render::print_no_results("No resources found.");
return Ok(());
}
let (headers, rows) = list_table(&merged);
let header_refs: Vec<&str> = headers.iter().map(String::as_str).collect();
render::render_table(&header_refs, rows, include_profile);
eprintln!(
"{}",
format_count_summary(merged.len(), total_count, &counts, include_profile).dimmed()
);
if !type_pinned {
eprintln!(
"{}",
"Columns are the union of the matched types; a blank cell means the resource \
does not carry that column. Narrow with --type for one type's set."
.dimmed()
);
}
}
}
Ok(())
}
pub async fn run_health_history(
targets: &[Arc<ExecutionTarget>],
resource_id: &str,
output: OutputFormat,
) -> Result<()> {
let resource_id = require_non_empty(resource_id, "resource id")?;
let target = single_target(targets, "health-history")?;
eprintln!(
"{}",
format!("Fetching health history for '{resource_id}'...").dimmed()
);
let resp = InfraApi::new(&target.client)
.health_history(resource_id)
.await
.with_context(|| format!("profile '{}' failed", target.profile_name))?;
let history = resp.health_history;
match output {
OutputFormat::Json | OutputFormat::Toon => {
let rows: Vec<Value> = history.iter().map(health_entry_to_json).collect();
render_machine_rows(output, &rows)?;
}
OutputFormat::Text => {
if history.is_empty() {
render::print_no_results("No health history found.");
return Ok(());
}
let rows: Vec<Vec<String>> = history
.iter()
.map(|entry| {
vec![
target.profile_name.clone(),
display_or_dash(entry.timestamp.as_deref()),
display_or_dash(entry.status.as_deref()),
]
})
.collect();
render::render_table(&["Timestamp", "Status"], rows, false);
}
}
Ok(())
}
pub async fn run_raw_data(
targets: &[Arc<ExecutionTarget>],
resource_id: &str,
output: OutputFormat,
) -> Result<()> {
let resource_id = require_non_empty(resource_id, "resource id")?;
let target = single_target(targets, "raw-data")?;
eprintln!(
"{}",
format!("Fetching raw resource data for '{resource_id}'...").dimmed()
);
let resp = InfraApi::new(&target.client)
.raw_data(resource_id)
.await
.with_context(|| format!("profile '{}' failed", target.profile_name))?;
let results: Vec<Value> = match resp.raw_data {
Some(doc) => vec![doc],
None => {
eprintln!("{}", "no raw data for this resource".yellow());
Vec::new()
}
};
match output {
OutputFormat::Json => render::render_json_auto(&results)?,
OutputFormat::Toon => render::render_toon(&results)?,
OutputFormat::Text => {
render::render_get_text(&results, false, "No raw data found.", None)?;
}
}
Ok(())
}
fn render_machine_rows(output: OutputFormat, rows: &[Value]) -> Result<()> {
match output {
OutputFormat::Json => render::render_json(rows),
OutputFormat::Toon => render::render_toon(rows),
OutputFormat::Text => {
unreachable!("callers render text themselves; only Json/Toon reach here")
}
}
}
struct ProfileCounts {
profile: String,
total_count: i64,
returned_count: usize,
}
fn aggregate_total(counts: &[ProfileCounts]) -> i64 {
counts
.iter()
.fold(0i64, |acc, c| acc.saturating_add(c.total_count))
}
fn build_list_envelope(
total_count: i64,
rows: Vec<Value>,
counts: &[ProfileCounts],
include_profile: bool,
) -> Value {
let mut envelope = serde_json::Map::new();
envelope.insert("total_count".to_string(), json!(total_count));
envelope.insert("returned_count".to_string(), json!(rows.len()));
if include_profile {
let per_profile: Vec<Value> = counts
.iter()
.map(|c| {
json!({
JSON_KEY_PROFILE: c.profile,
"total_count": c.total_count,
"returned_count": c.returned_count,
})
})
.collect();
envelope.insert("counts_by_profile".to_string(), Value::Array(per_profile));
}
envelope.insert("resources".to_string(), Value::Array(rows));
Value::Object(envelope)
}
fn render_machine_envelope(output: OutputFormat, envelope: &Value) -> Result<()> {
match output {
OutputFormat::Json => render::render_json_auto(std::slice::from_ref(envelope)),
OutputFormat::Toon => {
let encoded =
toon_encode(envelope).map_err(|e| anyhow!("TOON encoding failed: {e}"))?;
println!("{encoded}");
Ok(())
}
OutputFormat::Text => {
unreachable!("callers render text themselves; only Json/Toon reach here")
}
}
}
fn format_count_summary(
returned: usize,
total: i64,
counts: &[ProfileCounts],
include_profile: bool,
) -> String {
let mut out = format!("Showing {returned} of {total} total resources");
if include_profile {
for c in counts {
out.push_str(&format!(
"\n {}: {} of {}",
c.profile, c.returned_count, c.total_count
));
}
}
out
}
fn require_non_empty<'v>(value: &'v str, field_name: &str) -> Result<&'v str> {
let trimmed = value.trim();
if trimmed.is_empty() {
bail!("{field_name} must not be empty");
}
Ok(trimmed)
}
fn single_target<'t>(
targets: &'t [Arc<ExecutionTarget>],
subcommand: &str,
) -> Result<&'t ExecutionTarget> {
match targets {
[target] => Ok(target),
[] => bail!("no profile resolved for `cx infra resources {subcommand}`"),
_ => bail!(
"`cx infra resources {subcommand}` accepts a single profile, but {} were given; \
a resource id is scoped to one team and cannot resolve in another profile. \
Re-run once per profile with a single -p.",
targets.len()
),
}
}
impl PageWindow {
fn validate(self) -> Result<()> {
let Self { start_row, end_row } = self;
if let Some(start) = start_row {
if start < 0 {
bail!("--start-row must not be negative (got {start}); rows are 0-based");
}
}
if let Some(end) = end_row {
if end < 0 {
bail!("--end-row must not be negative (got {end})");
}
}
if let (Some(start), Some(end)) = (start_row, end_row) {
if end <= start {
bail!(
"--end-row ({end}) must be greater than --start-row ({start}); \
--end-row is exclusive, so this window selects no rows"
);
}
}
Ok(())
}
}
fn build_filter(match_all: &[String], match_any: &[String]) -> Result<Option<Filter>> {
let all = parse_matches(match_all, "--match-all")?;
let any_matches = parse_matches(match_any, "--match-any")?;
if let Some(field) = all.iter().map(|m| &m.field).find(|field| {
any_matches
.iter()
.any(|m| m.field.eq_ignore_ascii_case(field))
}) {
bail!(
"attribute '{field}' appears in both --match-all and --match-any; \
an attribute belongs to one of them - require it with --match-all, \
or make it one alternative with --match-any"
);
}
let mut operands: Vec<Filter> = all
.into_iter()
.flat_map(|m| {
let field = m.field;
m.values.into_iter().map(move |value| {
Filter::Match(FieldMatch {
field: field.clone(),
values: vec![value],
})
})
})
.collect();
let any: Vec<Filter> = any_matches.into_iter().map(Filter::Match).collect();
if any.len() == 1 {
operands.extend(any);
} else if !any.is_empty() {
operands.push(Filter::Bool(BoolFilter {
op: Op::Or,
operands: any,
}));
}
if operands.len() == 1 {
return Ok(operands.pop());
}
Ok((!operands.is_empty()).then_some(Filter::Bool(BoolFilter {
op: Op::And,
operands,
})))
}
fn parse_matches(raw: &[String], flag: &str) -> Result<Vec<FieldMatch>> {
let mut matches: Vec<FieldMatch> = Vec::new();
for entry in raw {
let Some((field, values_raw)) = entry.split_once('=') else {
bail!("invalid {flag} '{entry}': expected NAME=VALUE");
};
let field = field.trim();
if field.is_empty() {
bail!("invalid {flag} '{entry}': attribute name must not be empty");
}
let mut values: Vec<String> = Vec::new();
for value in values_raw.split(',').map(str::trim) {
if !value.is_empty() && !values.iter().any(|seen| seen == value) {
values.push(value.to_string());
}
}
if values.is_empty() {
bail!("invalid {flag} '{entry}': value must not be empty");
}
if matches.iter().any(|m| m.field.eq_ignore_ascii_case(field)) {
bail!(
"{flag} attribute '{field}' given more than once; \
list its values on one flag instead - {flag} {field}=a,b"
);
}
matches.push(FieldMatch {
field: field.to_string(),
values,
});
}
Ok(matches)
}
fn filter_to_json(item: &FilterDescriptor, include_profile: bool, profile: &str) -> Value {
let v = json!({
"name": item.name,
"kind": item.kind,
"wildcard": item.wildcard,
"values": item.values,
"types": item
.types
.iter()
.map(|t| json!({ "category": t.category, "type": t.type_name }))
.collect::<Vec<Value>>(),
});
tag_profile(v, include_profile, profile)
}
fn format_type_pairs(types: &[CategoryType]) -> Vec<String> {
types
.iter()
.map(|t| {
format!(
"{}/{}",
display_or_dash(t.category.as_deref()),
display_or_dash(t.type_name.as_deref())
)
})
.collect()
}
fn join_or_dash(values: &[String]) -> String {
if values.is_empty() {
"-".to_string()
} else {
values.join(", ")
}
}
fn resource_to_json(item: &ResourceData, include_profile: bool, profile: &str) -> Value {
let v = json!({
"resource_id": item.resource_id,
"name": item.name,
"category": item.category,
"type": item.type_name,
"columns": item.columns,
});
tag_profile(v, include_profile, profile)
}
fn tag_profile(mut v: Value, include_profile: bool, profile: &str) -> Value {
if include_profile {
if let Value::Object(ref mut m) = v {
m.insert(
JSON_KEY_PROFILE.to_string(),
Value::String(profile.to_string()),
);
}
}
v
}
fn health_entry_to_json(item: &HealthHistoryEntry) -> Value {
json!({
"timestamp": item.timestamp,
"status": item.status,
})
}
fn type_mapping_to_json(item: &ResourceTypeMapping, include_profile: bool, profile: &str) -> Value {
let v = json!({
"category": item.category_type.as_ref().and_then(|c| c.category.clone()),
"type": item.category_type.as_ref().and_then(|c| c.type_name.clone()),
"label": item.label,
});
tag_profile(v, include_profile, profile)
}
fn display_or_dash(value: Option<&str>) -> String {
value.filter(|s| !s.is_empty()).unwrap_or("-").to_string()
}
fn list_table(merged: &[(String, ResourceData)]) -> (Vec<String>, Vec<Vec<String>>) {
let resources: Vec<&ResourceData> = merged.iter().map(|(_, r)| r).collect();
let columns = union_of_columns(&resources);
let headers: Vec<String> = ["Resource ID", "Name", "Category", "Type"]
.into_iter()
.map(String::from)
.chain(columns.iter().cloned())
.collect();
let rows: Vec<Vec<String>> = merged
.iter()
.map(|(profile, r)| {
let mut row = vec![
profile.clone(),
display_or_dash(r.resource_id.as_deref()),
display_or_dash(display_name(r)),
display_or_dash(r.category.as_deref()),
display_or_dash(r.type_name.as_deref()),
];
row.extend(
columns
.iter()
.map(|column| r.columns.get(column).cloned().unwrap_or_default()),
);
row
})
.collect();
(headers, rows)
}
fn union_of_columns(resources: &[&ResourceData]) -> Vec<String> {
let mut columns: Vec<String> = Vec::new();
for resource in resources {
for name in resource.columns.keys() {
if !name.eq_ignore_ascii_case("name") && !columns.contains(name) {
columns.push(name.clone());
}
}
}
columns
}
fn display_name(item: &ResourceData) -> Option<&str> {
item.columns
.iter()
.find(|(key, _)| key.eq_ignore_ascii_case("name"))
.map(|(_, value)| value.as_str())
.filter(|s| !s.is_empty())
.or(item.name.as_deref())
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
#[test]
fn require_non_empty_trims_and_accepts_values() {
assert_eq!(require_non_empty(" Hosts ", "--category").unwrap(), "Hosts");
}
#[test]
fn require_non_empty_rejects_empty_and_whitespace() {
let err = require_non_empty("", "--category").unwrap_err();
assert!(err.to_string().contains("--category must not be empty"));
let err = require_non_empty(" ", "resource id").unwrap_err();
assert!(err.to_string().contains("resource id must not be empty"));
}
#[test]
fn parse_matches_reads_one_attribute_and_one_value() {
let matches = parse_matches(&["Region=eu-west-1".to_string()], "--match-all").unwrap();
assert_eq!(
matches,
vec![FieldMatch {
field: "Region".to_string(),
values: vec!["eu-west-1".to_string()],
}]
);
}
#[test]
fn parse_matches_splits_values_on_commas() {
let matches =
parse_matches(&["Region=eu-west-1,us-east-1".to_string()], "--match-all").unwrap();
assert_eq!(matches[0].values, vec!["eu-west-1", "us-east-1"]);
}
#[test]
fn parse_matches_dedupes_repeated_values_in_one_list() {
let matches = parse_matches(
&["Region=eu-west-1,us-east-1,eu-west-1".to_string()],
"--match-all",
)
.unwrap();
assert_eq!(matches[0].values, vec!["eu-west-1", "us-east-1"]);
}
#[test]
fn parse_matches_trims_whitespace_around_both_sides() {
let matches = parse_matches(
&[" Region = eu-west-1 , us-east-1 ".to_string()],
"--match-all",
)
.unwrap();
assert_eq!(matches[0].field, "Region");
assert_eq!(matches[0].values, vec!["eu-west-1", "us-east-1"]);
}
#[test]
fn parse_matches_keeps_a_value_containing_an_equals() {
let matches = parse_matches(&["Tag=env=prod".to_string()], "--match-all").unwrap();
assert_eq!(matches[0].values, vec!["env=prod"]);
}
#[test]
fn parse_matches_rejects_a_missing_equals() {
let err = parse_matches(&["Region".to_string()], "--match-all").unwrap_err();
assert!(err.to_string().contains("expected NAME=VALUE"));
}
#[test]
fn parse_matches_rejects_an_empty_attribute_name() {
let err = parse_matches(&["=eu-west-1".to_string()], "--match-all").unwrap_err();
assert!(err.to_string().contains("must not be empty"));
}
#[test]
fn parse_matches_rejects_an_empty_value() {
for entry in ["Region=", "Region=,", "Region= , "] {
let err = parse_matches(&[entry.to_string()], "--match-all").unwrap_err();
assert!(
err.to_string().contains("value must not be empty"),
"{entry} should be refused"
);
}
}
#[test]
fn parse_matches_rejects_a_repeated_attribute() {
let err = parse_matches(
&[
"Region=eu-west-1".to_string(),
"Region=us-east-1".to_string(),
],
"--match-all",
)
.unwrap_err();
let msg = err.to_string();
assert!(msg.contains("'Region' given more than once"), "got: {msg}");
assert!(msg.contains("--match-all Region=a,b"), "got: {msg}");
}
#[test]
fn parse_matches_detects_a_repeat_whatever_its_case() {
let err = parse_matches(
&[
"Region=eu-west-1".to_string(),
"region=us-east-1".to_string(),
],
"--match-any",
)
.unwrap_err();
assert!(err.to_string().contains("given more than once"));
}
#[test]
fn parse_matches_names_the_flag_it_was_given() {
let err = parse_matches(&["Region".to_string()], "--match-any").unwrap_err();
assert!(err.to_string().contains("--match-any"));
}
#[test]
fn parse_matches_empty_input_yields_no_matches() {
assert!(parse_matches(&[], "--match-all").unwrap().is_empty());
}
#[test]
fn build_filter_is_absent_without_either_flag() {
assert_eq!(build_filter(&[], &[]).unwrap(), None);
}
#[test]
fn build_filter_collapses_a_single_attribute() {
let filter = build_filter(&["Health=critical".to_string()], &[])
.unwrap()
.unwrap();
assert_eq!(
filter,
Filter::Match(FieldMatch {
field: "Health".to_string(),
values: vec!["critical".to_string()],
})
);
}
#[test]
fn build_filter_collapses_a_single_match_any() {
let filter = build_filter(&[], &["Health=critical".to_string()])
.unwrap()
.unwrap();
assert!(matches!(filter, Filter::Match(_)), "{filter:?}");
}
#[test]
fn build_filter_ands_every_match_all() {
let filter = build_filter(
&[
"Region=eu-west-1".to_string(),
"Health=critical".to_string(),
],
&[],
)
.unwrap()
.unwrap();
let Filter::Bool(BoolFilter { op, operands }) = filter else {
panic!("expected a bool");
};
assert_eq!(op, Op::And);
assert_eq!(operands.len(), 2);
assert!(operands.iter().all(|o| matches!(o, Filter::Match(_))));
}
#[test]
fn build_filter_ors_every_match_any() {
let filter = build_filter(
&[],
&[
"Name=coredns".to_string(),
"Namespace=kube-system".to_string(),
],
)
.unwrap()
.unwrap();
let Filter::Bool(BoolFilter { op, operands }) = filter else {
panic!("expected a bool");
};
assert_eq!(op, Op::Or);
assert_eq!(operands.len(), 2);
}
#[test]
fn build_filter_nests_the_or_group_inside_the_and() {
let filter = build_filter(
&["OS=Linux".to_string()],
&[
"Health=critical".to_string(),
"Region=eu-west-1".to_string(),
],
)
.unwrap()
.unwrap();
let Filter::Bool(BoolFilter { op, operands }) = filter else {
panic!("expected a bool");
};
assert_eq!(op, Op::And);
assert_eq!(operands.len(), 2);
assert_eq!(
operands[0],
Filter::Match(FieldMatch {
field: "OS".to_string(),
values: vec!["Linux".to_string()],
})
);
let Filter::Bool(BoolFilter {
op: inner_op,
operands: inner,
}) = &operands[1]
else {
panic!("expected the second operand to be the OR group");
};
assert_eq!(*inner_op, Op::Or);
assert_eq!(inner.len(), 2);
}
#[test]
fn build_filter_refuses_one_attribute_in_both_groups() {
let err = build_filter(
&["Region=eu-west-1".to_string()],
&["Region=us-east-1".to_string()],
)
.unwrap_err();
let msg = err.to_string();
assert!(msg.contains("'Region' appears in both"), "got: {msg}");
assert!(
msg.contains("--match-all") && msg.contains("--match-any"),
"got: {msg}"
);
}
#[test]
fn build_filter_detects_a_cross_group_repeat_whatever_its_case() {
let err = build_filter(
&["Region=eu-west-1".to_string()],
&["region=us-east-1".to_string()],
)
.unwrap_err();
assert!(err.to_string().contains("appears in both"));
}
#[test]
fn build_filter_ands_the_values_of_one_match_all() {
let filter = build_filter(&["Tag=a,b".to_string()], &[])
.unwrap()
.unwrap();
let Filter::Bool(BoolFilter { op, operands }) = filter else {
panic!("expected a bool");
};
assert_eq!(op, Op::And);
assert_eq!(
operands,
vec![
Filter::Match(FieldMatch {
field: "Tag".to_string(),
values: vec!["a".to_string()],
}),
Filter::Match(FieldMatch {
field: "Tag".to_string(),
values: vec!["b".to_string()],
}),
]
);
}
#[test]
fn build_filter_ors_the_values_of_one_match_any() {
let filter = build_filter(&[], &["Tag=a,b".to_string()])
.unwrap()
.unwrap();
assert_eq!(
filter,
Filter::Match(FieldMatch {
field: "Tag".to_string(),
values: vec!["a".to_string(), "b".to_string()],
})
);
}
#[test]
fn build_filter_expands_each_match_all_attribute_independently() {
let filter = build_filter(&["Tag=a,b".to_string(), "OS=linux".to_string()], &[])
.unwrap()
.unwrap();
let Filter::Bool(BoolFilter { op, operands }) = filter else {
panic!("expected a bool");
};
assert_eq!(op, Op::And);
assert_eq!(operands.len(), 3);
assert!(operands.iter().all(|o| matches!(o, Filter::Match(_))));
}
#[test]
fn build_filter_keeps_the_groups_distinct() {
let filter = build_filter(&["Tag=a,b".to_string()], &["Region=eu,us".to_string()])
.unwrap()
.unwrap();
let Filter::Bool(BoolFilter { op, operands }) = filter else {
panic!("expected a bool");
};
assert_eq!(op, Op::And);
assert_eq!(
operands,
vec![
Filter::Match(FieldMatch {
field: "Tag".to_string(),
values: vec!["a".to_string()],
}),
Filter::Match(FieldMatch {
field: "Tag".to_string(),
values: vec!["b".to_string()],
}),
Filter::Match(FieldMatch {
field: "Region".to_string(),
values: vec!["eu".to_string(), "us".to_string()],
}),
]
);
}
#[test]
fn build_filter_propagates_a_parse_error() {
assert!(build_filter(&["Region".to_string()], &[]).is_err());
assert!(build_filter(&[], &["Region".to_string()]).is_err());
}
#[test]
fn page_window_accepts_an_ascending_window_and_open_ends() {
assert!(PageWindow {
start_row: None,
end_row: None
}
.validate()
.is_ok());
assert!(PageWindow {
start_row: Some(0),
end_row: Some(100)
}
.validate()
.is_ok());
assert!(PageWindow {
start_row: Some(100),
end_row: Some(200)
}
.validate()
.is_ok());
assert!(PageWindow {
start_row: Some(100),
end_row: None
}
.validate()
.is_ok());
assert!(PageWindow {
start_row: None,
end_row: Some(50)
}
.validate()
.is_ok());
assert!(PageWindow {
start_row: Some(0),
end_row: Some(1)
}
.validate()
.is_ok());
}
#[test]
fn page_window_rejects_a_negative_start_row() {
let err = PageWindow {
start_row: Some(-5),
end_row: None,
}
.validate()
.unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("--start-row must not be negative"),
"got: {msg}"
);
assert!(msg.contains("-5"), "got: {msg}");
}
#[test]
fn page_window_rejects_a_negative_end_row() {
let err = PageWindow {
start_row: None,
end_row: Some(-1),
}
.validate()
.unwrap_err();
assert!(err.to_string().contains("--end-row must not be negative"));
}
#[test]
fn page_window_rejects_an_inverted_window() {
let err = PageWindow {
start_row: Some(200),
end_row: Some(100),
}
.validate()
.unwrap_err();
let msg = err.to_string();
assert!(msg.contains("must be greater than"), "got: {msg}");
assert!(msg.contains("100") && msg.contains("200"), "got: {msg}");
}
#[test]
fn page_window_rejects_an_empty_window() {
let err = PageWindow {
start_row: Some(100),
end_row: Some(100),
}
.validate()
.unwrap_err();
assert!(err.to_string().contains("selects no rows"));
}
#[test]
fn tag_profile_inserts_key_only_when_multi_profile() {
let tagged = tag_profile(json!({"a": 1}), true, "prod");
assert_eq!(tagged["profile"], "prod");
let untagged = tag_profile(json!({"a": 1}), false, "prod");
assert!(untagged.get("profile").is_none());
}
#[test]
fn aggregate_total_sums_profile_totals() {
let counts = counts(&[("prod", 150, 100), ("staging", 90, 90)]);
assert_eq!(aggregate_total(&counts), 240);
}
#[test]
fn aggregate_total_of_no_profiles_is_zero() {
assert_eq!(aggregate_total(&[]), 0);
}
#[test]
fn aggregate_total_saturates_instead_of_overflowing() {
let counts = counts(&[("a", i64::MAX, 1), ("b", 1, 1)]);
assert_eq!(aggregate_total(&counts), i64::MAX);
}
#[test]
fn envelope_reports_total_and_returned_counts() {
let counts = counts(&[("prod", 512_000, 100)]);
let envelope = build_list_envelope(512_000, rows(100), &counts, false);
assert_eq!(envelope["total_count"], 512_000);
assert_eq!(envelope["returned_count"], 100);
assert_eq!(envelope["resources"].as_array().unwrap().len(), 100);
}
#[test]
fn envelope_orders_counts_before_resources() {
let counts = counts(&[("prod", 5, 5)]);
let envelope = build_list_envelope(5, rows(5), &counts, false);
let keys: Vec<&str> = envelope
.as_object()
.unwrap()
.keys()
.map(String::as_str)
.collect();
assert_eq!(keys, vec!["total_count", "returned_count", "resources"]);
}
#[test]
fn envelope_distinguishes_a_partial_window_from_the_fleet_total() {
let counts = counts(&[("prod", 512_000, 100)]);
let envelope = build_list_envelope(512_000, rows(100), &counts, false);
assert_ne!(envelope["total_count"], envelope["returned_count"]);
assert_eq!(envelope["total_count"], 512_000);
assert_eq!(envelope["returned_count"], 100);
}
#[test]
fn envelope_returned_count_matches_the_emitted_row_count() {
let counts = counts(&[("prod", 150, 100), ("staging", 90, 90)]);
let envelope = build_list_envelope(240, rows(190), &counts, true);
assert_eq!(envelope["returned_count"], 190);
assert_eq!(
envelope["returned_count"].as_u64().unwrap() as usize,
envelope["resources"].as_array().unwrap().len()
);
}
#[test]
fn envelope_omits_per_profile_counts_for_a_single_profile() {
let counts = counts(&[("prod", 150, 100)]);
let envelope = build_list_envelope(150, rows(100), &counts, false);
assert!(envelope.get("counts_by_profile").is_none());
}
#[test]
fn envelope_breaks_counts_down_per_profile_when_fanning_out() {
let counts = counts(&[("prod", 150, 100), ("staging", 90, 90)]);
let envelope = build_list_envelope(240, rows(190), &counts, true);
let per_profile = envelope["counts_by_profile"].as_array().unwrap();
assert_eq!(per_profile.len(), 2);
assert_eq!(per_profile[0]["profile"], "prod");
assert_eq!(per_profile[0]["total_count"], 150);
assert_eq!(per_profile[0]["returned_count"], 100);
assert_eq!(per_profile[1]["profile"], "staging");
assert_eq!(per_profile[1]["total_count"], 90);
assert_eq!(per_profile[1]["returned_count"], 90);
}
#[test]
fn envelope_for_no_results_still_reports_counts() {
let envelope = build_list_envelope(0, rows(0), &counts(&[("prod", 0, 0)]), false);
assert_eq!(envelope["total_count"], 0);
assert_eq!(envelope["returned_count"], 0);
assert!(envelope["resources"].as_array().unwrap().is_empty());
}
#[test]
fn count_summary_reports_the_total() {
let counts = counts(&[("prod", 512_000, 100)]);
assert_eq!(
format_count_summary(100, 512_000, &counts, false),
"Showing 100 of 512000 total resources"
);
}
#[test]
fn count_summary_breaks_down_per_profile_when_fanning_out() {
let counts = counts(&[("prod", 150, 100), ("staging", 90, 90)]);
assert_eq!(
format_count_summary(190, 240, &counts, true),
"Showing 190 of 240 total resources\n prod: 100 of 150\n staging: 90 of 90"
);
}
#[test]
fn display_or_dash_falls_back_on_none_and_empty() {
assert_eq!(display_or_dash(Some("value")), "value");
assert_eq!(display_or_dash(Some("")), "-");
assert_eq!(display_or_dash(None), "-");
}
fn resource(name: Option<&str>, columns: &[(&str, &str)]) -> ResourceData {
ResourceData {
resource_id: Some("4013226:host_id=i-077a1626590913a16".to_string()),
name: name.map(String::from),
columns: columns
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect(),
category: Some("Hosts".to_string()),
type_name: Some("EC2_Instances".to_string()),
}
}
#[test]
fn display_name_prefers_the_name_column() {
let r = resource(
Some("i-077a1626590913a16"),
&[("Name", "ip-10-109-46-236.eu-west-1.compute.internal")],
);
assert_eq!(
display_name(&r),
Some("ip-10-109-46-236.eu-west-1.compute.internal")
);
}
#[test]
fn display_name_matches_the_column_key_case_insensitively() {
let r = resource(Some("i-abc123"), &[("name", "web-server-1")]);
assert_eq!(display_name(&r), Some("web-server-1"));
}
#[test]
fn display_name_falls_back_to_the_name_field() {
let missing = resource(Some("i-abc123"), &[("region", "eu-west-1")]);
assert_eq!(display_name(&missing), Some("i-abc123"));
let empty = resource(Some("i-abc123"), &[("Name", "")]);
assert_eq!(display_name(&empty), Some("i-abc123"));
let neither = resource(None, &[]);
assert_eq!(display_name(&neither), None);
}
fn typed_resource(category: &str, type_name: &str, columns: &[(&str, &str)]) -> ResourceData {
let mut r = resource(Some("name"), columns);
r.category = Some(category.to_string());
r.type_name = Some(type_name.to_string());
r
}
#[test]
fn union_of_columns_sorts_each_row_then_appends_new_names() {
let a = typed_resource(
"Hosts",
"EC2_Instances",
&[("Region", "eu"), ("OS", "Linux")],
);
let b = typed_resource("Kubernetes", "Pods", &[("Namespace", "kube-system")]);
assert_eq!(
union_of_columns(&[&a, &b]),
vec![
"OS".to_string(),
"Region".to_string(),
"Namespace".to_string()
]
);
}
#[test]
fn union_of_columns_leaves_name_to_its_own_column() {
let r = typed_resource(
"Hosts",
"EC2_Instances",
&[("Name", "web-01"), ("Region", "eu")],
);
assert_eq!(union_of_columns(&[&r]), vec!["Region".to_string()]);
}
#[test]
fn union_of_columns_does_not_repeat_a_shared_column() {
let a = typed_resource("Hosts", "EC2_Instances", &[("Region", "eu")]);
let b = typed_resource("Hosts", "Azure_VMs", &[("Region", "westeu")]);
assert_eq!(union_of_columns(&[&a, &b]), vec!["Region".to_string()]);
}
#[test]
fn union_of_columns_is_empty_without_rows() {
assert!(union_of_columns(&[]).is_empty());
}
fn merged_row(
category: &str,
type_name: &str,
columns: &[(&str, &str)],
) -> (String, ResourceData) {
(
"p".to_string(),
typed_resource(category, type_name, columns),
)
}
#[test]
fn list_table_always_carries_the_classification_columns() {
let (headers, rows) = list_table(&[merged_row(
"Hosts",
"EC2_Instances",
&[("Region", "eu-west-1")],
)]);
assert_eq!(headers[..4], ["Resource ID", "Name", "Category", "Type"]);
assert_eq!(rows[0][3], "Hosts");
assert_eq!(rows[0][4], "EC2_Instances");
}
#[test]
fn list_table_has_one_shape_whatever_the_row_mix() {
let one_type = list_table(&[merged_row("Hosts", "EC2_Instances", &[("Region", "eu")])]).0;
let mixed = list_table(&[
merged_row("Hosts", "EC2_Instances", &[("Region", "eu")]),
merged_row("Hosts", "Azure_VMs", &[("Region", "westeu")]),
])
.0;
assert_eq!(one_type, mixed);
}
#[test]
fn list_table_leaves_a_missing_column_blank() {
let (headers, rows) = list_table(&[
merged_row("Hosts", "EC2_Instances", &[("Region", "eu-west-1")]),
merged_row("Kubernetes", "Pods", &[("Namespace", "kube-system")]),
]);
assert_eq!(headers[4..], ["Region", "Namespace"]);
assert_eq!(rows[0][5], "eu-west-1");
assert_eq!(rows[0][6], "");
assert_eq!(rows[1][5], "");
assert_eq!(rows[1][6], "kube-system");
}
#[test]
fn list_table_dashes_a_missing_fixed_column() {
let mut row = typed_resource("Hosts", "EC2_Instances", &[("Region", "eu")]);
row.category = None;
let (_, rows) = list_table(&[("p".to_string(), row)]);
assert_eq!(rows[0][3], "-");
assert_eq!(rows[0][5], "eu");
}
#[test]
fn a_json_row_carries_the_scope_and_the_columns() {
let item = ResourceData {
resource_id: Some("4013226:host_id=i-077a".to_string()),
name: Some("prod-api-01".to_string()),
columns: BTreeMap::from([
("Name".to_string(), "prod-api-01".to_string()),
("Region".to_string(), "eu-west-1".to_string()),
]),
category: Some("Hosts".to_string()),
type_name: Some("EC2_Instances".to_string()),
};
assert_eq!(
resource_to_json(&item, false, "prod"),
json!({
"resource_id": "4013226:host_id=i-077a",
"name": "prod-api-01",
"category": "Hosts",
"type": "EC2_Instances",
"columns": { "Name": "prod-api-01", "Region": "eu-west-1" },
})
);
}
#[test]
fn a_json_row_is_tagged_with_its_profile_only_when_asked() {
let item = ResourceData {
resource_id: Some("id".to_string()),
name: Some("n".to_string()),
columns: BTreeMap::new(),
category: Some("Hosts".to_string()),
type_name: Some("EC2_Instances".to_string()),
};
assert_eq!(resource_to_json(&item, true, "prod")["profile"], "prod");
assert!(resource_to_json(&item, false, "prod")
.get("profile")
.is_none());
}
fn counts(entries: &[(&str, i64, usize)]) -> Vec<ProfileCounts> {
entries
.iter()
.map(|(profile, total_count, returned_count)| ProfileCounts {
profile: profile.to_string(),
total_count: *total_count,
returned_count: *returned_count,
})
.collect()
}
fn rows(n: usize) -> Vec<Value> {
(0..n)
.map(|i| json!({ "resource_id": format!("id-{i}") }))
.collect()
}
}