use sdforge::cli::{CliBuilder, CliCommandRegistration, CliHandlerRegistration};
use sdforge::core::{ApiError, HandlerArgs, HandlerFuture, HandlerState};
use sdforge::inventory;
#[cfg(all(
feature = "cli-ops",
feature = "account-credential",
feature = "protocol-zeroize",
feature = "db-sqlite",
feature = "protocol-jwt",
feature = "config-yaml",
feature = "field-encryption",
feature = "dao-key-index"
))]
pub mod ops;
#[cfg(all(feature = "auth-server", feature = "cache-memory"))]
pub mod serve;
pub fn build_root_command() -> CliBuilder {
CliBuilder::new().with_name("garrison")
}
inventory::submit! {
CliCommandRegistration::new(
"healthcheck",
env!("CARGO_PKG_VERSION"),
"Probe GET /healthz on the local auth server (default port from GARRISON_EXTERNAL_PORT, fallback 8080)",
"handle_healthcheck_cmd",
)
.with_args(&[
sdforge::cli::CliArgInfo::new(
"port",
"Probe port override (default: GARRISON_EXTERNAL_PORT env, then 8080)",
sdforge::cli::CliArgType::Body,
false,
None,
),
])
}
inventory::submit! { CliHandlerRegistration { name: "healthcheck", handler: handle_healthcheck_cmd } }
fn handle_healthcheck_cmd(args: HandlerArgs, _state: HandlerState) -> HandlerFuture {
Box::pin(async move { run_healthcheck(args).await })
}
async fn run_healthcheck(args: HandlerArgs) -> Result<serde_json::Value, ApiError> {
let port_override: Option<u16> = match args.get("port") {
Some(raw) => Some(raw.parse::<u16>().map_err(|e| {
ApiError::internal_error(
format!("healthcheck-port-invalid::{raw}::{e}"),
"garrison.healthcheck.port",
)
})?),
None => None,
};
let port = match port_override {
Some(p) => p,
None => crate::health::probe::parse_port(
std::env::var("GARRISON_EXTERNAL_PORT").ok().as_deref(),
)
.map_err(|reason| {
ApiError::internal_error(
crate::i18n::translate_detail(
"bin-healthcheck-failed",
&[("arg0", reason.as_str())],
),
"garrison.healthcheck.port",
)
})?,
};
let result = tokio::task::spawn_blocking(move || crate::health::probe::probe(port))
.await
.map_err(|e| {
ApiError::internal_error(
format!("healthcheck-join::{e}"),
"garrison.healthcheck.join",
)
})?;
match result {
Ok(code) if crate::health::probe::is_healthy(code) => {
let port_arg = port.to_string();
let code_arg = code.to_string();
Ok(serde_json::Value::String(crate::i18n::translate_detail(
"cli-healthcheck-healthy",
&[("port", port_arg.as_str()), ("code", code_arg.as_str())],
)))
},
Ok(code) => Err(ApiError::internal_error(
crate::i18n::translate_detail(
"bin-healthcheck-status",
&[
("arg0", port.to_string().as_str()),
("arg1", code.to_string().as_str()),
],
),
"garrison.healthcheck.status",
)),
Err(reason) => Err(ApiError::internal_error(
crate::i18n::translate_detail("bin-healthcheck-failed", &[("arg0", reason.as_str())]),
"garrison.healthcheck.probe",
)),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn internal_message(err: &ApiError) -> String {
match err {
ApiError::Internal { message, .. } if !message.trim().is_empty() => message.clone(),
other => other.to_string(),
}
}
#[test]
fn healthcheck_command_registered_unconditionally() {
let names: Vec<&str> = sdforge::inventory::iter::<CliCommandRegistration>()
.map(|r| r.name)
.collect();
assert!(names.contains(&"healthcheck"), "实际注册面: {names:?}");
assert_eq!(
names.iter().filter(|n| **n == "healthcheck").count(),
1,
"healthcheck 不得重复注册(原 garrison-cli 子命令已合并到顶层)"
);
if cfg!(all(feature = "auth-server", feature = "cache-memory")) {
assert!(
names.contains(&"serve"),
"auth-server 构建应注册 serve: {names:?}"
);
} else {
assert!(
!names.contains(&"serve"),
"缺 auth-server/cache-memory 时 serve 应被裁剪: {names:?}"
);
}
}
fn serve_once(response: &'static str) -> u16 {
use std::io::{Read, Write};
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind ephemeral port");
let port = listener.local_addr().expect("local addr").port();
std::thread::spawn(move || {
let (mut conn, _) = listener.accept().expect("accept");
let mut buf = [0u8; 1024];
let _ = conn.read(&mut buf);
conn.write_all(response.as_bytes()).expect("write response");
});
port
}
#[tokio::test(flavor = "multi_thread")]
async fn healthcheck_ok_on_live_target() {
let port = serve_once("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
let mut args = HandlerArgs::new();
args.insert("port".to_string(), port.to_string());
let value = run_healthcheck(args)
.await
.expect("live target must be reported healthy");
let text = value.as_str().expect("healthy 报告应为字符串");
assert!(text.contains(&port.to_string()), "报告应含端口: {text}");
}
#[tokio::test(flavor = "multi_thread")]
async fn healthcheck_fails_on_non_2xx() {
let port = serve_once("HTTP/1.1 503 Service Unavailable\r\n\r\n");
let mut args = HandlerArgs::new();
args.insert("port".to_string(), port.to_string());
let err = run_healthcheck(args)
.await
.expect_err("503 must not be reported healthy");
let reason = internal_message(&err);
assert!(
reason.contains("503"),
"错误原因必须携带状态码,实际: {reason}"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn healthcheck_fails_on_dead_port() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
let port = listener.local_addr().expect("local addr").port();
drop(listener);
let mut args = HandlerArgs::new();
args.insert("port".to_string(), port.to_string());
let err = run_healthcheck(args)
.await
.expect_err("dead port must fail");
let reason = internal_message(&err);
assert!(
reason.contains("127.0.0.1") || reason.contains("connect"),
"连接失败必须显性报错,实际: {reason}"
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial_test::serial]
async fn healthcheck_invalid_port_env_fails_closed() {
std::env::set_var("GARRISON_EXTERNAL_PORT", "not-a-port");
let err = run_healthcheck(HandlerArgs::new())
.await
.expect_err("非法端口必须显性失败");
assert!(!err.to_string().is_empty());
std::env::remove_var("GARRISON_EXTERNAL_PORT");
}
}