Router, add xrpc function interface, test in main

Adds an interface for adding xrpc queries and procedures that is a bit
simpler than directly interfacing with axum. Should provide good
scaffolding for next steps.
This commit is contained in:
Julia Lange 2025-04-24 14:45:53 -07:00
parent 07f4720244
commit d4a3a71e2f
Signed by: Julia
SSH key fingerprint: SHA256:50XUMcOFYPUs9/1j7p9SPnwASZ7QnxXm7THF7HkbqzQ
5 changed files with 221 additions and 32 deletions

View file

@ -1,31 +1,58 @@
use crate::router::xrpc::XrpcEndpoint;
use axum::Router as axumRouter;
use crate::router::xrpc::{
XrpcEndpoint,
XrpcHandler,
QueryInput,
ProcedureInput,
};
use axum::Router as AxumRouter;
use core::net::SocketAddr;
use std::net::{IpAddr, Ipv4Addr};
use tokio::net::TcpListener;
pub struct Router {
addr: SocketAddr,
xrpc: Vec<XrpcEndpoint>,
router: AxumRouter,
}
mod xrpc;
// In case server ever needs to support more than just XRPC
pub enum Endpoint {
Xrpc(XrpcEndpoint),
}
impl Endpoint {
pub fn new_xrpc_query<Q>(nsid: String, query: Q) -> Self
where
Q: XrpcHandler<QueryInput> + Clone
{
Endpoint::Xrpc(XrpcEndpoint::new_query(nsid,query))
}
pub fn new_xrpc_procedure<P>(nsid: String, procedure: P) -> Self
where
P: XrpcHandler<ProcedureInput> + Clone
{
Endpoint::Xrpc(XrpcEndpoint::new_procedure(nsid,procedure))
}
}
pub mod xrpc;
impl Router {
pub fn new() -> Self {
let xrpc = vec![XrpcEndpoint::not_implemented()];
let mut router = AxumRouter::new();
router = XrpcEndpoint::not_implemented().add_to_router(router);
let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127,0,0,1)), 6702);
Router { xrpc, addr }
Router { router, addr }
}
pub fn add_endpoint(mut self, endpoint: Endpoint) -> Self {
match endpoint {
Endpoint::Xrpc(ep) => self.router = ep.add_to_router(self.router),
};
self
}
pub async fn serve(self) {
let listener = TcpListener::bind(self.addr).await.unwrap();
let mut router = axumRouter::new();
for endpoint in self.xrpc {
router = endpoint.add_to_router(router);
}
axum::serve(listener, router).await.unwrap();
axum::serve(listener, self.router).await.unwrap();
}
}