Write Cloudflare Workers in 100% Rust via WebAssembly

Overview

workers-rs crates.io docs.rs

Work-in-progress ergonomic Rust bindings to Cloudflare Workers environment. Write your entire worker in Rust!

Read the Notes and FAQ

Example Usage

use worker::*;

#[event(fetch)]
pub async fn main(req: Request, env: Env) -> Result<Response> {
    console_log!(
        "{} {}, located at: {:?}, within: {}",
        req.method().to_string(),
        req.path(),
        req.cf().coordinates().unwrap_or_default(),
        req.cf().region().unwrap_or("unknown region".into())
    );

    if !matches!(req.method(), Method::Post) {
        return Response::error("Method Not Allowed", 405);
    }

    if let Some(file) = req.form_data().await?.get("file") {
        return match file {
            FormEntry::File(buf) => {
                Response::ok(&format!("size = {}", buf.bytes().await?.len()))
            }
            _ => Response::error("`file` part of POST form must be a file", 400),
        };
    }

    Response::error("Bad Request", 400)
}

Or use the Router:

Parameterize routes and access the parameter values from within a handler. Each handler function takes a Request, and a RouteContext. The RouteContext has shared data, route params, Env bindings, and more.

use worker::*;

#[event(fetch)]
pub async fn main(req: Request, env: Env) -> Result<Response> {
    
    // Create an instance of the Router, and pass it some shared data to be used within routes.
    // In this case, `()` is used for "no data" so the type information is set for the generic used.
    // Access the shared data in your routes using the `ctx.data()` method.
    let router = Router::new(());

    // useful for JSON APIs
    #[derive(Deserialize, Serialize)]
    struct Account {
        id: u64,
        // ...
    }
    router
        .get_async("/account/:id", |_req, ctx| async move {
            if let Some(id) = ctx.param("id") {
                let accounts = ctx.kv("ACCOUNTS")?;
                return match accounts.get(id).await? {
                    Some(account) => Response::from_json(&account.as_json::<Account>()?),
                    None => Response::error("Not found", 404),
                };
            }

            Response::error("Bad Request", 400)
        })
        // handle files and fields from multipart/form-data requests
        .post_async("/upload", |mut req, _ctx| async move {
            let form = req.form_data().await?;
            if let Some(entry) = form.get("file") {
                match entry {
                    FormEntry::File(file) => {
                        let bytes = file.bytes().await?;
                    }
                    FormEntry::Field(_) => return Response::error("Bad Request", 400),
                }
                // ...

                if let Some(permissions) = form.get("permissions") {
                    // permissions == "a,b,c,d"
                }
                // or call `form.get_all("permissions")` if using multiple entries per field
            }

            Response::error("Bad Request", 400)
        })
        // read/write binary data
        .post_async("/echo-bytes", |mut req, _ctx| async move {
            let data = req.bytes().await?;
            if data.len() < 1024 {
                return Response::error("Bad Request", 400);
            }

            Response::from_bytes(data)
        })
        .run(req, env).await
}   

Getting Started

Make sure you have wrangler installed at a recent version (>=v1.19.2). If you want to publish your Rust worker code, you will need to have a Cloudflare account.

Run wrangler --version to check your installation and if it meets the version requirements.

wrangler generate --type=rust project_name
cd project_name
wrangler build

You should see a new project layout with a src/lib.rs. Start there! Use any local or remote crates and modules (as long as they compile to the wasm32-unknown-unknown target).

Once you're ready to run your project:

wrangler dev

And then go live:

# configure your routes, zones & more in your worker's `wrangler.toml` file
wrangler publish

Durable Object, KV, Secret, & Variable Bindings

All "bindings" to your script (Durable Object & KV Namespaces, Secrets, and Variables) are accessible from the env parameter provided to both the entrypoint (main in this example), and to the route handler callback (in the ctx argument), if you use the Router from the worker crate.

use worker::*;

