Expand description
§Features
§d1
Allows the use of D1 bindings and query!
macro.
§queue
Enables queue
event type in [event]
macro.
// Consume messages from a queue
#[event(queue)]
pub async fn main(message_batch: MessageBatch<MyType>, env: Env, _ctx: Context) -> Result<()> {
Ok(())
}
§http
worker
0.0.21
introduced an http
feature flag which starts to replace custom types with widely used types from the http
crate.
This makes it much easier to use crates which use these standard types such as axum
.
This currently does a few things:
- Introduce
Body
, which implementshttp_body::Body
and is a simple wrapper aroundweb_sys::ReadableStream
. - The
req
argument when using the[event(fetch)]
macro becomeshttp::Request<worker::Body>
. - The expected return type for the fetch handler is
http::Response<B>
whereB
can be anyhttp_body::Body<Data=Bytes>
. - The argument for
Fetcher::fetch_request
ishttp::Request<worker::Body>
. - The return type of
Fetcher::fetch_request
ishttp::Response<worker::Body>
.
The end result is being able to use frameworks like axum
directly (see example):
pub async fn root() -> &'static str {
"Hello Axum!"
}
fn router() -> Router {
Router::new().route("/", get(root))
}
#[event(fetch)]
async fn fetch(
req: HttpRequest,
_env: Env,
_ctx: Context,
) -> Result<http::Response<axum::body::Body>> {
Ok(router().call(req).await?)
}
We also implement try_from
between worker::Request
and http::Request<worker::Body>
, and between worker::Response
and http::Response<worker::Body>
.
This allows you to convert your code incrementally if it is tightly coupled to the original types.
§Send
Helpers
A number of frameworks (including axum
) require that objects that they are given (including route handlers) can be
sent between threads (i.e are marked as Send
). Unfortuntately, objects which interact with JavaScript are frequently
not marked as Send
. In the Workers environment, this is not an issue, because Workers are single threaded. There are still
some ergonomic difficulties which we address with some wrapper types:
send::SendFuture
- wraps anyFuture
and marks it asSend
:
// `fut` is `Send`
let fut = send::SendFuture::new(async move {
// `JsFuture` is not `Send`
JsFuture::from(promise).await
});
send::SendWrapper
- Marks an arbitrary object asSend
and implementsDeref
andDerefMut
, as well asClone
,Debug
, andDisplay
if the inner type does. This is useful for attaching types as state to anaxum
Router
:
// `KvStore` is not `Send`
let store = env.kv("FOO")?;
// `state` is `Send`
let state = send::SendWrapper::new(store);
let router = axum::Router::new()
.layer(Extension(state));
[worker::send]
- Macro to make anyasync
functionSend
. This can be a little tricky to identify as the problem, butaxum
’s[debug_handler]
macro can help, and looking for warnings that a function or object cannot safely be sent between threads.
// This macro makes the whole function (i.e. the `Future` it returns) `Send`.
#[worker::send]
async fn handler(Extension(env): Extension<Env>) -> Response<String> {
let kv = env.kv("FOO").unwrap()?;
// Holding `kv`, which is not `Send` across `await` boundary would mark this function as `!Send`
let value = kv.get("foo").text().await?;
Ok(format!("Got value: {:?}", value));
}
let router = axum::Router::new()
.route("/", get(handler))
§RPC Support
workers-rs
has experimental support for Workers RPC.
For now, this relies on JavaScript bindings and may require some manual usage of wasm-bindgen
.
Not all features of RPC are supported yet (or have not been tested), including:
- Function arguments and return values
- Class instances
- Stub forwarding
§RPC Server
Writing an RPC server with workers-rs
is relatively simple. Simply export methods using wasm-bindgen
. These
will be automatically detected by worker-build
and made available to other Workers. See
example.
§RPC Client
Creating types and bindings for invoking another Worker’s RPC methods is a bit more involved. You will need to
write more complex wasm-bindgen
bindings and some boilerplate to make interacting with the RPC methods more
idiomatic. See example.
With manually written bindings, it should be possible to support non-primitive argument and return types, using
serde-wasm-bindgen
.
§Generating Client Bindings
There are many routes that can be taken to describe RPC interfaces. Under the hood, Workers RPC uses Cap’N Proto. A possible future direction is for Wasm guests to include Cap’N Proto serde support and speak directly to the RPC protocol, bypassing JavaScript. This would likely involve defining the RPC interface in Cap’N Proto schema and generating Rust code from that.
Another popular interface schema in the WebAssembly community is
WIT. This is a lightweight format
designed for the WebAssembly Component model. workers-rs
includes an experimental code generator which
allows you to describe your RPC interface using WIT and generate JavaScript bindings as shown in the
rpc-client example.
The easiest way to use this code generator is using a
build script as shown in the example.
This code generator is pre-alpha, with no support guarantee, and implemented only for primitive types at this time.
Re-exports§
Modules§
- crypto
- d1
- Requires
d1
feature. - durable
- Durable Objects provide low-latency coordination and consistent storage for the Workers platform. A given namespace can support essentially unlimited Durable Objects, with each Object having access to a transactional, key-value storage API.
- postgres_
tls - Implements
TlsConnect
forSocket
to enabletokio_postgres
connections to databases using TLS. - send
- This module provides utilities for working with JavaScript types
which do not implement
Send
, in contexts whereSend
is required. Workers is guaranteed to be single-threaded, so it is safe to wrap any type withSend
andSync
traits. - ws_
events
Macros§
- console_
debug - When debugging your Worker via
wrangler dev
,wrangler tail
, or from the Workers Dashboard, anything passed to this macro will be printed to the terminal or written to the console. - console_
error - When debugging your Worker via
wrangler dev
,wrangler tail
, or from the Workers Dashboard, anything passed to this macro will be printed to the terminal or written to the console. - console_
log - When debugging your Worker via
wrangler dev
,wrangler tail
, or from the Workers Dashboard, anything passed to this macro will be printed to the terminal or written to the console. - console_
warn - When debugging your Worker via
wrangler dev
,wrangler tail
, or from the Workers Dashboard, anything passed to this macro will be printed to the terminal or written to the console. - query
- Requires
d1
feature. Prepare a D1 query from the provided D1Database, query string, and optional query parameters.
Structs§
- Abort
Controller - An interface that allows you to abort in-flight Fetch requests.
- Abort
Signal - An interface representing a signal that can be passed to cancellable operations, primarily a Fetch request.
- Ai
- Batch
Message Builder - Batch
Send Message - Body
- Requires
http
feature. A convenience Body type which wrapsweb_sys::ReadableStream
and implementshttp_body::Body
- Bucket
- An instance of the R2 bucket binding.
- Byte
Stream - Cache
- Provides access to the Cache API.
Because
match
is a reserved keyword in Rust, thematch
method has been renamed toget
. - Cf
- In addition to the methods on the
Request
struct, theCf
struct on an inbound Request contains information about the request provided by Cloudflare’s edge. - CfProperties
- https://developers.cloudflare.com/workers/runtime-apis/request#requestinitcfproperties
- CfResponse
Properties - Close
Event - Wrapper/Utility struct for the
web_sys::CloseEvent
- Conditional
- You can pass an Conditional object to GetOptionsBuilder. If the condition check fails, the body will not be returned. This will make get have lower latency.
- Connection
Builder - Context
- A context bound to a
fetch
event. - Cors
- Cors struct, holding cors configuration
- Create
Multipart Upload Options Builder - Options for configuring the create_multipart_upload operation.
- Date
- The equivalent to a JavaScript
Date
Object. - Delay
- A Future for asynchronously waiting.
- Dynamic
Dispatcher - A binding for dispatching events to Workers inside of a dispatch namespace by their name. This allows for your worker to directly invoke many workers by name instead of having multiple service worker bindings.
- Env
- Env contains any bindings you have associated with the Worker when you uploaded it.
- Event
Stream - A
Stream
that yieldsWebsocketEvent
s emitted by the innerWebSocket
. The stream is guaranteed to always yield aWebsocketEvent::Close
as the final non-none item. - Fetcher
- A struct for invoking fetch events to other Workers.
- File
- A File representation used with
FormData
. - Fixed
Length Stream - Form
Data - A FormData representation of the request body, providing access to form encoded fields and files.
- GetOptions
Builder - Options for configuring the get operation.
- Headers
- A Headers representation used in Request and Response objects.
- Http
Metadata - Metadata that’s automatically rendered into R2 HTTP API endpoints.
- Hyperdrive
- List
Options Builder - Options for configuring the list operation.
- Message
- A message that is sent to a consumer Worker.
- Message
Batch - A batch of messages that are sent to a consumer Worker.
- Message
Builder - Message
Event - Wrapper/Utility struct for the
web_sys::MessageEvent
- Message
Iter - Minify
Config - Configuration options for Cloudflare’s minification features: https://www.cloudflare.com/website-optimization/
- Multipart
Upload - Object
- Object is created when you put an object into a Bucket. Object represents the metadata of an object based on the information provided by the uploader. Every object that you put into a Bucket will have an Object created.
- Object
Body - The data contained within an Object.
- Objects
- A series of Objects returned by list.
- PutOptions
Builder - Options for configuring the put operation.
- Queue
- Queue
Retry Options - Optional configuration when marking a message or a batch of messages for retry.
- Queue
Retry Options Builder - Queue
Send Batch Options - Queue
Send Options - Rate
Limiter - RawMessage
- A message that is sent to a consumer Worker.
- RawMessage
Builder - RawMessage
Iter - Request
- A Request representation for handling incoming and creating outbound HTTP requests.
- Request
Init - Optional options struct that contains settings to apply to the
Request
. - Response
- A Response representation for
working with or returning a response to a
Request
. - Response
Builder - Route
Context - Container for a route’s parsed parameters, data, and environment bindings from the Runtime (such as KV Stores, Durable Objects, Variables, and Secrets).
- Route
Params - Represents the URL parameters parsed from the path, e.g. a route with “/user/:id” pattern would contain a single “id” key.
- Router
- A path-based HTTP router supporting exact-match or wildcard placeholders and shared data.
- Schedule
Context - Scheduled
Event - Schedule
- Secret
- A string value representing a binding to a secret in a Worker.
- Send
Message - A wrapper type used for sending message.
- Socket
- Represents an outbound TCP connection from your Worker.
- Socket
Address - The host and port that you wish to connect to.
- Socket
Info - Socket
Options - Used to configure outbound TCP connections.
- TlsClient
Auth - Only set when using Cloudflare Access or API Shield
- Uploaded
Part - UploadedPart represents a part that has been uploaded. UploadedPart objects are returned from upload_part operations and must be passed to the complete operation.
- Url
- A parsed URL record.
- WebSocket
- Wrapper struct for underlying worker-sys
WebSocket
- WebSocket
Pair - Struct holding the values for a JavaScript
WebSocketPair
- Worker
Version Metadata
Enums§
- Cache
Deletion Outcome - Successful outcomes when attempting to delete a
Response
from the cache - Cache
Key - The
String
orRequest
object used as the lookup key.String
s are interpreted as the URL for a newRequest
object. - Data
- Date
Init - Initialize a
Date
by constructing this enum. - Encode
Body - Control how the body of the response will be encoded by the runtime before it is returned to the user.
- Error
- All possible Error variants that might be encountered while working with a Worker.
- Fetch
- Construct a Fetch call from a URL string or a Request object. Call its
send
method to execute the request. - Form
Entry - Representing the options any FormData value can be, a field or a file.
- Include
- Method
- A
Method
representation used on Request objects. - Polish
Config - Configuration options for Cloudflare’s image optimization feature: https://blog.cloudflare.com/introducing-polish-automatic-image-optimizati/
- Queue
Content Type - Range
- Request
Redirect - Response
Body - Secure
Transport - Secure transport options for outbound TCP connections.
- Websocket
Event - Events that can be yielded by a
EventStream
.
Traits§
- EnvBinding
- From
Request - A trait used to represent any viable Request type that can be used in the Worker. The only requirement is that it be convertible from a web_sys::Request.
- Into
Response - A trait used to represent any viable Response type that can be used in the Worker. The only requirement is that it be convertible to a web_sys::Response.
- Message
Ext
Functions§
- request_
from_ wasm - Requires
http
feature. Convertweb_sys::Request
toworker::HttpRequest
- request_
to_ wasm - Requires
http
feature. Converthttp::Request
toweb_sys::Request
- response_
from_ wasm - Requires
http
feature. Convertweb_sys::Response
toworker::HttpResponse
- response_
to_ wasm - Requires
http
feature. Convert generichttp::Response<B>
toweb_sys::Response
whereB
can be anyhttp_body::Body
Type Aliases§
- Http
Request - Requires
http
feature. Type alias forhttp::Request<worker::Body>
. - Http
Response - Requires
http
feature. Type alias forhttp::Response<worker::Body>
. - Result
- Var
- A string value representing a binding to an environment variable in a Worker.
Attribute Macros§
- durable_
object - event
- The
event
macro is used to denote a Worker handler, essentially binding from the JS runtime to a Rust function. - send
- Convert an async function which is
!Send
to beSend
.