Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,13 @@ Be aware that workerd uses tcmalloc for memory allocation in the typical case. W
- **`src/rust/`** - Rust crates without a C++ home of their own and the in-tree cxx fork; see `src/rust/AGENTS.md` for the full macro reference and GC tracing guide (component crates such as the server live beside their C++)
- **`src/opentelemetry/`** - OTLP schemas vendored from opentelemetry-proto, for tests that decode the spans and logs workerd exports; see `src/opentelemetry/AGENTS.md` for how they are updated

### The Rust seam

The runtime reaches its embedders (the workerd server and others) through a set of interfaces
called the Rust seam. Each is a Rust trait with a C++ adapter on either side, so that the runtime
side can move to Rust while embedders stay C++. See
[docs/reference/rust-seam.md](docs/reference/rust-seam.md) for the ground rules.

### Configuration System

- Uses **Cap'n Proto** for configuration files (`.capnp` format); a `wrangler.json(c)` is also
Expand All @@ -201,6 +208,7 @@ Be aware that workerd uses tcmalloc for memory allocation in the typical case. W
| Add autogate | `src/workerd/util/autogate.h` | Add key to WORKERD_AUTOGATES macro; kebab-case name auto-derived; see header comment |
| Config schema | `src/workerd/server/workerd.capnp` | Cap'n Proto; capability-based security |
| Server / binary | `src/workerd/server/` | Rust `workerd-server` crate (`server/`) drives the C++ `worker-factory`; see `server/AGENTS.md` |
| Rust seam | `docs/reference/rust-seam.md`, `src/rust/worker/` | Runtime/embedder boundary: trait + `Rust*`/`Cxx*` adapters per interface; requests in via `worker::Interface` |
| Worker lifecycle | `src/workerd/io/worker.{h,c++}` | Isolate, Script, Worker, Actor classes |
| Request lifecycle | `src/workerd/io/io-context.{h,c++}` | IoContext: the per-request god object |
| Coroutine cancellation | `docs/reference/detail/async-patterns.md` | `CURRENT_INVOCATION` with `KJ_DEFER`; `KJ_ON_SCOPE_FAILURE` is exception-only |
Expand Down
69 changes: 69 additions & 0 deletions docs/reference/rust-seam.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# The Rust seam

The runtime reaches whoever embeds it through a set of interfaces: the _Rust seam_. On the runtime
side are `WorkerEntrypoint`, `IoContext` and the APIs. They are moving to Rust. On the embedder side
are the workerd server and other embedders. They can stay C++, and they keep compiling and working
unchanged while the runtime side moves.

```
embedder (C++ or Rust) | seam interfaces | runtime (moving to Rust)
| |
workerd server, | requests in ---> | WorkerEntrypoint,
other embedders | <--- calls out | IoContext, APIs
```

Two directions cross the seam:

- **Requests in.** An embedder delivers events to a Worker through C++ `WorkerInterface`
(`src/workerd/io/worker-interface.h`) or its Rust counterpart, `worker::Interface`
(`src/rust/worker/`, see its [`AGENTS.md`](../../src/rust/worker/AGENTS.md)). On the runtime side,
C++ `WorkerEntrypoint` receives them and hands the events that Rust delivers to the `entrypoint`
crate (`src/workerd/io/entrypoint/`).
- **Calls out.** The runtime calls its host through `IoChannelFactory`, `LimitEnforcer`,
`TimerChannel`, the observers, `BaseTracer` and `SpanSubmitter`, the actor storage hooks and
`Worker::Api`. These are C++ interfaces with no Rust trait. Each is a seam interface that gets a
trait and both adapters.

## Seam interfaces

A _seam interface_ has three parts:

- **A Rust trait**, in Rust types. For requests in, it is `worker::Interface`.
- **A `Rust*` adapter**: a C++ class over a Rust trait object, so that C++ calls Rust.
`RustWorkerInterface` (`src/rust/worker/bridge.h`) is a C++ `WorkerInterface` that forwards each
event to a Rust `worker::Interface`.
- **A `Cxx*` adapter**: a Rust type over a C++ object, so that Rust calls C++. `CxxWorkerInterface`
(`src/rust/worker/cxx_worker.rs`) is a Rust `worker::Interface` that forwards each event to a C++
`WorkerInterface`.

With both adapters, either side can hold an implementation from the other without knowing its
language.

## Ground rules