#[event(fetch, respond_with_errors)]
pub async fn main(req: Request, env: Env) -> Result<Response> {
    utils::set_panic_hook();

    let router = Router::new(()); 

    router
        .on_async("/durable", |_req, ctx| async move {
            let namespace = ctx.durable_object("CHATROOM")?;
            let stub = namespace.id_from_name("A")?.get_stub()?;
            stub.fetch_with_str("/messages").await
        })
        .get("/secret", |_req, ctx| {
            Response::ok(ctx.secret("CF_API_TOKEN")?.to_string())
        })
        .get("/var", |_req, ctx| {
            Response::ok(ctx.var("BUILD_NUMBER")?.to_string())
        })
        .post_async("/kv", |_req, ctx| async move {
            let kv = ctx.kv("SOME_NAMESPACE")?;

            kv.put("key", "value")?.execute().await?;

            Response::empty()
        })
        .run(req, env).await
}

For more information about how to configure these bindings, see:

Durable Objects

BETA WARNING

Durable Objects are still in BETA, so the same rules apply to the Durable Object code and APIs here in these crates.

Define a Durable Object in Rust

To define a Durable Object using the worker crate you need to implement the DurableObject trait on your own struct. Additionally, the #[durable_object] attribute macro must be applied to both your struct definition and the trait impl block for it.

use worker::*;

#[durable_object]
pub struct Chatroom {
    users: Vec<User>,
    messages: Vec<Message>
    state: State,
    env: Env, // access `Env` across requests, use inside `fetch`

}

#[durable_object]
impl DurableObject for Chatroom {
    fn new(state: State, env: Env) -> Self {
        Self {
            users: vec![],
            messages: vec![],
            state: state,
            env,
        }
    }

    async fn fetch(&mut self, _req: Request) -> Result<Response> {
        // do some work when a worker makes a request to this DO
        Response::ok(&format!("{} active users.", self.users.len()))
    }
}

You'll need to "migrate" your worker script when it's published so that it is aware of this new Durable Object, and include a binding in your wrangler.toml.

  • Include the Durable Object binding type in you wrangler.toml file:
# ...

[durable_objects]
bindings = [
  { name = "CHATROOM", class_name = "Chatroom" } # the `class_name` uses the Rust struct identifier name
]

[[migrations]]
tag = "v1" # Should be unique for each entry
new_classes = ["Chatroom"] # Array of new classes

Notes and FAQ

It is exciting to see how much is possible with a framework like this, by expanding the options developers have when building on top of the Workers platform. However, there is still much to be done. Expect a few rough edges, some unimplemented APIs, and maybe a bug or two here and there. It’s worth calling out here that some things that may have worked in your Rust code might not work here - it’s all WebAssembly at the end of the day, and if your code or third-party libraries don’t target wasm32-unknown-unknown, they can’t be used on Workers. Additionally, you’ve got to leave your threaded async runtimes at home; meaning no Tokio or async_std support. However, async/await syntax is still available and supported out of the box when you use the worker crate.

We fully intend to support this crate and continue to build out its missing features, but your help and feedback is a must. We don’t like to build in a vacuum, and we’re in an incredibly fortunate position to have brilliant customers like you who can help steer us towards an even better product.

So give it a try, leave some feedback, and star the repo to encourage us to dedicate more time and resources to this kind of project.

If this is interesting to you and you want to help out, we’d be happy to get outside contributors started. We know there are improvements to be made such as compatibility with popular Rust HTTP ecosystem types (we have an example conversion for Headers if you want to make one), implementing additional Web APIs, utility crates, and more. In fact, we’re always on the lookout for great engineers, and hiring for many open roles - please take a look.

FAQ

  1. Can I deploy a Worker that uses tokio or async_std runtimes?
  • Currently no. All crates in your Worker project must compile to wasm32-unknown-unknown target, which is more limited in some ways than targets for x86 and ARM64.
  1. The worker crate doesn't have X! Why not?
  • Most likely, it should, we just haven't had the time to fully implement it or add a library to wrap the FFI. Please let us know you need a feature by opening an issue.
  1. My bundle size exceeds Workers 1MB limits, what do I do?

Contributing

Your feedback is welcome and appreciated! Please use the issue tracker to talk about potential implementations or make feature requests. If you're interested in making a PR, we suggest opening up an issue to talk about the change you'd like to make as early as possible.

