Skip to main content

atrg_xrpc/
lib.rs

1#![deny(unsafe_code)]
2#![warn(missing_docs)]
3//! XRPC route registration helpers and error types for at-rust-go.
4//!
5//! Provides [`xrpc_router()`] — a pre-configured Axum router for `/xrpc/*`
6//! endpoints that automatically wraps errors in the AT Protocol error envelope.
7
8pub mod error;
9
10pub use error::{XrpcError, XrpcErrorName};
11
12use axum::response::IntoResponse;
13use axum::routing::any;
14use axum::Router;
15
16/// Create a new XRPC router with the standard AT Protocol error fallback.
17///
18/// Mount your XRPC procedures on this router, then merge it into your app:
19///
20/// ```rust,ignore
21/// let xrpc = atrg_xrpc::xrpc_router()
22///     .route("/xrpc/com.example.getPosts", get(get_posts))
23///     .route("/xrpc/com.example.createPost", post(create_post));
24/// ```
25pub fn xrpc_router<S: Clone + Send + Sync + 'static>() -> Router<S> {
26    Router::new().fallback(any(xrpc_fallback))
27}
28
29/// Fallback handler for unmatched XRPC methods.
30async fn xrpc_fallback() -> impl IntoResponse {
31    XrpcError {
32        name: XrpcErrorName::MethodNotImplemented,
33        message: "XRPC method not implemented".to_string(),
34    }
35}
36
37/// Convenience constructor: returns an `InvalidRequest` error.
38pub fn xrpc_invalid_request(msg: impl Into<String>) -> XrpcError {
39    XrpcError {
40        name: XrpcErrorName::InvalidRequest,
41        message: msg.into(),
42    }
43}
44
45/// Convenience constructor: returns an `AuthRequired` error.
46pub fn xrpc_auth_required(msg: impl Into<String>) -> XrpcError {
47    XrpcError {
48        name: XrpcErrorName::AuthRequired,
49        message: msg.into(),
50    }
51}
52
53/// Convenience constructor: returns a `Forbidden` error.
54pub fn xrpc_forbidden(msg: impl Into<String>) -> XrpcError {
55    XrpcError {
56        name: XrpcErrorName::Forbidden,
57        message: msg.into(),
58    }
59}
60
61/// Convenience constructor: returns a `NotFound` error.
62pub fn xrpc_not_found(msg: impl Into<String>) -> XrpcError {
63    XrpcError {
64        name: XrpcErrorName::NotFound,
65        message: msg.into(),
66    }
67}
68
69/// Convenience constructor: returns a `RateLimitExceeded` error.
70pub fn xrpc_rate_limit(msg: impl Into<String>) -> XrpcError {
71    XrpcError {
72        name: XrpcErrorName::RateLimitExceeded,
73        message: msg.into(),
74    }
75}