1. **Every seam interface is a Rust trait plus a `Rust*` and a `Cxx*` adapter.** Callers on either
side don't know which language implements it.
2. **The C++ interface is a contract with embedders.** Changing or removing a virtual method needs a
matching change in every embedder. A new method needs a default that keeps existing
implementations compiling.
3. **Behaviour changes go behind an autogate.** Until the gate is removed, a Worker sees the same
behaviour on both paths. A difference that no Worker can observe, such as one that only a
runtime bug reaches, is documented where the Rust path makes it. The `@all-autogates` variant
of each test takes the Rust path.
4. **Keep the shape.** See "Porting C++ to Rust" in
[`src/workerd/io/AGENTS.md`](../../src/workerd/io/AGENTS.md#porting-c-to-rust).
5. **Runtime code doesn't depend on its executor.** No tokio in runtime crates. I/O and spawning go
through the layer below, so that the code runs on the KJ event loop.
6. **The C++ side runs when a step is called**, not when its future is first polled. A step that
waits returns a future for the wait only. The scheduled event splits into a synchronous start and
an async finish for this reason (`src/workerd/io/entrypoint/`).
7. **No C++ JSG in the C++ shims behind Rust bindings.** The shims are listed in `CPP_SHIMS`
(`src/rust/jsg/BUILD.bazel`), and `//src/rust/jsg:cpp-jsg-allowlist-test` fails on any use that
isn't allowlisted.
8. **An interface on a hot path gets a benchmark before its Rust path ships.**

## Naming

"Rust seam" is the boundary described here. "Seam interface" is one trait with its two adapters. The
TypeScript and C++ `EventTarget` bootstrap boundary (`api/event-target-bootstrap.h`) is also called
a seam; it is unrelated.
2 changes: 2 additions & 0 deletions src/rust/jsg/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ CPP_SHIMS = glob([
"//src/rust/api:inspector.h",
"//src/workerd/io/io-context:ffi.c++",
"//src/workerd/io/io-context:ffi.h",
"//src/workerd/io/entrypoint:ffi.c++",
"//src/workerd/io/entrypoint:ffi.h",
# The interop tier; see cpp-jsg-allowlist.txt.
"//src/rust/jsg-cpp:ffi.c++",
"//src/rust/jsg-cpp:jsg-cpp.h",
Expand Down
26 changes: 26 additions & 0 deletions src/rust/worker/AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# src/rust/worker/

## OVERVIEW

The `worker` crate: the requests-in side of the [Rust seam](../../../docs/reference/rust-seam.md). `worker::Interface` (`lib.rs`) is the Rust counterpart of C++ `WorkerInterface` (`io/worker-interface.h`), with one method per event: `request()` and `connect()` from `kj::http::Service`, then `prewarm()`, `run_scheduled()`, `run_alarm()`, `abandon_alarm()`, `test()`, `bench()` and `custom_event()`. Two adapters carry it across the language boundary in each direction. The crate also has a few small implementations of `Interface`.

## KEY FILES

| File | Role |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `lib.rs` | The `Interface` trait, the result types, and `not_supported()`, which answers a `CustomEvent` as C++ `event->notSupported()` does |
| `ffi.rs` | The cxx bridge. `Wrapper` boxes a `dyn Interface` for C++; the `worker_*` functions call a C++ `WorkerInterface` from Rust |
| `bridge.h` | `RustWorkerInterface`, the `Rust*` adapter: a C++ `WorkerInterface` over a `Wrapper`. `fromImpl()` makes one from a `Box<Wrapper>`; `newPromisedInterface()` wraps a starting worker |
| `ffi.h/c++` | The C++ side of the `worker_*` functions, and `RustWorkerInterface::bench()` |
| `cxx_worker.rs` | `CxxWorkerInterface`, the `Cxx*` adapter: a Rust `Interface` that forwards every event to an owned C++ `WorkerInterface` |
| `promised.rs` | `PromisedInterface`: an `Interface` whose target is still starting, as C++ `PromisedWorkerInterface` |
| `failure.rs` | The worker that `WorkerInterface::fromException()` makes, behind `RUST_FAILURE_WORKER_INTERFACE` |
| `error.rs`, `ok.rs`, `kill_switch.rs` | Workers that answer every event the same way: with an error, with OK, or as killed |
| `test.c++` | C++ tests of the implementations and of both adapters |

## CONVENTIONS

- **Crossing the boundary.** A Rust implementation becomes a C++ `WorkerInterface` with `Interface::into_kj()`, which goes through `RustWorkerInterface`. Rust code holds a C++ `WorkerInterface` as `CxxWorkerInterface::new(KjOwn<WorkerInterface>)`. The Rust server (`src/workerd/server/server/`) does both: its services implement `Interface`, and it reaches C++ Workers through `CxxWorkerInterface`.
- **Embedders keep the C++ interface.** A C++ embedder implements and calls C++ `WorkerInterface` as before; it never needs to see this crate.
- **Adding an event** touches each layer: a method on `Interface`, with a default where C++ `WorkerInterface` has one; a `Wrapper` method in `ffi.rs` and its override in `RustWorkerInterface`; a `worker_*` function in `ffi.rs` and `ffi.h/c++`, and its use in `CxxWorkerInterface`. Results cross as the shared structs in `ffi.rs`, kept in sync with `io/worker-interface.h`.
- **The `worker_*` functions take times as nanoseconds** since the Unix epoch (`kj_rs::repr::{to,from}Nanos`), not as `KjDate`.
13 changes: 13 additions & 0 deletions src/workerd/api/tests/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,19 @@ wd_test(
data = ["temporal-test.js"],
)

wd_test(
src = "scheduled-test.wd-test",
# service_binding_extra_handlers, for the scheduled() of a service binding, is experimental.
args = ["--experimental"],
data = [
"scheduled-test.js",
"scheduled-test-handler.js",
"scheduled-test-listener.js",
"scheduled-test-no-listener.js",
"scheduled-test-tail.js",
],
)

wd_test(
# It runs several other tests' workers to trace them, which takes up to 12.5s of the 15s
# "medium" timeout in debug builds.
Expand Down
30 changes: 30 additions & 0 deletions src/workerd/api/tests/scheduled-test-handler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Copyright (c) 2026 Cloudflare, Inc.
// Licensed under the Apache 2.0 license found in the LICENSE file or at:
// https://opensource.org/licenses/Apache-2.0

// A scheduled() handler that does what the event's cron pattern names.
export default {
scheduled(controller, env, ctx) {
console.log(
`scheduled ${controller.cron} ${controller.scheduledTime} ${typeof env} ${typeof ctx}`
);
switch (controller.cron) {
case 'reject':
return Promise.reject(new Error('rejected'));
case 'wait-until':
ctx.waitUntil(
scheduler.wait(10).then(() => console.log('waitUntil finished'))
);
return;
default:
return;
}
},
};

// An entrypoint without a scheduled() handler.
export const noHandler = {
fetch() {
return new Response('ok');
},
};
20 changes: 20 additions & 0 deletions src/workerd/api/tests/scheduled-test-listener.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Copyright (c) 2026 Cloudflare, Inc.
// Licensed under the Apache 2.0 license found in the LICENSE file or at:
// https://opensource.org/licenses/Apache-2.0

// A Service Workers syntax "scheduled" listener that does what the event's cron pattern names.
addEventListener('scheduled', (event) => {
console.log(`listener ${event.cron} ${event.scheduledTime}`);
switch (event.cron) {
case 'no-retry':
event.noRetry();
break;
case 'throw':
throw new Error('thrown by the listener');
case 'wait-until':
event.waitUntil(
scheduler.wait(10).then(() => console.log('waitUntil finished'))
);
break;
}
});
8 changes: 8 additions & 0 deletions src/workerd/api/tests/scheduled-test-no-listener.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// Copyright (c) 2026 Cloudflare, Inc.
// Licensed under the Apache 2.0 license found in the LICENSE file or at:
// https://opensource.org/licenses/Apache-2.0

// A Service Workers syntax Worker with no "scheduled" listener.
addEventListener('fetch', (event) => {
event.respondWith(new Response('ok'));
});
179 changes: 179 additions & 0 deletions src/workerd/api/tests/scheduled-test-tail.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
// Copyright (c) 2026 Cloudflare, Inc.
// Licensed under the Apache 2.0 license found in the LICENSE file or at:
// https://opensource.org/licenses/Apache-2.0

// The tail worker and the streaming tail worker of the Workers that scheduled-test.js sends
// scheduled events to. Its test checks what each received for each event.
//
// The test waits until both have received every event, however long that takes, rather than for a
// fixed time: an event can still be reaching them after scheduled-test's test has finished. It
// polls, because a request that only waits for another request to settle a promise looks hung,
// and is cancelled. While it waits, it logs what has arrived every few seconds, so that a test
// that times out shows what is missing.

import assert from 'node:assert';

function summarize(event) {
switch (event.type) {
case 'onset':
return { type: event.type, info: event.info };
case 'log':
return { type: event.type, level: event.level, message: event.message };
case 'exception':
return { type: event.type, name: event.name, message: event.message };
case 'outcome':
return { type: event.type, outcome: event.outcome };
default:
return { type: event.type };
}
}

function onset(cron) {
// Tests run in predictable mode, which hides the scheduled time from streaming tail workers.
return {
type: 'onset',
info: { type: 'scheduled', scheduledTime: new Date(0), cron },
};
}

function log(message, level = 'log') {
return { type: 'log', level, message: [message] };
}

const RETURN = { type: 'return' };
const OK = { type: 'outcome', outcome: 'ok' };
const EXCEPTION = { type: 'outcome', outcome: 'exception' };

// What the streaming tail worker receives for each event, in the order scheduled-test sends them.
const EXPECTED_STREAMS = [
// scheduled-test-handler
[
onset('reject'),
log('scheduled reject 1000 object object'),
{ type: 'exception', name: 'Error', message: 'rejected' },
EXCEPTION,
],
[
onset('wait-until'),
log('scheduled wait-until 1000 object object'),
RETURN,
log('waitUntil finished'),
OK,
],
// scheduled-test-handler's noHandler entrypoint
[
onset('ok'),
log(
'Received a ScheduledEvent but we lack a handler for ScheduledEvents (a.k.a. Cron ' +
'Triggers). Did you remember to export a scheduled() function?',
'warn'
),
{
type: 'exception',
name: 'Error',
message: 'Handler does not export a scheduled() function',
},
EXCEPTION,
],
// scheduled-test-listener
[onset('ok'), log('listener ok 1000'), OK],
[onset('no-retry'), log('listener no-retry 1000'), OK],
[
onset('throw'),
log('listener throw 1000'),
{ type: 'exception', name: 'Error', message: 'thrown by the listener' },
EXCEPTION,
],
[
onset('wait-until'),
log('listener wait-until 1000'),
log('waitUntil finished'),
OK,
],
// scheduled-test-no-listener
[
onset('ok'),
log(
'Received a ScheduledEvent but we lack an event listener for scheduled events (a.k.a. ' +
'Cron Triggers). Did you remember to call addEventListener("scheduled", ...)?',
'warn'
),
{
type: 'exception',
name: 'Error',
message: 'No event listener registered for scheduled events.',
},
EXCEPTION,
],
];

// The event of each trace that the tail worker receives. Unlike a streaming tail worker, it sees
// the scheduled time in predictable mode.
function trace(cron, outcome) {
return { scheduledTime: 1000, cron, outcome };
}

// Sorted, since nothing orders the delivery of one event's trace before the next one's.
const EXPECTED_TRACES = sortTraces([
trace('reject', 'exception'),
trace('wait-until', 'ok'),
trace('ok', 'exception'),
trace('ok', 'ok'),
trace('no-retry', 'ok'),
trace('throw', 'exception'),
trace('wait-until', 'ok'),
trace('ok', 'exception'),
]);

function sortTraces(traces) {
const key = (trace) => JSON.stringify(trace);
return traces.toSorted((a, b) => key(a).localeCompare(key(b)));
}

// Each stream received so far, as the list of its events, summarized.
const streams = [];
let finishedStreams = 0;
const traces = [];

export default {
tailStream(onsetEvent) {
const events = [summarize(onsetEvent.event)];
streams.push(events);
return (event) => {
events.push(summarize(event.event));
if (event.event.type === 'outcome') finishedStreams++;
};
},

tail(received) {
for (const trace of received) {
traces.push({
scheduledTime: trace.event.scheduledTime,
cron: trace.event.cron,
outcome: trace.outcome,
});
}
},
};

export const test = {
async test() {
for (
let polls = 1;
finishedStreams < EXPECTED_STREAMS.length ||
traces.length < EXPECTED_TRACES.length;
polls++
) {
await scheduler.wait(10);
if (polls % 500 === 0) {
console.log(
`still waiting: ${finishedStreams} of ${EXPECTED_STREAMS.length} streams finished, ` +
`${traces.length} of ${EXPECTED_TRACES.length} traces received`,
JSON.stringify({ streams, traces })
);
}
}
assert.deepStrictEqual(streams, EXPECTED_STREAMS);
assert.deepStrictEqual(sortTraces(traces), EXPECTED_TRACES);
},
};
Loading
Loading