Project Contents

  • worker: the user-facing crate, with Rust-famaliar abstractions over the Rust<->JS/WebAssembly interop via wrappers and convenience library over the FFI bindings.
  • worker-sys: Rust extern "C" definitions for FFI compatibility with the Workers JS Runtime.
  • worker-macros: exports event and durable_object macros for wrapping Rust entry point in a fetch method of an ES Module, and code generation to create and interact with Durable Objects.
  • worker-sandbox: a functioning Cloudflare Worker for testing features and ergonomics.
  • worker-build: a cross-platform build command for workers-rs-based projects.
Comments
  • 🐛 BUG: reqwest doesn't have resolve method in ClientBuilder

    🐛 BUG: reqwest doesn't have resolve method in ClientBuilder

    What version of Wrangler are you using?

    2.6.2

    What operating system are you using?

    Mac

    Describe the Bug

    With reqwest = "0.11.13" I can use resolve() in the following way:

    let client = reqwest::ClientBuilder::new()
        .resolve("cloudflare-dns.com", "1.1.1.1:443".parse().unwrap())
        .build()?;
    let res = client
        .get("https://cloudflare-dns.com/")
        .send()
        .await?
        .text()
        .await?;
    

    But when I try to use it with workers even though I can cargo build without an error, when I use wrangler dev it says .resolve method not found in ClientBuilder

    Cargo clean doesn't help either.

    bug 
    opened by thesved 2
  • [BUG] npm init cloudflare fails

    [BUG] npm init cloudflare fails

    Is there an existing issue for this?

    • [X] I have searched the existing issues

    What version of workers-rs are you using?

    main

    Describe the bug

    when I do:

    npm init cloudflare project_name worker-rust
    

    I get an error:

    Need to install the following packages:
      [email protected]
    Ok to proceed? (y) y
    
    Error: EXDEV: cross-device link not permitted, rename '/tmp/2122340072f1d-91d055235fe5d/worker-rust' -> '/home/xxx/project_name'
    
    npm ERR! code 1
    

    Steps To Reproduce

    linux 6.0.11-arch1-1 npm 9.2.0 run npm init cloudflare project_name worker-rust

    opened by vincentserpoul 0
  • [Feature] Move worker-sandbox to an examples folder

    [Feature] Move worker-sandbox to an examples folder

    Is there an existing issue for this?

    • [X] I have searched the existing issues

    Description

    It's standard for rust repos to have a folder named examples which holds examples of how to use the crate. I thought that the only examples were the README. It was only when searching in the issues pane for someone requesting fetch to be implemented that I found a link to lib.rs in worker-sandbox.

    Would it be possible to rearrange this directory such that it follows the examples standard or this is called out as containing lots of examples?

    opened by dustinknopoff 0
  • feat: Add queue support

    feat: Add queue support

    This PR adds support for queues.

    I've only been able to test this manually as I'm not sure how I would set up the workers sandbox to test queues, if you have any ideas please let me know.

    opened by jdon 3
  • [WASI] Is there plans to support WASI

    [WASI] Is there plans to support WASI

    Is there an existing issue for this?

    • [X] I have searched the existing issues

    Description

    Hello! Is there plans to support recently annonced WASI integration?

    opened by ofen 0
Releases(v0.0.12)
Owner
Cloudflare
Cloudflare
An asynchronous runtime compatible with WebAssembly and non-WebAssembly targets.

Promise x Tokio = Prokio An asynchronous runtime compatible with WebAssembly and non-WebAssembly targets. Rationale When designing components and libr

Yew Stack 29 Feb 6, 2023
Rust in 100 seconds, potentially and beyond!

Rust in 100 seconds Watch the Rust in 100 Seconds Video. Article: What is Rust, and why is it so popular? What is Rust? Rust is blazingly fast and mem

Fireship 39 Dec 5, 2022
Learn to write Rust procedural macros [Rust Latam conference, Montevideo Uruguay, March 2019]

Rust Latam: procedural macros workshop This repo contains a selection of projects designed to learn to write Rust procedural macros — Rust code that g

David Tolnay 2.5k Dec 29, 2022
A cli tool to write your idea in terminal

Ideas ideas is a cli tools to write your idea in your terminal. Demo Features tagged idea, contains tips, idea, todo status switch ascii icon write yo

