use super::*;
pub fn inspect_live_bridge(base_url: &str) -> io::Result<LiveInspectReport> {
let (host_port, base_prefix): (String, String) = parse_http_base_url(base_url)?;
let health_path: String = format!("{base_prefix}{PATH_AI_HEALTH}");
let health_resp: Result<(u16, String), Error> = http_get_text(&host_port, &health_path);
let (reachable, health_status, err_opt): (bool, String, Option<String>) = match health_resp {
Ok((200, body)) => {
let status_str: String = from_str::<Value>(&body)
.ok()
.and_then(|val: Value| {
val.get(JSON_KEY_STATUS)
.and_then(Value::as_str)
.map(str::to_string)
})
.unwrap_or_else(|| STATUS_OK.to_string());
(true, status_str, None)
}
Ok((code, _)) => (true, format!("http-{code}"), None),
Err(err) => (
false,
INSPECT_UNREACHABLE_STATUS.to_string(),
Some(err.to_string()),
),
};
if !reachable {
let mut unreachable_report: LiveInspectReport =
LiveInspectReport::new(base_url.to_string(), false, health_status);
let _: &mut LiveInspectReport = unreachable_report
.set_active_route(INSPECT_UNKNOWN_ROUTE.to_string())
.set_error(err_opt);
return Ok(unreachable_report);
}
let candidate_paths: [&str; 3] = [PATH_AI_SNAPSHOT_V2, PATH_AI_SNAPSHOT, PATH_AI_SCHEMA];
let mut snapshot_json: Option<Value> = None;
for suffix in candidate_paths.iter() {
let full_path: String = format!("{base_prefix}{suffix}");
if let Ok((200, body)) = http_get_text(&host_port, &full_path)
&& let Ok(parsed) = from_str::<Value>(&body)
{
snapshot_json = Some(parsed);
break;
}
}
let mut protocol_version: String = String::new();
let mut active_route: String = INSPECT_UNKNOWN_ROUTE.to_string();
let mut node_count: usize = 0;
let mut anomalies: Vec<String> = Vec::new();
if let Some(root_val) = snapshot_json {
if let Some(proto) = root_val
.get(JSON_KEY_PROTOCOL)
.or_else(|| root_val.get(JSON_KEY_SCHEMA))
.or_else(|| root_val.get(JSON_KEY_VERSION))
.and_then(Value::as_str)
{
protocol_version = proto.to_string();
}
if let Some(route) = root_val
.get(JSON_KEY_ACTIVE_ROUTE)
.or_else(|| root_val.get(JSON_KEY_ROUTE))
.and_then(Value::as_str)
{
active_route = route.to_string();
}
if let Some(count) = root_val.get(JSON_KEY_NODE_COUNT).and_then(Value::as_u64) {
node_count = count as usize;
} else if let Some(nodes_arr) = root_val.get(JSON_KEY_NODES).and_then(Value::as_array) {
node_count = nodes_arr.len();
}
let anomaly_array: Option<&Vec<Value>> = root_val
.get(JSON_KEY_ANOMALIES)
.or_else(|| root_val.get(JSON_KEY_LAYOUT_ANOMALIES))
.and_then(Value::as_array);
if let Some(items) = anomaly_array {
for item in items.iter() {
anomalies.push(describe_anomaly_value(item));
}
}
}
let anomaly_count: usize = anomalies.len();
let mut report: LiveInspectReport =
LiveInspectReport::new(base_url.to_string(), true, health_status);
let _: &mut LiveInspectReport = report
.set_protocol_version(protocol_version)
.set_active_route(active_route)
.set_node_count(node_count)
.set_anomaly_count(anomaly_count)
.set_anomalies(anomalies);
Ok(report)
}
pub fn inspect_dist_directory(dist_dir: &Path) -> io::Result<DistInspectReport> {
if !dist_dir.is_dir() {
return Err(Error::new(
ErrorKind::NotFound,
format!("{ERR_DIST_DIR_MISSING}: {}", dist_dir.display()),
));
}
let mut files: Vec<DistFileStat> = Vec::new();
let mut js_files: Vec<String> = Vec::new();
let mut total_bytes: u64 = 0;
collect_dist_files(
dist_dir,
dist_dir,
&mut files,
&mut js_files,
&mut total_bytes,
)?;
let file_count: usize = files.len();
files.sort_by(|left: &DistFileStat, right: &DistFileStat| {
right
.get_size_bytes()
.cmp(&left.get_size_bytes())
.then_with(|| left.get_path().cmp(right.get_path()))
});
let largest_files: Vec<DistFileStat> =
files.into_iter().take(INSPECT_MAX_LARGEST_FILES).collect();
js_files.sort();
let zero_js_compliant: bool = js_files.is_empty();
let manifest_path: PathBuf = dist_dir.join(RELEASE_MANIFEST_NAME);
let manifest_present: bool = manifest_path.is_file();
let mut manifest_version: Option<String> = None;
let mut manifest_errors: Vec<String> = Vec::new();
if manifest_present {
verify_release_manifest_file(
dist_dir,
&manifest_path,
&mut manifest_version,
&mut manifest_errors,
);
}
let manifest_verified: bool = manifest_present && manifest_errors.is_empty();
let mut report: DistInspectReport =
DistInspectReport::new(dist_dir.display().to_string(), file_count, total_bytes);
let _: &mut DistInspectReport = report
.set_largest_files(largest_files)
.set_js_files(js_files)
.set_zero_js_compliant(zero_js_compliant)
.set_manifest_present(manifest_present)
.set_manifest_version(manifest_version)
.set_manifest_verified(manifest_verified)
.set_manifest_errors(manifest_errors);
Ok(report)
}
#[must_use]
pub fn format_live_inspect_report(report: &LiveInspectReport, anomalies_only: bool) -> String {
let mut out: String = format!(
"euv inspect — bridge: {} [{}]\n",
report.get_url(),
report.get_health_status()
);
if let Some(err) = report.try_get_error() {
out.push_str(&format!(" error: {err}\n"));
return out;
}
if !anomalies_only {
out.push_str(&format!(
" protocol: {}\n route: {}\n nodes: {}\n",
report.get_protocol_version(),
report.get_active_route(),
report.get_node_count()
));
}
out.push_str(&format!(" anomalies: {}\n", report.get_anomaly_count()));
for item in report.get_anomalies().iter() {
out.push_str(&format!(" - {item}\n"));
}
out
}
#[must_use]
pub fn format_dist_inspect_report(report: &DistInspectReport) -> String {
let zero_js_badge: &str = if report.get_zero_js_compliant() {
StatusBadge::Pass.as_str()
} else {
StatusBadge::Fail.as_str()
};
let manifest_badge: &str = if !report.get_manifest_present() {
StatusBadge::Skip.as_str()
} else if report.get_manifest_verified() {
StatusBadge::Pass.as_str()
} else {
StatusBadge::Fail.as_str()
};
let ver_label: &str = report
.try_get_manifest_version()
.as_deref()
.unwrap_or(STATUS_MISSING);
let mut out: String = format!(
"euv inspect --dist {}\n files: {} ({})\n zero-js: [{}]\n euv-release.json: [{}] (version={ver_label})\n\n",
report.get_dist_dir(),
report.get_file_count(),
format_bytes_human(report.get_total_bytes()),
zero_js_badge,
manifest_badge
);
let mut table: TerminalTable = TerminalTable::with_headers(vec![
INSPECT_HDR_FILE.to_string(),
INSPECT_HDR_SIZE.to_string(),
]);
for stat in report.get_largest_files().iter() {
table.push_row(vec![
stat.get_path().clone(),
format_bytes_human(stat.get_size_bytes()),
]);
}
out.push_str(&table.render());
for err in report.get_manifest_errors().iter() {
out.push_str(&format!(" [{}] {err}\n", StatusBadge::Fail.as_str()));
}
out
}
fn collect_dist_files(
root: &Path,
dir: &Path,
files: &mut Vec<DistFileStat>,
js_files: &mut Vec<String>,
total_bytes: &mut u64,
) -> io::Result<()> {
for entry_res in fs::read_dir(dir)? {
let entry: DirEntry = entry_res?;
let path: PathBuf = entry.path();
let meta: Metadata = fs::symlink_metadata(&path)?;
if meta.file_type().is_symlink() {
continue;
}
if meta.is_dir() {
collect_dist_files(root, &path, files, js_files, total_bytes)?;
continue;
}
if !meta.is_file() {
continue;
}
let rel_path: String = path
.strip_prefix(root)
.unwrap_or(&path)
.to_string_lossy()
.replace('\\', "/");
let lower: String = rel_path.to_ascii_lowercase();
if lower.ends_with(SUFFIX_JS) || lower.ends_with(SUFFIX_MJS) || lower.ends_with(SUFFIX_DTS)
{
js_files.push(rel_path.clone());
}
let size: u64 = meta.len();
*total_bytes = total_bytes.saturating_add(size);
files.push(DistFileStat::new(rel_path, size));
}
Ok(())
}
fn verify_release_manifest_file(
dist_dir: &Path,
manifest_path: &Path,
manifest_version: &mut Option<String>,
errors: &mut Vec<String>,
) {
let raw: String = match fs::read_to_string(manifest_path) {
Ok(content) => content,
Err(err) => {
errors.push(format!("failed to read {RELEASE_MANIFEST_NAME}: {err}"));
return;
}
};
let parsed: Value = match from_str::<Value>(&raw) {
Ok(val) => val,
Err(err) => {
errors.push(format!("invalid JSON in {RELEASE_MANIFEST_NAME}: {err}"));
return;
}
};
let format_ver: Option<u64> = parsed.get(JSON_KEY_FORMAT).and_then(Value::as_u64);
if format_ver != Some(1) {
errors.push(format!(
"unsupported manifest format: expected 1, got {format_ver:?}"
));
}
*manifest_version = parsed
.get(JSON_KEY_VERSION)
.and_then(Value::as_str)
.map(str::to_string);
let Some(file_entries) = parsed.get(JSON_KEY_FILES).and_then(Value::as_array) else {
errors.push(format!("missing files array in {RELEASE_MANIFEST_NAME}"));
return;
};
for entry in file_entries.iter() {
let Some(rel_path) = entry.get(JSON_KEY_PATH).and_then(Value::as_str) else {
errors.push(format!(
"manifest entry missing path in {RELEASE_MANIFEST_NAME}"
));
continue;
};
let expected_sha: &str = entry
.get(JSON_KEY_SHA256)
.and_then(Value::as_str)
.unwrap_or("");
let expected_size: u64 = entry
.get(JSON_KEY_SIZE)
.and_then(Value::as_u64)
.unwrap_or(0);
let full_path: PathBuf = dist_dir.join(rel_path);
match fs::read(&full_path) {
Ok(bytes) => {
if (bytes.len() as u64) != expected_size {
errors.push(format!(
"size mismatch for {rel_path}: expected {expected_size}, got {}",
bytes.len()
));
}
let actual_sha: String = sha256_hex(&bytes);
if actual_sha != expected_sha {
errors.push(format!(
"sha256 mismatch for {rel_path}: expected {expected_sha}, got {actual_sha}"
));
}
}
Err(_) => {
errors.push(format!("manifest file missing on disk: {rel_path}"));
}
}
}
}
fn describe_anomaly_value(value: &Value) -> String {
if let Some(text) = value.as_str() {
return text.to_string();
}
let rule: &str = value
.get(JSON_KEY_RULE)
.or_else(|| value.get(JSON_KEY_KIND))
.and_then(Value::as_str)
.unwrap_or("");
let msg: &str = value
.get(JSON_KEY_MESSAGE)
.and_then(Value::as_str)
.unwrap_or("");
if !rule.is_empty() && !msg.is_empty() {
format!("[{rule}] {msg}")
} else if !msg.is_empty() {
msg.to_string()
} else if !rule.is_empty() {
rule.to_string()
} else {
value.to_string()
}
}
fn parse_http_base_url(base_url: &str) -> io::Result<(String, String)> {
let trimmed: &str = base_url.trim().trim_end_matches('/');
let Some(rest) = trimmed.strip_prefix(HTTP_SCHEME_PREFIX) else {
return Err(Error::new(
ErrorKind::InvalidInput,
format!("{ERR_INVALID_INSPECT_URL}: `{base_url}`"),
));
};
let (authority, prefix): (&str, &str) = match rest.find('/') {
Some(idx) => (&rest[..idx], &rest[idx..]),
None => (rest, ""),
};
if authority.is_empty() {
return Err(Error::new(
ErrorKind::InvalidInput,
format!("{ERR_INVALID_INSPECT_URL}: `{base_url}`"),
));
}
let host_port: String = if authority.contains(':') {
authority.to_string()
} else {
format!("{authority}:80")
};
Ok((host_port, prefix.to_string()))
}
fn http_get_text(host_port: &str, path: &str) -> io::Result<(u16, String)> {
let mut stream: TcpStream = TcpStream::connect(host_port)?;
stream.set_read_timeout(Some(Duration::from_secs(3)))?;
stream.set_write_timeout(Some(Duration::from_secs(3)))?;
let request: String =
format!("GET {path} HTTP/1.1\r\nHost: {host_port}\r\nConnection: close\r\n\r\n");
stream.write_all(request.as_bytes())?;
stream.flush()?;
let mut raw: Vec<u8> = Vec::new();
let _: usize = stream.read_to_end(&mut raw)?;
let split_pos: usize = raw
.windows(HTTP_HEADER_DELIM.len())
.position(|window: &[u8]| window == HTTP_HEADER_DELIM)
.ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_MALFORMED_HTTP_RESPONSE))?;
let head_text: String = String::from_utf8_lossy(&raw[..split_pos]).into_owned();
let body_bytes: &[u8] = &raw[split_pos + HTTP_HEADER_DELIM.len()..];
let status_code: u16 = head_text
.lines()
.next()
.and_then(|line: &str| line.split_whitespace().nth(1))
.and_then(|code: &str| code.parse::<u16>().ok())
.unwrap_or_else(|| {
if head_text.contains(HTTP_STATUS_OK_TOKEN) {
200
} else {
0
}
});
let is_chunked: bool = head_text.lines().any(|line: &str| {
let lower: String = line.to_ascii_lowercase();
lower.starts_with(HTTP_HDR_TRANSFER_ENCODING) && lower.contains(HTTP_TOKEN_CHUNKED)
});
let decoded: Vec<u8> = if is_chunked {
decode_chunked_body(body_bytes)
} else {
body_bytes.to_vec()
};
Ok((status_code, String::from_utf8_lossy(&decoded).into_owned()))
}
fn decode_chunked_body(raw: &[u8]) -> Vec<u8> {
let mut out: Vec<u8> = Vec::new();
let mut pos: usize = 0;
while pos < raw.len() {
let Some(rel_crlf) = raw[pos..]
.windows(HTTP_CRLF_BYTES.len())
.position(|pair: &[u8]| pair == HTTP_CRLF_BYTES)
else {
break;
};
let size_hex: &str = from_utf8(&raw[pos..pos + rel_crlf])
.unwrap_or("")
.split(';')
.next()
.unwrap_or("")
.trim();
let Ok(chunk_len) = usize::from_str_radix(size_hex, 16) else {
break;
};
pos += rel_crlf + HTTP_CRLF_BYTES.len();
if chunk_len == 0 || pos + chunk_len > raw.len() {
break;
}
out.extend_from_slice(&raw[pos..pos + chunk_len]);
pos += chunk_len;
if pos + HTTP_CRLF_BYTES.len() <= raw.len()
&& &raw[pos..pos + HTTP_CRLF_BYTES.len()] == HTTP_CRLF_BYTES
{
pos += HTTP_CRLF_BYTES.len();
}
}
out
}