1use std::path::PathBuf;
2use std::sync::Arc;
3
4use clap::Subcommand;
5
6use crate::config::Bundle;
7use crate::error::{Result, ServerError};
8use crate::mcp::serve_mcp;
9use crate::pipeline::Pipeline;
10use crate::policy::PolicyEngine;
11use crate::proxy::build_proxy_router;
12use crate::server::build_router;
13
14const PUBLIC_KEY_ENV: &str = "KEYZERO_PUBLIC_KEY_PATH";
15
16#[derive(Debug, Subcommand)]
21pub enum ServerCommand {
22 Start {
24 #[arg(long)]
26 bundle: PathBuf,
27 #[arg(long, default_value = "0.0.0.0:8080")]
29 listen: String,
30 #[arg(long, conflicts_with = "proxy")]
32 mcp: bool,
33 #[arg(long, conflicts_with = "mcp")]
35 proxy: bool,
36 },
37 Check {
39 #[arg(long)]
41 bundle: PathBuf,
42 },
43}
44
45pub async fn run(cmd: ServerCommand) -> Result<()> {
50 match cmd {
51 ServerCommand::Start {
52 bundle,
53 listen,
54 mcp,
55 proxy,
56 } => start(bundle, listen, mcp, proxy).await,
57 ServerCommand::Check { bundle } => check(bundle),
58 }
59}
60
61async fn start(bundle_path: PathBuf, listen: String, mcp: bool, proxy: bool) -> Result<()> {
66 let bundle = Bundle::load(&bundle_path)?;
67
68 if mcp {
69 let pipeline = Pipeline::new(bundle).await?;
71 serve_mcp(Arc::new(pipeline)).await?;
72 } else if proxy {
73 let public_key_path = std::env::var(PUBLIC_KEY_ENV).map_err(|_| {
75 ServerError::Config(format!(
76 "{PUBLIC_KEY_ENV} must be set for proxy mode"
77 ))
78 })?;
79 let public_key_pem = std::fs::read_to_string(&public_key_path).map_err(|e| {
80 ServerError::Config(format!(
81 "cannot read public key at '{public_key_path}': {e}"
82 ))
83 })?;
84
85 let pipeline = Pipeline::new(bundle.clone()).await?;
86 let resolvers = pipeline.into_resolvers();
87 let router = build_proxy_router(bundle, &public_key_pem, resolvers)?;
88
89 tracing::info!("proxy listening on {listen}");
90 let listener = tokio::net::TcpListener::bind(&listen).await.map_err(|e| {
91 ServerError::Config(format!("cannot bind to {listen}: {e}"))
92 })?;
93 axum::serve(listener, router).await?;
94 } else {
95 let router = build_router(bundle).await?;
97
98 tracing::info!("server listening on {listen}");
99 let listener = tokio::net::TcpListener::bind(&listen).await.map_err(|e| {
100 ServerError::Config(format!("cannot bind to {listen}: {e}"))
101 })?;
102 axum::serve(listener, router).await?;
103 }
104
105 Ok(())
106}
107
108fn check(bundle_path: PathBuf) -> Result<()> {
113 let bundle = Bundle::load(&bundle_path)?;
114
115 let _engine = PolicyEngine::new(&bundle.policies)?;
117 println!(
118 " {} policies compiled successfully",
119 bundle.policies.len()
120 );
121
122 let mut errors = Vec::new();
124 for resource in &bundle.resources {
125 if !bundle.backends.contains_key(&resource.resolver) {
126 errors.push(format!(
127 "resource '{}' references unknown backend '{}'",
128 resource.ref_pattern, resource.resolver
129 ));
130 }
131 }
132
133 if errors.is_empty() {
134 println!(
135 " {} resources validated ({} backends)",
136 bundle.resources.len(),
137 bundle.backends.len()
138 );
139 println!("bundle OK");
140 Ok(())
141 } else {
142 for err in &errors {
143 eprintln!(" error: {err}");
144 }
145 Err(ServerError::Config(format!(
146 "bundle validation failed with {} error(s)",
147 errors.len()
148 )))
149 }
150}