王祎 12 Jun 22, 2022
Write Anchor-compatible Solana programs in Python

seahorse: Write Solana programs in Python The ease of Python with the safety of Rust. Seahorse lets you write Solana programs in Python. It is a commu

✨ amelia chen ✨ 214 Dec 28, 2022
Thread-safe clone-on-write container for fast concurrent writing and reading.

sync_cow Thread-safe clone-on-write container for fast concurrent writing and reading. SyncCow is a container for concurrent writing and reading of da

null 40 Jan 16, 2023
Compact, clone-on-write vector and string.

ecow Compact, clone-on-write vector and string. Types An EcoVec is a reference-counted clone-on-write vector. It takes up two words of space (= 2 usiz

Typst 78 Apr 18, 2023
A relatively simple puzzle generator application written in Rust and used via Javascript

Puzzlip Basic Overview This is a relatively simple puzzle generator application written in Rust and used via Javascript in https://puzzlip.com. If you

Nenad 5 Dec 7, 2022
Charted's email service built in Rust that can be connected via gRPC

email-service is a small microservice to help transfer emails towards other people without trying to implement it in different languages. This is used in charted-server for member invitations, passwordless authentication, and more.

charted 7 Mar 6, 2023
Shared Channel for WebAssembly

Shared Channel for WebAssembly This crate provides a way for WebAssembly threads to receive messages from other threads using a JavaScript primitive c

wasm.rs 27 Nov 24, 2022
Leetcode Solutions in Rust, Advent of Code Solutions in Rust and more

RUST GYM Rust Solutions Leetcode Solutions in Rust AdventOfCode Solutions in Rust This project demostrates how to create Data Structures and to implem

Larry Fantasy 635 Jan 3, 2023
Simple autoclicker written in Rust, to learn the Rust language.

RClicker is an autoclicker written in Rust, written to learn more about the Rust programming language. RClicker was was written by me to learn more ab

null 7 Nov 15, 2022
Rust programs written entirely in Rust

mustang Programs written entirely in Rust Mustang is a system for building programs built entirely in Rust, meaning they do not depend on any part of

Dan Gohman 561 Dec 26, 2022
Rust 核心库和标准库的源码级中文翻译,可作为 IDE 工具的智能提示 (Rust core library and standard library translation. can be used as IntelliSense for IDE tools)

Rust 标准库中文版 这是翻译 Rust 库 的地方, 相关源代码来自于 https://github.com/rust-lang/rust。 如果您不会说英语,那么拥有使用中文的文档至关重要,即使您会说英语,使用母语也仍然能让您感到愉快。Rust 标准库是高质量的,不管是新手还是老手,都可以从中

wtklbm 493 Jan 4, 2023
A library for extracting #[no_mangle] pub extern "C" functions (https://docs.rust-embedded.org/book/interoperability/rust-with-c.html#no_mangle)

A library for extracting #[no_mangle] pub extern "C" functions In order to expose a function with C binary interface for interoperability with other p

Dmitrii - Demenev 0 Feb 17, 2022
clone of grep cli written in Rust. From Chapter 12 of the Rust Programming Language book

minigrep is a clone of the grep cli in rust Minigrep will find a query string in a file. To test it out, clone the project and run cargo run body poem

Raunak Singh 1 Dec 14, 2021
Rust-blog - Educational blog posts for Rust beginners

pretzelhammer's Rust blog ?? I write educational content for Rust beginners and Rust advanced beginners. My posts are listed below in reverse chronolo

kirill 5.2k Jan 1, 2023
The ray tracer challenge in rust - Repository to follow my development of "The Raytracer Challenge" book by Jamis Buck in the language Rust

The Ray Tracer Challenge This repository contains all the code written, while step by implementing Ray Tracer, based on the book "The Ray Tracer Chall

Jakob Westhoff 54 Dec 25, 2022
Learn-rust-the-hard-way - "Learn C The Hard Way" by Zed Shaw Converted to Rust

Learn Rust The Hard Way This is an implementation of Zed Shaw's Learn X The Hard Way for the Rust Programming Language. Installing Rust TODO: Instruct

Ryan Levick 309 Dec 8, 2022