mid coding commit

This commit is contained in:
zazawowow
2026-01-24 22:59:20 +00:00
parent 64cc3bc7fb
commit 731cd67cfb
2228 changed files with 135554 additions and 18 deletions
+64
View File
@@ -0,0 +1,64 @@
use crate::api::rpc::RpcHandler;
use crate::config::Config;
use anyhow::Result;
use http_body_util::{BodyExt, Full};
use hyper::body::Bytes;
use hyper::{Method, Request, Response, StatusCode};
use hyper_util::rt::TokioIo;
use std::sync::Arc;
use tracing::debug;
pub struct ApiHandler {
config: Config,
rpc_handler: Arc<RpcHandler>,
// Add other handlers here (websocket, static files, etc.)
}
impl ApiHandler {
pub async fn new(config: Config) -> Result<Self> {
let rpc_handler = Arc::new(RpcHandler::new(config.clone()).await?);
Ok(Self {
config,
rpc_handler,
})
}
pub async fn handle_request(
&self,
req: Request<http_body_util::Body<Bytes>>,
) -> Result<Response<Full<Bytes>>> {
let path = req.uri().path();
let method = req.method();
// Convert Incoming body to bytes
let (parts, body) = req.into_parts();
let collected = body.collect().await
.map_err(|e| anyhow::anyhow!("Failed to read body: {}", e))?;
let body_bytes = collected.to_bytes();
// Reconstruct request with Full<Bytes> body for RPC handler
let req_with_bytes = Request::from_parts(parts, Full::new(body_bytes));
debug!("{} {}", method, path);
// Route requests
match (method, path) {
(&Method::POST, "/rpc/v1") => {
self.rpc_handler.handle(req_with_bytes).await
}
(&Method::GET, "/health") => {
Ok(Response::builder()
.status(StatusCode::OK)
.body(Full::new(Bytes::from("OK")))
.unwrap())
}
_ => {
Ok(Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Full::new(Bytes::from("Not Found")))
.unwrap())
}
}
}
}
+5
View File
@@ -0,0 +1,5 @@
mod handler;
mod rpc;
pub use handler::ApiHandler;
pub use rpc::RpcHandler;
+336
View File
@@ -0,0 +1,336 @@
use crate::config::Config;
use crate::container::DevContainerOrchestrator;
use anyhow::{Context, Result};
use http_body_util::{BodyExt, Full};
use hyper::body::Bytes;
use hyper::{Request, Response, StatusCode};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::{debug, error};
#[derive(Debug, Deserialize)]
struct RpcRequest {
method: String,
params: Option<serde_json::Value>,
}
#[derive(Debug, Serialize)]
struct RpcResponse {
result: Option<serde_json::Value>,
error: Option<RpcError>,
}
#[derive(Debug, Serialize)]
struct RpcError {
code: i32,
message: String,
data: Option<serde_json::Value>,
}
pub struct RpcHandler {
config: Config,
orchestrator: Option<Arc<DevContainerOrchestrator>>,
}
impl RpcHandler {
pub async fn new(config: Config) -> Result<Self> {
let orchestrator = if config.dev_mode {
Some(Arc::new(
DevContainerOrchestrator::new(config.clone()).await?,
))
} else {
None
};
Ok(Self {
config,
orchestrator,
})
}
pub async fn handle(
&self,
req: Request<Full<Bytes>>,
) -> Result<Response<Full<Bytes>>> {
// Read request body - Full<Bytes> is already collected
let (_, body) = req.into_parts();
// Full<Bytes> implements Body, collect it to get the bytes
use http_body_util::BodyExt;
let collected = body.collect().await
.context("Failed to collect body")?;
let body_bytes = collected.to_bytes();
let rpc_req: RpcRequest = serde_json::from_slice(&body_bytes)
.context("Invalid RPC request")?;
debug!("RPC method: {}", rpc_req.method);
// Route to handler
let result = match rpc_req.method.as_str() {
"echo" => self.handle_echo(rpc_req.params).await,
"server.echo" => self.handle_echo(rpc_req.params).await,
"container-install" => self.handle_container_install(rpc_req.params).await,
"container-start" => self.handle_container_start(rpc_req.params).await,
"container-stop" => self.handle_container_stop(rpc_req.params).await,
"container-remove" => self.handle_container_remove(rpc_req.params).await,
"container-list" => self.handle_container_list().await,
"container-status" => self.handle_container_status(rpc_req.params).await,
"container-logs" => self.handle_container_logs(rpc_req.params).await,
"container-health" => self.handle_container_health(rpc_req.params).await,
_ => {
Err(anyhow::anyhow!("Unknown method: {}", rpc_req.method))
}
};
// Build response
let rpc_resp = match result {
Ok(data) => RpcResponse {
result: Some(data),
error: None,
},
Err(e) => {
error!("RPC error: {}", e);
RpcResponse {
result: None,
error: Some(RpcError {
code: -1,
message: e.to_string(),
data: None,
}),
}
}
};
let body = serde_json::to_vec(&rpc_resp)
.context("Failed to serialize response")?;
Ok(Response::builder()
.status(StatusCode::OK)
.header("Content-Type", "application/json")
.body(Full::new(Bytes::from(body)))
.unwrap())
}
async fn handle_echo(&self, params: Option<serde_json::Value>) -> Result<serde_json::Value> {
if let Some(p) = params {
if let Some(msg) = p.get("message").and_then(|v| v.as_str()) {
return Ok(serde_json::json!({ "message": msg }));
}
}
Ok(serde_json::json!({ "message": "Hello from Archipelago!" }))
}
async fn handle_container_install(
&self,
params: Option<serde_json::Value>,
) -> Result<serde_json::Value> {
let orchestrator = self
.orchestrator
.as_ref()
.ok_or_else(|| anyhow::anyhow!("Container orchestrator not available (dev mode required)"))?;
let params = params.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
let manifest_path = params
.get("manifest_path")
.and_then(|v| v.as_str())
.ok_or_else(|| anyhow::anyhow!("Missing manifest_path"))?;
// Load manifest
let manifest_content = tokio::fs::read_to_string(manifest_path)
.await
.context("Failed to read manifest file")?;
let manifest: archipelago_container::AppManifest = serde_yaml::from_str(&manifest_content)
.context("Failed to parse manifest")?;
let container_name = orchestrator
.install_container(&manifest, manifest_path)
.await
.context("Failed to install container")?;
Ok(serde_json::json!(container_name))
}
async fn handle_container_start(
&self,
params: Option<serde_json::Value>,
) -> Result<serde_json::Value> {
let orchestrator = self
.orchestrator
.as_ref()
.ok_or_else(|| anyhow::anyhow!("Container orchestrator not available (dev mode required)"))?;
let params = params.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
let app_id = params
.get("app_id")
.and_then(|v| v.as_str())
.ok_or_else(|| anyhow::anyhow!("Missing app_id"))?;
orchestrator
.start_container(app_id)
.await
.context("Failed to start container")?;
Ok(serde_json::json!({ "status": "started" }))
}
async fn handle_container_stop(
&self,
params: Option<serde_json::Value>,
) -> Result<serde_json::Value> {
let orchestrator = self
.orchestrator
.as_ref()
.ok_or_else(|| anyhow::anyhow!("Container orchestrator not available (dev mode required)"))?;
let params = params.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
let app_id = params
.get("app_id")
.and_then(|v| v.as_str())
.ok_or_else(|| anyhow::anyhow!("Missing app_id"))?;
orchestrator
.stop_container(app_id)
.await
.context("Failed to stop container")?;
Ok(serde_json::json!({ "status": "stopped" }))
}
async fn handle_container_remove(
&self,
params: Option<serde_json::Value>,
) -> Result<serde_json::Value> {
let orchestrator = self
.orchestrator
.as_ref()
.ok_or_else(|| anyhow::anyhow!("Container orchestrator not available (dev mode required)"))?;
let params = params.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
let app_id = params
.get("app_id")
.and_then(|v| v.as_str())
.ok_or_else(|| anyhow::anyhow!("Missing app_id"))?;
let preserve_data = params
.get("preserve_data")
.and_then(|v| v.as_bool())
.unwrap_or(false);
orchestrator
.remove_container(app_id, preserve_data)
.await
.context("Failed to remove container")?;
Ok(serde_json::json!({ "status": "removed" }))
}
async fn handle_container_list(&self) -> Result<serde_json::Value> {
let orchestrator = self
.orchestrator
.as_ref()
.ok_or_else(|| anyhow::anyhow!("Container orchestrator not available (dev mode required)"))?;
let containers = orchestrator
.list_containers()
.await
.context("Failed to list containers")?;
Ok(serde_json::to_value(containers)?)
}
async fn handle_container_status(
&self,
params: Option<serde_json::Value>,
) -> Result<serde_json::Value> {
let orchestrator = self
.orchestrator
.as_ref()
.ok_or_else(|| anyhow::anyhow!("Container orchestrator not available (dev mode required)"))?;
let params = params.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
let app_id = params
.get("app_id")
.and_then(|v| v.as_str())
.ok_or_else(|| anyhow::anyhow!("Missing app_id"))?;
let status = orchestrator
.get_container_status(app_id)
.await
.context("Failed to get container status")?;
Ok(serde_json::to_value(status)?)
}
async fn handle_container_logs(
&self,
params: Option<serde_json::Value>,
) -> Result<serde_json::Value> {
let orchestrator = self
.orchestrator
.as_ref()
.ok_or_else(|| anyhow::anyhow!("Container orchestrator not available (dev mode required)"))?;
let params = params.ok_or_else(|| anyhow::anyhow!("Missing params"))?;
let app_id = params
.get("app_id")
.and_then(|v| v.as_str())
.ok_or_else(|| anyhow::anyhow!("Missing app_id"))?;
let lines = params
.get("lines")
.and_then(|v| v.as_u64())
.unwrap_or(100) as u32;
let logs = orchestrator
.get_container_logs(app_id, lines)
.await
.context("Failed to get container logs")?;
Ok(serde_json::to_value(logs)?)
}
async fn handle_container_health(
&self,
params: Option<serde_json::Value>,
) -> Result<serde_json::Value> {
let orchestrator = self
.orchestrator
.as_ref()
.ok_or_else(|| anyhow::anyhow!("Container orchestrator not available (dev mode required)"))?;
// If app_id is provided, get health for that app
if let Some(params) = params {
if let Some(app_id) = params.get("app_id").and_then(|v| v.as_str()) {
let health = orchestrator
.get_health_status(app_id)
.await
.context("Failed to get container health")?;
return Ok(serde_json::json!({ app_id: health }));
}
}
// Otherwise, get health for all containers
let containers = orchestrator
.list_containers()
.await
.context("Failed to list containers")?;
let mut health_map = serde_json::Map::new();
for container in containers {
// Extract app_id from container name
if let Some(app_id) = container.name.strip_prefix("archipelago-") {
if let Some(app_id) = app_id.strip_suffix("-dev") {
match orchestrator.get_health_status(app_id).await {
Ok(health) => {
health_map.insert(app_id.to_string(), serde_json::Value::String(health));
}
Err(_) => {
health_map.insert(app_id.to_string(), serde_json::Value::String("unknown".to_string()));
}
}
}
}
}
Ok(serde_json::Value::Object(health_map))
}
}