Skip to main content

Crate tako

Crate tako 

Source
Expand description

Tako is a multi-transport Rust web framework: one router, middleware stack, and observability model for HTTP/1.1, HTTP/2, HTTP/3, WebSocket, SSE, gRPC, TCP, UDP, and Unix sockets, on Tokio or Compio.

The package on crates.io is tako-rs; the library it provides is tako. The separate tako crate on crates.io is an unrelated project.

§Quickstart

[dependencies]
tako-rs = "2.5"
tokio = { version = "1", features = ["macros", "net", "rt-multi-thread"] }
use tako::{router::Router, types::BoxError, Server};
use tokio::net::TcpListener;

#[tokio::main]
async fn main() -> Result<(), BoxError> {
    let mut router = Router::new();
    router.get("/", || async { "Hello, Tako!" });

    let listener = TcpListener::bind("127.0.0.1:8080").await?;
    Server::builder()
        .build()
        .try_spawn_http(listener, router)?
        .result()
        .await?;

    Ok(())
}

§Handlers and extractors

Handlers are async functions. Their arguments are extractors that pull typed data out of the request, and their return values implement Responder. Only the last argument may consume the body.

use serde::{Deserialize, Serialize};
use tako::extractors::{json::Json, path::Path, state::State};
use tako::{responder::Responder, router::Router, StatusCode};

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

#[derive(Deserialize)]
struct NewUser {
    name: String,
}

#[derive(Serialize)]
struct User {
    id: u64,
    name: String,
}

async fn show_user(Path(id): Path<u64>, State(state): State<AppState>) -> String {
    format!("{}, user {id}", state.greeting)
}

async fn create_user(Json(new): Json<NewUser>) -> impl Responder {
    (StatusCode::CREATED, Json(User { id: 1, name: new.name }))
}

let mut router = Router::new();
router.with_state(AppState { greeting: "Hello".into() });
router.get("/users/{id}", show_user);
router.post("/users", create_user);

§Feature flags

The default build serves HTTP/1.1, raw TCP, and Unix sockets on Tokio, with the core extractors and middleware. Everything else is opt-in:

FeatureEnables
http2, http3, tlsHTTP/2 including h2c, HTTP/3 over QUIC, and rustls TLS
ws, sse, udpWebSocket upgrades, Server-Sent Events, and UDP servers
grpc, protobufgRPC over HTTP/2 and protobuf bodies
pluginsCORS, compression, rate limiting, and idempotency
signals, queue-cronIn-process signals and cron-scheduled queue jobs
metrics-prometheus, metrics-opentelemetryMetrics export
async-graphql, utoipa, vesperaGraphQL and OpenAPI integrations
per-threadThread-per-core server
compioThe Compio runtime: io_uring on Linux, IOCP on Windows

The feature reference lists every flag.

§Learn more

§Crate layout

This umbrella crate stitches together the workspace sub-crates:

  • tako-rs-core: routing, handlers, middleware and plugin traits, body and request types, state, signals, queue, WebSocket, plus GraphQL, gRPC, and OpenAPI helpers
  • tako-rs-extractors: concrete request extractors (cookies, form, query, path, JWT, multipart, SIMD JSON, …)
  • tako-rs-server: HTTP/1, TLS, HTTP/3, WebTransport, raw TCP, UDP, and Unix sockets, PROXY protocol, plus the Compio variants
  • tako-rs-streams: SSE, file streaming, static file serving, and raw QUIC sessions
  • tako-rs-plugins: built-in middleware (auth, CSRF, sessions, …) and plugins (CORS, compression, rate limiting, idempotency, metrics)

Public APIs are re-exported under tako::* according to the selected features.

Modules§

