Skip to main content

Crate tork

Crate tork 

Source
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.
AsyncApi
Configures AsyncAPI document generation.
BearerToken
A bearer token extracted from the Authorization header.
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.
ErrorContext
Context passed to an exception_handler alongside the recovered typed error.
ErrorDetail
A single field-level error, included in validation responses.
ErrorEvent
Context for on_error: a non-validation error was produced.
FileBytes
A buffered uploaded file, held entirely in memory.
FileLogConfig
Configuration for a rolling file log sink.
Form
An application/x-www-form-urlencoded request body, deserialized and validated.
HeaderMap
A specialized multimap for header names and values.
HeaderName
Represents an HTTP header field name
HeaderValue
Represents an HTTP header field value.
Http1Config
HTTP/1 connection tuning applied to every served connection.
Http2Config
HTTP/2 connection tuning applied to every served connection.
Hub
A registry of broadcast Rooms keyed by name.
Json
A JSON response wrapper.
LastEventId
The Last-Event-ID header sent by a client resuming an SSE stream.
LifespanContext
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 enter a scope or run a future inside it.
Logger
A context-aware logger.
LoggerConfig
How the application logs.
Matcher
Compiled, per-method path matcher over a flat route table.
MemoryStore
An in-memory CacheStore with per-entry TTL, backed by moka.
MemoryThrottleStore
An in-memory ThrottleStore backed by a map of counters.
Method
The Request Method (VERB)
Multipart
A multipart/form-data request body bound to a form model.
Next
A handle to the remainder of the middleware chain.
OpenApi
Configures OpenAPI document generation.
PanicEvent
Context for on_panic: a handler panicked and the panic was caught by the panic boundary.
PathParams
Raw path parameters captured by the router, in match order.
ReadyContext
Context passed to on_ready hooks, after the listener has bound.
RequestContext
Everything an extractor needs to resolve a value from the current request.
RequestEvent
Context for on_request: a request has arrived.
RespBody
The outbound response body.
ResponseEvent
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.
RouteMeta
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.
SecretString
A string whose value is kept out of logs and debug output.
SettingsLoader
Loads and validates a typed configuration from layered sources.
Sse
A streaming text/event-stream response carrying events of data type T.
SseEvent
A single Server-Sent Event with optional metadata.
SseResume
The Last-Event-ID header parsed into a typed resume cursor.
State
Extractor that yields a clone of an application state value of type S.
StateMap
A type-erased, thread-safe container for application state values.
StatusCode
An HTTP status code (status-code in RFC 9110 et al.).
TelemetryConfig
Configuration for OpenTelemetry trace export (effective with the otel feature).
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.
TorkService
A Hyper Service that hands each request to the application.
UploadConfig
Limits and temp-file behavior for multipart uploads.
UploadFile
An uploaded file backed by a spooled temporary file.
Valid
Deserializes the JSON request body into T and validates it.
ValidationErrorEvent
Context for on_validation_error: a request body failed validation (422).
WebSocket
A WebSocket upgrade handle: call accept to open it.
WebSocketConfig
Limits and timeouts for a WebSocket connection.
WebSocketConn
A live WebSocket connection.
WsClose
A close control frame: a status code and a human-readable reason.
WsConnectInfo
Context for on_ws_connect: a socket opened.
WsDisconnectInfo
Context for on_ws_disconnect: a socket closed.
WsError
An error raised while handling a WebSocket connection.
WsReceiver
Receiving-half of the broadcast channel.

Enums§

DuplicatePolicy
Controls what happens when a middleware whose name already exists is registered again.
ErrorKind
The category of an Error, which determines the HTTP status code.
ErrorLogDetail
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.
RequestBodyKind
The encoding of a route’s request body, for OpenAPI documentation.
Rotation
How often a file log is rolled over.
ThrottlePolicy
The rate-limit policy attached to a route, emitted by the throttle attribute.
WsCloseCode
A WebSocket close status code.
WsMessage
A WebSocket message.

Traits§

AsyncApiProvider
Produces the routes that serve the AsyncAPI document.
CacheStore
A cache backend that stores opaque byte values under string keys.
FromMultipart
Builds a value from a parsed multipart body.
FromPathParam
Parses a single captured URL segment into a typed path parameter.
FromRequest
Produces a value from the current request to satisfy a handler parameter.
IntoResponse
Converts a value into an HTTP Response.
Lifespan
The startup and shutdown lifecycle of a resource container.
Middleware
A request/response middleware layer.
OpenApiProvider
Produces the routes that serve the OpenAPI document and documentation UI.
Resources
A type that contributes resources to the application registry.
ThrottleKey
Produces the key a request is rate-limited by (the “tracker”).
ThrottleStore
A backend that counts requests per key within a time window.

Functions§

box_body
Erases any compatible HTTP body into the runtime’s ReqBody type.
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 value to JSON and builds a response with the given status.

Type Aliases§

AppStateRef
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.
HandlerFn
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 Result whose error type defaults to Error.
SchemaThunk
Produces a JSON Schema for a type, recorded as a function pointer so that RouteMeta stays Copy-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 DELETE route.
dependency
Turns a type into a request dependency.
get
Declares a GET route. See get and 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 PATCH route.
post
Declares a POST route.
post_sse
Declares a Server-Sent Events endpoint served over POST.
put
Declares a PUT route.
settings
Declares a typed application configuration.
sse
Declares a Server-Sent Events endpoint (default GET).
websocket
Declares a WebSocket endpoint.

Derive Macros§

AppError
Derives From<Self> for tork::Error, storing the value as a typed source.
FormModel
Derives FromMultipart for a multipart/form-data model.
Inject
Derives request-time construction by injecting each field.
Resources
Declares a resource container.