diff --git a/README.md b/README.md index 20b7a339518..47f0555419b 100644 --- a/README.md +++ b/README.md @@ -111,8 +111,9 @@ bazel build --config=thin-lto //src/workerd/server:workerd For simple projects, `workerd serve wrangler.jsonc` also accepts a Wrangler config. `main` is bundled with esbuild, as Wrangler does. The supported fields are `name`, `main`, `compatibility_date`, `compatibility_flags`, `vars`, -`durable_objects`, `exports`, `migrations`, `no_bundle` and `$schema`; any -other field is an error. +`durable_objects`, `exports`, `migrations`, `no_bundle`, `$schema` and, with +`--experimental`, `kv_namespaces`; any other field is an error. Each KV +namespace is one Durable Object, so its throughput is that of one object. A simple "Hello World!" config file might look like: diff --git a/src/workerd/server/AGENTS.md b/src/workerd/server/AGENTS.md index e2bdeb62781..f807a2f7fb9 100644 --- a/src/workerd/server/AGENTS.md +++ b/src/workerd/server/AGENTS.md @@ -29,72 +29,73 @@ Bazel labels: `//src/workerd/server:workerd`, `//src/workerd/server:workerd-cli` ### `src/workerd/server/` (this package) -| File | Role | -| ----------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `workerd.rs` | Crate root of the `:workerd` binary; calls `workerd_cli::main()` | -| `workerd.capnp` | Config schema: `Config`, `Service`, `Worker`, `Socket`, `Extension`. Capability-based security model | -| `compiled-bindings.capnp` | `Global` / `Globals`: one worker's bindings after the server interpreted them; channel numbering rules in its header comment | -| `config-compiler.h/c++` | Compiles a schema-file config (`capnp::SchemaParser` over `schema-file.h`) into an encoded message for `cli/lib.rs`; reports parse errors as data and registers the files it reads for `--watch` | -| `schema-file.h/c++` | The `capnp::SchemaFile` implementations: config files on disk with workerd's import resolution, and the schemas built into the binary | -| `workerd-api.h/c++` | `WorkerdApi`: registers all JS API types with JSG, compiles modules/globals, extracts source from config. `compileGlobals` sets the bindings of a `Globals` message (`compiled-bindings.capnp`) on `env` / `ctx.exports`, one `switch` case per binding kind | -| `alarm-scheduler.h/c++` | DO alarm scheduling with SQLite-backed persistence | -| `channel-token.h/c++`, `channel-token.capnp` | Opaque token encoding for cross-service channel references; the factory is the `ChannelTokenHandler`, the Rust `Server` its resolver | -| `json-logger.h/c++`, `log-schema.capnp` | Structured JSON logging for tail workers | -| `v8-platform-impl.h/c++` | Custom `v8::Platform` bridging V8 tasks to KJ event loop | -| `fallback-service.h/c++` | Module fallback resolution via external service (on its own thread) | -| `container-client.h/c++`, `docker-api.capnp` | Docker container lifecycle for DO containers | -| `facet-tree-index.h/c++` | The on-disk index of an actor's facets | -| `actor-id-impl.h/c++` | `ActorIdFactory` for the single-tenant server | -| `workerd-debug-port-client.h/c++` | The client side of `--debug-port` | +| File | Role | +| -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `workerd.rs` | Crate root of the `:workerd` binary; calls `workerd_cli::main()` | +| `workerd.capnp` | Config schema: `Config`, `Service`, `Worker`, `Socket`, `Extension`. Capability-based security model | +| `compiled-bindings.capnp` | `Global` / `Globals`: one worker's bindings after the server interpreted them; channel numbering rules in its header comment | +| `config-compiler.h/c++` | Compiles a schema-file config (`capnp::SchemaParser` over `schema-file.h`) into an encoded message for `cli/lib.rs`; reports parse errors as data and registers the files it reads for `--watch` | +| `schema-file.h/c++` | The `capnp::SchemaFile` implementations: config files on disk with workerd's import resolution, and the schemas built into the binary | +| `workerd-api.h/c++` | `WorkerdApi`: registers all JS API types with JSG, compiles modules/globals, extracts source from config. `compileGlobals` sets the bindings of a `Globals` message (`compiled-bindings.capnp`) on `env` / `ctx.exports`, one `switch` case per binding kind | +| `alarm-scheduler.h/c++` | DO alarm scheduling with SQLite-backed persistence | +| `channel-token.h/c++`, `channel-token.capnp` | Opaque token encoding for cross-service channel references; the factory is the `ChannelTokenHandler`, the Rust `Server` its resolver | +| `json-logger.h/c++`, `log-schema.capnp` | Structured JSON logging for tail workers | +| `v8-platform-impl.h/c++` | Custom `v8::Platform` bridging V8 tasks to KJ event loop | +| `fallback-service.h/c++` | Module fallback resolution via external service (on its own thread) | +| `container-client.h/c++`, `docker-api.capnp` | Docker container lifecycle for DO containers | +| `facet-tree-index.h/c++` | The on-disk index of an actor's facets | +| `actor-id-impl.h/c++` | `ActorIdFactory` for the single-tenant server | +| `workerd-debug-port-client.h/c++` | The client side of `--debug-port` | ### `cli/` (`workerd-cli`) -| File | Role | -| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `lib.rs` | Crate root: `main()`, the commands, the server's `Watch` future for `--watch` | -| `args.rs` | clap definitions | -| `config.rs` | Config sources (schema file, compiled binary, embedded) and the synthesized Python config | -| `deploy.rs` | Cluster mode: `workerd deploy`, a wrangler project (`wrangler.rs`) or Cap'n Proto config checked as a deployment, then published to the bucket `--bucket` names (`cluster::deploy`), with the instances' bucket client and environment fallbacks; each instance skips it if it does not compose with its own config | -| `deployments.rs` | Cluster mode: before `serve` starts the server, merges deployments from the bucket (`cluster::deploy`) into the config (`cluster::compose`), skips those that do not compose, and tells the server which services came from each deployment | -| `process.rs` | Executable discovery, the compiled-binary format, `Process` (the files to watch, re-exec) | -| `socket_fd.rs` | `--socket-fd` / `--control-fd` descriptors, made owned; the platform halves are `socket_fd/{unix,windows}.rs` | -| `watch.rs` | `--watch`: the file watcher | -| `wrangler.rs` | A `wrangler.json(c)` config: the supported fields translated into a `Config`, `main` bundled with esbuild (or scanned under `no_bundle`), or for `deploy` into a services-only deployment | -| `bridge.rs` | The cxx bridge (`workerd::server::cli`) to `config-compiler.h` and the build facts in `factory/bootstrap.h`; header `` | +| File | Role | +| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `lib.rs` | Crate root: `main()`, the commands, the server's `Watch` future for `--watch` | +| `args.rs` | clap definitions | +| `config.rs` | Config sources (schema file, compiled binary, embedded) and the synthesized Python config | +| `deploy.rs` | Cluster mode: `workerd deploy`, a wrangler project (`wrangler.rs`) or Cap'n Proto config checked as a deployment, then published to the bucket `--bucket` names (`cluster::deploy`), with the instances' bucket client and environment fallbacks; each instance skips it if it does not compose with its own config | +| `deployments.rs` | Cluster mode: before `serve` starts the server, merges deployments from the bucket (`cluster::deploy`) into the config (`cluster::compose`), skips those that do not compose, and tells the server which services came from each deployment | +| `process.rs` | Executable discovery, the compiled-binary format, `Process` (the files to watch, re-exec) | +| `socket_fd.rs` | `--socket-fd` / `--control-fd` descriptors, made owned; the platform halves are `socket_fd/{unix,windows}.rs` | +| `watch.rs` | `--watch`: the file watcher | +| `wrangler.rs` | A `wrangler.json(c)` config: the supported fields translated into a `Config`, `main` bundled with esbuild (or scanned under `no_bundle`), or for `deploy` into a services-only deployment. `kv_namespaces` (with `--experimental`) become `kvNamespace` bindings to the Worker `-kv`, which runs the bundled module `/workerd/kv.js` (`kv/kv.js`), plus disks for its objects and blobs; tests in `tests/kv/` | +| `bridge.rs` | The cxx bridge (`workerd::server::cli`) to `config-compiler.h` and the build facts in `factory/bootstrap.h`; header `` | ### `server/` (`workerd-server`) -| File | Role | -| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `lib.rs` | Crate root: `Error` / `Result` | -| `bridge.rs` | The cxx bridge (`workerd::server`) to `factory/worker-factory.h` and `factory/bootstrap.h`. `extern "C++"`: the factory (compile, start request, bench, actors and storage, RPC, tokens, inspector, `factory_spawn`), the bootstrap, the process's logging and its exit; `extern "Rust"`: the channel objects, the channel factory, the pending command. Ownership rules in its `//!` | -| `entry.rs` | `serve` / `test` / `bench`: the process's schedule (`with_process_context`, the `kj_rs_tokio::Runtime`, `bootstrap`, `block_on`, exit), `server_serve` / `server_test` / `server_bench`, the `Watch` future the command line supplies, printing config errors and the exit status they make, SIGTERM drain, `--watch` reload, shutdown order (settle tasks, drop the factory and with it V8 and the perfetto session, then the Runtime) | -| `run.rs` | `run()` / `test()` / `bench()`: bind sockets, start the inspector (before any isolate exists), build the graph, start the listeners (not for a config the `Reporter` refuses), drain, control-fd events, the check that every `--directory-path` / `--external-addr` override named a service | -| `bench.rs` | `workerd bench`'s options and report (`io/bench.capnp`): a group for each `bench()` handler `run::bench` runs (through the factory's `worker_bench`), progress logged as `workerd test` logs it, the environment, and the report as a table or as JSON | -| `config.rs` | `Server`: the service graph from the config in three passes (actor configs, construction, link); `Factory`, the Rust owner of the C++ `WorkerFactory`; `Reporter`, which attributes a deployment's config errors to it; resolves channel tokens and debug-port requests | -| `channels.rs` | The handles C++ holds and the runtime reaches into the server through: `SubrequestChannel` (an `Rc`), `ActorClassChannel` (an `Rc`), `ChannelFactory` (a worker's `LinkedChannels`), `WorkerStub`, and the `Weak` back-pointers (`ServerHandle`, `ActorNamespaceHandle`, `ActorHooks`). Single-threaded | -| `bindings.rs` | `compile_bindings` / `loopback_globals`: `Worker.bindings` and `ctx.exports` to the `Globals` message and the channel tables the link stage fills | -| `worker.rs` | `WorkerService`: compiled through the factory, `PendingLink` designators resolved into `LinkedChannels` once every service exists; entrypoints, actor classes, the I/O channel table requests see | -| `actor.rs` | `ActorNamespace` / `ActorContainer`: actor lifecycle, facets, idle shutdown, eviction, and the sweep that drops long-idle `ActorContainer`s. The sweep keeps a container anything but its map holds (a stub or a request, each a `Client`; an eviction in progress), so nothing else holds one strongly: back-pointers to a container are `Weak`. A root actor with an onHibernate handler retires instead of shutting down at once: once it is idle, `try_evict` spawns `retire_actor`, which runs the handler, then shuts the actor down. The container owns the task (`retirement`), so canceling the eviction or idle timer that started it doesn't cancel it. Requests and evictions that arrive meanwhile wait for it, then reach a new instance, or get its error if it failed and broke the container. A request the handler makes to its own object waits too, until the handler's wall-clock budget cuts the handler off. Only `abort` cancels a running handler, with or without a reason; a cluster drain aborts every actor. A cluster node whose lease has lapsed doesn't start a retirement. Docker containers, their registry and the cleanup join at shutdown are the factory's (`-actor.c++`) | -| `loader.rs` | Dynamic workers (`workerLoader`): `WorkerStub`, one shared startup future per loaded worker | -| `services/mod.rs` | External and network services over kj-hyper's pooled client (one `ClientPool` per service, so connections are reused across events, lent to a `Client` per event; a `style = proxy` external server is asked for whole URLs), and service construction | -| `services/network.rs` | `TlsOptions` to rustls and the `allow` / `deny` peer filter | -| `services/disk.rs` | The `disk` service (synchronous file I/O in 64 KiB steps) | -| `services/rewriter.rs` | A socket's or external server's `HttpOptions` applied to traffic: URL style, cf blob header, injected headers, the capnp-over-CONNECT host. Headers stay `kj::HttpHeaders`: the rewriter names the edits (`HeaderEdit`) and the factory applies them by table id | -| `listen/mod.rs` | Sockets bound through kj-rs-io (`TokioAddress`; a `loopback:` name is a queue of the server's registry) before the services start; HTTP/HTTPS through kj-hyper, TCP as `connect()` events, the debug port. One future per listener (accept loop plus its connections); an accept-loop failure is fatal, a connection failure ends that connection. A failed HTTP call is logged (`Uncaught exception: ` and the error as KJ prints it, `log_uncaught`); kj-hyper answers it with a bare 500 | -| `listen/udp.rs` | UDP sockets: each peer's datagrams as one flow (`UdpFlow`), dispatched as a `connect()` event | -| `listen/loopback.rs` | The `loopback:` registry: queues by name behind a mutex (kj-hyper's dialers are `Send + Sync`), `tokio::io::duplex` pipes, `LoopbackStream` with its hang-up signal | -| `tasks.rs` | `Factory::spawn` / `spawn_detached` / `settle_tasks`, `TaskHandle` (drop cancels at the next poll), `SpawnedTask` (the future the C++ task set polls) | -| `in_process.rs` | `InProcessServer`: the server run inside a test process on a factory the test built, for `server-test.c++` (see TEST INFRASTRUCTURE) | -| `pyodide.rs` | The Pyodide bundle a Python worker needs, fetched before it compiles (`preloadPython` awaits `pyodide_bundle_fetch` and stores the bytes in its `PyodideBundleManager`): from `--pyodide-bundle-disk-cache-dir`, else downloaded (hyper, kj-hyper's TLS over the platform's trust store) and cached; verified against the release's checksum | -| `log.rs` | `install()`: the `tracing` subscriber that renders events the way `KJ_LOG` does and forwards them to `kj_log` | +| File | Role | +| ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `lib.rs` | Crate root: `Error` / `Result` | +| `bridge.rs` | The cxx bridge (`workerd::server`) to `factory/worker-factory.h` and `factory/bootstrap.h`. `extern "C++"`: the factory (compile, start request, bench, actors and storage, RPC, tokens, inspector, `factory_spawn`), the bootstrap, the process's logging and its exit; `extern "Rust"`: the channel objects, the channel factory, the pending command. Ownership rules in its `//!` | +| `entry.rs` | `serve` / `test` / `bench`: the process's schedule (`with_process_context`, the `kj_rs_tokio::Runtime`, `bootstrap`, `block_on`, exit), `server_serve` / `server_test` / `server_bench`, the `Watch` future the command line supplies, printing config errors and the exit status they make, SIGTERM drain, `--watch` reload, shutdown order (settle tasks, drop the factory and with it V8 and the perfetto session, then the Runtime) | +| `run.rs` | `run()` / `test()` / `bench()`: bind sockets, start the inspector (before any isolate exists), build the graph, start the listeners (not for a config the `Reporter` refuses), drain, control-fd events, the check that every `--directory-path` / `--external-addr` override named a service | +| `bench.rs` | `workerd bench`'s options and report (`io/bench.capnp`): a group for each `bench()` handler `run::bench` runs (through the factory's `worker_bench`), progress logged as `workerd test` logs it, the environment, and the report as a table or as JSON | +| `config.rs` | `Server`: the service graph from the config in three passes (actor configs, construction, link); `Factory`, the Rust owner of the C++ `WorkerFactory`; `Reporter`, which attributes a deployment's config errors to it; resolves channel tokens and debug-port requests | +| `channels.rs` | The handles C++ holds and the runtime reaches into the server through: `SubrequestChannel` (an `Rc`), `ActorClassChannel` (an `Rc`), `ChannelFactory` (a worker's `LinkedChannels`), `WorkerStub`, and the `Weak` back-pointers (`ServerHandle`, `ActorNamespaceHandle`, `ActorHooks`). Single-threaded | +| `bindings.rs` | `compile_bindings` / `loopback_globals`: `Worker.bindings` and `ctx.exports` to the `Globals` message and the channel tables the link stage fills | +| `worker.rs` | `WorkerService`: compiled through the factory, `PendingLink` designators resolved into `LinkedChannels` once every service exists; entrypoints, actor classes, the I/O channel table requests see | +| `actor.rs` | `ActorNamespace` / `ActorContainer`: actor lifecycle, facets, idle shutdown, eviction, and the sweep that drops long-idle `ActorContainer`s. The sweep keeps a container anything but its map holds (a stub or a request, each a `Client`; an eviction in progress), so nothing else holds one strongly: back-pointers to a container are `Weak`. A root actor with an onHibernate handler retires instead of shutting down at once: once it is idle, `try_evict` spawns `retire_actor`, which runs the handler, then shuts the actor down. The container owns the task (`retirement`), so canceling the eviction or idle timer that started it doesn't cancel it. Requests and evictions that arrive meanwhile wait for it, then reach a new instance, or get its error if it failed and broke the container. A request the handler makes to its own object waits too, until the handler's wall-clock budget cuts the handler off. Only `abort` cancels a running handler, with or without a reason; a cluster drain aborts every actor. A cluster node whose lease has lapsed doesn't start a retirement. Docker containers, their registry and the cleanup join at shutdown are the factory's (`-actor.c++`) | +| `loader.rs` | Dynamic workers (`workerLoader`): `WorkerStub`, one shared startup future per loaded worker | +| `services/mod.rs` | External and network services over kj-hyper's pooled client (one `ClientPool` per service, so connections are reused across events, lent to a `Client` per event; a `style = proxy` external server is asked for whole URLs), and service construction | +| `services/network.rs` | `TlsOptions` to rustls and the `allow` / `deny` peer filter | +| `services/disk.rs` | The `disk` service (synchronous file I/O in 64 KiB steps) | +| `services/bucket.rs` | The `bucket` service (`ClusterBucket`): a directory of the cluster's bucket over HTTP; KV (`kv/kv.js`) keeps large values there in a cluster; tests in `tests/kv/` and `tests/cluster/` | +| `services/rewriter.rs` | A socket's or external server's `HttpOptions` applied to traffic: URL style, cf blob header, injected headers, the capnp-over-CONNECT host. Headers stay `kj::HttpHeaders`: the rewriter names the edits (`HeaderEdit`) and the factory applies them by table id | +| `listen/mod.rs` | Sockets bound through kj-rs-io (`TokioAddress`; a `loopback:` name is a queue of the server's registry) before the services start; HTTP/HTTPS through kj-hyper, TCP as `connect()` events, the debug port. One future per listener (accept loop plus its connections); an accept-loop failure is fatal, a connection failure ends that connection. A failed HTTP call is logged (`Uncaught exception: ` and the error as KJ prints it, `log_uncaught`); kj-hyper answers it with a bare 500 | +| `listen/udp.rs` | UDP sockets: each peer's datagrams as one flow (`UdpFlow`), dispatched as a `connect()` event | +| `listen/loopback.rs` | The `loopback:` registry: queues by name behind a mutex (kj-hyper's dialers are `Send + Sync`), `tokio::io::duplex` pipes, `LoopbackStream` with its hang-up signal | +| `tasks.rs` | `Factory::spawn` / `spawn_detached` / `settle_tasks`, `TaskHandle` (drop cancels at the next poll), `SpawnedTask` (the future the C++ task set polls) | +| `in_process.rs` | `InProcessServer`: the server run inside a test process on a factory the test built, for `server-test.c++` (see TEST INFRASTRUCTURE) | +| `pyodide.rs` | The Pyodide bundle a Python worker needs, fetched before it compiles (`preloadPython` awaits `pyodide_bundle_fetch` and stores the bytes in its `PyodideBundleManager`): from `--pyodide-bundle-disk-cache-dir`, else downloaded (hyper, kj-hyper's TLS over the platform's trust store) and cached; verified against the release's checksum | +| `log.rs` | `install()`: the `tracing` subscriber that renders events the way `KJ_LOG` does and forwards them to `kj_log` | ### `factory/` (C++) -| File | Role | -| ----------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| File | Role | +| ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `worker-factory.h`, `worker-factory*.c++` | `WorkerFactory`: everything the workers of one run share. `-impl.h` the private state, `worker-factory.c++` compile / request / bindings, `-actor.c++` actors, storage, alarms, containers, `-rpc.c++` the capnp RPC servers, `-listen.c++` the listeners' shims (the rewriter's header edits, rewriting responses, raw TCP `ConnectResponse`, UDP flows) | -| `bootstrap.h/c++` | The C++ half of a command: build capabilities, `with_process_context` (the crash handler, verbosity and the JSON logger on the stack), `bootstrap` (perfetto, autogates and V8 on the Rust-owned loop, attached to the factory it returns), `cli_exit`, `kj_log`, `json_log_to_stderr` | +| `bootstrap.h/c++` | The C++ half of a command: build capabilities, `with_process_context` (the crash handler, verbosity and the JSON logger on the stack), `bootstrap` (perfetto, autogates and V8 on the Rust-owned loop, attached to the factory it returns), `cli_exit`, `kj_log`, `json_log_to_stderr` | ## TEST INFRASTRUCTURE diff --git a/src/workerd/server/BUILD.bazel b/src/workerd/server/BUILD.bazel index 3cc5a5efbe4..bb064479fc7 100644 --- a/src/workerd/server/BUILD.bazel +++ b/src/workerd/server/BUILD.bazel @@ -248,6 +248,7 @@ wd_cc_library( "//src/workerd/io", "//src/workerd/io:worker-modules", "//src/workerd/jsg", + "//src/workerd/server/kv:kv-js", "//src/workerd/util:perfetto", "@capnp-cpp//src/kj/compat:kj-gzip", ] + select({ diff --git a/src/workerd/server/cli/lib.rs b/src/workerd/server/cli/lib.rs index ff6d6f2073d..8e2c9eb9fcb 100644 --- a/src/workerd/server/cli/lib.rs +++ b/src/workerd/server/cli/lib.rs @@ -125,7 +125,12 @@ fn run_command(args: args::Main, executable: Option) -> workerd_serv let watcher = watcher::(&serve_or_test, executable.as_ref()); let (options, inherited_sockets) = serve_options::(serve, &serve_or_test); let process = Process::new(executable, watcher, inherited_sockets); - let config = load_config::(config, const_name.const_name, &process); + let config = load_config::( + config, + const_name.const_name, + &process, + serve_or_test.experimental, + ); let (config, options) = with_deployments(config, &serve_or_test, options, &process); entry::serve( verbose, @@ -156,7 +161,7 @@ fn run_command(args: args::Main, executable: Option) -> workerd_serv check_serve_or_test::(&serve_or_test); let watcher = watcher::(&serve_or_test, executable.as_ref()); let process = Process::new(executable, watcher, Vec::new()); - let config = load_config::(config, None, &process); + let config = load_config::(config, None, &process, serve_or_test.experimental); entry::test( verbose, config.into_words(), @@ -176,7 +181,12 @@ fn run_command(args: args::Main, executable: Option) -> workerd_serv let filter = test.filter.take().unwrap_or_default(); let watcher = watcher::(&serve_or_test, executable.as_ref()); let process = Process::new(executable, watcher, Vec::new()); - let config = load_config::(config, filter.const_name.clone(), &process); + let config = load_config::( + config, + filter.const_name.clone(), + &process, + serve_or_test.experimental, + ); entry::test( verbose, config.into_words(), @@ -257,7 +267,7 @@ fn run_deploy( binary: args.binary, config_file, }; - (name, load_config::(config, const_name, &process)) + (name, load_config::(config, const_name, &process, true)) } Err(error) => usage_error::(error), }; @@ -301,7 +311,8 @@ fn run_compile( ); } let process = Process::new(executable, None, Vec::new()); - let config = load_config::(config, const_name, &process); + // The binary checks `--experimental` when it runs (the server, for bundled modules). + let config = load_config::(config, const_name, &process, true); let written = if config_only { config.write_to_stdout() } else { @@ -324,7 +335,12 @@ fn run_bench( let filter = bench.filter.take().unwrap_or_default(); let watcher = watcher::(serve_or_test, executable.as_ref()); let process = Process::new(executable, watcher, Vec::new()); - let config = load_config::(config, filter.test.const_name.clone(), &process); + let config = load_config::( + config, + filter.test.const_name.clone(), + &process, + serve_or_test.experimental, + ); entry::bench( verbose, config.into_words(), @@ -408,6 +424,7 @@ fn load_config( config: args::ConfigFileArgs, const_name: Option, process: &Process, + experimental: bool, ) -> Config { let args::ConfigFileArgs { import_paths, @@ -443,7 +460,7 @@ fn load_config( if !std::path::Path::new(&config_file).is_file() { usage_error::(format!("{config_file}: No such file.")); } - return wrangler::load(&config_file, process) + return wrangler::load(&config_file, process, experimental) .unwrap_or_else(|error| config_errors(&[format!("{config_file}: {error}")], process)); } diff --git a/src/workerd/server/cli/wrangler-test.rs b/src/workerd/server/cli/wrangler-test.rs index fe2c9714ca5..67c7f08eb00 100644 --- a/src/workerd/server/cli/wrangler-test.rs +++ b/src/workerd/server/cli/wrangler-test.rs @@ -3,6 +3,7 @@ // https://opensource.org/licenses/Apache-2.0 use workerd_capnp::service; +use workerd_capnp::service_designator; use workerd_capnp::worker; use super::*; @@ -32,6 +33,7 @@ fn load_project(files: &[(&str, &str)]) -> Result { load( dir.join("wrangler.jsonc").to_str().unwrap(), &Process::new(None, None, Vec::new()), + true, ) } @@ -352,15 +354,108 @@ fn unsupported_field_is_an_error() { ( "wrangler.jsonc", r#"{ "main": "index.js", "compatibility_date": "2026-01-01", - "kv_namespaces": [{ "binding": "KV", "id": "x" }] }"#, + "kv_namespaces": [{ "binding": "KV", "bogus": "y" }] }"#, ), ("index.js", ""), ]) .err() .unwrap(); + assert!(error.contains("bogus"), "{error}"); +} + +#[test] +fn kv_namespaces_require_experimental() { + let dir = project(&[ + ( + "wrangler.jsonc", + r#"{ "main": "index.js", "compatibility_date": "2026-01-01", + "kv_namespaces": [{ "binding": "KV", "id": "x" }] }"#, + ), + ("index.js", ""), + ]); + let process = Process::new(None, None, Vec::new()); + let path = dir.join("wrangler.jsonc"); + let error = load(path.to_str().unwrap(), &process, false).err().unwrap(); + assert!(error.contains("kv_namespaces"), "{error}"); + assert!(error.contains("--experimental"), "{error}"); + let error = load_deployment(path.to_str().unwrap(), Some("app"), &process) + .err() + .unwrap(); assert!(error.contains("kv_namespaces"), "{error}"); } +#[test] +fn kv_namespaces_bind_the_kv_worker() { + let dir = project(&[ + ( + "wrangler.jsonc", + r#"{ "name": "app", "main": "index.js", "compatibility_date": "2026-01-01", + "no_bundle": true, + "kv_namespaces": [{ "binding": "A", "id": "a", "preview_id": "p" }, + { "binding": "B", "remote": true }] }"#, + ), + ("index.js", ""), + ]); + let config = load( + dir.join("wrangler.jsonc").to_str().unwrap(), + &Process::new(None, None, Vec::new()), + true, + ) + .unwrap(); + let message = read(config); + let conf = message.get_root::().unwrap(); + let services = conf.get_services().unwrap(); + let names: Vec<_> = services + .iter() + .map(|s| s.get_name().unwrap().to_str().unwrap().to_owned()) + .collect(); + assert_eq!(names, ["app", "app-kv", "app-kv-storage", "app-kv-blobs"]); + let service::Which::Disk(disk) = services.get(3).which().unwrap() else { + panic!("not a disk"); + }; + let disk = disk.unwrap(); + assert!(disk.get_writable()); + let blobs = dir.join(".wrangler/state/workerd/kv/blobs"); + assert!(blobs.is_dir()); + assert_eq!( + fs::canonicalize(disk.get_path().unwrap().to_str().unwrap()).unwrap(), + fs::canonicalize(blobs).unwrap() + ); + let service::Which::Worker(w) = services.get(0).which().unwrap() else { + panic!("not a worker"); + }; + let bound: Vec<_> = w + .unwrap() + .get_bindings() + .unwrap() + .iter() + .map(|b| { + let worker::binding::Which::KvNamespace(d) = b.which().unwrap() else { + panic!("not a kvNamespace"); + }; + let d = d.unwrap(); + let service_designator::props::Which::Json(props) = d.get_props().which().unwrap() + else { + panic!("no JSON props"); + }; + let text = |t: capnp::text::Reader<'_>| t.to_str().unwrap().to_owned(); + ( + text(b.get_name().unwrap()), + text(d.get_name().unwrap()), + text(props.unwrap()), + ) + }) + .collect(); + let kv = |b: &str, id: &str| { + ( + b.into(), + "app-kv".into(), + format!(r#"{{"namespace":"{id}"}}"#), + ) + }; + assert_eq!(bound, [kv("A", "a"), kv("B", "B")]); +} + #[test] fn unbundled_typescript_main_is_an_error() { let error = load_project(&[ diff --git a/src/workerd/server/cli/wrangler.rs b/src/workerd/server/cli/wrangler.rs index cdbbc1f3101..75decc09d48 100644 --- a/src/workerd/server/cli/wrangler.rs +++ b/src/workerd/server/cli/wrangler.rs @@ -9,17 +9,21 @@ //! externals; every input esbuild read outside `node_modules` is watched. Under `no_bundle: true`, //! `main` must be an ES module and the modules it imports are found by scanning its directory with //! wrangler's default module rules. Supported fields: `name`, `main`, `compatibility_date`, -//! `compatibility_flags`, `vars`, `durable_objects`, `exports`, `migrations`, `no_bundle` and -//! `$schema`. Any other field is an error rather than silently ignored. +//! `compatibility_flags`, `vars`, `durable_objects`, `exports`, `migrations`, `kv_namespaces`, +//! `no_bundle` and `$schema`. Any other field is an error rather than silently ignored. //! //! Durable Objects are stored on disk under `.wrangler/state/workerd/` next to the config, one -//! directory per class, named `-` by its storage key (see [`do_classes`]). The server -//! listens on `localhost:8787`, as `wrangler dev` does; `--socket-addr http=` overrides it. +//! directory per class, named `-` by its storage key (see [`do_classes`]). +//! `kv_namespaces` need `--experimental`. Each is a binding to the Worker `-kv` +//! (the bundled module `/workerd/kv.js`), with the namespace's `id` (else its binding name) in +//! its props; `preview_id` and `remote` are ignored. Its objects are in +//! `.wrangler/state/workerd/kv/`, and its large values in `kv/blobs/` there. The server listens +//! on `localhost:8787`, as `wrangler dev` does; `--socket-addr http=` overrides it. //! //! For `workerd deploy`, [`load_deployment`] translates the same fields into a cluster deployment //! (`cluster::compose`), which holds only services: the worker, named after the deployment, with //! no socket, and its Durable Objects stored on the disk service [`DEPLOYMENT_STORAGE`], which -//! each node's own config defines. +//! each node's own config defines. A deployment cannot have `kv_namespaces` yet. use std::collections::BTreeMap; use std::fs; @@ -29,6 +33,8 @@ use std::path::PathBuf; use serde::Deserialize; use serde_json::Value; use workerd_capnp::config; +use workerd_capnp::service; +use workerd_capnp::worker; use crate::config::Config; use crate::config::words_from_bytes; @@ -59,9 +65,22 @@ struct Wrangler { #[serde(default)] migrations: Vec, #[serde(default)] + kv_namespaces: Vec, + #[serde(default)] no_bundle: bool, } +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct KvNamespace { + binding: String, + id: Option, + #[serde(rename = "preview_id")] + _preview_id: Option, + #[serde(rename = "remote")] + _remote: Option, +} + #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct DurableObjects { @@ -181,15 +200,15 @@ pub fn project_config(dir: &Path) -> Result { enum Target<'a> { /// A config to serve: the worker named after the config's `name`, else `main`, a socket, and /// a disk service for its Durable Objects under `.wrangler/state/workerd`. - Serve, + Serve { experimental: bool }, /// A cluster deployment, services only: the worker named `name`, else after the config's /// `name`, and its Durable Objects stored on the node's [`DEPLOYMENT_STORAGE`]. Deployment { name: Option<&'a str> }, } /// The config `workerd serve` runs for the wrangler config at `path`. -pub fn load(path: &str, process: &Process) -> Result { - translate(path, process, &Target::Serve).map(|(_, config)| config) +pub fn load(path: &str, process: &Process, experimental: bool) -> Result { + translate(path, process, &Target::Serve { experimental }).map(|(_, config)| config) } /// The deployment `workerd deploy` publishes for the wrangler config at `path`, and its name: @@ -208,15 +227,17 @@ fn translate(path: &str, process: &Process, target: &Target) -> Result<(String, .watch_file(p.as_os_str().as_encoded_bytes()) .map_err(|e| e.description().to_owned()) }; - let file = fs::canonicalize(path).map_err(|e| e.to_string())?; + // Not `canonicalize`, whose `\\?\` paths on Windows kj cannot parse. + let file = std::path::absolute(path).map_err(|e| e.to_string())?; watch(&file)?; let source = fs::read_to_string(&file).map_err(|e| e.to_string())?; let wrangler: Wrangler = serde_json::from_str(&strip_jsonc(&source)).map_err(|e| e.to_string())?; + check_kv(&wrangler, target)?; let root = file.parent().unwrap_or(&file); let name = match target { - Target::Serve => wrangler.name.clone().unwrap_or_else(|| "main".to_owned()), + Target::Serve { .. } => wrangler.name.clone().unwrap_or_else(|| "main".to_owned()), Target::Deployment { name } => name .map(str::to_owned) .or_else(|| wrangler.name.clone()) @@ -232,17 +253,29 @@ fn translate(path: &str, process: &Process, target: &Target) -> Result<(String, bundle(&esbuild(root), root, &wrangler.main, &watch)? }; - let serving = matches!(target, Target::Serve); + let serving = matches!(target, Target::Serve { .. }); let storage = root.join(".wrangler/state/workerd"); if serving && !classes.is_empty() { fs::create_dir_all(&storage).map_err(|e| format!("{}: {e}", storage.display()))?; } + let kv = !wrangler.kv_namespaces.is_empty(); let mut message = capnp::message::Builder::new_default(); let mut conf = message.init_root::(); + let do_storage = u32::from(serving && !classes.is_empty()); let mut services = conf .reborrow() - .init_services(if serving && !classes.is_empty() { 2 } else { 1 }); + .init_services(1 + do_storage + 3 * u32::from(kv)); + // Named after the worker, so they cannot collide with it. + let kv_service = format!("{name}-kv"); + if kv { + kv_services( + &mut services, + 1 + do_storage, + &kv_service, + &storage.join("kv"), + )?; + } let mut service = services.reborrow().get(0); service.set_name(&name); @@ -253,7 +286,7 @@ fn translate(path: &str, process: &Process, target: &Target) -> Result<(String, .map_err(|e| e.to_string())?; set_modules(worker.reborrow(), &sources)?; - set_bindings(worker.reborrow(), &wrangler); + set_bindings(worker.reborrow(), &wrangler, &kv_service); if !classes.is_empty() { let mut ns = worker @@ -298,11 +331,7 @@ fn translate(path: &str, process: &Process, target: &Target) -> Result<(String, Ok((name, config)) } -/// The worker's modules: `sources`. -fn set_modules( - worker: workerd_capnp::worker::Builder<'_>, - sources: &[Source], -) -> Result<(), String> { +fn set_modules(worker: worker::Builder<'_>, sources: &[Source]) -> Result<(), String> { let mut ms = worker.init_modules(sources.len() as u32); for (i, (module_name, kind, bytes)) in sources.iter().enumerate() { let mut m = ms.reborrow().get(i as u32); @@ -319,13 +348,72 @@ fn set_modules( Ok(()) } -/// The worker's bindings: `vars`, then the Durable Object bindings. -fn set_bindings(worker: workerd_capnp::worker::Builder<'_>, wrangler: &Wrangler) { +/// `kv_namespaces` need `--experimental`, and a deployment cannot have them yet. +fn check_kv(wrangler: &Wrangler, target: &Target) -> Result<(), String> { + match target { + _ if wrangler.kv_namespaces.is_empty() => Ok(()), + Target::Serve { experimental: true } => Ok(()), + Target::Serve { .. } => Err("kv_namespaces is an experimental feature which may change \ + or go away in the future. You must run workerd with \ + `--experimental` to use it." + .to_owned()), + Target::Deployment { .. } => Err("A deployment cannot have kv_namespaces yet.".to_owned()), + } +} + +/// The KV Worker `name` at `services[at]`, then its disks under `dir`. +fn kv_services( + services: &mut capnp::struct_list::Builder<'_, service::Owned>, + at: u32, + name: &str, + dir: &Path, +) -> Result<(), String> { + let blobs = dir.join("blobs"); + fs::create_dir_all(&blobs).map_err(|e| format!("{}: {e}", blobs.display()))?; + for (i, what, path) in [(at + 1, "storage", dir), (at + 2, "blobs", &blobs)] { + let mut disk_service = services.reborrow().get(i); + disk_service.set_name(format!("{name}-{what}")); + let mut disk = disk_service.init_disk(); + disk.set_path(path.to_string_lossy()); + disk.set_writable(true); + } + kv_worker(services.reborrow().get(at), name); + Ok(()) +} + +/// The KV Worker `name`, over the disks `-storage` and `-blobs`. +fn kv_worker(mut service: service::Builder<'_>, name: &str) { + service.set_name(name); + let mut w = service.init_worker(); + let mut module = w.reborrow().init_modules(1).get(0); + module.set_name("kv.js"); + module.set_bundled("/workerd/kv.js"); + w.set_compatibility_date("2026-01-01"); + let mut class = w.reborrow().init_durable_object_namespaces(1).get(0); + class.set_class_name("KVNamespace"); + class.set_unique_key("KVNamespace"); + class.set_enable_sql(true); + w.reborrow() + .init_durable_object_storage() + .set_local_disk(format!("{name}-storage")); + let mut bindings = w.init_bindings(2); + let mut shard = bindings.reborrow().get(0); + shard.set_name("SHARD"); + shard + .init_durable_object_namespace() + .set_class_name("KVNamespace"); + let mut blobs = bindings.get(1); + blobs.set_name("BLOBS"); + blobs.init_service().set_name(format!("{name}-blobs")); +} + +fn set_bindings(worker: worker::Builder<'_>, wrangler: &Wrangler, kv_service: &str) { + let kv = &wrangler.kv_namespaces; let do_bindings = wrangler .durable_objects .as_ref() .map_or(&[][..], |d| &d.bindings); - let mut bs = worker.init_bindings((wrangler.vars.len() + do_bindings.len()) as u32); + let mut bs = worker.init_bindings((wrangler.vars.len() + do_bindings.len() + kv.len()) as u32); for (i, (k, v)) in wrangler.vars.iter().enumerate() { let mut b = bs.reborrow().get(i as u32); b.set_name(k); @@ -340,6 +428,17 @@ fn set_bindings(worker: workerd_capnp::worker::Builder<'_>, wrangler: &Wrangler) b.init_durable_object_namespace() .set_class_name(&d.class_name); } + for (i, k) in kv.iter().enumerate() { + let mut b = bs + .reborrow() + .get((wrangler.vars.len() + do_bindings.len() + i) as u32); + b.set_name(&k.binding); + let id = k.id.as_ref().unwrap_or(&k.binding); + let mut designator = b.init_kv_namespace(); + designator.set_name(kv_service); + let props = serde_json::json!({ "namespace": id }); + designator.init_props().set_json(props.to_string()); + } } type Source = (String, Kind, Vec); diff --git a/src/workerd/server/cluster/cluster.rs b/src/workerd/server/cluster/cluster.rs index 06f5f882c50..dfc73306664 100644 --- a/src/workerd/server/cluster/cluster.rs +++ b/src/workerd/server/cluster/cluster.rs @@ -116,6 +116,13 @@ impl Cluster { }) } + /// The bucket below `services//`, apart from the cluster's + /// own state (`ClusterBucket` in workerd.capnp). + pub fn services(&self, path: &str) -> Bucket { + self.bucket + .at(&format!("{}services/{path}", self.bucket.prefix())) + } + pub fn node(&self) -> &str { self.registry.node() } diff --git a/src/workerd/server/cluster/compose-test.rs b/src/workerd/server/cluster/compose-test.rs index b07eb79ea20..6b15dc25902 100644 --- a/src/workerd/server/cluster/compose-test.rs +++ b/src/workerd/server/cluster/compose-test.rs @@ -34,6 +34,7 @@ struct Worker<'a> { enum Kind<'a> { Worker(Worker<'a>), Disk, + Bucket, Network, } @@ -88,6 +89,9 @@ fn set_service(mut service: service::Builder<'_>, name: &str, kind: Kind<'_>) { Kind::Disk => { service.init_disk().set_writable(true); } + Kind::Bucket => { + service.init_bucket().set_path("kv"); + } Kind::Network => { service.init_network(); } @@ -219,11 +223,17 @@ fn a_deployment_may_contain_only_services() { #[test] fn a_deployment_defines_no_disk_and_no_internet() { - let config = services(&[("files", Kind::Disk), ("internet", Kind::Network)]); + let config = services(&[ + ("files", Kind::Disk), + ("blobs", Kind::Bucket), + ("internet", Kind::Network), + ]); assert_eq!( refusal(deployment_config("app", &config)), "deployment \"app\" defines disk service \"files\". A deployment cannot define a disk. \ Define the disk in the instance's config and refer to it by name.\n\ + deployment \"app\" defines bucket service \"blobs\". A deployment cannot define a \ + bucket service. Define it in the instance's config and refer to it by name.\n\ deployment \"app\" defines service \"internet\". Only an instance's config may define \ this service." ); diff --git a/src/workerd/server/cluster/compose.rs b/src/workerd/server/cluster/compose.rs index 75998507974..cb2fcfbeffe 100644 --- a/src/workerd/server/cluster/compose.rs +++ b/src/workerd/server/cluster/compose.rs @@ -384,6 +384,10 @@ fn check_deployment( "{owner} defines disk service \"{name}\". A deployment cannot define a disk. \ Define the disk in the instance's config and refer to it by name." )), + Ok(service::Which::Bucket(_)) => errors.push(format!( + "{owner} defines bucket service \"{name}\". A deployment cannot define a \ + bucket service. Define it in the instance's config and refer to it by name." + )), Ok(service::Which::Worker(worker)) => { let worker = worker?; let context = format!("service \"{name}\" in {owner}"); diff --git a/src/workerd/server/kv/BUILD.bazel b/src/workerd/server/kv/BUILD.bazel new file mode 100644 index 00000000000..86dc4ca0a3d --- /dev/null +++ b/src/workerd/server/kv/BUILD.bazel @@ -0,0 +1,8 @@ +load("//:build/wd_cc_embed.bzl", "wd_cc_embed") + +# The KV Worker, the bundled module `/workerd/kv.js` (Worker.Module.bundled). +wd_cc_embed( + name = "kv-js", + src = "kv.js", + visibility = ["//src/workerd/server:__pkg__"], +) diff --git a/src/workerd/server/kv/kv.js b/src/workerd/server/kv/kv.js new file mode 100644 index 00000000000..f5fd7627072 --- /dev/null +++ b/src/workerd/server/kv/kv.js @@ -0,0 +1,773 @@ +// 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 + +// KV, on the protocol workerd's KV binding speaks (src/workerd/api/kv.c++): +// GET, PUT and DELETE on /, GET /?prefix= for a page of keys, POST +// /bulk/get. The binding's props name the namespace: +// +// kvNamespace = (name = "", +// props = (json = "{\"namespace\": \"\"}")) +// +// The config that runs this module (`bundled = "/workerd/kv.js"`) is an +// interface: cli/wrangler.rs, Miniflare and hand-written configs write it, +// each for the workerd it ships with or runs on. Anything added to it later +// must be optional, so that configs written before keep working. It is: +// +// - a Worker with RPC: a compatibility date of 2024-04-03 or later, or +// the `rpc` flag; +// - the Durable Object class `KVNamespace`, SQLite-backed (`enableSql`), +// stored on a local disk. Its `uniqueKey` and that disk are where the +// namespaces live: a config that changes either starts empty; +// - these bindings: +// +// SHARD the `KVNamespace` class +// BLOBS values over `INLINE` bytes: a writable `disk`, or in a +// cluster a `bucket` service +// BLOB_CACHE in a cluster, a writable `disk` on the node that caches +// blobs (optional) +// CLUSTERED JSON `true` in a cluster (optional) +// TEST_CLOCK JSON `true` for tests (optional) +// +// A namespace is a Durable Object (`KVNamespace`, by `idFromName`) whose +// SQLite table `entries` is its index: each key's expiration, metadata, +// and its value inline up to `INLINE` bytes or else the path of a blob, +// `/b/` in `BLOBS`. A blob is immutable: it is reserved, written, +// then claimed by its row's write, and deleted after the row stops naming +// it, through the object's `garbage` table and its alarm. One object holds +// a namespace, so its throughput is one object's. +// +// This Worker reads and writes blobs itself, so large values do not pass +// through the object. In a cluster it keeps a per-process cache of rows and +// misses for each read's `cacheTtl`, which this process's writes update and +// nothing else invalidates. Locally it keeps none: the object is in the +// process, and another process on the same storage, such as `wrangler kv +// key put --local`, must be seen at once. Rows name blobs rather than hold +// them, so entries are small; blobs never change, so `BLOB_CACHE` needs no +// invalidation. +// +// With `TEST_CLOCK`, POST /clock?advance= moves this process's clock for +// expiry and the entry cache, for tests; blob collection keeps the real +// clock. + +import { DurableObject } from 'cloudflare:workers'; + +const INLINE = 64 * 1024; +const MAX_VALUE = 25 * 1024 * 1024; +const MAX_METADATA = 1024; +const MAX_KEY = 512; +const MAX_BULK_BYTES = 25 * 1024 * 1024; +const MAX_LIST = 1000; +const MAX_BULK = 100; +const MIN_EXPIRATION_TTL = 60; +const MIN_CACHE_TTL = 30; +const CACHE_TTL = 60; +const CACHE_BYTES = 64 * 1024 * 1024; +// A reserved blob unclaimed this long is deleted. +const RESERVE_MS = 600_000; +// A blob no row names is deleted this much later, which spares readers +// that read the row a moment before a retry; less under `TEST_CLOCK`. +const GRACE_MS = 2_000; +const TEST_GRACE_MS = 100; +const READS = 3; +const BLOB_CACHE_BYTES = 1024 * 1024 * 1024; + +class Fail extends Error { + constructor(status, text) { + super(text); + this.status = status; + } +} + +const fail = (status, text) => + new Response(null, { status, statusText: text.replace(/[\r\n]/g, ' ') }); + +let clustered; +let hasRpc = false; +let skew = 0; +const clock = () => Date.now() + skew; + +export default { + async fetch(request, env, ctx) { + clustered ??= env.CLUSTERED === true; + const ns = ctx.props?.namespace; + if (typeof ns !== 'string') { + return fail(400, 'No namespace: props must be {"namespace": ""}.'); + } + // Without RPC every call to the object fails as "not a function". + hasRpc ||= + typeof env.SHARD.get(env.SHARD.idFromName(ns)).read === 'function'; + if (!hasRpc) { + return fail( + 500, + 'KV needs RPC: give its Worker a compatibility date of 2024-04-03 ' + + 'or later, or the "rpc" compatibility flag.' + ); + } + try { + return await serve(request, env, ns); + } catch (e) { + return fail(e.status ?? 500, String(e.message ?? e)); + } + }, +}; + +async function serve(request, env, ns) { + const url = request.url; + const rest = url.slice(url.indexOf('://') + 3); + const at = rest.search(/[/?]/); + const target = at < 0 ? '' : rest.slice(at); + const q = target.indexOf('?'); + const path = (q < 0 ? target : target.slice(0, q)) || '/'; + const params = new URLSearchParams(q < 0 ? '' : target.slice(q + 1)); + const id = env.SHARD.idFromName(ns); + const space = { ns, dir: id.toString(), shard: env.SHARD.get(id) }; + let key; + try { + key = decodeURIComponent(path.slice(1)); + } catch { + throw new Fail(400, 'Invalid key encoding'); + } + switch (request.method) { + case 'POST': + if (path === '/bulk/get') return bulk(request, env, space); + if (path === '/clock' && env.TEST_CLOCK) { + const advance = Number(params.get('advance')); + if (!Number.isFinite(advance)) { + return fail(400, 'advance must be a number of milliseconds.'); + } + skew += advance; + return new Response(null); + } + break; + case 'GET': + if (path === '/') return list(space, params); + return get(env, space, key, params); + case 'PUT': + return put(request, env, space, key, params); + case 'DELETE': + remember(space, key, null, CACHE_TTL, await space.shard.remove(key)); + return new Response(null); + } + return fail(405, 'Method Not Allowed'); +} + +function cacheTtl(value) { + if (value === null || value === undefined) return CACHE_TTL; + const ttl = Number(value); + if (!Number.isInteger(ttl) || ttl < MIN_CACHE_TTL) { + throw new Fail( + 400, + `Invalid cache_ttl of ${value}. Cache TTL must be at least ` + + `${MIN_CACHE_TTL}.` + ); + } + return ttl; +} + +async function get(env, space, key, params) { + const ttl = cacheTtl(params.get('cache_ttl')); + const { entry, hit } = (await read(env, space, [key], ttl))[0]; + const headers = { 'CF-Cache-Status': hit ? 'HIT' : 'MISS' }; + if (entry === null) return new Response(null, { status: 404, headers }); + if (entry.metadata !== null) headers['CF-KV-Metadata'] = entry.metadata; + return new Response(entry.value, { headers }); +} + +// A key's validity, as a single get checks it in the binding. +function validate(key) { + if (key === '') throw new Fail(400, 'Key names must not be empty'); + if (key === '.' || key === '..') { + throw new Fail( + 400, + `Illegal key name "${key}". Please use a different name.` + ); + } + validateLength(key); +} + +function validateLength(key) { + const n = bytes(key); + if (n > MAX_KEY) { + throw new Fail( + 414, + `UTF-8 encoded length of ${n} exceeds key length limit of ${MAX_KEY}.` + ); + } +} + +const bytes = (s) => new TextEncoder().encode(s).byteLength; + +async function put(request, env, space, key, params) { + const value = new Uint8Array(await request.arrayBuffer()); + if (value.byteLength > MAX_VALUE) { + throw new Fail( + 413, + `Value length of ${value.byteLength} exceeds limit of ${MAX_VALUE}.` + ); + } + const expiration = expires(params); + const metadata = request.headers.get('CF-KV-Metadata'); + if (metadata !== null && bytes(metadata) > MAX_METADATA) { + throw new Fail( + 413, + `Metadata length of ${bytes(metadata)} exceeds limit of ` + + `${MAX_METADATA}.` + ); + } + let blob = null; + if (value.byteLength > INLINE) { + blob = `${space.dir}/b/${hex(crypto.getRandomValues(new Uint8Array(32)))}`; + await space.shard.reserve(key, blob); + const r = await env.BLOBS.fetch(`http://blobs/${blob}`, { + method: 'PUT', + body: value, + }); + if (!r.ok) throw new Error(`Writing the value failed: ${r.status}.`); + await cacheBlob(env, blob, value); + } + const inline = blob === null ? value : null; + const version = await space.shard.write( + key, + inline, + blob, + expiration, + metadata + ); + const row = { value: inline, blob, expiration, metadata }; + remember(space, key, row, CACHE_TTL, version); + return new Response(null); +} + +// An `expiration` or `expiration_ttl` parameter as a time in ms, parsed +// and refused as production does. +function expires(params) { + const now = Math.floor(clock() / 1000); + const ttlText = params.get('expiration_ttl'); + if (ttlText !== null) { + const ttl = parseInt(ttlText); + const bad = `Invalid expiration_ttl of ${ttlText}.`; + if (Number.isNaN(ttl) || ttl <= 0) { + throw new Fail(400, `${bad} Please specify integer greater than 0.`); + } + if (ttl < MIN_EXPIRATION_TTL) { + throw new Fail( + 400, + `${bad} Expiration TTL must be at least ${MIN_EXPIRATION_TTL}.` + ); + } + return (now + ttl) * 1000; + } + const atText = params.get('expiration'); + if (atText === null) return null; + const at = parseInt(atText); + const bad = `Invalid expiration of ${atText}.`; + if (Number.isNaN(at) || at <= now) { + throw new Fail( + 400, + `${bad} Please specify integer greater than the current number of ` + + 'seconds since the UNIX epoch.' + ); + } + if (at < now + MIN_EXPIRATION_TTL) { + throw new Fail( + 400, + `${bad} Expiration times must be at least ${MIN_EXPIRATION_TTL} ` + + 'seconds in the future.' + ); + } + return at * 1000; +} + +async function list(space, params) { + const text = params.get('key_count_limit'); + const limit = text === null ? MAX_LIST : parseInt(text); + const bad = `Invalid key_count_limit of ${limit}.`; + if (Number.isNaN(limit) || limit < 1) { + throw new Fail(400, `${bad} Please specify an integer greater than 0.`); + } + if (limit > MAX_LIST) { + throw new Fail( + 400, + `${bad} Please specify an integer less than ${MAX_LIST}.` + ); + } + let after = ''; + const cursor = params.get('cursor'); + if (cursor) { + try { + after = utf8(Uint8Array.from(atob(cursor), (c) => c.charCodeAt(0))); + } catch { + throw new Fail(400, 'Invalid cursor.'); + } + } + const prefix = params.get('prefix') ?? ''; + validateLength(prefix); + const rows = await space.shard.list(prefix, after, limit + 1); + const keys = rows.slice(0, limit).map(({ key, expiration, metadata }) => { + const k = { name: key }; + if (expiration !== null) k.expiration = Math.floor(expiration / 1000); + if (metadata !== null) k.metadata = metadata; + return k; + }); + const page = { keys, list_complete: rows.length <= limit }; + if (!page.list_complete) { + const bytes = new TextEncoder().encode(keys.at(-1).name); + page.cursor = btoa(String.fromCharCode(...bytes)); + } + return Response.json(page); +} + +async function bulk(request, env, space) { + let body; + try { + body = await request.json(); + } catch { + throw new Fail(400, 'Invalid JSON'); + } + if (typeof body !== 'object' || body === null) { + throw new Fail(400, 'Invalid JSON'); + } + const keys = Array.isArray(body.keys) ? body.keys : []; + const type = body.type ?? 'text'; + if (type !== 'text' && type !== 'json') { + throw new Fail(400, `"${type}" is not a valid type. Use "json" or "text"`); + } + if (keys.length > MAX_BULK) { + throw new Fail(400, `You can request a maximum of ${MAX_BULK} keys`); + } + if (keys.length < 1) { + throw new Fail(400, 'You must request a minimum of 1 key'); + } + for (const key of keys) validate(String(key)); + const ttl = cacheTtl(body.cacheTtl); + const got = await read(env, space, keys, ttl, MAX_BULK_BYTES); + const out = {}; + keys.forEach((key, i) => { + const { entry } = got[i]; + if (entry === null) { + out[key] = null; + return; + } + // Text decodes as a single get does; JSON must be valid UTF-8. + let value = new TextDecoder().decode(entry.value); + if (type === 'json') { + try { + value = JSON.parse(utf8(entry.value)); + } catch { + throw new Fail( + 400, + 'At least one of the requested keys corresponds to a non-json value' + ); + } + } + out[key] = body.withMetadata + ? { value, metadata: entry.metadata && JSON.parse(entry.metadata) } + : value; + }); + return Response.json(out); +} + +// ======================================================================= +// Reads and the cache + +const cache = new Map(); +let cached = 0; + +const cacheKey = (space, key) => `${space.ns}\0${key}`; + +function forget(k) { + const c = cache.get(k); + if (c === undefined) return; + cache.delete(k); + cached -= c.size; +} + +// What an entry costs: its strings at two bytes a character, its inline +// value, and about 128 bytes for the map entry and the objects. +function cost(k, row) { + const chars = + k.length + (row?.metadata?.length ?? 0) + (row?.blob?.length ?? 0); + return 2 * chars + (row?.value?.byteLength ?? 0) + 128; +} + +// `row` (null for a miss) for `ttl` seconds, as of the object's `version`, +// unless the cache holds a later one: replies to one node's concurrent +// reads and writes can arrive out of order. +function remember(space, key, row, ttl, version) { + if (!clustered) return; + const k = cacheKey(space, key); + if ((cache.get(k)?.version ?? -1) > version) return; + forget(k); + const size = cost(k, row); + const at = clock(); + cache.set(k, { row, at, until: at + ttl * 1000, size, version }); + cached += size; + for (const old of cache.keys()) { + if (cached <= CACHE_BYTES) break; + forget(old); + } +} + +// The cached row, if no older than the reader's `ttl` seconds. +function recall(space, key, ttl) { + const k = cacheKey(space, key); + const c = cache.get(k); + if (c === undefined) return undefined; + const now = clock(); + const old = c.until <= now || now - c.at >= ttl * 1000; + if (old || (c.row?.expiration ?? Infinity) <= now) { + forget(k); + return undefined; + } + cache.delete(k); + cache.set(k, c); + return c.row; +} + +// Each key's entry (`{value, expiration, metadata}` or null) and whether +// its row came from the cache, refused with a 413 once their values pass +// `cap` bytes, before any further blob is read. +async function read(env, space, keys, ttl, cap = Infinity) { + const rows = keys.map((key) => recall(space, key, ttl)); + const hits = rows.map((row) => row !== undefined); + const misses = keys.filter((_, i) => !hits[i]); + if (misses.length > 0) { + const got = await space.shard.read(misses); + let m = 0; + keys.forEach((key, i) => { + if (hits[i]) return; + rows[i] = got.rows[m++]; + remember(space, key, rows[i], ttl, got.version); + }); + } + const out = []; + let total = 0; + for (const [i, key] of keys.entries()) { + const entry = await load(env, space, key, rows[i], ttl); + total += entry?.value.byteLength ?? 0; + if (total > cap) { + throw new Fail( + 413, + `Total size of request exceeds the limit of ${cap / 1024 / 1024}MB` + ); + } + out.push({ entry, hit: hits[i] }); + } + return out; +} + +// A row as an entry, reading its blob. A blob that is gone was replaced +// since the row was read, so the row is read again. +async function load(env, space, key, row, ttl) { + for (let i = 0; ; i++) { + if (row === null) return null; + const { expiration, metadata } = row; + if (row.blob === null) { + return { value: new Uint8Array(row.value), expiration, metadata }; + } + const value = await readBlob(env, row.blob); + if (value !== null) return { value, expiration, metadata }; + if (i === READS) throw new Error('Reading the value failed: 404.'); + const { version, rows } = await space.shard.read([key]); + remember(space, key, (row = rows[0]), ttl, version); + } +} + +// ======================================================================= +// Blobs, and their cache on a cluster node's disk + +// The blobs in `BLOB_CACHE` by path, least recently used first, with +// their sizes. The Worker and its objects share the process's isolate, so +// this is the node's one index. It is in memory, so each process caches in +// a directory of its own, `c//`, and deletes the others'. +const cachedBlobs = new Map(); +let cachedBytes = 0; +let generation = null; + +function cacheUrl(path) { + return `http://cache/c/${generation}/${path}`; +} + +// The cache, null if there is none. The first call deletes the other +// generations. +async function blobCache(env) { + const cache = env.BLOB_CACHE; + if (cache === undefined || generation !== null) return cache ?? null; + generation = hex(crypto.getRandomValues(new Uint8Array(8))); + const r = await cache.fetch('http://cache/c'); + for (const { name } of r.ok ? await r.json() : []) { + if (name === generation) continue; + await cache.fetch(`http://cache/c/${name}`, { method: 'DELETE' }); + } + return cache; +} + +// A blob's bytes, or null if it is not in `BLOBS`. +async function readBlob(env, path) { + const cache = await blobCache(env); + if (cache !== null && cachedBlobs.has(path)) { + const r = await cache.fetch(cacheUrl(path)); + if (r.ok) { + const size = cachedBlobs.get(path); + cachedBlobs.delete(path); + cachedBlobs.set(path, size); + return new Uint8Array(await r.arrayBuffer()); + } + await uncacheBlob(cache, path); + } + const r = await env.BLOBS.fetch(`http://blobs/${path}`); + if (r.status === 404) return null; + if (!r.ok) throw new Error(`Reading the value failed: ${r.status}.`); + const value = new Uint8Array(await r.arrayBuffer()); + await cacheBlob(env, path, value); + return value; +} + +// Writes a blob to the cache, evicting the least recently used past +// `BLOB_CACHE_BYTES`. +async function cacheBlob(env, path, value) { + const cache = await blobCache(env); + const size = value.byteLength; + if (cache === null || size > BLOB_CACHE_BYTES) return; + const r = await cache.fetch(cacheUrl(path), { method: 'PUT', body: value }); + if (!r.ok || cachedBlobs.has(path)) return; + cachedBlobs.set(path, size); + cachedBytes += size; + const evicted = []; + for (const old of cachedBlobs.keys()) { + if (cachedBytes <= BLOB_CACHE_BYTES) break; + evicted.push(uncacheBlob(cache, old)); + } + await Promise.all(evicted); +} + +async function uncacheBlob(cache, path) { + const size = cachedBlobs.get(path); + if (size === undefined) return; + cachedBlobs.delete(path); + cachedBytes -= size; + await cache.fetch(cacheUrl(path), { method: 'DELETE' }); +} + +const hex = (bytes) => + Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join(''); + +const utf8 = (bytes) => new TextDecoder('utf-8', { fatal: true }).decode(bytes); + +// The least string above every string starting with `prefix`, or null if +// there is none. +function above(prefix) { + const points = [...prefix]; + while (points.length > 0) { + const last = points.pop().codePointAt(0); + if (last < 0x10ffff) { + const next = last === 0xd7ff ? 0xe000 : last + 1; + return points.join('') + String.fromCodePoint(next); + } + } + return null; +} + +// ======================================================================= +// The namespace's object + +// The schema, as the steps from each version to the next: a database at +// version `v` (its `schema` row; 0 when new) runs `MIGRATIONS.slice(v)`. +const MIGRATIONS = [ + (sql) => { + sql.exec(`CREATE TABLE entries ( + key TEXT PRIMARY KEY, value BLOB, blob TEXT, expiration INTEGER, + metadata TEXT)`); + sql.exec('CREATE INDEX entries_expiration ON entries(expiration)'); + // Blobs to delete when due: reserved ones, keyed by the key whose write + // may claim them, and unclaimable ones, keyed by null. + sql.exec(`CREATE TABLE garbage ( + blob TEXT PRIMARY KEY, due INTEGER NOT NULL, key TEXT)`); + // The number of writes so far: each write's version, and a read's. + sql.exec('CREATE TABLE clock (v INTEGER NOT NULL)'); + sql.exec('INSERT INTO clock VALUES (0)'); + }, +]; + +export class KVNamespace extends DurableObject { + #alarm = null; + + constructor(ctx, env) { + super(ctx, env); + this.sql = ctx.storage.sql; + // The version is read in the transaction that migrates, so two processes + // opening a new namespace at once don't both migrate it. + ctx.storage.transactionSync(() => { + this.sql.exec('CREATE TABLE IF NOT EXISTS schema (v INTEGER NOT NULL)'); + const v = this.sql.exec('SELECT v FROM schema').toArray()[0]?.v ?? 0; + if (v > MIGRATIONS.length) { + throw new Error( + `This namespace's schema (${v}) is newer than this workerd's ` + + `(${MIGRATIONS.length}).` + ); + } + if (v === MIGRATIONS.length) return; + for (const migrate of MIGRATIONS.slice(v)) migrate(this.sql); + this.sql.exec('DELETE FROM schema'); + this.sql.exec('INSERT INTO schema VALUES (?)', MIGRATIONS.length); + }); + ctx.blockConcurrencyWhile(async () => { + this.#alarm = await ctx.storage.getAlarm(); + }); + } + + // Each key's row, or null if it is absent or expired, and the version + // they are as of. + read(keys) { + const now = clock(); + const [{ v }] = this.sql.exec('SELECT v FROM clock').toArray(); + const rows = keys.map( + (key) => + this.sql + .exec( + `SELECT value, blob, expiration, metadata FROM entries + WHERE key = ? AND (expiration IS NULL OR expiration > ?)`, + key, + now + ) + .toArray()[0] ?? null + ); + return { version: v, rows }; + } + + // Reserves `blob` before it is written, so that it is deleted unless a + // write of `key` claims it. + reserve(key, blob) { + this.#collect(blob, Date.now() + RESERVE_MS, key); + } + + // The write's version. + write(key, value, blob, expiration, metadata) { + if (blob !== null) { + const claimed = this.sql.exec( + 'DELETE FROM garbage WHERE blob = ? AND key IS ? RETURNING blob', + blob, + key + ); + if (claimed.toArray().length === 0) { + throw new Error('The value was collected before its write.'); + } + } + this.#drop(key); + this.sql.exec( + 'INSERT INTO entries VALUES (?, ?, ?, ?, ?)', + key, + value, + blob, + expiration, + metadata + ); + if (expiration !== null) this.#wake(expiration); + return this.#tick(); + } + + // The delete's version. + remove(key) { + this.#drop(key); + return this.#tick(); + } + + #tick() { + return this.sql.exec('UPDATE clock SET v = v + 1 RETURNING v').one().v; + } + + #drop(key) { + const removed = this.sql.exec( + 'DELETE FROM entries WHERE key = ? RETURNING blob', + key + ); + for (const { blob } of removed) { + if (blob !== null) this.#collect(blob, Date.now() + this.#grace()); + } + } + + // Up to `limit` unexpired keys starting with `prefix`, after `after`. + list(prefix, after, limit) { + const end = above(prefix); + return this.sql + .exec( + `SELECT key, expiration, metadata FROM entries + WHERE key > ? AND key >= ? AND (? IS NULL OR key < ?) + AND substr(key, 1, length(?)) = ? + AND (expiration IS NULL OR expiration > ?) + ORDER BY key LIMIT ?`, + after, + prefix, + end, + end, + prefix, + prefix, + clock(), + limit + ) + .toArray(); + } + + // Deletes expired rows and due blobs, then waits for the next. + async alarm() { + this.#alarm = null; + const now = Date.now(); + const expired = this.sql.exec( + 'SELECT key FROM entries WHERE expiration <= ? LIMIT 1000', + now + ); + for (const { key } of expired.toArray()) this.#drop(key); + // A due blob stays in `garbage` until its delete succeeds, unclaimable + // and due again a grace period later, so a crash cannot leak it. + const due = this.sql + .exec('SELECT blob FROM garbage WHERE due <= ? LIMIT 100', now) + .toArray(); + for (const { blob } of due) this.#collect(blob, now + this.#grace()); + await Promise.all( + due.map(async ({ blob }) => { + const r = await this.env.BLOBS.fetch(`http://blobs/${blob}`, { + method: 'DELETE', + }); + const cache = this.env.BLOB_CACHE; + if (cache !== undefined && generation !== null) { + await uncacheBlob(cache, blob); + } + if (r.ok || r.status === 404) { + this.sql.exec( + 'DELETE FROM garbage WHERE blob = ? AND key IS NULL', + blob + ); + } + }) + ); + const [{ next }] = this.sql + .exec( + `SELECT min(t) AS next FROM ( + SELECT min(due) AS t FROM garbage + UNION ALL SELECT min(expiration) FROM entries)` + ) + .toArray(); + if (next !== null) this.#wake(Math.max(next, Date.now() + 100)); + } + + #grace() { + return this.env.TEST_CLOCK ? TEST_GRACE_MS : GRACE_MS; + } + + #collect(blob, due, key = null) { + this.sql.exec( + 'INSERT OR REPLACE INTO garbage VALUES (?, ?, ?)', + blob, + due, + key + ); + this.#wake(due); + } + + #wake(at) { + if (this.#alarm !== null && this.#alarm <= at) return; + this.ctx.storage.setAlarm(at); + this.#alarm = at; + } +} diff --git a/src/workerd/server/server/config-test.rs b/src/workerd/server/server/config-test.rs index 8cf392421da..75b466c0909 100644 --- a/src/workerd/server/server/config-test.rs +++ b/src/workerd/server/server/config-test.rs @@ -112,6 +112,27 @@ fn ephemeral_namespaces_need_experimental() { ); } +#[test] +fn bundled_modules_need_experimental() { + let (result, errors) = actor_configs_of( + |config| { + let mut service = config.init_services(1).get(0); + service.set_name("kv"); + let worker = service.init_worker(); + worker.init_modules(1).get(0).set_bundled("/workerd/kv.js"); + }, + false, + ); + result.unwrap(); + assert_eq!( + errors, + [ + "Bundled modules are an experimental feature which may change or go away in the \ + future. You must run workerd with `--experimental` to use this feature." + ] + ); +} + #[test] fn durable_classes_need_storage() { let (result, errors) = actor_configs_of( diff --git a/src/workerd/server/server/config.rs b/src/workerd/server/server/config.rs index 77bcf970e18..eb27593debd 100644 --- a/src/workerd/server/server/config.rs +++ b/src/workerd/server/server/config.rs @@ -681,6 +681,29 @@ pub fn collect_actor_configs( Ok(actor_configs) } +/// Bundled modules (`Worker.Module.bundled`) need `--experimental`. +fn check_bundled( + name: &str, + worker: worker::Reader<'_>, + experimental: bool, + report: &Reporter, +) -> capnp::Result<()> { + let bundled = match worker.which() { + Ok(worker::Which::Modules(modules)) => modules? + .iter() + .any(|m| matches!(m.which(), Ok(worker::module::Which::Bundled(_)))), + _ => false, + }; + if bundled && !experimental { + report.error_in( + name, + "Bundled modules are an experimental feature which may change or go away in the \ + future. You must run workerd with `--experimental` to use this feature.", + ); + } + Ok(()) +} + /// [`collect_actor_configs`] for the service `name`, whose config is `service_conf`. fn collect_service_actor_configs( name: &str, @@ -696,6 +719,7 @@ fn collect_service_actor_configs( return Ok(configs); }; let worker_conf = worker_conf?; + check_bundled(name, worker_conf, experimental, report)?; let mut had_durable = false; for (namespace_index, ns) in (0..).zip(worker_conf.get_durable_object_namespaces()?) { let class_name = ns.get_class_name()?.to_string()?; @@ -777,6 +801,8 @@ fn collect_service_actor_configs( } // Meant for parameterized workers; nothing implements it, so nothing may set it. + // TODO(someday): implement it, so that a Worker with Durable Objects can be + // `inherit`ed, as a bundled Worker's config constant would be. if worker_conf.has_durable_object_unique_key_modifier() { report.service_error( name, @@ -1456,6 +1482,7 @@ impl Server { namespace.set_cluster(Rc::clone(cluster)); } } + make_bucket_services(config, &mut services, cluster.as_ref(), &factory, &report)?; let server = Rc::new(Self { report, @@ -1769,6 +1796,8 @@ async fn make_service( .map(Service::Disk), )) } + // Made once the cluster is joined (`make_bucket_services`). + Ok(service::Which::Bucket(_)) => Ok(Service::Leaf(Rc::new(InvalidConfigChannel))), Err(capnp::NotInSchema(_)) => { report.error_in(name, format!( "Service named \"{name}\" has unrecognized type. Was the config compiled with a \ @@ -1927,6 +1956,38 @@ impl Server { #[path = "config-test.rs"] mod tests; +/// Replaces each `bucket` service's stand-in with the directory of the +/// cluster's bucket it names. +fn make_bucket_services( + config: config::Reader<'_>, + services: &mut Services, + cluster: Option<&Rc>, + factory: &Rc, + report: &Reporter, +) -> Result<()> { + for conf in config.get_services().map_err(capnp_error)? { + let Ok(service::Which::Bucket(bucket)) = conf.which() else { + continue; + }; + let name = text(conf.get_name())?; + let Some(node) = cluster else { + report.service_error(&name, "A bucket service requires Config.cluster."); + continue; + }; + let bucket = bucket.map_err(capnp_error)?; + let made = crate::services::bucket::make_bucket_service(bucket, node, factory); + let channel: Rc = match made { + Ok(service) => Rc::new(service), + Err(error) => { + report.service_error(&name, error.description()); + continue; + } + }; + services.0.insert(name, Service::Leaf(channel)); + } + Ok(()) +} + /// The cluster of `Config.cluster`, joined at `address`. `None` after reporting a config error. fn make_cluster( factory: &Rc, diff --git a/src/workerd/server/server/services/bucket.rs b/src/workerd/server/server/services/bucket.rs new file mode 100644 index 00000000000..a5fe375daf4 --- /dev/null +++ b/src/workerd/server/server/services/bucket.rs @@ -0,0 +1,156 @@ +// 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 `bucket` service (`ClusterBucket` in workerd.capnp): a directory of +//! the cluster's bucket, served over HTTP as GET, PUT and DELETE on files. + +use std::pin::Pin; +use std::rc::Rc; +use std::time::SystemTime; + +use cluster::Bucket; +use kj::http::ConnectResponse; +use kj::http::ConnectSettings; +use kj::http::Headers; +use kj::http::HeadersRef; +use kj::http::Method; +use kj::http::Service as HttpService; +use kj::http::ServiceResponse; +use kj::io::AsyncInputStream; +use kj::io::AsyncIoStream; +use kj_rs::KjOwn; +use worker::AlarmResult; +use worker::Interface; +use worker::ScheduledResult; +use workerd_capnp::cluster_bucket; + +use crate::Result; +use crate::channels::Channel; +use crate::channels::PendingToken; +use crate::channels::RequestMetadata; +use crate::channels::TokenUsage; +use crate::channels::WorkerInterface; +use crate::cluster::ClusterNode; +use crate::config::Factory; +use crate::config::text; +use crate::services::disk::path_segments; +use crate::services::header_table; +use crate::services::not_transferable; +use crate::services::send_error; +use crate::services::unsupported; + +struct Shared { + bucket: Bucket, + factory: Rc, +} + +pub struct BucketService(Rc); + +pub fn make_bucket_service( + conf: cluster_bucket::Reader<'_>, + node: &ClusterNode, + factory: &Rc, +) -> Result { + let path = text(conf.get_path())?; + let url = format!("http://bucket/{path}"); + if path.is_empty() || path_segments(&url).is_none_or(|s| s.join("/") != path) { + return Err(kj::failed!( + "bucket path {path:?} must be `/`-separated names." + )); + } + Ok(BucketService(Rc::new(Shared { + bucket: node.cluster.services(&path), + factory: Rc::clone(factory), + }))) +} + +impl Channel for BucketService { + fn start_request(&self, _metadata: KjOwn) -> Result> { + Ok(BucketRequest(Rc::clone(&self.0)).into_kj()) + } + + fn token(&self, _usage: TokenUsage) -> Result> { + Err(not_transferable("Bucket services")) + } +} + +struct BucketRequest(Rc); + +async fn read_body(mut body: Pin<&mut AsyncInputStream>) -> Result> { + let mut out = Vec::new(); + let mut buffer = vec![0; 64 * 1024]; + loop { + let read = body.as_mut().try_read(&mut buffer, 1).await?; + if read == 0 { + return Ok(out); + } + out.extend_from_slice(&buffer[..read]); + } +} + +#[async_trait::async_trait(?Send)] +impl HttpService for BucketRequest { + async fn request<'a>( + &'a mut self, + method: Method, + url: &'a [u8], + _headers: HeadersRef<'a>, + body: Pin<&'a mut AsyncInputStream>, + response: ServiceResponse<'a>, + ) -> Result<()> { + let none = Headers::new(header_table(&self.0.factory)); + let bucket = &self.0.bucket; + let fail = |e: cluster::Error| kj::failed!("{e}"); + let Some(key) = path_segments(&String::from_utf8_lossy(url)) + .filter(|s| !s.is_empty()) + .map(|s| s.join("/")) + else { + return send_error(response, 404, "Not Found", &none).await; + }; + match method { + Method::GET => { + let Some((value, _)) = bucket.get(&key).await.map_err(fail)? else { + return send_error(response, 404, "Not Found", &none).await; + }; + let len = value.len() as u64; + let mut out = response.send(200, "OK", &none, Some(len))?; + out.write(&value).await + } + Method::PUT => { + let value = read_body(body).await?; + bucket.put(&key, value, &[]).await.map_err(fail)?; + response.send(204, "No Content", &none, None)?; + Ok(()) + } + Method::DELETE => { + bucket.delete(&key).await.map_err(fail)?; + response.send(204, "No Content", &none, None)?; + Ok(()) + } + _ => send_error(response, 501, "Not Implemented", &none).await, + } + } + + async fn connect<'a>( + &'a mut self, + _host: &'a [u8], + _headers: HeadersRef<'a>, + _connection: Pin<&'a mut AsyncIoStream>, + _response: ConnectResponse<'a>, + _settings: ConnectSettings<'a>, + ) -> Result<()> { + Err(unsupported("Bucket services")) + } +} + +#[async_trait::async_trait(?Send)] +impl Interface for BucketRequest { + async fn run_scheduled(&mut self, _time: &SystemTime, _cron: &str) -> Result { + Err(unsupported("Bucket services")) + } + + async fn run_alarm(&mut self, _time: &SystemTime, _retry_count: u32) -> Result { + Err(unsupported("Bucket services")) + } +} diff --git a/src/workerd/server/server/services/mod.rs b/src/workerd/server/server/services/mod.rs index a01530a1b95..22ef8422391 100644 --- a/src/workerd/server/server/services/mod.rs +++ b/src/workerd/server/server/services/mod.rs @@ -10,6 +10,7 @@ //! whole life, so connections are reused across events, and lends it to a `Client` per event, //! which borrows the factory's header table. +pub mod bucket; pub mod disk; pub mod network; pub mod rewriter; diff --git a/src/workerd/server/tests/cluster/cluster-test.mjs b/src/workerd/server/tests/cluster/cluster-test.mjs index 2148884b2d3..c29a07d5059 100644 --- a/src/workerd/server/tests/cluster/cluster-test.mjs +++ b/src/workerd/server/tests/cluster/cluster-test.mjs @@ -35,6 +35,8 @@ // handoff's work are not held, and a DO whose handoff outlasts its // deadline moves once the node left. A rolling restart of the cluster, // paced by the nodes' readiness, fails, loses and replays no request. +// 13. KV: a namespace is seen from every node, its large values are in the +// bucket and cached on each node's disk, and it survives its owner. // // A takeover waits out a dead owner's 20 s lease, so each one here costs // that much: one test per mechanism. The simulations in ../../cluster @@ -394,6 +396,14 @@ class FakeS3 { ).json(); } + // How many body bytes GETs of `key` were served. + async served(key) { + const query = new URLSearchParams({ key }); + return ( + await fetch(`http://127.0.0.1:${this.port}/_served?${query}`) + ).json(); + } + // The keys of the nodes with a lease record. async nodes() { // Not the `.probe` a starting node writes and deletes. @@ -905,6 +915,192 @@ test('cluster: concurrent first requests to a DO read its owner record once per }); }); +test('cluster: a KV namespace is an object, seen from every node', async () => { + await withCluster(2, async ({ nodes, bucket }) => { + const [a, b] = nodes.map((n) => n.httpPort); + const q = (params) => new URLSearchParams(params); + for (const key of ['p/1', 'p/2', 'p/3', 'q']) { + const put = await fetchJson(a, `/kv/put?${q({ key, value: key })}`); + assert.strictEqual(put.status, 200, JSON.stringify(put.body)); + } + const meta = { key: 'm', value: 'v', metadata: '{"n":1}', ttl: '3600' }; + await fetchJson(a, `/kv/put?${q(meta)}`); + + const got = await fetchJson(b, `/kv/get?${q({ key: 'm' })}`); + assert.deepStrictEqual(got.body, { + value: 'v', + metadata: { n: 1 }, + cacheStatus: 'MISS', + }); + + const names = []; + let page = { list_complete: false }; + while (!page.list_complete) { + const query = { prefix: 'p/', limit: '2', cursor: page.cursor ?? '' }; + page = (await fetchJson(b, `/kv/list?${q(query)}`)).body; + names.push(...page.keys.map((k) => k.name)); + } + assert.deepStrictEqual(names, ['p/1', 'p/2', 'p/3']); + const listed = (await fetchJson(b, `/kv/list?${q({ prefix: 'm' })}`)).body; + assert.deepStrictEqual(listed.keys[0].metadata, { n: 1 }); + assert.ok(listed.keys[0].expiration > Date.now() / 1000 + 3500); + + await fetchJson(b, `/kv/delete?${q({ key: 'q' })}`); + const gone = await fetchJson(b, `/kv/get?${q({ key: 'q' })}`); + assert.strictEqual(gone.body.value, null); + // Small values are inline in the object: none is in the bucket. + assert.deepStrictEqual(await bucket.list('services/kv/'), []); + + // A large value is a blob, and a listing does not read it. + for (const size of ['65536', '65537']) { + const big = { key: `big/${size}`, size, metadata: '{"b":1}' }; + await fetchJson(a, `/kv/put?${q(big)}`); + } + const blobs = await bucket.list('services/kv/'); + assert.strictEqual(blobs.length, 1, blobs.join()); + const served = () => bucket.served(`v1/${blobs[0]}`); + const before = await served(); + const bigListed = (await fetchJson(b, `/kv/list?${q({ prefix: 'big' })}`)) + .body; + assert.deepStrictEqual( + bigListed.keys.map((k) => k.name), + ['big/65536', 'big/65537'] + ); + assert.strictEqual(await served(), before); + const value = await fetchJson(b, `/kv/get?${q({ key: 'big/65537' })}`); + assert.strictEqual(value.body.value.length, 65537); + assert.strictEqual(await served(), before + 65537); + }); +}); + +// A node keeps the KV blobs it writes and reads on its disk, so it +// downloads a value once. +test('cluster: a node caches KV blobs on its disk', async () => { + await withCluster(2, async ({ nodes, bucket }) => { + const [a, b] = nodes.map((n) => n.httpPort); + const q = (params) => new URLSearchParams(params); + const MiB = 1024 * 1024; + const put = (port, key, size) => + fetchJson(port, `/kv/put?${q({ key, size: String(size) })}`); + const get = async (port, key) => + (await fetchJson(port, `/kv/get?${q({ key })}`)).body.value.length; + // Bytes the bucket served of every blob it has held. + const seen = new Set(); + const served = async () => { + for (const key of await bucket.list('services/kv/')) seen.add(key); + let n = 0; + for (const key of seen) n += await bucket.served(`v1/${key}`); + return n; + }; + + await put(a, 'k1', 1.5 * MiB); + const before = await served(); + // The writer wrote it through; another node downloads it once. + assert.strictEqual(await get(a, 'k1'), 1.5 * MiB); + assert.strictEqual(await served(), before); + for (let i = 0; i < 2; i++) { + assert.strictEqual(await get(b, 'k1'), 1.5 * MiB); + assert.strictEqual(await served(), before + 1.5 * MiB); + } + + // An overwrite is a new blob. + await put(a, 'k1', 1.25 * MiB); + assert.strictEqual(await get(a, 'k1'), 1.25 * MiB); + assert.strictEqual(await served(), before + 1.5 * MiB); + }); +}); + +// A read whose reply arrives after a newer write from the same node does +// not replace the write's entry in the node's cache. +test('cluster: a KV read racing a write keeps the write cached', async () => { + await withCluster(1, async ({ nodes }) => { + const [a] = nodes.map((n) => n.httpPort); + const q = (params) => new URLSearchParams(params); + const size = String(2 * 1024 * 1024); + await fetchJson(a, `/kv/put?${q({ key: 'race', size })}`); + await Promise.all([ + fetchJson(a, `/kv/get?${q({ key: 'race' })}`), + fetchJson(a, `/kv/put?${q({ key: 'race', value: 'new' })}`), + ]); + const now = (await fetchJson(a, `/kv/get?${q({ key: 'race' })}`)).body; + assert.deepStrictEqual([now.value, now.cacheStatus], ['new', 'HIT']); + }); +}); + +// A node's cache keeps what it read for the read's cacheTtl; another +// node's write does not reach it sooner. +test('cluster: KV reads are stale for at most cacheTtl', async () => { + await withCluster(2, async ({ nodes }) => { + const [a, b] = nodes.map((n) => n.httpPort); + const q = (params) => new URLSearchParams(params); + const read = async (port) => + (await fetchJson(port, `/kv/get?${q({ key: 's', cacheTtl: '30' })}`)) + .body; + await fetchJson(b, `/kv/put?${q({ key: 's', value: 'old' })}`); + assert.strictEqual((await read(a)).value, 'old'); + await fetchJson(b, `/kv/put?${q({ key: 's', value: 'new' })}`); + assert.strictEqual((await read(b)).value, 'new'); + const stale = await read(a); + assert.deepStrictEqual([stale.value, stale.cacheStatus], ['old', 'HIT']); + await fetchJson(a, `/kv/clock?${q({ advance: '31000' })}`); + assert.strictEqual((await read(a)).value, 'new'); + }); +}); + +// KV fails over as any object does: once a namespace's owner dies, the +// survivor reads its large values from the bucket, expires its keys, and +// collects the blobs it replaces. +test('cluster: a KV namespace survives its owner', async () => { + await withCluster(2, async ({ nodes, bucket, nodeKeys }) => { + const kv = (node, op, params) => + fetchJson(node.httpPort, `/kv/${op}?${new URLSearchParams(params)}`, { + timeoutMs: 10_000, + }); + await kv(nodes[0], 'put', { key: 'big', size: '100000' }); + await kv(nodes[0], 'put', { key: 'ttl', value: 'v', ttl: '60' }); + const records = await bucket.list(objectPrefix('', 'kv')); + const own = records.find((key) => key.endsWith('/own.json')); + const ownerKey = JSON.parse(await bucket.get(own)).node; + const owner = nodes.find((n) => nodeKeys.get(n.nodeId) === ownerKey); + const survivor = nodes.find((n) => n !== owner); + await owner.stop({ signal: 'SIGKILL', timeoutMs: 2000 }); + + // Requests fail until the dead owner's lease expires. + let got = null; + const deadline = Date.now() + 30_000; + while (Date.now() < deadline) { + got = await kv(survivor, 'get', { key: 'big' }).catch(() => null); + if (got?.status === 200) break; + await sleep(200); + } + assert.strictEqual(got?.status, 200, JSON.stringify(got?.body)); + assert.strictEqual(got.body.value.length, 100000); + + assert.strictEqual( + (await kv(survivor, 'get', { key: 'ttl' })).body.value, + 'v' + ); + await kv(survivor, 'clock', { advance: '61000' }); + assert.strictEqual( + (await kv(survivor, 'get', { key: 'ttl' })).body.value, + null + ); + const listed = await kv(survivor, 'list', { prefix: '' }); + assert.deepStrictEqual( + listed.body.keys.map((k) => k.name), + ['big'] + ); + + assert.strictEqual((await bucket.list('services/kv/')).length, 1); + await kv(survivor, 'put', { key: 'big', value: 'small' }); + const collected = Date.now() + 10_000; + while ((await bucket.list('services/kv/')).length > 0) { + assert(Date.now() < collected, 'the replaced blob was never collected'); + await sleep(100); + } + }); +}); + // Where a Durable Object's records are in the bucket: a hash of its // namespace's uniqueKey, then its ID. function objectPrefix(id, uniqueKey = 'counter-test-namespace') { diff --git a/src/workerd/server/tests/cluster/cluster-test.wd-test b/src/workerd/server/tests/cluster/cluster-test.wd-test index bca5dae5fa2..5c7c66a0314 100644 --- a/src/workerd/server/tests/cluster/cluster-test.wd-test +++ b/src/workerd/server/tests/cluster/cluster-test.wd-test @@ -46,6 +46,12 @@ const services :List(Workerd.Service) = [ ( name = "COUNTER", durableObjectNamespace = "Counter" ), ( name = "NODE_ID", fromEnvironment = "NODE_ID" ), ( name = "ON_HIBERNATE", service = "on-hibernate" ), + ( name = "KV", + kvNamespace = ( + name = "kv", props = ( json = "{\"namespace\": \"cluster-kv\"}" ) ) ), + ( name = "KV_WORKER", + service = ( + name = "kv", props = ( json = "{\"namespace\": \"cluster-kv\"}" ) ) ), ], durableObjectNamespaces = [ ( className = "Counter", uniqueKey = "counter-test-namespace" ), @@ -54,6 +60,27 @@ const services :List(Workerd.Service) = [ ) ), + # KV, whose large values are in the bucket at `services/kv/`, cached on + # each instance's disk. + ( name = "kv", + worker = ( + modules = [ ( name = "kv.js", bundled = "/workerd/kv.js" ) ], + compatibilityDate = "2026-01-01", + bindings = [ + ( name = "SHARD", durableObjectNamespace = "KVNamespace" ), + ( name = "BLOBS", service = "kv-blobs" ), + ( name = "BLOB_CACHE", service = "local" ), + ( name = "CLUSTERED", json = "true" ), + ( name = "TEST_CLOCK", json = "true" ), + ], + durableObjectNamespaces = [ + ( className = "KVNamespace", uniqueKey = "kv", enableSql = true ), + ], + durableObjectStorage = ( localDisk = "local" ), + ) + ), + ( name = "kv-blobs", bucket = ( path = "kv" ) ), + ( name = "on-hibernate", worker = ( modules = [ diff --git a/src/workerd/server/tests/cluster/cluster-worker.js b/src/workerd/server/tests/cluster/cluster-worker.js index c230cc9313a..e77c49492ea 100644 --- a/src/workerd/server/tests/cluster/cluster-worker.js +++ b/src/workerd/server/tests/cluster/cluster-worker.js @@ -102,6 +102,16 @@ export default { return env.ON_HIBERNATE.fetch(request); } + if (url.pathname.startsWith('/kv/')) { + if (url.pathname === '/kv/clock') { + await env.KV_WORKER.fetch(`http://kv/clock${url.search}`, { + method: 'POST', + }); + return Response.json({}); + } + return kv(url, env.KV); + } + // The DO name to act on is given via the `name` query parameter (defaults // to "default"). All instances using the same name will route to the same // DO id. @@ -140,6 +150,37 @@ export default { }, }; +// The KV binding, by query parameters: /kv/put?key=K&value=V (or &size=N +// for N 'x's)[&metadata=JSON] +// [&ttl=S], /kv/get?key=K[&cacheTtl=S], /kv/delete?key=K and /kv/list?prefix=P[&limit=N] +// [&cursor=C]. Answers JSON. +async function kv(url, ns) { + const q = Object.fromEntries(url.searchParams); + switch (url.pathname) { + case '/kv/put': { + const options = {}; + if (q.metadata) options.metadata = JSON.parse(q.metadata); + if (q.ttl) options.expirationTtl = Number(q.ttl); + const value = q.size ? 'x'.repeat(Number(q.size)) : q.value; + await ns.put(q.key, value, options); + return Response.json({}); + } + case '/kv/get': { + const options = q.cacheTtl ? { cacheTtl: Number(q.cacheTtl) } : {}; + return Response.json(await ns.getWithMetadata(q.key, options)); + } + case '/kv/delete': + await ns.delete(q.key); + return Response.json({}); + case '/kv/list': { + const options = { prefix: q.prefix, cursor: q.cursor }; + if (q.limit) options.limit = Number(q.limit); + return Response.json(await ns.list(options)); + } + } + return Response.json({ error: 'no such path' }, { status: 404 }); +} + // RpcTarget vended by Counter's [restore]() that mutates the counter's storage. // It runs in the Counter's context on whichever node owns the Counter. class CounterAdder extends RpcTarget { diff --git a/src/workerd/server/tests/cluster/fake-s3.js b/src/workerd/server/tests/cluster/fake-s3.js index 589735bc1b3..5e845567ac2 100644 --- a/src/workerd/server/tests/cluster/fake-s3.js +++ b/src/workerd/server/tests/cluster/fake-s3.js @@ -29,6 +29,8 @@ export class Bucket extends DurableObject { next = 0; // Requests per object key, for tests that bound a cluster's bucket traffic. requests = new Map(); + // Body bytes served per object key. + served = new Map(); faults = []; async fetch(request) { @@ -37,6 +39,9 @@ export class Bucket extends DurableObject { if (url.pathname === '/_requests') { return Response.json(this.requests.get(url.searchParams.get('key')) ?? 0); } + if (url.pathname === '/_served') { + return Response.json(this.served.get(url.searchParams.get('key')) ?? 0); + } if (url.pathname === '/_faults') { if (request.method === 'POST') { this.faults = (await request.json()).map((f) => ({ ...f, hits: 0 })); @@ -126,6 +131,7 @@ export class Bucket extends DurableObject { keys.forEach((k, i) => out.set(new Uint8Array(chunks.get(k)), i * CHUNK) ); + this.served.set(counted, (this.served.get(counted) ?? 0) + out.length); return new Response(out, { headers: { ...headers, etag: object.etag }, }); diff --git a/src/workerd/server/tests/kv/BUILD.bazel b/src/workerd/server/tests/kv/BUILD.bazel new file mode 100644 index 00000000000..070a5cdf4a1 --- /dev/null +++ b/src/workerd/server/tests/kv/BUILD.bazel @@ -0,0 +1,19 @@ +load("@aspect_rules_js//js:defs.bzl", "js_test") +load("//:build/wd_test.bzl", "wd_test") + +# Moves 25 MiB values, which takes most of 15 s on ASan and debug builds. +wd_test( + size = "large", + src = "kv-test.wd-test", + args = ["--experimental"], + data = ["kv-test.js"], +) + +# `workerd serve` of a wrangler.jsonc's kv_namespaces. +js_test( + name = "kv-wrangler-test", + data = ["//src/workerd/server:workerd"], + entry_point = "kv-wrangler-test.mjs", + env = {"WORKERD_BINARY": "$(rootpath //src/workerd/server:workerd)"}, + tags = ["js-test"], +) diff --git a/src/workerd/server/tests/kv/kv-test.js b/src/workerd/server/tests/kv/kv-test.js new file mode 100644 index 00000000000..34d8735328f --- /dev/null +++ b/src/workerd/server/tests/kv/kv-test.js @@ -0,0 +1,379 @@ +// 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 + +import assert from 'node:assert'; + +const now = () => Math.floor(Date.now() / 1000); + +// The blob files of every namespace. +async function blobs(env) { + const ls = async (path) => { + const r = await env.DISK.fetch(`http://d/${path}`); + return r.ok ? (await r.json()).map((e) => e.name) : []; + }; + const out = []; + for (const dir of await ls('')) out.push(...(await ls(`${dir}/b/`))); + return out.sort(); +} + +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +export const getPutDelete = { + async test(ctrl, env) { + assert.strictEqual(await env.KV.get('missing'), null); + await env.KV.put('k', 'v'); + assert.strictEqual(await env.KV.get('k'), 'v'); + assert.strictEqual(await env.SAME.get('k'), 'v'); + assert.strictEqual(await env.OTHER.get('k'), null); + await env.KV.put('k', new Uint8Array([1, 2, 3])); + const bytes = await env.KV.get('k', 'arrayBuffer'); + assert.deepStrictEqual(new Uint8Array(bytes), new Uint8Array([1, 2, 3])); + await env.KV.put('j', JSON.stringify({ a: [1] })); + assert.deepStrictEqual(await env.KV.get('j', 'json'), { a: [1] }); + const big = 'x'.repeat(1024 * 1024); + await env.KV.put('big', big); + assert.strictEqual(await env.KV.get('big'), big); + const odd = 'a/b c?d=e&f%20é/..'; + await env.KV.put(odd, 'odd'); + assert.strictEqual(await env.KV.get(odd), 'odd'); + await env.KV.delete('k'); + await env.KV.delete('never-there'); + assert.strictEqual(await env.KV.get('k'), null); + }, +}; + +// A value written as a stream, in chunks, inline and as a blob. +export const streamedPut = { + async test(ctrl, env) { + for (const size of [1000, 70_000, 2 * 1024 * 1024]) { + const value = Uint8Array.from({ length: size }, (_, i) => i % 251); + let sent = 0; + const stream = new ReadableStream({ + pull(c) { + c.enqueue(value.slice(sent, (sent += 16_384))); + if (sent >= size) c.close(); + }, + }); + await env.KV.put(`stream/${size}`, stream); + const got = await env.KV.get(`stream/${size}`, 'arrayBuffer'); + assert.deepStrictEqual(new Uint8Array(got), value); + } + }, +}; + +export const metadata = { + async test(ctrl, env) { + await env.KV.put('m', 'v', { metadata: { n: 1, s: 'é' } }); + const got = await env.KV.getWithMetadata('m'); + assert.deepStrictEqual(got.value, 'v'); + assert.deepStrictEqual(got.metadata, { n: 1, s: 'é' }); + await env.KV.put('m', 'w'); + assert.strictEqual((await env.KV.getWithMetadata('m')).metadata, null); + await assert.rejects( + env.KV.put('m', 'v', { metadata: { big: 'x'.repeat(2000) } }), + /413/ + ); + }, +}; + +export const expiration = { + async test(ctrl, env) { + await env.KV.put('e/ttl', 'v', { expirationTtl: 60 }); + await env.KV.put('e/at', 'v', { expiration: now() + 3600 }); + assert.strictEqual(await env.KV.get('e/ttl'), 'v'); + const { keys } = await env.KV.list({ prefix: 'e/' }); + assert.strictEqual(keys.length, 2); + const at = keys.find((k) => k.name === 'e/at').expiration; + const ttl = keys.find((k) => k.name === 'e/ttl').expiration; + assert.ok(Math.abs(at - (now() + 3600)) <= 2, `${at}`); + assert.ok(Math.abs(ttl - (now() + 60)) <= 2, `${ttl}`); + await assert.rejects(env.KV.put('e/x', 'v', { expirationTtl: 10 }), /400/); + await assert.rejects( + env.KV.put('e/x', 'v', { expiration: now() - 10 }), + /400/ + ); + }, +}; + +export const list = { + async test(ctrl, env) { + for (const k of ['p/a', 'p/b', 'p/c', 'p/d', 'p/e', 'q']) { + await env.KV.put(k, '', { metadata: { k } }); + } + let page = await env.KV.list({ prefix: 'p/', limit: 2 }); + assert.deepStrictEqual( + page.keys.map((k) => k.name), + ['p/a', 'p/b'] + ); + assert.deepStrictEqual(page.keys[0].metadata, { k: 'p/a' }); + assert.strictEqual(page.list_complete, false); + const names = page.keys.map((k) => k.name); + while (!page.list_complete) { + page = await env.KV.list({ prefix: 'p/', limit: 2, cursor: page.cursor }); + names.push(...page.keys.map((k) => k.name)); + } + assert.deepStrictEqual(names, ['p/a', 'p/b', 'p/c', 'p/d', 'p/e']); + const all = await env.OTHER.list(); + assert.deepStrictEqual(all.keys, []); + assert.strictEqual(all.list_complete, true); + }, +}; + +export const bulk = { + async test(ctrl, env) { + await env.KV.put('b1', '"one"', { metadata: 1 }); + await env.KV.put('b2', '2'); + const got = await env.KV.get(['b1', 'b2', 'nope']); + assert.deepStrictEqual( + [...got], + [ + ['b1', '"one"'], + ['b2', '2'], + ['nope', null], + ] + ); + const json = await env.KV.getWithMetadata(['b1', 'b2'], 'json'); + assert.deepStrictEqual(json.get('b1'), { value: 'one', metadata: 1 }); + assert.deepStrictEqual(json.get('b2'), { value: 2, metadata: null }); + // Bytes that are not UTF-8 read as text, as a single get does. + await env.KV.put('b3', new Uint8Array([0xff, 0x61])); + assert.strictEqual((await env.KV.get(['b3'])).get('b3'), '\ufffda'); + await assert.rejects(env.KV.get(['b3'], 'json'), /non-json/); + }, +}; + +// Up to 64 KiB is inline in the index; more is a blob. +export const threshold = { + async test(ctrl, env) { + const before = (await blobs(env)).length; + const at = 'x'.repeat(64 * 1024); + await env.KV.put('t/at', at); + assert.strictEqual((await blobs(env)).length, before); + await env.KV.put('t/over', at + 'y'); + assert.strictEqual((await blobs(env)).length, before + 1); + assert.strictEqual(await env.OTHER.get('t/over'), null); + assert.strictEqual(await env.KV.get('t/at'), at); + assert.strictEqual(await env.KV.get('t/over'), at + 'y'); + await env.KV.delete('t/at'); + await env.KV.delete('t/over'); + }, +}; + +// An overwritten or deleted blob is deleted once its grace period, shortened +// by `TEST_CLOCK`, is over. +export const blobGc = { + async test(ctrl, env) { + await sleep(500); + const before = await blobs(env); + const big = (c) => c.repeat(100_000); + await env.KV.put('gc', big('a')); + await env.KV.put('gc', big('b')); + assert.strictEqual((await blobs(env)).length, before.length + 2); + assert.strictEqual(await env.KV.get('gc'), big('b')); + await sleep(500); + assert.strictEqual((await blobs(env)).length, before.length + 1); + await env.KV.put('gc', 'small'); + await env.KV.put('gc2', big('c')); + await env.KV.delete('gc2'); + await sleep(500); + assert.deepStrictEqual(await blobs(env), before); + assert.strictEqual(await env.KV.get('gc'), 'small'); + assert.strictEqual(await env.KV.get('gc2'), null); + }, +}; + +export const listInlineAndBlobs = { + async test(ctrl, env) { + const big = 'z'.repeat(70_000); + await env.KV.put('mix/a', 'a', { metadata: 'a' }); + await env.KV.put('mix/b', big, { metadata: 'b' }); + await env.KV.put('mix/c', 'c', { metadata: 'c' }); + const page = await env.KV.list({ prefix: 'mix/', limit: 2 }); + assert.deepStrictEqual(page.keys, [ + { name: 'mix/a', metadata: 'a' }, + { name: 'mix/b', metadata: 'b' }, + ]); + const rest = await env.KV.list({ prefix: 'mix/', cursor: page.cursor }); + assert.deepStrictEqual(rest.keys, [{ name: 'mix/c', metadata: 'c' }]); + assert.strictEqual(rest.list_complete, true); + const got = await env.KV.get(['mix/a', 'mix/b']); + assert.strictEqual(got.get('mix/b'), big); + }, +}; + +// Locally nothing is cached: another process on the same storage, as +// `wrangler kv key put --local` is, must be seen at once (kv-wrangler-test). +// The cluster's cache is cluster-test's. +export const cacheTtl = { + async test(ctrl, env) { + await env.KV.put('c', 'v'); + assert.strictEqual(await env.KV.get('c', { cacheTtl: 30 }), 'v'); + await assert.rejects( + env.KV.get('c', { cacheTtl: 29 }), + /400 Invalid cache_ttl of 29. Cache TTL must be at least 30./ + ); + const got = await env.KV.getWithMetadata('c'); + assert.deepStrictEqual([got.value, got.cacheStatus], ['v', 'MISS']); + }, +}; + +// A read racing a write from the same process. +export const readRacesWrite = { + async test(ctrl, env) { + const old = 'o'.repeat(2 * 1024 * 1024); + await env.KV.put('race', old); + const [got] = await Promise.all([ + env.KV.get('race'), + env.KV.put('race', 'new'), + ]); + assert.ok(got === old || got === 'new'); + assert.strictEqual(await env.KV.get('race'), 'new'); + }, +}; + +// The errors production gives, as Miniflare's KV tests check them. +export const errors = { + async test(ctrl, env) { + const fails = (p, text) => + assert.rejects(p, (e) => { + assert.strictEqual(e.message, text); + return true; + }); + const t = now(); + const put = (options) => env.KV.put('k', 'v', options); + for (const ttl of [0, -5]) { + await fails( + put({ expirationTtl: ttl }), + `KV PUT failed: 400 Invalid expiration_ttl of ${ttl}. Please ` + + 'specify integer greater than 0.' + ); + } + await fails( + put({ expirationTtl: 30 }), + 'KV PUT failed: 400 Invalid expiration_ttl of 30. Expiration TTL ' + + 'must be at least 60.' + ); + for (const at of [t, -5]) { + await fails( + put({ expiration: at }), + `KV PUT failed: 400 Invalid expiration of ${at}. Please specify ` + + 'integer greater than the current number of seconds since the ' + + 'UNIX epoch.' + ); + } + await fails( + put({ expiration: t + 30 }), + `KV PUT failed: 400 Invalid expiration of ${t + 30}. Expiration ` + + 'times must be at least 60 seconds in the future.' + ); + const max = 25 * 1024 * 1024; + await fails( + env.KV.put('k', new Uint8Array(max + 1)), + `KV PUT failed: 413 Value length of ${max + 1} exceeds limit of ${max}.` + ); + // Metadata counts in UTF-8 bytes: "é…é" is 2 + 2n of them. + await put({ metadata: 'é'.repeat(511) }); + await fails( + put({ metadata: 'é'.repeat(512) }), + 'KV PUT failed: 413 Metadata length of 1026 exceeds limit of 1024.' + ); + await fails( + env.KV.list({ limit: 1001 }), + 'KV GET failed: 400 Invalid key_count_limit of 1001. Please specify ' + + 'an integer less than 1000.' + ); + await fails( + env.KV.list({ prefix: 'p'.repeat(513) }), + 'KV GET failed: 414 UTF-8 encoded length of 513 exceeds key length ' + + 'limit of 512.' + ); + const keys = Array.from({ length: 101 }, (_, i) => `k${i}`); + await fails( + env.KV.get(keys), + 'KV GET_BULK failed: 400 You can request a maximum of 100 keys' + ); + await fails( + env.KV.get([]), + 'KV GET_BULK failed: 400 You must request a minimum of 1 key' + ); + await fails( + env.KV.get(['a', '']), + 'KV GET_BULK failed: 400 Key names must not be empty' + ); + await fails( + env.KV.get(['a', '..']), + 'KV GET_BULK failed: 400 Illegal key name "..". Please use a ' + + 'different name.' + ); + await fails( + env.KV.get(['a', 'k'.repeat(513)]), + 'KV GET_BULK failed: 414 UTF-8 encoded length of 513 exceeds key ' + + 'length limit of 512.' + ); + const half = 'x'.repeat(13 * 1024 * 1024); + await env.KV.put('half1', half); + await env.KV.put('half2', half); + await fails( + env.KV.get(['half1', 'half2']), + 'KV GET_BULK failed: 413 Total size of request exceeds the limit of ' + + '25MB' + ); + assert.strictEqual((await env.KV.get(['half1'])).get('half1'), half); + }, +}; + +// A malformed key escape or a bulk body that isn't an object is a 400. +export const malformedRequests = { + async test(ctrl, env) { + const bad = await env.KV_WORKER.fetch('http://kv/%E0%A4%A'); + assert.strictEqual(bad.status, 400); + const bulk = await env.KV_WORKER.fetch('http://kv/bulk/get', { + method: 'POST', + body: 'null', + }); + assert.strictEqual(bulk.status, 400); + }, +}; + +// Keys disappear from get and list once the expiration clock passes them. +export const expiry = { + async test(ctrl, env) { + await env.KV.put('x/ttl', 'v', { expirationTtl: 60 }); + await env.KV.put('x/at', 'v', { expiration: now() + 120 }); + await env.KV.put('x/forever', 'v'); + const advance = (s) => + env.KV_WORKER.fetch(`http://kv/clock?advance=${s * 1000}`, { + method: 'POST', + }); + try { + await advance(61); + assert.strictEqual(await env.KV.get('x/ttl'), null); + assert.strictEqual(await env.KV.get('x/at'), 'v'); + let { keys } = await env.KV.list({ prefix: 'x/' }); + assert.deepStrictEqual( + keys.map((k) => k.name), + ['x/at', 'x/forever'] + ); + await advance(60); + assert.strictEqual(await env.KV.get('x/at'), null); + ({ keys } = await env.KV.list({ prefix: 'x/' })); + assert.deepStrictEqual( + keys.map((k) => k.name), + ['x/forever'] + ); + } finally { + await advance(-121); + } + }, +}; + +// A key whose name is a URL's special characters. +export const keyNames = { + async test(ctrl, env) { + for (const key of ['a/../b', '.a', '?', '#', '%', ' ', 'bulk/get']) { + await env.KV.put(key, key); + assert.strictEqual(await env.KV.get(key), key); + } + }, +}; diff --git a/src/workerd/server/tests/kv/kv-test.wd-test b/src/workerd/server/tests/kv/kv-test.wd-test new file mode 100644 index 00000000000..0508a52937d --- /dev/null +++ b/src/workerd/server/tests/kv/kv-test.wd-test @@ -0,0 +1,40 @@ +using Workerd = import "/workerd/workerd.capnp"; + +const unitTests :Workerd.Config = ( + services = [ + ( name = "TEST_TMPDIR", disk = (writable = true) ), + ( name = "kv-test", + worker = ( + modules = [ ( name = "worker", esModule = embed "kv-test.js" ) ], + compatibilityFlags = ["nodejs_compat", "streams_enable_constructors"], + bindings = [ + ( name = "KV", + kvNamespace = ( name = "kv", props = ( json = "{\"namespace\": \"test\"}" ) ) ), + ( name = "SAME", + kvNamespace = ( name = "kv", props = ( json = "{\"namespace\": \"test\"}" ) ) ), + ( name = "OTHER", + kvNamespace = ( name = "kv", props = ( json = "{\"namespace\": \"other\"}" ) ) ), + ( name = "KV_WORKER", + service = ( name = "kv", props = ( json = "{\"namespace\": \"test\"}" ) ) ), + ( name = "DISK", service = "TEST_TMPDIR" ), + ], + ) + ), + # Its objects and large values both in TEST_TMPDIR. + ( name = "kv", + worker = ( + modules = [ ( name = "kv.js", bundled = "/workerd/kv.js" ) ], + compatibilityFlags = ["rpc"], + bindings = [ + ( name = "SHARD", durableObjectNamespace = "KVNamespace" ), + ( name = "BLOBS", service = "TEST_TMPDIR" ), + ( name = "TEST_CLOCK", json = "true" ), + ], + durableObjectNamespaces = [ + ( className = "KVNamespace", uniqueKey = "KVNamespace", enableSql = true ), + ], + durableObjectStorage = ( localDisk = "TEST_TMPDIR" ), + ) + ), + ], +); diff --git a/src/workerd/server/tests/kv/kv-wrangler-test.mjs b/src/workerd/server/tests/kv/kv-wrangler-test.mjs new file mode 100644 index 00000000000..ba220a394f1 --- /dev/null +++ b/src/workerd/server/tests/kv/kv-wrangler-test.mjs @@ -0,0 +1,145 @@ +// 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 +// +// `workerd serve` of a wrangler.jsonc with two kv_namespaces: each is its +// own namespace, values persist across a restart, and without +// --experimental the server refuses to start and says why. + +import { spawn } from 'node:child_process'; +import { mkdtemp, stat, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { env } from 'node:process'; +import { test } from 'node:test'; +import assert from 'node:assert'; + +const WRANGLER = { + name: 'kv', + main: 'index.js', + compatibility_date: '2026-01-01', + no_bundle: true, + kv_namespaces: [ + { binding: 'A', id: 'a' }, + { binding: 'B', id: 'b' }, + ], +}; + +// //: PUT the body, GET, DELETE. +const WORKER = `export default { + async fetch(request, env) { + const [, binding, key] = new URL(request.url).pathname.split('/'); + const kv = env[binding]; + if (request.method === 'PUT') { + await kv.put(key, request.body); + return new Response(null, { status: 204 }); + } + if (request.method === 'DELETE') { + await kv.delete(key); + return new Response(null, { status: 204 }); + } + const value = await kv.get(key); + return new Response(value, { status: value === null ? 404 : 200 }); + }, +}; +`; + +const CONTROL_FD = 3; + +// Runs workerd on `dir`'s wrangler.jsonc until it listens, or until it +// exits. Answers {port, stop} or {code, stderr}. +function serve(dir, args) { + const child = spawn( + env.WORKERD_BINARY, + [ + 'serve', + join(dir, 'wrangler.jsonc'), + `--control-fd=${CONTROL_FD}`, + '--socket-addr=http=127.0.0.1:0', + ...args, + ], + { stdio: ['ignore', 'inherit', 'pipe', 'pipe'] } + ); + let stderr = ''; + child.stderr.on('data', (d) => { + stderr += d; + process.stderr.write(d); + }); + const exited = new Promise((resolve) => child.once('exit', resolve)); + return new Promise((resolve, reject) => { + let buffer = ''; + child.stdio[CONTROL_FD].on('data', (d) => { + buffer += d; + for (const line of buffer.split('\n').slice(0, -1)) { + const m = JSON.parse(line); + if (m.event === 'listen') { + const stop = () => (child.kill(), exited); + resolve({ port: m.port, stop }); + } + } + buffer = buffer.slice(buffer.lastIndexOf('\n') + 1); + }); + child.once('error', reject); + exited.then((code) => resolve({ code, stderr })); + }); +} + +test('kv_namespaces in a wrangler.jsonc', async () => { + const dir = await mkdtemp(join(env.TEST_TMPDIR ?? tmpdir(), 'kv-')); + await writeFile(join(dir, 'wrangler.jsonc'), JSON.stringify(WRANGLER)); + await writeFile(join(dir, 'index.js'), WORKER); + + const refused = await serve(dir, []); + assert.notStrictEqual(refused.code, 0); + assert.match(refused.stderr, /kv_namespaces.*--experimental/s); + + const big = 'x'.repeat(70_000); + let server = await serve(dir, ['--experimental']); + const url = (path) => `http://127.0.0.1:${server.port}${path}`; + const put = async (path, body) => + assert.strictEqual( + (await fetch(url(path), { method: 'PUT', body })).status, + 204 + ); + const get = async (path) => { + const r = await fetch(url(path)); + return r.status === 404 ? null : await r.text(); + }; + await put('/A/k', 'in a'); + await put('/B/k', 'in b'); + await put('/A/big', big); + assert.strictEqual(await get('/A/k'), 'in a'); + assert.strictEqual(await get('/B/k'), 'in b'); + assert.strictEqual(await get('/B/big'), null); + await server.stop(); + + server = await serve(dir, ['--experimental']); + assert.strictEqual(await get('/A/k'), 'in a'); + assert.strictEqual(await get('/A/big'), big); + await fetch(url('/A/k'), { method: 'DELETE' }); + assert.strictEqual(await get('/A/k'), null); + assert.strictEqual(await get('/B/k'), 'in b'); + await server.stop(); + const storage = join(dir, '.wrangler/state/workerd/kv'); + assert.ok((await stat(join(storage, 'KVNamespace'))).isDirectory()); + + // Two processes on the same storage, as `wrangler dev` and `wrangler kv + // key put --local` are: each sees the other's writes at once, misses + // included, since nothing is cached outside a cluster. + const [one, two] = [ + await serve(dir, ['--experimental']), + await serve(dir, ['--experimental']), + ]; + const at = (s, path) => `http://127.0.0.1:${s.port}${path}`; + const read = async (s, path) => { + const r = await fetch(at(s, path)); + return r.status === 404 ? null : await r.text(); + }; + assert.strictEqual(await read(one, '/A/shared'), null); + await fetch(at(two, '/A/shared'), { method: 'PUT', body: 'from two' }); + assert.strictEqual(await read(one, '/A/shared'), 'from two'); + await fetch(at(two, '/A/shared'), { method: 'DELETE' }); + assert.strictEqual(await read(one, '/A/shared'), null); + await one.stop(); + await two.stop(); +}); diff --git a/src/workerd/server/workerd-api.c++ b/src/workerd/server/workerd-api.c++ index 9fb1fc6b724..934e53d8412 100644 --- a/src/workerd/server/workerd-api.c++ +++ b/src/workerd/server/workerd-api.c++ @@ -18,6 +18,7 @@ #endif // defined(WORKERD_USE_TRANSPILER) #include #include +#include #include #include #include @@ -30,6 +31,7 @@ #include #include #include +#include using namespace kj_rs; @@ -44,6 +46,16 @@ static const PythonConfig defaultConfig{ .createBaselineSnapshot = false, }; +// The sources of the ES modules a config names with `Worker.Module.bundled`. +kj::Maybe findBundled(kj::StringPtr name) { + static const auto bundled = [] { + kj::HashMap map; + map.insert("/workerd/kv.js"_kj, KV_JS); + return map; + }(); + return bundled.find(name).map([](auto& source) { return source; }); +} + // An ActorStorage implementation which will always respond to reads as if the state is empty, // and will fail any writes. class EmptyReadOnlyActorStorageImpl final: public rpc::ActorStorage::Stage::Server { @@ -398,6 +410,18 @@ Worker::Script::Module WorkerdApi::readModuleConf(config::Worker::Module::Reader } case config::Worker::Module::PYTHON_MODULE: return Worker::Script::PythonModule{conf.getPythonModule()}; + case config::Worker::Module::BUNDLED: { + auto name = conf.getBundled(); + KJ_IF_SOME(source, findBundled(name)) { + return Worker::Script::EsModule{source}; + } + auto message = kj::str("No bundled module named \"", name, "\"."); + KJ_IF_SOME(e, errorReporter) { + e.addError(kj::mv(message)); + return Worker::Script::TextModule{""}; + } + KJ_FAIL_REQUIRE(message); + } case config::Worker::Module::OBSOLETE_PYTHON_REQUIREMENT: KJ_FAIL_REQUIRE( "NOSENTRY Worker bundle specified Python requirement which is no longer supported"); diff --git a/src/workerd/server/workerd.capnp b/src/workerd/server/workerd.capnp index afb711f4093..bc79bba9fb1 100644 --- a/src/workerd/server/workerd.capnp +++ b/src/workerd/server/workerd.capnp @@ -403,6 +403,9 @@ struct Service { # An HTTP service backed by a directory on disk, supporting a basic HTTP GET/PUT. Generally # not intended to be exposed directly to the internet; typically you want to bind this into # a Worker that adds logic for setting Content-Type and the like. + + bucket @6 :ClusterBucket; + # A directory in the cluster's bucket, served over HTTP. Requires `Config.cluster`. } # TODO(someday): Allow defining a list of middlewares to stack on top of the service. This would @@ -411,6 +414,17 @@ struct Service { # pointing to the service itself (or to the next middleware in the stack). } +struct ClusterBucket { + # GET, PUT and DELETE on `/` read, write and remove the object + # `services//` in the cluster's bucket (`Config.cluster`), so + # that every instance sees the same files. The cluster keeps its own state outside + # `services/`, where this service cannot reach it. A binding to this service grants only its + # directory, as a writable `disk` does. Experimental: requires `--experimental`. + + path @0 :Text; + # The directory below `services/`: one or more `/`-separated names, none `.` or `..`. +} + struct ServiceDesignator { # A reference to a service from elsewhere in the config file, e.g. from a service binding in a # Worker. @@ -553,6 +567,11 @@ struct Worker { obsoletePythonRequirement @9 :Text; # This position used to be the pythonRequirement type that has now been deprecated. + + bundled @11 :Text; + # An ES module whose source is bundled with workerd, by name: `/workerd/kv.js`, the KV + # Worker (see its header for the bindings it takes). Unlike built-in modules such as + # `node:` ones, user code cannot import it; it is a Worker's source. Experimental. } namedExports @10 :List(Text);