body
TakoBody, the body of every request and response.
config
Config, typed configuration loaded from environment variables.
conn_info
ConnInfo, which every transport adds to request extensions next to its own entries, such as SocketAddr or UnixPeerAddr.
extractors
Request data extraction utilities.
file_streamfile-stream
Streamed file responses, plus the precondition and ETag helpers behind them.
graphiqlgraphiql
GraphiQL IDE page for a GraphQL endpoint.
graphqlasync-graphql
async-graphql extractors, responders and WebSocket subscriptions.
grpcgrpc
gRPC over HTTP/2: each method is a POST /<package>.<Service>/<Method> route, and Option<GrpcDeadline> extracts the client’s grpc-timeout.
header
HTTP header types
middleware
Middleware for processing requests and responses in a pipeline.
openapiutoipa or vespera
OpenAPI route metadata plus two spec backends: utoipa (derive macros, recommended) and vespera (a spec built at runtime, also from the routes’ metadata).
pluginsplugins
prelude
The types most handlers need, for use tako::prelude::*;. Modules stay at their canonical paths, such as tako::extractors and tako::middleware.
problem
RFC 7807 / RFC 9457 application/problem+json error responses.
proxy_protocolproxy-protocol
PROXY protocol v1 (text) and v2 (binary) parsing, for the real client address a load balancer such as HAProxy or AWS NLB prepends to each TCP connection.
queue
In-memory background job queue with retries, delayed and deduplicated jobs, a dead letter queue and graceful shutdown.
redirect
Redirect responses and an HTTP-to-HTTPS redirect router.
responder
The Responder trait, which turns handler return values into responses.
route
The Route that router registration returns, for configuring that one route.
router
The Router, which matches requests to routes and runs them through middleware.
router_state
Per-router typed state; State<T> reads it before falling back to the process-global get_state.
server_tcp
Raw TCP servers that hand each accepted stream to a handler, on Tokio or compio.
server_tls_compiocompio-tls
TLS HTTP server on compio; HTTP/2 over ALPN h2 runs on the send_wrapper glue in compio_h2.
server_udpudp
Raw UDP servers that hand each datagram to a handler, on Tokio or compio.
server_unixUnix
Raw and HTTP servers on Unix domain sockets. A path starting with @ names a Linux abstract socket, which skips the stale-file cleanup and the removal after shutdown.
signalssignals
In-process named signals for cross-cutting hooks such as metrics, logging and app events.
socket_activationsocket-activation
Listening sockets inherited through systemd, s6 or catflap socket activation (LISTEN_FDS), as Tokio types; indexes follow the order the unit file declares them in.
ssesse
Server-Sent Events. Responses send Cache-Control: no-cache, no-store, must-revalidate and X-Accel-Buffering: no, so neither caches nor nginx hold events back.
state
Process-global state with one slot per type; prefer Router::with_state for router-scoped values.
static
ServeDir for a directory tree, with index files, .br/.gz sidecars, an SPA fallback and traversal checks, and ServeFile for one file.
stores
Pluggable backend traits for stateful middleware (sessions, rate limiting, …).
tlscompio-tls or http3 or tls
Shared PEM loading for TLS transports.
tracingtako-tracing
A tracing-subscriber formatter with source locations, installed by init_tracing.
types
Request, response and middleware type aliases used across the framework.
webtransportwebtransport
W3C WebTransport sessions on the HTTP/3 server, on either runtime; on Tokio also RawQuicSession, a plain QUIC endpoint for peers that do not speak WebTransport.
wsws
WebSocket (RFC 6455) server connections.
zero_copy_extractorszero-copy-extractors
Borrowing variants of the body, JSON, form, query, path and header extractors. The body ones collect the body once into the request extensions and borrow from it.

Structs§

AcceptBackoff
Exponential backoff for accept loops, whose errors (e.g. EMFILE) are transient rather than fatal to the listener.
Bytes
A cheaply cloneable and sliceable chunk of contiguous memory.
CompioServercompio
Compio-runtime server (io_uring on Linux, IOCP on Windows, kqueue on macOS) with the Tokio Server API. Construct with CompioServer::builder.
CompioServerBuildercompio
Fluent constructor for the compio-runtime CompioServer.
Full
A body that consists of a single chunk.
Jemallocjemalloc
Handle to the jemalloc allocator
Method
The Request Method (VERB)
PerThreadConfigper-thread
Configuration for serve_per_thread and spawn_per_thread.
PerThreadShutdownper-thread
Stops the workers of spawn_per_thread; the signal is sticky, so a worker that starts waiting after trigger still sees it.
ReloadableResolvercompio-tls or http3 or tls
Certificate resolver whose key can be swapped at runtime; keep the Arc passed to TlsCert::resolver to reload. Each handshake costs one lock-free Arc clone.
ServerConfig
Limits and timeouts shared by every transport; pass it to the server builder’s config.
ServerError
A clonable server startup or background-task failure.
ServerHandle
Handle to a spawned server on either runtime. Dropping it does not stop the server; call ServerHandle::shutdown, or ServerHandle::trigger and then join, to drain it.
StatusCode
An HTTP status code (status-code in RFC 9110 et al.).

Enums§

ClientAuthcompio-tls or http3 or tls
mTLS policy: client certificates are verified against the rustls::RootCertStore.
H3Congestion
QUIC congestion controller for HTTP/3, from quinn::congestion without a quinn dependency.
TlsCert
Certificate source for spawn_tls and spawn_h3; Der and Resolver need the tls feature.

Constants§

NOT_FOUND
Plain-text 404 response, e.g. for router.fallback(|_| async { NOT_FOUND }).

Functions§

bind_with_port_fallback
Binds addr, asking on stdin whether to try the next port while the port is in use; meant for local development and examples.
build_rustls_server_configcompio-tls or http3 or tls
Builds the rustls config the TLS spawn methods use, for the serve_*_with_rustls_config functions. With h3 in alpn, 0-RTT early data is disabled.
serve_per_threadper-thread
Runs workers until Ctrl+C or SIGTERM, then drains requests; fails if no worker could bind.
shutdown_signal
Waits for Ctrl+C or, on Unix, SIGTERM, using a dedicated signal driver when called outside Tokio.
spawn_per_threadper-thread
Starts workers and returns their thread handles and the trigger that stops them.

Attribute Macros§

delete
#[delete("/path", [name = "Foo"])] — shorthand for #[route(DELETE, ...)].
get
#[get("/path", [name = "Foo"])] — shorthand for #[route(GET, ...)].
head
#[head("/path", [name = "Foo"])] — shorthand for #[route(HEAD, ...)].
options
#[options("/path", [name = "Foo"])] — shorthand for #[route(OPTIONS, ...)].
patch
#[patch("/path", [name = "Foo"])] — shorthand for #[route(PATCH, ...)].
post
#[post("/path", [name = "Foo"])] — shorthand for #[route(POST, ...)].
put
#[put("/path", [name = "Foo"])] — shorthand for #[route(PUT, ...)].
route
Registers the handler for Router::mount_all; typed placeholders such as {id: u64} also generate a TypedParams struct named <Handler>Params unless name = "..." overrides it.