Skip to main content

Crate afast

Crate afast 

Source
Expand description

§afast

A high-performance Rust web framework that eliminates manual route definitions. Handlers are registered declaratively and the framework generates TypeScript and JavaScript client code automatically. Data transport uses a compact binary protocol over HTTP, WebSocket, or TCP.

§Quick Start

use afast::{AFast, handler, service, State, Data, Result};
use afast::{AFastDeserialize, AFastSerialize, Tag};

#[derive(Clone)]
struct AppState { db_url: String }

#[derive(AFastDeserialize, Tag)]
#[tag("Request body")]
struct HelloReq { name: String }

#[derive(AFastSerialize, Tag)]
#[tag("Response body")]
struct HelloResp { message: String }

#[handler(desc("Say hello"))]
async fn hello(
    state: State<AppState>,
    req: Data<HelloReq>,
) -> Result<HelloResp> {
    Ok(HelloResp { message: format!("Hello, {}!", req.0.name) })
}

#[tokio::main]
async fn main() {
    let svc = service!("api" => { h(hello) });
    let app = AFast::new()
        .state(AppState { db_url: "localhost".into() })
        .service(svc)
        .http("0.0.0.0:5000");
    app.run().await.unwrap();
}

§Core Concepts

§Handlers

A handler is an async function annotated with #[handler(desc("..."))]. The framework registers it automatically and dispatches binary protocol requests to it. Handlers can extract shared state via State<T>, request data via Data<T>, and auth context via Custom<T>.

use afast::{handler, Data, State, Result};
use afast::{AFastDeserialize, AFastSerialize, Tag};

#[derive(AFastDeserialize, Tag)]
#[tag("Login request")]
struct LoginReq { username: String, password: String }

#[derive(AFastSerialize, Tag)]
#[tag("Login response")]
struct LoginResp { token: String }

#[handler(desc("Login with username and password"))]
async fn login(
    state: State<AppState>,
    req: Data<LoginReq>,
) -> Result<LoginResp> {
    // Validate credentials, generate token, etc.
    Ok(LoginResp { token: "abc123".into() })
}

Handler attributes:

  • desc("...") — Human-readable description (required)
  • name("...") — Client-side method name override
  • cache(seconds) — Client-side cache duration
  • rate_limit("id") — Rate-limit policy ID

§Services

A service groups handlers into a namespace. Each service generates a separate client code file. Use the service! macro:

let svc = service!("api", "My API" => {
    h(health),
    group("user" => {
        h(create_user),
        h(list_users),
    }),
});

§Ordinary HTTP Routes

With the ordinary-http feature, you can define REST-style endpoints using #[get], #[post], #[put], #[delete], #[patch] macros. These use JSON request/response bodies instead of the binary protocol.

use afast::{get, post, Query, Param, Body, Json, HttpResult};

#[get(desc("List users"))]
async fn list_users(query: Query<ListQuery>) -> HttpResult<Json<UserList>> {
    Ok(Json(UserList { total: 0, items: vec![] }))
}

#[post(desc("Create user"))]
async fn create_user(body: Body<CreateBody>) -> HttpResult<Json<User>> {
    Ok(Json(User { id: 1, username: body.0.username }))
}

§Error Handling

All handlers return Result<T>, which is Result<T, Error>. Use Error::custom to create user-defined errors:

return Err(Error::custom(404, "user not found"));

Custom error types can implement AFastError to be returned directly from handlers.

§Features

FeatureDescription
wsWebSocket server via tokio-tungstenite
httpHTTP server via hyper
tcpTCP server with length-prefix framing
tsTypeScript client code generation
jsJavaScript client code generation
ktKotlin client code generation
rsRust client code generation
codeHTTP endpoint for on-demand client code generation
docInteractive API documentation page
ordinary-httpREST-style HTTP endpoints with JSON request/response bodies
ordinary-wsPath-based WebSocket endpoints with text/JSON frames
ordinary-sseServer-Sent Events endpoints
tlsHTTPS support via rustls with ALPN for HTTP/2
seq64Use i64 for WebSocket request IDs (default i32)
len64Use u64 for WebSocket payload lengths (default u32)
rate-limitRequest rate limiting with named policies and pluggable store
hookRequest and connection lifecycle hooks
markerConditional serialization with marker-based field skipping

§Module Guide

ModuleDescription
errorError types and error codes
handlerHandler abstractions, metadata, and type tags
serviceService container for grouping handlers
stateType-map for shared application state
[hook]Request/connection lifecycle hooks (feature hook)
[rate_limit]Rate limiting with named policies (feature rate-limit)
markerConditional serialization with markers (feature marker)

Re-exports§

pub use ctx::RequestCtx;
pub use error::AFastError;
pub use error::Error;
pub use handler::DummyInvoker;
pub use handler::Handler;
pub use handler::EnumVariantMeta;
pub use handler::FieldMeta;
pub use handler::Structure;
pub use handler::TagKind;
pub use handler::TagMeta;
pub use handler::ValidateRule;
pub use handler::no_structure;
pub use handler::HandlerEntry;
pub use handler::HandlerInvoker;
pub use handler::HandlerMeta;
pub use handler::ParamMeta;
pub use handler::Receiver;
pub use handler::Sender;
pub use service::Service;
pub use state::StateMap;
pub use app::AFast;
pub use app::GenerateTarget;
pub use app::JsTsCallType;
pub use app::Lang;
pub use app::NetCallType;

Modules§

app
Application builder, transport servers, and code generation.
ctx
Per-request context container.
error
Error types and error codes for the afast framework.
handler
Handler abstractions and metadata for the afast framework.
marker
Conditional serialization/deserialization with optional marker support.
service
Service container for grouping handlers into API namespaces.
state
Type-map for storing shared application state.

Macros§

register
Produces a HandlerEntry for the given handler function.
register_ordinary
Produces an OrdinaryHandlerDef for the given ordinary HTTP handler.
register_with_path
Produces a HandlerEntry with a stable ID computed from the full handler path.
service
Builds a Service with handlers and nested groups.

Structs§

Ctx
Injects per-request context data into a handler.
Custom
Deserializes custom authentication or context data into T.
Data
Deserializes the binary request payload into T.
State
Injects shared application state into a handler.

Traits§

AFastDeserialize
反序列化 trait,为类型提供从字节数组还原的能力。
AFastSerialize
序列化 trait,为类型提供转换为字节数组的能力。

Functions§

is_standard_header
Returns true if the given header name is in the standard set.

Type Aliases§

Result
A Result type alias with Error as the default error type.

Attribute Macros§

handler
Marks an async function as a binary-protocol handler.

Derive Macros§

AFastDeserialize
Re-export derive 宏。
AFastSerialize
Re-export derive 宏。
FromFormData
Derives the FromFormData trait for structs with named fields.
Tag
Derives the Structure trait for a struct or enum.