workerd / rust
AGENTS.md8.8k starsChanged 9 months agoApache-2.0View on GitHub
A dozen or so Rust crates — mostly libraries, plus the gen-compile-cache binary — linked into workerd via CXX FFI. No Cargo workspace — entirely Bazel-driven (wd_rust_crate.bzl / wd_rust_binary.bzl). Clippy pedantic+nursery enabled; allow-unwrap-in-tests; clippy.toml and rustfmt.toml live at the repository root and apply to every crate. Rust does not have to live here. A crate that belongs to a component lives beside that component's C++, in the same package, in a subdirectory named for the crate: e.g. workerd's entry point…
Trending
Quiet since August.thin dataabout the whole repository
Who's talking about cloudflare/workerd
- A Hacker News story“OS Workerd, Cloudflare's JavaScript/WASM Runtime”Hacker News · Sep 27, 2022 · 27 points
- withastro/astro“Cloudflare adapter returning [object Object]”GitHub · Oct 10, 2025 · 18 reactions
- supabase/supabase-js“The 'cache' field on 'RequestInitializerDict' is not implemented - Cloudflare Workers”GitHub · Mar 28, 2024 · 16 reactions
- nodejs/node“src: improve buffer.transcode performance”GitHub · Aug 1, 2024 · 13 reactions
- NixOS/nixpkgs“Package request: workerd”GitHub · Nov 12, 2024 · 12 reactions
The biggest 5 of 12 mentions linking to the repository that our crawl found. Each line is their own headline.
See all 12
Talked about on GitHub, Bluesky and Hacker News (12 times).
On GitHub · 6
- Oct 10, 2025Cloudflare adapter returning [object Object] — withastro/astro18 reactions · 15 comments
- Mar 28, 2024The 'cache' field on 'RequestInitializerDict' is not implemented - Cloudflare Workers — supabase/supabase-js16 reactions · 24 comments
- Aug 1, 2024src: improve buffer.transcode performance — nodejs/node13 reactions · 26 comments
- Nov 12, 2024Package request: workerd — NixOS/nixpkgs12 reactions · 8 comments
- Feb 19, 2024Add Curve25519 — w3c/webcrypto9 reactions · 16 comments
1 more on GitHub
- Nov 3, 2025Optimize TextEncoder::encode — nodejs/performance7 reactions · 33 comments
On Bluesky · 4
- Mar 24, 2026workerd : le runtime JavaScript/Wasm open source de Cloudflare Workers — @news.humancoders.com4 likes and reposts
- Aug 22, 2026Current status: trying to build github.com/cloudflare/w... on various sandbox providers — @jeremymorrell.dev1 likes and repost
- Mar 24, 2026workerd : le runtime JavaScript/Wasm qui propulse Cloudflare Workers est maintenant open source. Basé sur les standards web, il permet… — @humancoders.com1 likes and repost
- Nov 5, 2024Technically workers are open source github.com/cloudflare/w... — @userops.bsky.social1 likes and repost
On Hacker News · 2
- Sep 27, 2022OS Workerd, Cloudflare's JavaScript/WASM Runtime27 points · 2 comments
- Oct 5, 2023Cloudflare workers is adopting Ada URL parser2 points
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.
Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository61 other files it gives its agents.
- AGENTS.mdAGENTS.md
- build/AGENTS.mdAGENTS.md
- src/cloudflare/AGENTS.mdAGENTS.md
- src/node/AGENTS.mdAGENTS.md
- src/per_isolate/AGENTS.mdAGENTS.md
- src/per_isolate/crypto/AGENTS.mdAGENTS.md
- src/per_isolate/webfs/AGENTS.mdAGENTS.md
- src/per_isolate/webstreams/AGENTS.mdAGENTS.md
- src/pyodide/AGENTS.mdAGENTS.md
- src/rust/cxx/AGENTS.mdAGENTS.md
- src/tests/node/AGENTS.mdAGENTS.md
- src/tests/node/http-client/AGENTS.mdAGENTS.md
- src/tests/node/http-server/AGENTS.mdAGENTS.md
- src/tests/node/net/AGENTS.mdAGENTS.md
- src/tests/node/stream/AGENTS.mdAGENTS.md
- src/tests/streams/AGENTS.mdAGENTS.md
- src/tests/streams/cache/AGENTS.mdAGENTS.md
- src/tests/streams/compression/AGENTS.mdAGENTS.md
- src/tests/streams/digest/AGENTS.mdAGENTS.md
- src/tests/streams/encoding/AGENTS.mdAGENTS.md
- src/tests/streams/formdata/AGENTS.mdAGENTS.md
- src/tests/streams/htmlrewriter/AGENTS.mdAGENTS.md
- src/tests/streams/identity/AGENTS.mdAGENTS.md
- src/tests/streams/inspect/AGENTS.mdAGENTS.md
- src/tests/streams/iocontext/AGENTS.mdAGENTS.md
- src/tests/streams/piping/AGENTS.mdAGENTS.md
- src/tests/streams/r2-patterns/AGENTS.mdAGENTS.md
- src/tests/streams/readable/AGENTS.mdAGENTS.md
- src/tests/streams/readable-byte/AGENTS.mdAGENTS.md
- src/tests/streams/scaling/AGENTS.mdAGENTS.md
- src/tests/streams/sockets/AGENTS.mdAGENTS.md
- src/tests/streams/strategies/AGENTS.mdAGENTS.md
- src/tests/streams/transform/AGENTS.mdAGENTS.md
- src/tests/streams/writable/AGENTS.mdAGENTS.md
- src/workerd/api/AGENTS.mdAGENTS.md
- src/workerd/api/crypto/AGENTS.mdAGENTS.md
- src/workerd/api/node/AGENTS.mdAGENTS.md
- src/workerd/api/streams/AGENTS.mdAGENTS.md
- src/workerd/io/AGENTS.mdAGENTS.md
- src/workerd/jsg/AGENTS.mdAGENTS.md
- src/workerd/server/AGENTS.mdAGENTS.md
- src/workerd/util/AGENTS.mdAGENTS.md
- types/AGENTS.mdAGENTS.md
- bazel-test-hygieneSkill
- commit-categoriesSkill
- dad-jokesSkill
- find-and-run-testsSkill
- identify-reviewerSkill
- investigation-notesSkill
- kj-styleSkill
- markdown-draftsSkill
- parent-project-skillsSkill
- pr-review-guideSkill
- receiving-code-reviewSkill
- rust-reviewSkill
- ts-styleSkill
- update-v8Skill
- wd-test-formatSkill
- workerd-api-reviewSkill
- workerd-safety-reviewSkill
- The first 60 shown.
The file
We split this AGENTS.md into the rules it gives an agent
4 rules. About 0 are common, 0 are distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 44
Method naming: do not use get_ prefixes on methods — e.g.
- Very specific: line 89
cxx::KjError: Use the kj crate's error macros (kj::failed!, kj::overloaded!, kj::disconnected!, kj::not_implemented! - Very specific: line 108
Put the shim header in the package — the macro globs /*.h into the generated @cxx library's hdrs, so the include!
- Very specific: line 110
Add that wd_cc_library to the crate's link_deps so the symbol resolves at the final link.
≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
src/rust/
OVERVIEW
A dozen or so Rust crates — mostly libraries, plus the gen-compile-cache binary — linked into workerd via CXX FFI. No Cargo workspace — entirely Bazel-driven (wd_rust_crate.bzl / wd_rust_binary.bzl). Clippy pedantic+nursery enabled; allow-unwrap-in-tests; clippy.toml and rustfmt.toml live at the repository root and apply to every crate.
Rust does not have to live here. A crate that belongs to a component lives beside that component's C++, in the same package, in a subdirectory named for the crate: e.g. workerd's entry point (workerd-cli, src/workerd/server/cli/, next to cli-main.c++). Such crates glob their srcs from that subdirectory, list cxx_bridge_hdrs explicitly, and use the component's C++ namespace for their bridge. This directory holds the crates that have no C++ home of their own, and the in-tree cxx fork.
The "CXX FFI" above is the in-tree
src/rust/cxxfork of cxx-rs — not stock cxx-rs. It adds deep KJ interoperability upstream lacks:asyncfns becomekj::Promise<T>, you can return/holdkj::Own<T>,Result<T>throwskj::Exception, and other KJ types cross the boundary (see CXX BRIDGE below). cxx-rs is well represented in LLM training data, so it is easy to "recall" an API that is wrong here — prefer the prior art in these crates and the in-tree CXX sources (especially itskj-rscrate) over upstream cxx-rs docs or memory.
CRATES
Snapshot — the set drifts as crates come and go; bazel query //src/rust/... is authoritative.
| Crate | Purpose |
jsg/ | Rust JSG bindings: Lock, Rc<T>, Resource, Struct, Type, Realm, FeatureFlags, module registration; V8 handle types including typed arrays, ArrayBuffer, ArrayBufferView, SharedArrayBuffer, BackingStore |
jsg-macros/ | Proc macros: #[jsg_struct], #[jsg_method], #[jsg_resource], #[jsg_oneof], #[jsg_static_constant], #[jsg_constructor] |
jsg-test/ | Test harness (Harness) for JSG Rust bindings |
api/ | Rust-implemented Node.js APIs; registers modules via register_nodejs_modules() |
encoding/ | WHATWG legacy text decoders via encoding_rs; an opaque streaming Decoder emits UTF-16 over the CXX bridge |
kj/ | Rust bindings for KJ library (http, io, own submodules); Result<T> = Result<T, cxx::KjError> |
worker/ | Rust counterpart of workerd::WorkerInterface: the worker::Interface trait (into_kj hands an implementation to C++ as KjOwn<WorkerInterface>; not_supported answers a CustomEvent as C++'s event->notSupported() does), PromisedInterface (an Interface whose target is still starting, as C++'s PromisedWorkerInterface) plus FFI bindings; multi-bridge crate |
cxx-integration/ | Tokio runtime init; called from C++ main() before anything else |
cxx-integration-test/ | Non-production crate exercising Rust/C++ integration: callbacks, shared structs, Result error mapping |
transpiler/ | TS type stripping via SWC (ts_strip(), StripOnly mode) |
python-parser/ | Python import extraction via ruff_python_parser; namespace: edgeworker::rust:: |
gen-compile-cache/ | Binary crate — V8 bytecode cache generator; calls C++ compile() via CXX |
CONVENTIONS
- CXX bridge:
#[cxx::bridge(namespace = "workerd::rust::<crate>")]with companionffi.c++/ffi.hfiles - Namespace:
workerd::rust::*for crates in this directory, exceptpython-parser→edgeworker::rust::python_parser; a crate living beside C++ uses that C++'s namespace (e.g.workerd::server::cli) - Errors:
thiserrorfor library crates;jsg::ErrorwithExceptionTypefor JSG-facing crates - JSG resources:
#[jsg_resource]on struct + impl block;#[jsg_method]auto-convertssnake_case→camelCase; methods with&self/&mut selfbecome instance methods, methods without a receiver become static methods;#[jsg_static_constant]onconstitems exposes read-only numeric constants on both constructor and prototype (name kept as-is, no camelCase); resources integrate with GC viaTraced+GarbageCollected: every named field is traced viaTraced::trace(&self.field, visitor)and all non-traceable types use no-opTracedimpls - JSG properties: two property macros on
#[jsg_resource]impl blocks —#[jsg_property(prototype|instance [, name = "..."] [, readonly])](registers an accessor;prototypemaps toJSG_PROTOTYPE_PROPERTY,instancemaps toJSG_INSTANCE_PROPERTY;readonlyis a compile-time check preventing a paired setter;name = "..."overrides the JS name; preferprototypein almost all cases), and#[jsg_inspect_property](registered under a unique symbol, invisible to normal enumeration and string-key lookup, surfaced bynode:utilinspect(), equivalent toJSG_INSPECT_PROPERTY); setter auto-detected fromset_prefix; read-only when no setter present; getter/setter.lengthand.nameare set correctly whenspec_compliant_property_attributescompat flag is enabled Traced: core tracing trait injsg::wrappable; built-ins include no-op impls for primitives/value types and delegating impls for wrappers/collections (Option,Nullable,Vec, maps/sets,Cell,jsg::Rc,jsg::Weak,jsg::v8::Global)#[jsg_resource(custom_trace)]: suppresses the auto-generatedTracedimpl so the user can write their own;GarbageCollected(memory_name),jsg::Type,jsg::ToJS, andjsg::FromJSare still generated- Formatting:
rustfmt.toml—group_imports = "StdExternalCrate",imports_granularity = "Item"(oneuseper import) - Linting:
just clippy <crate>for a crate here,just clippy <label>for one elsewhere — pedantic+nursery;allow-unwrap-in-tests - Tests: inline
#[cfg(test)]modules; JSG tests usejsg_test::Harness::run_in_context(). Always run the fullsrc/rust/...test suite (bazel test //src/rust/...) rather than targeting a single crate — changes in shared crates likejsgorjsg-macroscan break downstream consumers - FFI pointers: functions receiving raw pointers must be
unsafe fn(seejsg/README.md) - Parameter ordering:
&Lock/&mut Lockmust always be the first parameter in any function that takes a lock (matching the C++ convention wherejsg::Lock&is always first). This applies to free functions, trait methods, and associated functions (excluding&self/&mut selfreceivers which come beforelock). - Method naming: do not use
get_prefixes on methods — e.g.buf.backing_store()notbuf.get_backing_store(). Static constructors belong on the marker struct (impl ArrayBuffer { fn new(...) }) not onimpl Local<'_, ArrayBuffer>. - FFI naming: instance methods on an existing handle use a
local_<type>_<method>prefix (e.g.local_array_buffer_byte_length). Static constructors that create a new value do not use thelocal_prefix — name them<type>_<method>(e.g.array_buffer_new_with_mode,array_buffer_maybe_new,backing_store_new_resizable). - FFI groups:
v8.rsmod ffi,ffi.h, andffi.c++all use matching comment groups (e.g.// Local<T>,// Local<Array>,// Local<TypedArray>,// Local<ArrayBuffer>,// Local<ArrayBufferView>,// Local<SharedArrayBuffer>,// BackingStore,// Unwrappers,// Global<T>,// FunctionCallbackInfo). When adding new FFI functions, place them in the correct group in all three files. Do not scatter related functions across groups. - Feature flags:
Lock::feature_flags()returns a capnpcompatibility_flags::Readerfor the current worker. Uselock.feature_flags().get_node_js_compat(). Flags are parsed once and stored in theRealmat construction; C++ passes canonical capnp bytes torealm_create(). Schema:src/workerd/io/compatibility-date.capnp, generated Rust bindings:compatibility_date_capnpcrate.
CXX BRIDGE: ASYNC AND ERROR HANDLING
C++ calling async Rust (extern "Rust")
Mark an extern "Rust" function async to generate a C++ function returning kj::Promise<T>. If the function borrows any references (including &self), it needs an explicit lifetime annotation, which in turn requires unsafe:
extern "Rust" {
// Borrows &self — needs explicit lifetime + unsafe.
async unsafe fn do_work<'a>(self: &'a MyType, arg: i32) -> Result<u64>;
// Only owned parameters — no lifetime or unsafe needed.
async fn do_work_owned(arg: i32) -> Result<u64>;
}Without the explicit lifetime, the CXX macro requires the future to be 'static, which fails if the async body references borrowed parameters.
Rust calling async C++ (extern "C++")
Mark an extern "C++" function async to wrap a C++ function returning kj::Promise<T> as a Rust Future. The Rust caller can .await it:
unsafe extern "C++" {
async fn request(
this_: Pin<&mut HttpService>,
method: HttpMethod,
url: &[u8],
) -> Result<()>;
}Note: this_ is used instead of self because CXX's self receiver syntax doesn't support Pin<&mut T>. This is needed for C++ types with virtual methods where the Rust side calls into a pinned C++ object.
Error handling across FFI
Functions returning Result<T> in extern "Rust" blocks translate to C++ functions that throw kj::Exception on error. The error type must implement std::error::Error (which provides IntoKjException). Recommended patterns:
thiserrorenums: Define a crate-levelErrorenum for structured errors. This is the preferred pattern for crates with multiple error cases.std::io::Error: Acceptable for purely I/O-related errors.cxx::KjError: Use thekjcrate's error macros (kj::failed!,kj::overloaded!,kj::disconnected!,kj::not_implemented!to construct a value;kj::fail_require!,kj::overloaded_require!,kj::disconnected_require!,kj::not_implemented_require!to early-returnErr(...)) when you need direct control over the KJ exception type. These mirror C++'sKJ_EXCEPTION/KJ_FAIL_REQUIRE/KJ_UNIMPLEMENTEDmacros fromkj/debug.h; seesrc/rust/kj/macros.rs.
The reverse direction has a stricter, non-optional rule: any extern "C++" shim that can throw (jsg::check(), KJ_REQUIRE/KJ_ASSERT, constructing a rust::String/rust::Vec that can panic, etc.) MUST return Result<T>. The fork's generated shim catches every C++ exception at the bridge. For an infallible signature, ordinary exceptions become a Rust panic, which callers cannot handle; a Result<T> signature turns them into an Err instead (//src/rust/cxx/gen/src/write.rs, write_cxx_function_shim). kj::CanceledException is the exception: with either signature it propagates as a dedicated Rust panic, so cancellation unwinds rather than surfacing as an Err (//src/rust/cxx/src/result.rs, into_result). See //src/rust/jsg/v8.rs "Unwrappers" section for worked examples: unwrap_string/unwrap_number/the typed-array unwrap shims are fallible (they call jsg::check() / construct rust::String), while unwrap_boolean is the deliberate infallible counterexample (no jsg::check(), no fallible construction). Fallible shims typically funnel their C++-side TryCatch/KJ_REQUIRE handling into a cxx::KjException, which impl From<cxx::KjException> for jsg::Error (//src/rust/jsg/lib.rs) then converts back into a throwable JS error on the Rust side.
CXX BRIDGE: BUILD WIRING
wd_rust_crate (and wd_rust_binary) generate, for each cxx_bridge_src / cxx_bridge_srcs entry, a companion :<bridge>@cxx cc_library — the C++ side of the bridge: the cxx-generated <bridge>.rs.{h,cc} plus the headers the bridge include!()s (cxx_bridge_hdrs, by default every **/*.h in the package). C++ consumers #include the generated header at the package's C++ include path — <workerd/rust/<pkg>/<bridge>.rs.h> for src/rust/<pkg>, <workerd/server/<bridge>.rs.h> for src/workerd/server — and depend on the crate; depend on :<bridge>@cxx alone if you only need the header. Any crate with a bridge auto-gets //src/rust/cxx:cxx and //src/rust/cxx/kj-rs.
Rust → C++ (calling a C++ function from Rust)
Template: gen-compile-cache, whose main.rs bridge calls C++ compile(). The shim header is conventionally named cxx-bridge.h (or bridge.h):
unsafe extern "C++" {
include!("workerd/rust/gen-compile-cache/cxx-bridge.h");
fn compile(path: &str, source_code: &str) -> Vec<u8>;
}- Put the shim header in the package — the macro globs
**/*.hinto the generated@cxxlibrary'shdrs, so theinclude!resolves. Keep it light (ideally just#include <rust/cxx.h>forrust::Str/rust::Vec). - Implement the function in a
.c++exposed as a separatewd_cc_library(e.g.gen-compile-cache's:cxx-bridge); the heavy C++ deps (JSG, etc.) live there, not in the shim header. - Add that
wd_cc_libraryto the crate'slink_depsso the symbol resolves at the final link.
Avoiding the C++ → Rust → C++ dependency cycle
If a C++ library already depends on your crate (C++ → Rust) and you also add a Rust → C++ shim, the shim must be a separate cc_library from the one that depends on the crate, or Bazel reports a cycle. To pass a cxx shared struct to the shim without a cycle (see the worker crate's :bridge):
- The shim's
.c++includes<workerd/rust/<pkg>/<bridge>.rs.h>and the shimcc_librarydepends on the generated:<bridge>@cxxfor that header. This is acyclic::<bridge>@cxxdepends only on cxx/kj-rs, never on the shim, and the shim's symbol is resolved at the final link. - Forward-declare the struct in the shim header — do not
#includethe generated<bridge>.rs.hthere, because that generated header#includes your shim header, so including it back is circular. A forward declaration is enough for aconst T¶meter; the full definition is only needed in the.c++.
cxx also supports reusing a binding type across bridges (docs): the worker crate's error.rs / ok.rs / kill_switch.rs bridges reuse ffi.rs's types by depending on :ffi.rs@cxx. Still, keep a struct that only crosses FFI within one crate in that crate's bridge.
V8 handles must always cross the FFI as the shared jsg::v8::ffi types, never as a bare usize. When another crate's bridge passes a V8 Local/Global, reuse the jsg shared struct via a type alias (type Local = jsg::v8::ffi::Local;) plus include!("workerd/rust/jsg/v8.rs.h"), and depend on //src/rust/jsg (which supplies the generated header transitively). Do not smuggle the handle word through a usize — the shared type keeps both sides in one canonical, cxx-verified definition. See node-exceptions/lib.rs.
Testing crates that cross the FFI
A rust_test exercising code that calls into heavy C++ (V8, etc.) must link those impl symbols itself via test_deps — the production binary already links them, so only the standalone test binary needs them. Symptom if missing: undefined C++ symbols at test link.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

