Expand description
Tork — a FastAPI-style backend web framework for Rust, built on Hyper and Tokio.
This is the facade crate: the single crate end users depend on. It re-exports
the runtime from tork-core, the procedural macros from tork-macros, and,
when the openapi feature is enabled, the OpenAPI support from tork-openapi.
§Example
ⓘ
use tork::{App, OpenApi};
#[tork::main]
async fn main() -> tork::Result<()> {
App::new()
.include_router(users::router())
.openapi(OpenApi::new().title("My API").version("1.0.0").docs("/docs"))
.serve("0.0.0.0:8000")
.await
}Modules§
- constants
- Named constants used across the runtime.
- header
- HTTP header types
- middleware
- The middleware layer.
- mime
- Mime
- security
- Small security helpers for application code.
- testing
- In-process test harness.
Macros§
- assert_
logs - Asserts a recorder captured a log with the given context and message substring.
Structs§
- App
- The application builder.
- AppInner
- The finalized application: shared state plus a compiled route matcher.
- Async
Api - Configures AsyncAPI document generation.
- Bearer
Token - A bearer token extracted from the
Authorizationheader. - ByIp
- The default key strategy: the client IP address.
- Cache
- A cheap-to-clone handle over a
CacheStore, with a typed, ergonomic API. - Error
- A framework error that can be turned into an HTTP error response.
- Error
Context - Context passed to an
exception_handleralongside the recovered typed error. - Error
Detail - A single field-level error, included in validation responses.
- Error
Event - Context for
on_error: a non-validation error was produced. - File
Bytes - A buffered uploaded file, held entirely in memory.
- File
LogConfig - Configuration for a rolling file log sink.
- Form
- An
application/x-www-form-urlencodedrequest body, deserialized and validated. - Header
Map - A specialized multimap for header names and values.
- Header
Name - Represents an HTTP header field name
- Header
Value - Represents an HTTP header field value.
- Http1
Config - HTTP/1 connection tuning applied to every served connection.
- Http2
Config - HTTP/2 connection tuning applied to every served connection.
- Hub
- A registry of broadcast
Rooms keyed by name. - Json
- A JSON response wrapper.
- Last
Event Id - The
Last-Event-IDheader sent by a client resuming an SSE stream. - Lifespan
Context - Context passed to a lifespan’s
startup. - LogEvent
- A log record being built. Add fields and an error, then
emit. - LogSpan
- A span being built. Add fields, then
entera scope orruna future inside it. - Logger
- A context-aware logger.
- Logger
Config - How the application logs.
- Matcher
- Compiled, per-method path matcher over a flat route table.
- Memory
Store - An in-memory
CacheStorewith per-entry TTL, backed bymoka. - Memory
Throttle Store - An in-memory
ThrottleStorebacked by a map of counters. - Method
- The Request Method (VERB)
- Multipart
- A
multipart/form-datarequest body bound to a form model. - Next
- A handle to the remainder of the middleware chain.
- OpenApi
- Configures OpenAPI document generation.
- Panic
Event - Context for
on_panic: a handler panicked and the panic was caught by the panic boundary. - Path
Params - Raw path parameters captured by the router, in match order.
- Ready
Context - Context passed to
on_readyhooks, after the listener has bound. - Request
Context - Everything an extractor needs to resolve a value from the current request.
- Request
Event - Context for
on_request: a request has arrived. - Resp
Body - The outbound response body.
- Response
Event - Context for
on_response: a response is ready. - Room
- A single broadcast room: send to all subscribers, or subscribe to receive.
- Route
- A single route: an HTTP method, a path pattern, a handler, and metadata.
- Route
Meta - Introspection metadata for a route, used to build the OpenAPI document.
- Router
- A group of routes sharing a path prefix and a set of tags.
- Secret
String - A string whose value is kept out of logs and debug output.
- Settings
Loader - Loads and validates a typed configuration from layered sources.
- Sse
- A streaming
text/event-streamresponse carrying events of data typeT. - SseEvent
- A single Server-Sent Event with optional metadata.
- SseResume
- The
Last-Event-IDheader parsed into a typed resume cursor. - State
- Extractor that yields a clone of an application state value of type
S. - State
Map - A type-erased, thread-safe container for application state values.
- Status
Code - An HTTP status code (
status-codein RFC 9110 et al.). - Telemetry
Config - Configuration for OpenTelemetry trace export (effective with the
otelfeature). - TestApp
- An application built for in-process testing.
- Throttle
- Configures rate limiting; see
App::throttle. - Throttler
- The runtime throttle engine, injectable and used by generated route code.
- Tork
Service - A Hyper
Servicethat hands each request to the application. - Upload
Config - Limits and temp-file behavior for multipart uploads.
- Upload
File - An uploaded file backed by a spooled temporary file.
- Valid
- Deserializes the JSON request body into
Tand validates it. - Validation
Error Event - Context for
on_validation_error: a request body failed validation (422). - WebSocket
- A WebSocket upgrade handle: call
acceptto open it. - WebSocket
Config - Limits and timeouts for a WebSocket connection.
- WebSocket
Conn - A live WebSocket connection.
- WsClose
- A close control frame: a status code and a human-readable reason.
- WsConnect
Info - Context for
on_ws_connect: a socket opened. - WsDisconnect
Info - Context for
on_ws_disconnect: a socket closed. - WsError
- An error raised while handling a WebSocket connection.
- WsReceiver
- Receiving-half of the
broadcastchannel.
Enums§
- Duplicate
Policy - Controls what happens when a middleware whose
namealready exists is registered again. - Error
Kind - The category of an
Error, which determines the HTTP status code. - Error
LogDetail - How much structured error detail a logged record includes.
- IpNet
- An IP network address, either IPv4 or IPv6.
- LogFormat
- The console output format.
- Match
- The outcome of matching a request against the route table.
- Request
Body Kind - The encoding of a route’s request body, for OpenAPI documentation.
- Rotation
- How often a file log is rolled over.
- Throttle
Policy - The rate-limit policy attached to a route, emitted by the
throttleattribute. - WsClose
Code - A WebSocket close status code.
- WsMessage
- A WebSocket message.
Traits§
- Async
ApiProvider - Produces the routes that serve the AsyncAPI document.
- Cache
Store - A cache backend that stores opaque byte values under string keys.
- From
Multipart - Builds a value from a parsed multipart body.
- From
Path Param - Parses a single captured URL segment into a typed path parameter.
- From
Request - Produces a value from the current request to satisfy a handler parameter.
- Into
Response - Converts a value into an HTTP
Response. - Lifespan
- The startup and shutdown lifecycle of a resource container.
- Middleware
- A request/response middleware layer.
- Open
ApiProvider - Produces the routes that serve the OpenAPI document and documentation UI.
- Resources
- A type that contributes resources to the application registry.
- Throttle
Key - Produces the key a request is rate-limited by (the “tracker”).
- Throttle
Store - A backend that counts requests per key within a time window.
Functions§
- box_
body - Erases any compatible HTTP body into the runtime’s
ReqBodytype. - bytes_
response - Builds a response from a pre-serialized body and an explicit content type.
- constant_
time_ eq - Compares two byte strings in constant time relative to their contents.
- json_
response - Serializes
valueto JSON and builds a response with the given status.
Type Aliases§
- AppState
Ref - A shared, reference-counted handle to the application state map.
- BoxError
- Boxed, thread-safe error type carried by an erased request body.
- BoxFuture
- A boxed, sendable future of a request handler’s response.
- Handler
Fn - A type-erased request handler.
- ReqBody
- The inbound request body type.
- Request
- The request type threaded through the middleware chain.
- Response
- The concrete HTTP response type used throughout the framework.
- Result
- A specialized
Resultwhose error type defaults toError. - Schema
Thunk - Produces a JSON Schema for a type, recorded as a function pointer so that
RouteMetastaysCopy-free of any concrete type while still describing request and response bodies.
Attribute Macros§
- api_
model - Turns a struct into a validated, documented API model.
- api_
router - Turns an inline module into a router.
- delete
- Declares a
DELETEroute. - dependency
- Turns a type into a request dependency.
- get
- Declares a
GETroute. Seegetand the other method macros for the supported attributes (response_model,summary,description,status_code,tags). - lifespan
- Declares an application lifespan on a resource container.
- main
- Marks the asynchronous entrypoint of a Tork application.
- middleware
- Turns an async function into a middleware layer.
- patch
- Declares a
PATCHroute. - post
- Declares a
POSTroute. - post_
sse - Declares a Server-Sent Events endpoint served over
POST. - put
- Declares a
PUTroute. - settings
- Declares a typed application configuration.
- sse
- Declares a Server-Sent Events endpoint (default
GET). - websocket
- Declares a WebSocket endpoint.