Compare commits

...

5 commits

Author SHA1 Message Date
d4a3a71e2f
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.
2025-04-24 14:45:53 -07:00
07f4720244
Router, add xrpc and router abstraction to router 2025-04-23 14:44:26 -07:00
57c396afe7
handle all xrpc routes with NotImplemented
Supported routes can be added as they become available
2025-04-18 19:10:17 -07:00
1d577ef396
rust router skeleton code
Just a basic axum setup with modules
2025-04-18 18:33:28 -07:00
1f6544a75e
add rust flakes 2025-04-17 16:07:03 -07:00
7 changed files with 2438 additions and 0 deletions

2045
rust/Cargo.lock generated Normal file

File diff suppressed because it is too large Load diff

14
rust/Cargo.toml Normal file
View file

@ -0,0 +1,14 @@
[package]
name = "rust"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
axum = { version = "0.8.3", features = ["json"] }
axum-macros = "0.5.0"
serde = "1.0.219"
serde_json = "1.0.140"
sqlx = { version = "0.8.5", features = ["runtime-tokio"] }
tokio = { version = "1.44.2", features = ["macros", "rt-multi-thread"] }

60
rust/flake.lock generated Normal file
View file

@ -0,0 +1,60 @@
{
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1735563628,
"narHash": "sha256-OnSAY7XDSx7CtDoqNh8jwVwh4xNL/2HaJxGjryLWzX8=",
"rev": "b134951a4c9f3c995fd7be05f3243f8ecd65d798",
"revCount": 637546,
"type": "tarball",
"url": "https://api.flakehub.com/f/pinned/NixOS/nixpkgs/0.2405.637546%2Brev-b134951a4c9f3c995fd7be05f3243f8ecd65d798/01941dc2-2ab2-7453-8ebd-88712e28efae/source.tar.gz"
},
"original": {
"type": "tarball",
"url": "https://flakehub.com/f/NixOS/nixpkgs/0.2405.%2A.tar.gz"
}
},
"nixpkgs_2": {
"locked": {
"lastModified": 1744536153,
"narHash": "sha256-awS2zRgF4uTwrOKwwiJcByDzDOdo3Q1rPZbiHQg/N38=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "18dd725c29603f582cf1900e0d25f9f1063dbf11",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixpkgs-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"nixpkgs": "nixpkgs",
"rust-overlay": "rust-overlay"
}
},
"rust-overlay": {
"inputs": {
"nixpkgs": "nixpkgs_2"
},
"locked": {
"lastModified": 1744857263,
"narHash": "sha256-M4X/CnquHozzgwDk+CbFb8Sb4rSGJttfNOKcpRwziis=",
"owner": "oxalica",
"repo": "rust-overlay",
"rev": "9f3d63d569536cd661a4adcf697e32eb08d61e31",
"type": "github"
},
"original": {
"owner": "oxalica",
"repo": "rust-overlay",
"type": "github"
}
}
},
"root": "root",
"version": 7
}

50
rust/flake.nix Normal file
View file

@ -0,0 +1,50 @@
{
description = "Example Rust development environment for Zero to Nix";
# Flake inputs
inputs = {
nixpkgs.url = "https://flakehub.com/f/NixOS/nixpkgs/0.2405.*.tar.gz";
rust-overlay.url = "github:oxalica/rust-overlay"; # A helper for Rust + Nix
};
# Flake outputs
outputs = { self, nixpkgs, rust-overlay }:
let
# Overlays enable you to customize the Nixpkgs attribute set
overlays = [
# Makes a `rust-bin` attribute available in Nixpkgs
(import rust-overlay)
# Provides a `rustToolchain` attribute for Nixpkgs that we can use to
# create a Rust environment
(self: super: {
rustToolchain = super.rust-bin.stable.latest.default;
})
];
# Systems supported
allSystems = [
"x86_64-linux" # 64-bit Intel/AMD Linux
"aarch64-linux" # 64-bit ARM Linux
"x86_64-darwin" # 64-bit Intel macOS
"aarch64-darwin" # 64-bit ARM macOS
];
# Helper to provide system-specific attributes
forAllSystems = f: nixpkgs.lib.genAttrs allSystems (system: f {
pkgs = import nixpkgs { inherit overlays system; };
});
in
{
# Development environment output
devShells = forAllSystems ({ pkgs }: {
default = pkgs.mkShell {
# The Nix packages provided in the environment
packages = (with pkgs; [
# The package provided by our custom overlay. Includes cargo, Clippy, cargo-fmt,
# rustdoc, rustfmt, and other tools.
rustToolchain
]) ++ pkgs.lib.optionals pkgs.stdenv.isDarwin (with pkgs; [ libiconv ]);
};
});
};
}

31
rust/src/main.rs Normal file
View file

@ -0,0 +1,31 @@
use crate::router::{
Router,
Endpoint,
xrpc::{
QueryInput,
ProcedureInput,
Response,
error,
},
};
use axum::http::StatusCode;
mod router;
mod db;
#[tokio::main]
async fn main() {
let mut router = Router::new();
router = router.add_endpoint(Endpoint::new_xrpc_query(String::from("me.woach.get"), test));
router = router.add_endpoint(Endpoint::new_xrpc_procedure(String::from("me.woach.post"), test2));
router.serve().await;
}
async fn test(_data: QueryInput) -> Response {
error(StatusCode::OK, "error", "message")
}
async fn test2(_data: ProcedureInput) -> Response {
error(StatusCode::OK, "error", "message")
}

