use std::collections::HashMap;
use std::sync::Arc;
use axum::extract::State as AxumState;
use axum::http::StatusCode;
use axum::response::Json;
use axum::routing::{get, post};
use axum::Router;
use rusty_agent_runtime::error::RustyError;
use rusty_agent_runtime::node::{Node, NodeContext};
use rusty_agent_runtime::remote::{NodeTask, NodeTaskResponse, PROTOCOL_VERSION};
use serde::Serialize;
use serde_json::{json, Value};
use tracing::Instrument;
use uuid::Uuid;
pub mod activity;
pub use activity::{Activity, ActivityCompletion, ActivityContext, ActivityWorker};
#[derive(Clone, Default)]
pub struct WorkerRegistry {
handlers: HashMap<String, Arc<dyn Node>>,
}
impl WorkerRegistry {
pub fn new() -> Self {
Self::default()
}
pub fn register<N>(&mut self, name: impl Into<String>, node: N) -> &mut Self
where
N: Node + 'static,
{
self.handlers.insert(name.into(), Arc::new(node));
self
}
pub fn with<N>(mut self, name: impl Into<String>, node: N) -> Self
where
N: Node + 'static,
{
self.register(name, node);
self
}
pub fn contains(&self, name: &str) -> bool {
self.handlers.contains_key(name)
}
pub fn len(&self) -> usize {
self.handlers.len()
}
pub fn is_empty(&self) -> bool {
self.handlers.is_empty()
}
pub fn names(&self) -> impl Iterator<Item = &str> {
self.handlers.keys().map(String::as_str)
}
pub fn handler(&self, name: &str) -> Option<Arc<dyn Node>> {
self.handlers.get(name).cloned()
}
}
type SharedRegistry = Arc<WorkerRegistry>;
#[derive(Debug, Serialize)]
struct OkResponse {
status: &'static str,
protocol_version: u32,
nodes: Vec<String>,
}
async fn ok_handler(AxumState(registry): AxumState<SharedRegistry>) -> Json<OkResponse> {
let mut nodes: Vec<String> = registry.names().map(str::to_owned).collect();
nodes.sort();
Json(OkResponse {
status: "ok",
protocol_version: PROTOCOL_VERSION,
nodes,
})
}
async fn execute_handler(
AxumState(registry): AxumState<SharedRegistry>,
Json(task): Json<NodeTask>,
) -> (StatusCode, Json<NodeTaskResponse>) {
let request_id = Uuid::new_v4();
let span = tracing::info_span!(
"rusty.execute",
%request_id,
node = %task.node,
thread_id = %task.config.thread_id,
step = task.config.step,
protocol_version = task.protocol_version,
);
execute_task(registry, task).instrument(span).await
}
async fn execute_task(
registry: SharedRegistry,
task: NodeTask,
) -> (StatusCode, Json<NodeTaskResponse>) {
if task.protocol_version != PROTOCOL_VERSION {
tracing::warn!("unsupported protocol version");
return (
StatusCode::BAD_REQUEST,
Json(NodeTaskResponse::error(format!(
"unsupported protocol_version {} (this worker speaks {})",
task.protocol_version, PROTOCOL_VERSION
))),
);
}
let Some(handler) = registry.handler(&task.node) else {
tracing::warn!("no handler registered for node");
let mut registered: Vec<&str> = registry.names().collect();
registered.sort_unstable();
return (
StatusCode::OK,
Json(NodeTaskResponse::error(format!(
"no handler registered for node `{}` on this worker (registered: {registered:?})",
task.node,
))),
);
};
let node_name = task.node.clone();
let resuming = task.config.resume.is_some();
let ctx = NodeContext::new(task.state, task.config);
let outcome = tokio::spawn(async move { handler.run(ctx).await }).await;
let result = match outcome {
Ok(result) => result,
Err(join_err) => {
let detail = if join_err.is_panic() {
let payload = join_err.into_panic();
let message = payload
.downcast_ref::<&str>()
.map(|s| (*s).to_owned())
.or_else(|| payload.downcast_ref::<String>().cloned())
.unwrap_or_else(|| "non-string panic payload".to_owned());
format!("handler panicked: {message}")
} else {
"handler task cancelled".to_owned()
};
Err(RustyError::Node(format!("node `{node_name}` {detail}")))
}
};
match result {
Ok(output) => {
tracing::info!(resuming, "node executed");
(StatusCode::OK, Json(NodeTaskResponse::ok(output)))
}
Err(e) if e.is_interrupt() => {
let value = e.interrupt_value().cloned().unwrap_or(Value::Null);
tracing::info!(payload = %value, "node interrupted");
(StatusCode::OK, Json(NodeTaskResponse::interrupt(value)))
}
Err(e) => {
tracing::warn!(error = %e, "node failed");
(StatusCode::OK, Json(NodeTaskResponse::error(e.to_string())))
}
}
}
pub fn router(registry: WorkerRegistry) -> Router {
Router::new()
.route("/execute", post(execute_handler))
.route("/ok", get(ok_handler))
.with_state(Arc::new(registry))
}
pub async fn serve(registry: WorkerRegistry, addr: impl AsRef<str>) -> std::io::Result<()> {
let listener = tokio::net::TcpListener::bind(addr.as_ref()).await?;
let local_addr = listener.local_addr()?;
tracing::info!(
addr = %local_addr,
nodes = ?registry.names().collect::<Vec<_>>(),
"rusty worker listening"
);
axum::serve(listener, router(registry)).await
}
pub fn probe_body() -> Value {
json!({
"protocol_version": PROTOCOL_VERSION,
"node": "<handler-name>",
"state": {},
"config": { "thread_id": "t-1", "step": 0, "resume": null, "extra": {} }
})
}
#[cfg(test)]
mod tests {
use super::*;
use rusty_agent_runtime::node::NodeOutput;
use rusty_agent_runtime::state::State;
use serde_json::json;
#[test]
fn registry_register_and_lookup() {
let mut registry = WorkerRegistry::new();
assert!(registry.is_empty());
registry.register("a", |_ctx: NodeContext| async { Ok(NodeOutput::empty()) });
registry.register("b", |_ctx: NodeContext| async { Ok(NodeOutput::empty()) });
assert_eq!(registry.len(), 2);
assert!(registry.contains("a"));
assert!(registry.contains("b"));
assert!(!registry.contains("c"));
assert!(registry.handler("a").is_some());
let mut names: Vec<&str> = registry.names().collect();
names.sort();
assert_eq!(names, vec!["a", "b"]);
}
#[test]
fn registry_builder_style_and_replace() {
let registry = WorkerRegistry::new()
.with("x", |_ctx: NodeContext| async {
Ok(NodeOutput::update("v", json!(1)))
})
.with("x", |_ctx: NodeContext| async {
Ok(NodeOutput::update("v", json!(2)))
});
assert_eq!(registry.len(), 1);
}
#[test]
fn probe_body_is_a_valid_node_task_shape() {
let body = probe_body();
let task: std::result::Result<NodeTask, _> = serde_json::from_value(body);
let task = task.unwrap();
assert_eq!(task.protocol_version, PROTOCOL_VERSION);
assert_eq!(task.state, State::new());
}
}