58
rust/src/router.rs Normal file
View file

@ -0,0 +1,58 @@
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,
router: AxumRouter,
}
// 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 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 { 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();
axum::serve(listener, self.router).await.unwrap();
}
}

180
rust/src/router/xrpc.rs Normal file
View file

@ -0,0 +1,180 @@
use std::{
collections::HashMap,
pin::Pin,
future::Future,
};
use axum::{
extract::{
Json,
Query,
Request,
FromRequest,
FromRequestParts,
rejection::QueryRejection,
},
body::Bytes,
routing::{
get,
post,
method_routing::MethodRouter,
},
http::{
StatusCode,
request::Parts,
},
Router as axumRouter,
};
use serde_json::{Value, json};
enum Nsid {
Nsid(String),
NotImplemented,
}
pub struct XrpcEndpoint {
nsid: Nsid,
resolver: MethodRouter,
}
pub type Response = (StatusCode, Json<Value>);
pub fn error(code: StatusCode, error: &str, message: &str) -> Response {
(
code,
Json(json!({
"error": error,
"message": message
}))
)
}
pub fn response(code: StatusCode, message: &str) -> Response {
error(code, "", message)
}
pub struct QueryInput {
parameters: HashMap<String, String>,
}
impl<S> FromRequestParts<S> for QueryInput
where
S: Send + Sync,
{
type Rejection = Response;
async fn from_request_parts(parts: &mut Parts, _state: &S)
-> Result<Self, Self::Rejection> {
let query_params: Result<Query<HashMap<String, String>>, QueryRejection> = Query::try_from_uri(&parts.uri);
match query_params {
Ok(p) => Ok(QueryInput { parameters: p.0 }),
Err(e) => Err(error(StatusCode::BAD_REQUEST, "Bad Parameters", &e.body_text())),
}
}
}
pub struct ProcedureInput {
parameters: HashMap<String, String>,
input: Json<Value>,
}
impl<S> FromRequest<S> for ProcedureInput
where
Bytes: FromRequest<S>,
S: Send + Sync,
{
type Rejection = Response;
async fn from_request(req: Request, state: &S)
-> Result<Self, Self::Rejection> {
let query_params: Result<Query<HashMap<String, String>>, QueryRejection> = Query::try_from_uri(req.uri());
let parameters = match query_params {
Ok(p) => p.0,
Err(e) => return Err(error(StatusCode::BAD_REQUEST, "Bad Parameters", &e.body_text())),
};
let json_value = Json::<Value>::from_request(req, state).await;
let input: Json<Value> = match json_value {
Ok(v) => v,
Err(e) => return Err(error(StatusCode::BAD_REQUEST, "Bad Parameters", &e.body_text())),
};
Ok(ProcedureInput { parameters, input })
}
}
pub trait XrpcHandler<Input>: Send + Sync + 'static {
fn call(&self, input: Input)
-> Pin<Box<dyn Future<Output = Response> + Send>>;
}
impl<F, Fut> XrpcHandler<QueryInput> for F
where
F: Fn(QueryInput) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Response> + Send + 'static,
{
fn call(&self, input: QueryInput)
-> Pin<Box<dyn Future<Output = Response>+ Send>> {
Box::pin((self)(input))
}
}
impl<F, Fut> XrpcHandler<ProcedureInput> for F
where
F: Fn(ProcedureInput) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Response> + Send + 'static,
{
fn call(&self, input: ProcedureInput)
-> Pin<Box<dyn Future<Output = Response>+ Send>> {
Box::pin((self)(input))
}
}
impl XrpcEndpoint {
pub fn new_query<Q>(nsid: String, query: Q) -> Self
where
Q: XrpcHandler<QueryInput> + Clone
{
XrpcEndpoint {
nsid: Nsid::Nsid(nsid),
resolver: get(async move | mut parts: Parts | -> Response {
match QueryInput::from_request_parts(&mut parts, &()).await {
Ok(qi) => query.call(qi).await,
Err(e) => e
}
})
}
}
pub fn new_procedure<P>(nsid: String, procedure: P) -> Self
where
P: XrpcHandler<ProcedureInput> + Clone
{
XrpcEndpoint {
nsid: Nsid::Nsid(nsid),
resolver: post(async move | req: Request | -> Response {
match ProcedureInput::from_request(req, &()).await {
Ok(pi) => procedure.call(pi).await,
Err(e) => e
}
})
}
}
pub fn add_to_router(self, router: axumRouter) -> axumRouter {
let path = match self.nsid {
Nsid::Nsid(s) => &("/xrpc/".to_owned() + &s),
Nsid::NotImplemented => "/xrpc/{*nsid}",
};
router.route(path, self.resolver)
}
pub fn not_implemented() -> Self {
let resolver = (
StatusCode::NOT_IMPLEMENTED,
Json(json!({
"error": "MethodNotImplemented",
"message": "Method Not Implemented"
}))
);
XrpcEndpoint {
nsid: Nsid::NotImplemented,
resolver: get(resolver.clone()).post(resolver),
}
}
}