diff --git a/src/workerd/server/AGENTS.md b/src/workerd/server/AGENTS.md index 1ab529f41a2..fe276bc5b0b 100644 --- a/src/workerd/server/AGENTS.md +++ b/src/workerd/server/AGENTS.md @@ -54,13 +54,13 @@ Bazel labels: `//src/workerd/server:workerd`, `//src/workerd/server:workerd-cli` | `lib.rs` | Crate root: `main()`, the commands, the server's `Watch` future for `--watch` | | `args.rs` | clap definitions | | `help.rs` | The help pages, written by hand; `args-test.rs` checks them against the parser | -| `config.rs` | Config sources (schema file, compiled binary, embedded) and the synthesized Python config; for `serve`, an empty cluster key and bucket filled from `WORKERD_CLUSTER_KEY` or `WORKERD_CLUSTER_KEY_FILE` and `WORKERD_CLUSTER_BUCKET` (`with_cluster_environment`), and an error if still empty | +| `config.rs` | Config sources (schema file, compiled binary, embedded) and the synthesized Python config; for `serve`, in one pass (`with_cluster`), `--cluster-addr` joining a config without `cluster` to one, refused for a compiled binary's config and for one without a writable `do-storage` disk, and an empty cluster key and bucket filled from `WORKERD_CLUSTER_KEY` or `WORKERD_CLUSTER_KEY_FILE` and `WORKERD_CLUSTER_BUCKET`, an error if still empty | | `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; `r2_buckets` become `r2Bucket` bindings to `-r2` (`r2/r2.js`), whose objects are in a local `bucket` store; `queues` become `queue` bindings to `-queues` (`queues/queues.js`), whose consumers deliver to the Worker; `workflows` run on the engine `-workflows` (`workflows/workflows.js`), the Worker's `workflowsEngine`; `d1_databases` become D1 bindings to `-d1` (`d1/d1.js`); `secrets_store_secrets` become service bindings to the `SecretsStoreSecret` entrypoint of `-secrets-store` (`secrets-store/secrets-store.js`), values from the variables `WORKERD_SECRET_`; `ratelimits` become service bindings to the `RateLimit` entrypoint of `-ratelimit` (`ratelimit/ratelimit.js`), settings in props, which counts in memory; tests in `tests/kv/`, `tests/r2/`, `tests/queues/`, `tests/workflows/`, `tests/d1/`, `tests/secrets-store/` and `tests/ratelimit/` | +| `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; `r2_buckets` become `r2Bucket` bindings to `-r2` (`r2/r2.js`), whose objects are in a local `bucket` store, or in a cluster in the cluster's bucket; `queues` become `queue` bindings to `-queues` (`queues/queues.js`), whose consumers deliver to the Worker; `workflows` run on the engine `-workflows` (`workflows/workflows.js`), the Worker's `workflowsEngine`; `d1_databases` become D1 bindings to `-d1` (`d1/d1.js`); `secrets_store_secrets` become service bindings to the `SecretsStoreSecret` entrypoint of `-secrets-store` (`secrets-store/secrets-store.js`), values from the variables `WORKERD_SECRET_`; `ratelimits` become service bindings to the `RateLimit` entrypoint of `-ratelimit` (`ratelimit/ratelimit.js`), settings in props, which counts in memory; tests in `tests/kv/`, `tests/r2/`, `tests/queues/`, `tests/workflows/`, `tests/d1/`, `tests/secrets-store/` and `tests/ratelimit/`. When served, Durable Objects are on the disk service `-do-storage`, or on `do-storage` (`CLUSTER_STORAGE`) when `--cluster-addr` joins a cluster; a joined config defines that disk, in the state directory's `do/`, even without Durable Objects of its own, for those of the cluster's deployments, and cannot have `kv_namespaces` or `queues` yet. The state directory, `.wrangler/state/workerd` in the project unless `--data-dir` names another, holds every disk and the Cache API's entries | | `bridge.rs` | The cxx bridge (`workerd::server::cli`) to `config-compiler.h` and the build facts in `factory/bootstrap.h`; header `` | ### `server/` (`workerd-server`) @@ -88,7 +88,7 @@ Bazel labels: `//src/workerd/server:workerd`, `//src/workerd/server:workerd-cli` | `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 | -| `cron.rs` | Cron triggers (`cron/cron.js`, the bundled module): one scheduled event at startup to each Worker that uses the module, which arms its schedules, and a listener that keeps the server up until it drains; tests in `tests/cron/` and `tests/cluster/` | +| `cron.rs` | Cron triggers (`cron/cron.js`, the bundled module): one scheduled event at startup to each Worker that uses the module, which arms its schedules, and a listener that keeps the server up until it drains; tests in `tests/cron/` and `tests/cluster/` | | `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 | diff --git a/src/workerd/server/cli/args-test.rs b/src/workerd/server/cli/args-test.rs index c814f7fbde9..477b42f60f9 100644 --- a/src/workerd/server/cli/args-test.rs +++ b/src/workerd/server/cli/args-test.rs @@ -75,6 +75,7 @@ fn serve_options() { "--async-trace-promises", "--cluster-addr=0.0.0.0:7000", "--cluster-advertise=10.0.0.4:7000", + "--data-dir=/var/lib/workerd", ]) .command else { @@ -97,6 +98,7 @@ fn serve_options() { assert_eq!(serve.control_fd, Some(3)); assert_eq!(serve.cluster_address.as_deref(), Some("0.0.0.0:7000")); assert_eq!(serve.cluster_advertise.as_deref(), Some("10.0.0.4:7000")); + assert_eq!(serve_or_test.data_dir.as_deref(), Some("/var/lib/workerd")); assert_eq!( serve.socket_addr_overrides, [Override { diff --git a/src/workerd/server/cli/args.rs b/src/workerd/server/cli/args.rs index 41d6d4fc100..e5937e5ed00 100644 --- a/src/workerd/server/cli/args.rs +++ b/src/workerd/server/cli/args.rs @@ -145,6 +145,9 @@ pub struct ServeOrTestArgs { #[arg(short = 'd', long = "directory-path", value_name = "name>=, + #[arg(long, value_name = "dir")] + pub data_dir: Option, + #[arg(short = 'e', long = "external-addr", value_name = "name>=, diff --git a/src/workerd/server/cli/config-test.rs b/src/workerd/server/cli/config-test.rs index 714cfcd945c..987cf9263d4 100644 --- a/src/workerd/server/cli/config-test.rs +++ b/src/workerd/server/cli/config-test.rs @@ -43,6 +43,21 @@ fn cluster_config(cluster: Option<(&str, &str)>) -> Config { ))) } +/// A config without a cluster that can join one: it defines the disk service `do-storage`. +fn joinable_config() -> Config { + let mut message = capnp::message::Builder::new_default(); + let mut services = message.init_root::().init_services(2); + services.reborrow().get(0).set_name("main"); + let mut storage = services.get(1); + storage.set_name(CLUSTER_STORAGE); + let mut disk = storage.init_disk(); + disk.set_path("/var/lib/workerd/do"); + disk.set_writable(true); + Config(words_from_bytes(&capnp::serialize::write_message_to_words( + &message, + ))) +} + /// The cluster's key and bucket in `config`. fn cluster_of(config: &Config) -> (String, String) { let message = read(config); @@ -58,6 +73,30 @@ fn cluster_of(config: &Config) -> (String, String) { ) } +/// [`Config::with_cluster`] in its two halves, as most tests take them. +trait Halves: Sized { + /// Fills the key and bucket from `var`, joining no cluster. + fn fill(self, var: impl Fn(&str) -> Option) -> Result; + /// Joins a cluster at `address` as `serve` does, filling nothing. + fn join(self, address: Option<&str>, advertise: Option<&str>) -> Result; +} + +impl Halves for Config { + fn fill(self, var: impl Fn(&str) -> Option) -> Result { + let var: Env<'_> = &var; + (self.with_cluster(&ClusterFlags::default(), Some(var))).map_err(|e| e.to_string()) + } + + fn join(self, address: Option<&str>, advertise: Option<&str>) -> Result { + let flags = ClusterFlags { + address, + advertise, + can_join: true, + }; + self.with_cluster(&flags, None).map_err(|e| e.to_string()) + } +} + /// An environment of `vars`. fn env<'a>(vars: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option + 'a { move |name| { @@ -93,9 +132,7 @@ const KEY: &str = "0123456789abcdef0123456789abcdef"; #[test] fn cluster_environment_fills_an_empty_key_and_bucket() { let vars = [(CLUSTER_KEY, KEY), (CLUSTER_BUCKET, "s3://bucket/prefix")]; - let config = cluster_config(Some(("", ""))) - .with_cluster_environment(env(&vars)) - .unwrap(); + let config = cluster_config(Some(("", ""))).fill(env(&vars)).unwrap(); assert_eq!( cluster_of(&config), (KEY.to_owned(), "s3://bucket/prefix".to_owned()) @@ -110,7 +147,7 @@ fn cluster_environment_does_not_replace_config_values() { ]; let config = cluster_config(Some((KEY, "s3://bucket/prefix"))); let before = config.0.clone(); - let config = config.with_cluster_environment(env(&vars)).unwrap(); + let config = config.fill(env(&vars)).unwrap(); assert_eq!(config.0, before); } @@ -119,7 +156,7 @@ fn cluster_environment_leaves_a_config_without_cluster_unchanged() { let vars = [(CLUSTER_KEY, KEY), (CLUSTER_BUCKET, "s3://bucket/prefix")]; let config = cluster_config(None); let before = config.0.clone(); - let config = config.with_cluster_environment(env(&vars)).unwrap(); + let config = config.fill(env(&vars)).unwrap(); assert_eq!(config.0, before); } @@ -128,7 +165,7 @@ fn cluster_environment_reads_the_key_file_without_trailing_whitespace() { let file = TempFile::new("workerd-cluster-key-test", format!("{KEY}\n")); let vars = [(CLUSTER_KEY_FILE, file.path())]; let config = cluster_config(Some(("", "s3://bucket/prefix"))) - .with_cluster_environment(env(&vars)) + .fill(env(&vars)) .unwrap(); assert_eq!(cluster_of(&config).0, KEY); } @@ -138,7 +175,7 @@ fn cluster_environment_trims_the_key_variable() { let key = format!("{KEY} \n"); let vars = [(CLUSTER_KEY, key.as_str())]; let config = cluster_config(Some(("", "s3://bucket/prefix"))) - .with_cluster_environment(env(&vars)) + .fill(env(&vars)) .unwrap(); assert_eq!(cluster_of(&config).0, KEY); } @@ -146,9 +183,7 @@ fn cluster_environment_trims_the_key_variable() { #[test] fn cluster_environment_trims_the_bucket_variable() { let vars = [(CLUSTER_BUCKET, "s3://bucket/prefix\n")]; - let config = cluster_config(Some((KEY, ""))) - .with_cluster_environment(env(&vars)) - .unwrap(); + let config = cluster_config(Some((KEY, ""))).fill(env(&vars)).unwrap(); assert_eq!(cluster_of(&config).1, "s3://bucket/prefix"); } @@ -170,9 +205,7 @@ fn cluster_environment_refuses_a_short_key_naming_its_source() { ), ), ] { - let Err(error) = - cluster_config(Some(("", "s3://bucket/prefix"))).with_cluster_environment(env(&vars)) - else { + let Err(error) = cluster_config(Some(("", "s3://bucket/prefix"))).fill(env(&vars)) else { panic!("expected an error for {vars:?}"); }; assert_eq!(error, expected); @@ -205,7 +238,7 @@ fn cluster_environment_requires_a_key_and_bucket() { missing_bucket.to_owned(), ), ] { - let Err(error) = cluster_config(Some(cluster)).with_cluster_environment(env(&vars)) else { + let Err(error) = cluster_config(Some(cluster)).fill(env(&vars)) else { panic!("expected an error for {cluster:?} and {vars:?}"); }; assert_eq!(error, expected); @@ -216,7 +249,7 @@ fn cluster_environment_requires_a_key_and_bucket() { fn cluster_environment_refuses_a_key_file_that_is_not_text() { let file = TempFile::new("workerd-cluster-key-binary-test", [0xff, 0xfe, 0x00, 0x80]); let vars = [(CLUSTER_KEY_FILE, file.path())]; - let Err(error) = cluster_config(Some(("", ""))).with_cluster_environment(env(&vars)) else { + let Err(error) = cluster_config(Some(("", ""))).fill(env(&vars)) else { panic!("expected an error"); }; assert_eq!( @@ -232,7 +265,7 @@ fn cluster_environment_refuses_a_key_file_that_is_not_text() { fn cluster_environment_refuses_both_key_variables() { let file = TempFile::new("workerd-cluster-key-both-test", KEY); let vars = [(CLUSTER_KEY, KEY), (CLUSTER_KEY_FILE, file.path())]; - let Err(error) = cluster_config(Some(("", ""))).with_cluster_environment(env(&vars)) else { + let Err(error) = cluster_config(Some(("", ""))).fill(env(&vars)) else { panic!("expected an error"); }; assert_eq!( @@ -250,7 +283,7 @@ fn cluster_environment_refuses_a_key_file_that_is_not_a_regular_file_or_too_larg (large.path(), "larger than 4096 bytes"), ] { let vars = [(CLUSTER_KEY_FILE, path)]; - let Err(error) = cluster_config(Some(("", ""))).with_cluster_environment(env(&vars)) else { + let Err(error) = cluster_config(Some(("", ""))).fill(env(&vars)) else { panic!("expected an error for {path}"); }; assert_eq!( @@ -269,7 +302,7 @@ fn cluster_environment_refuses_a_fifo_as_the_key_file_without_blocking() { // SAFETY: `c_path` is a valid NUL-terminated path. assert_eq!(unsafe { libc::mkfifo(c_path.as_ptr(), 0o600) }, 0); let vars = [(CLUSTER_KEY_FILE, path.to_str().unwrap())]; - let result = cluster_config(Some(("", ""))).with_cluster_environment(env(&vars)); + let result = cluster_config(Some(("", ""))).fill(env(&vars)); let _ = std::fs::remove_file(&path); let Err(error) = result else { panic!("expected an error"); @@ -280,7 +313,7 @@ fn cluster_environment_refuses_a_fifo_as_the_key_file_without_blocking() { #[test] fn cluster_environment_reports_an_unreadable_key_file() { let vars = [(CLUSTER_KEY_FILE, "/nonexistent/workerd-cluster-key")]; - let Err(error) = cluster_config(Some(("", ""))).with_cluster_environment(env(&vars)) else { + let Err(error) = cluster_config(Some(("", ""))).fill(env(&vars)) else { panic!("expected an error"); }; assert!( @@ -288,3 +321,140 @@ fn cluster_environment_reports_an_unreadable_key_file() { "{error}" ); } + +#[test] +fn cluster_address_joins_a_config_without_cluster_with_defaults() { + let config = joinable_config().join(Some("10.0.0.4:7000"), None).unwrap(); + let message = read(&config); + let cluster = message + .get_root::() + .unwrap() + .get_cluster() + .unwrap(); + assert_eq!(cluster.get_address().unwrap(), "10.0.0.4:7000"); + assert!(!cluster.has_advertise()); + assert!(!cluster.has_bucket_options()); + assert_eq!(cluster.get_stop_timeout_ms(), 8000); + assert!(!cluster.get_unsafe_public_address()); + // The key and bucket are left to the environment. + let vars = [(CLUSTER_KEY, KEY), (CLUSTER_BUCKET, "s3://bucket/prefix")]; + let config = config.fill(env(&vars)).unwrap(); + assert_eq!( + cluster_of(&config), + (KEY.to_owned(), "s3://bucket/prefix".to_owned()) + ); +} + +#[test] +fn cluster_address_leaves_a_config_with_cluster_unchanged() { + let config = cluster_config(Some((KEY, "s3://bucket/prefix"))); + let before = config.0.clone(); + let config = config + .join(Some("10.0.0.4:7000"), Some("10.0.0.4:7000")) + .unwrap(); + assert_eq!(config.0, before); +} + +#[test] +fn without_cluster_address_a_config_without_cluster_is_unchanged() { + let config = cluster_config(None); + let before = config.0.clone(); + let config = config.join(None, None).unwrap(); + assert_eq!(config.0, before); + assert!( + !read(&config) + .get_root::() + .unwrap() + .has_cluster() + ); +} + +#[test] +fn cluster_advertise_without_a_cluster_is_an_error() { + let Err(error) = cluster_config(None).join(None, Some("10.0.0.4:7000")) else { + panic!("expected an error"); + }; + assert_eq!( + error, + "--cluster-advertise: the config has no cluster. Pass --cluster-addr to join one." + ); +} + +#[test] +fn a_config_joins_and_takes_the_environment_in_one_pass() { + let key = "test-cluster-shared-secret-of-32-bytes"; + let vars = [(CLUSTER_KEY, key), (CLUSTER_BUCKET, "s3://bucket/prefix")]; + let var = env(&vars); + let flags = ClusterFlags { + address: Some("10.0.0.4:7000"), + advertise: None, + can_join: true, + }; + let config = joinable_config().with_cluster(&flags, Some(&var)).unwrap(); + assert_eq!( + cluster_of(&config), + (key.to_owned(), "s3://bucket/prefix".to_owned()) + ); + // Without the environment, the joined cluster's key is missing. + let Err(ClusterError::Environment(error)) = + joinable_config().with_cluster(&flags, Some(&env(&[]))) + else { + panic!("expected an environment error"); + }; + assert!(error.starts_with("cluster.key is not set."), "{error}"); +} + +#[test] +fn a_config_without_cluster_storage_cannot_join_a_cluster() { + let expected = "--cluster-addr: the config has no writable disk service named `do-storage`, \ + which holds the Durable Objects of the cluster's deployments on each \ + instance, so it cannot join a cluster. Add one, or serve the wrangler config \ + itself, which defines it when joined."; + // None at all, as in `cluster_config`, or one by that name that is not a disk or is read-only. + let storage = |disk: bool| { + let mut message = capnp::message::Builder::new_default(); + let mut services = message.init_root::().init_services(1); + let mut service = services.reborrow().get(0); + service.set_name(CLUSTER_STORAGE); + if disk { + service.init_disk().set_path("/var/lib/workerd/do"); + } else { + service.init_external().set_address("10.0.0.5:80"); + } + Config(words_from_bytes(&capnp::serialize::write_message_to_words( + &message, + ))) + }; + for config in [cluster_config(None), storage(false), storage(true)] { + let Err(error) = config.join(Some("10.0.0.4:7000"), None) else { + panic!("expected an error"); + }; + assert_eq!(error, expected); + } + // A config with a cluster is not checked: it is joined as written. + let config = cluster_config(Some((KEY, "s3://bucket/prefix"))); + assert!(config.join(Some("10.0.0.4:7000"), None).is_ok()); +} + +#[test] +fn a_compiled_config_without_cluster_cannot_join_one() { + let flags = ClusterFlags { + address: Some("10.0.0.4:7000"), + advertise: None, + can_join: false, + }; + let Err(ClusterError::Usage(error)) = cluster_config(None).with_cluster(&flags, None) else { + panic!("expected a usage error"); + }; + assert!( + error.starts_with( + "--cluster-addr: the config compiled into this executable has no cluster, so it \ + cannot join one." + ), + "{error}" + ); + // One with a cluster keeps it: --cluster-addr overrides its address. + let config = cluster_config(Some(("k", "s3://b"))); + let before = config.0.clone(); + assert_eq!(config.with_cluster(&flags, None).unwrap().0, before); +} diff --git a/src/workerd/server/cli/config.rs b/src/workerd/server/cli/config.rs index 16794608cf3..31bbb31ed58 100644 --- a/src/workerd/server/cli/config.rs +++ b/src/workerd/server/cli/config.rs @@ -11,8 +11,10 @@ use std::io::Write; use capnp::message::ReaderOptions; use workerd_capnp::config; +use workerd_capnp::service; use crate::bridge::ffi; +use crate::wrangler::CLUSTER_STORAGE; /// A `Config` message, checked: encoded as a Cap'n Proto stream (segment table, then segments), /// in 8-byte words. @@ -78,62 +80,93 @@ impl Config { bytes_from_words(&self.0) } - /// Fills `cluster.key` and `cluster.bucket` from the environment where the config leaves them - /// empty. See `ClusterConfig` in workerd.capnp. `var` reads an environment variable and - /// returns `None` when it is unset or empty. A config without `cluster` is unchanged. A key or - /// bucket that neither the config nor the environment sets is an error. - pub fn with_cluster_environment( + /// The config as `serve` runs it in a cluster, decoded and encoded once. + /// + /// First, a config without `cluster` joins one at `flags.address`, the value of + /// `--cluster-addr`, if it defines [`CLUSTER_STORAGE`] as a writable disk service: it gets a + /// `cluster` with that address and every other setting at its default, so the key and bucket + /// come from the environment and an `s3://` bucket's endpoint and credentials from the + /// `AWS_*` variables. A config with a `cluster` keeps it, since + /// `--cluster-addr` overrides its address. A config without either is unchanged, and then + /// `flags.advertise`, the value of `--cluster-advertise`, is an error. + /// + /// Then, with `var`, the cluster's `key` and `bucket` are filled from the environment where + /// they are empty. See `ClusterConfig` in workerd.capnp. `var` reads an environment variable + /// and returns `None` when it is unset or empty. A key or bucket that neither the config nor + /// the environment sets is an error. + pub fn with_cluster( self, - var: impl Fn(&str) -> Option, - ) -> Result { + flags: &ClusterFlags<'_>, + var: Option>, + ) -> Result { + let usage = |error: capnp::Error| ClusterError::Usage(error.to_string()); let bytes = self.to_bytes(); - let message = capnp::serialize::read_message(bytes.as_slice(), reader_options()) - .map_err(|error| error.to_string())?; - let root = message - .get_root::() - .map_err(|error| error.to_string())?; - if !root.has_cluster() { - return Ok(self); - } - let cluster = root.get_cluster().map_err(|error| error.to_string())?; - let empty = |text: capnp::Result>| -> Result { - let text = text.and_then(|text| Ok(text.to_string()?)); - Ok(text.map_err(|error| error.to_string())?.is_empty()) - }; - let key = if empty(cluster.get_key())? { - cluster_key(&var)? - } else { + let message = + capnp::serialize::read_message(bytes.as_slice(), reader_options()).map_err(usage)?; + let root = message.get_root::().map_err(usage)?; + let join = if root.has_cluster() { None - }; - let bucket = if empty(cluster.get_bucket())? { - var(CLUSTER_BUCKET).and_then(|bucket| non_blank(&bucket)) } else { - None + match (flags.address, flags.advertise) { + (Some(_), _) if !flags.can_join => { + return Err(ClusterError::Usage( + "--cluster-addr: the config compiled into this executable has no \ + cluster, so it cannot join one. Serve the config with `workerd serve \ + --cluster-addr` instead, or compile a config that has `cluster`." + .to_owned(), + )); + } + (Some(_), _) if !has_cluster_storage(root).map_err(usage)? => { + return Err(ClusterError::Usage(format!( + "--cluster-addr: the config has no writable disk service named \ + `{CLUSTER_STORAGE}`, which holds the Durable Objects of the cluster's \ + deployments on each instance, so it cannot join a cluster. Add one, or \ + serve the wrangler config itself, which defines it when joined." + ))); + } + (Some(address), _) => Some(address), + (None, Some(_)) => { + return Err(ClusterError::Usage( + "--cluster-advertise: the config has no cluster. Pass --cluster-addr to \ + join one." + .to_owned(), + )); + } + (None, None) => return Ok(self), + } }; - let mut missing = Vec::new(); - if key.is_none() && empty(cluster.get_key())? { - missing.push(format!( - "cluster.key is not set. Set it in the config, in {CLUSTER_KEY}, or in a file \ - named by {CLUSTER_KEY_FILE}." - )); - } - if bucket.is_none() && empty(cluster.get_bucket())? { - missing.push(format!( - "cluster.bucket is not set. Set it in the config or in {CLUSTER_BUCKET}." - )); - } - if !missing.is_empty() { - return Err(missing.join("\n")); - } - if key.is_none() && bucket.is_none() { + let (key, bucket) = match var { + None => (None, None), + Some(var) => { + // A joined config's cluster is new, so its key and bucket are empty. + let (key_empty, bucket_empty) = if join.is_some() { + (true, true) + } else { + let cluster = root.get_cluster().map_err(usage)?; + let empty = |text: capnp::Result>| { + text.and_then(|text| Ok(text.to_str()?.is_empty())) + .map_err(usage) + }; + (empty(cluster.get_key())?, empty(cluster.get_bucket())?) + }; + cluster_environment(var, key_empty, bucket_empty) + .map_err(ClusterError::Environment)? + } + }; + if join.is_none() && key.is_none() && bucket.is_none() { return Ok(self); } let mut message = capnp::message::Builder::new_default(); - message.set_root(root).map_err(|error| error.to_string())?; - let mut cluster = message - .get_root::() - .and_then(config::Builder::get_cluster) - .map_err(|error| error.to_string())?; + message.set_root(root).map_err(usage)?; + let root = message.get_root::().map_err(usage)?; + let mut cluster = match join { + Some(address) => { + let mut cluster = root.init_cluster(); + cluster.set_address(address); + cluster + } + None => root.get_cluster().map_err(usage)?, + }; if let Some(key) = key { cluster.set_key(key.as_str()); } @@ -155,6 +188,84 @@ impl Config { } } +/// Reads an environment variable: `None` when it is unset or empty. +pub type Env<'a> = &'a dyn Fn(&str) -> Option; + +/// What `serve` was told about the cluster: `--cluster-addr` and `--cluster-advertise`, and +/// whether a config without `cluster` may join one. +#[derive(Default)] +pub struct ClusterFlags<'a> { + pub address: Option<&'a str>, + pub advertise: Option<&'a str>, + /// False for the config compiled into an executable: `compile` translates a wrangler config + /// for a server that joins no cluster, so the binary has no way to become a node of one. + pub can_join: bool, +} + +/// Why [`Config::with_cluster`] refused a config. +#[derive(Debug)] +pub enum ClusterError { + /// The command line does not fit the config. + Usage(String), + /// A key or bucket is missing, or the environment variable for one is unusable. + Environment(String), +} + +impl fmt::Display for ClusterError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Usage(error) | Self::Environment(error) => f.write_str(error), + } + } +} + +/// Whether `root` defines [`CLUSTER_STORAGE`] as a writable disk service, which a config that +/// joins a cluster needs for the Durable Objects of the cluster's deployments. +fn has_cluster_storage(root: config::Reader<'_>) -> capnp::Result { + for service in root.get_services()? { + if service.get_name()?.to_str()? == CLUSTER_STORAGE { + return Ok(match service.which()? { + service::Which::Disk(disk) => disk?.get_writable(), + _ => false, + }); + } + } + Ok(false) +} + +/// The key and bucket to fill from the environment, for a cluster whose key and bucket are empty +/// as `key_empty` and `bucket_empty` say. `None` for one the config sets. A key or bucket that +/// neither sets is an error. +fn cluster_environment( + var: Env<'_>, + key_empty: bool, + bucket_empty: bool, +) -> Result<(Option, Option), String> { + let key = if key_empty { cluster_key(var)? } else { None }; + let bucket = if bucket_empty { + var(CLUSTER_BUCKET).and_then(|bucket| non_blank(&bucket)) + } else { + None + }; + let mut missing = Vec::new(); + if key_empty && key.is_none() { + missing.push(format!( + "cluster.key is not set. Set it in the config, in {CLUSTER_KEY}, or in a file named by \ + {CLUSTER_KEY_FILE}." + )); + } + if bucket_empty && bucket.is_none() { + missing.push(format!( + "cluster.bucket is not set. Set it in the config or in {CLUSTER_BUCKET}." + )); + } + if missing.is_empty() { + Ok((key, bucket)) + } else { + Err(missing.join("\n")) + } +} + /// The environment variable that holds the cluster key when the config leaves it empty. pub const CLUSTER_KEY: &str = "WORKERD_CLUSTER_KEY"; /// The environment variable that names a file holding the cluster key, such as a mounted secret. @@ -168,7 +279,7 @@ const MIN_KEY: usize = 32; /// The cluster key from `CLUSTER_KEY` or the file `CLUSTER_KEY_FILE` names, without trailing /// whitespace, such as a file's final newline. `None` when neither is set or the key is blank. -fn cluster_key(var: impl Fn(&str) -> Option) -> Result, String> { +fn cluster_key(var: Env<'_>) -> Result, String> { let (key, source) = match (var(CLUSTER_KEY), var(CLUSTER_KEY_FILE)) { (Some(_), Some(_)) => { return Err(format!( diff --git a/src/workerd/server/cli/deploy-test.rs b/src/workerd/server/cli/deploy-test.rs index 741fb7853a0..70e859ce0c3 100644 --- a/src/workerd/server/cli/deploy-test.rs +++ b/src/workerd/server/cli/deploy-test.rs @@ -122,7 +122,7 @@ fn the_help_names_the_deployment_storage() { .render_long_help() .to_string(); assert!( - help.contains(&format!("`{}`", wrangler::DEPLOYMENT_STORAGE)), + help.contains(&format!("`{}`", wrangler::CLUSTER_STORAGE)), "{help}" ); } diff --git a/src/workerd/server/cli/help.rs b/src/workerd/server/cli/help.rs index 225ec3e275d..b82e185ffd8 100644 --- a/src/workerd/server/cli/help.rs +++ b/src/workerd/server/cli/help.rs @@ -23,6 +23,7 @@ macro_rules! run_options { -w, --watch Reload when files change --experimental Allow experimental features --verbose Log to stderr + --data-dir Keep state in dir, not in .wrangler/state -d, --directory-path = Point disk service name at dir -e, --external-addr = Point external service name at addr -h, --help Print this help @@ -42,7 +43,7 @@ macro_rules! cluster_options { () => { "\ Cluster (experimental): - --cluster-addr Override cluster address; keep private + --cluster-addr Cluster address, joining if config has none --cluster-advertise Address peers reach this instance at s3:// buckets read AWS_ENDPOINT_URL, AWS_ACCESS_KEY_ID and the other AWS_* variables; gs:// buckets, GOOGLE_APPLICATION_CREDENTIALS. An @@ -59,24 +60,24 @@ macro_rules! cluster_setup { () => { "\ Cluster setup: - Publish the Worker to the bucket, then start each instance; restart - them after each deploy. + Start each instance with the same key and bucket. A wrangler.json + joins with --cluster-addr. --data-dir holds its Durable Objects and + those of the bucket's deployments. + + $ export WORKERD_CLUSTER_KEY= # openssl rand -hex 32 + $ export WORKERD_CLUSTER_BUCKET=s3://bucket/prefix + $ workerd serve --experimental wrangler.json \\ + --cluster-addr 10.0.0.1:7000 --data-dir /var/lib/workerd + + key is at least 32 bytes, the same everywhere. --cluster-addr is where + this instance listens for peers, on a private network; behind NAT, + --cluster-advertise is where they reach it. A .capnp config sets + these in cluster = (...) instead. + + To serve more Workers on every instance, publish them to the bucket, + then restart the instances: $ workerd deploy --experimental . --bucket s3://bucket/prefix - $ workerd serve --experimental instance.capnp config - - # instance.capnp, for a wrangler.json named app - using Workerd = import \"/workerd/workerd.capnp\"; - const config :Workerd.Config = ( - cluster = (bucket = \"s3://bucket/prefix\", key = \"\", - address = \"10.0.0.1:7000\"), - services = [(name = \"do-storage\", - disk = (path = \"/var/lib/workerd\", writable = true))], - sockets = [(name = \"http\", address = \"*:8787\", service = \"app\")], - ); - - key is at least 32 bytes, the same everywhere (openssl rand -hex 32). - address is where peers reach this instance, on a private network. " }; } @@ -171,8 +172,8 @@ Config: with --experimental: kv_namespaces, queues, triggers, workflows, d1_databases, assets Other fields are errors. esbuild (node_modules or PATH) bundles main - unless no_bundle is set. State: .wrangler/state/workerd/. A .capnp - config also works. + unless no_bundle is set. State: .wrangler/state/workerd/, or + --data-dir. A .capnp config also works. Options: -s, --socket-addr = Serve on addr, as in -s http=*:8080 diff --git a/src/workerd/server/cli/lib.rs b/src/workerd/server/cli/lib.rs index 28126b8c2d1..0e536b293f2 100644 --- a/src/workerd/server/cli/lib.rs +++ b/src/workerd/server/cli/lib.rs @@ -4,8 +4,8 @@ //! command line), parses the command line, produces the encoded config (C++ compiles schema //! files), and hands the command to the server crate (`workerd_server::entry`), whose C++ //! driver (bootstrap.c++) sets up the process and runs the Rust server. In cluster mode `serve` -//! first adds the deployments in the cluster's bucket to the config ([`deployments`]), and -//! `deploy` publishes one ([`deploy`]). +//! first joins a config without a cluster to one with `--cluster-addr` and adds the deployments in +//! the cluster's bucket to the config ([`deployments`]), and `deploy` publishes one ([`deploy`]). //! [`process::Process`] is the `--watch` half: the files to watch, and the reload. // Two modules allow `unsafe`: bridge.rs, whose `cxx::bridge` macro expands to FFI declarations, @@ -36,7 +36,10 @@ use workerd_server::entry; use workerd_server::run::RunOptions; use crate::bridge::ffi; +use crate::config::ClusterError; +use crate::config::ClusterFlags; use crate::config::Config; +use crate::config::Env; use crate::process::Executable; use crate::process::Process; use crate::socket_fd::InheritedSocket; @@ -93,13 +96,20 @@ fn run_compiled( let args: T = parse(T::command()); check_serve_or_test::(&args.serve_or_test); + if args.serve_or_test.data_dir.is_some() { + usage_error::( + "--data-dir: the config compiled into this executable fixed its directories when it \ + was compiled. Pass --directory-path to move a disk service.", + ); + } let config = Config::from_words(embedded_config).unwrap_or_else(|error| { usage_error::(format!("the config compiled into this executable: {error}")) }); let watcher = watcher::(&args.serve_or_test, executable.as_ref()); let (options, inherited_sockets) = serve_options::(args.serve, &args.serve_or_test); let process = Process::new(executable, watcher, inherited_sockets); - let (config, options) = with_deployments(config, &args.serve_or_test, options, &process); + let (config, options) = + with_cluster::(config, &args.serve_or_test, options, &process, false); entry::serve( args.global.verbose, config.into_words(), @@ -129,9 +139,12 @@ fn run_command(args: args::Main, executable: Option) -> workerd_serv config, const_name.const_name, &process, + &options, + serve_or_test.data_dir.as_deref(), serve_or_test.experimental, ); - let (config, options) = with_deployments(config, &serve_or_test, options, &process); + let (config, options) = + with_cluster::(config, &serve_or_test, options, &process, true); entry::serve( verbose, config.into_words(), @@ -161,13 +174,21 @@ 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, serve_or_test.experimental); + let options = run_options(&serve_or_test); + let config = load_config::( + config, + None, + &process, + &options, + serve_or_test.data_dir.as_deref(), + serve_or_test.experimental, + ); entry::test( verbose, config.into_words(), (&serve_or_test).into(), (&args::TestArgs::default()).into(), - run_options(&serve_or_test), + options, patterns(args::TestFilter::default()), watching(process), ) @@ -246,7 +267,15 @@ fn run_deploy( binary: args.binary, config_file, }; - (name, load_config::(config, const_name, &process, true)) + let config = load_config::( + config, + const_name, + &process, + &RunOptions::default(), + None, + true, + ); + (name, config) } Err(error) => usage_error::(error), }; @@ -290,7 +319,8 @@ fn run_compile( } let process = Process::new(executable, None, Vec::new()); // The binary checks `--experimental` when it runs (the server, for bundled modules). - let config = load_config::(config, const_name, &process, true); + let options = RunOptions::default(); + let config = load_config::(config, const_name, &process, &options, None, true); let written = if config_only { config.write_to_stdout() } else { @@ -313,10 +343,16 @@ fn run_test( 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 options = RunOptions { + socket_addresses: args::override_map(std::mem::take(&mut test.socket_addr_overrides)), + ..run_options(serve_or_test) + }; let config = load_config::( config, filter.const_name.clone(), &process, + &options, + serve_or_test.data_dir.as_deref(), serve_or_test.experimental, ); entry::test( @@ -324,10 +360,7 @@ fn run_test( config.into_words(), serve_or_test.into(), (&test).into(), - RunOptions { - socket_addresses: args::override_map(test.socket_addr_overrides), - ..run_options(serve_or_test) - }, + options, patterns(filter), watching(process), ) @@ -347,10 +380,13 @@ 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 options = run_options(serve_or_test); let config = load_config::( config, filter.test.const_name.clone(), &process, + &options, + serve_or_test.data_dir.as_deref(), serve_or_test.experimental, ); entry::bench( @@ -358,7 +394,7 @@ fn run_bench( config.into_words(), serve_or_test.into(), bench.options(filter.case_pattern), - run_options(serve_or_test), + options, patterns(filter.test), watching(process), ) @@ -402,14 +438,16 @@ fn release_version() -> &'static str { } /// The config to run: a schema file compiled now (the compiler registers every file it reads with -/// the process's watcher before reading it), or an encoded message read from a file or stdin. -/// Exits with a usage error on a problem with the file itself. Parse errors in a schema file are -/// printed; without `--watch` they end the process, with it the process waits for the files to -/// change and reloads. +/// the process's watcher before reading it), a wrangler config translated now for a run with +/// `options`, or an encoded message read from a file or stdin. Exits with a usage error on a +/// problem with the file itself. Parse errors in a schema file are printed; without `--watch` they +/// end the process, with it the process waits for the files to change and reloads. fn load_config( config: args::ConfigFileArgs, const_name: Option, process: &Process, + options: &RunOptions, + data_dir: Option<&str>, experimental: bool, ) -> Config { let args::ConfigFileArgs { @@ -417,6 +455,12 @@ fn load_config( binary, config_file, } = config; + if data_dir.is_some() && (binary || !wrangler::is_wrangler_config(&config_file)) { + usage_error::( + "--data-dir: only a wrangler config keeps its state there. A Cap'n Proto config names \ + its disk services' directories, or takes them from --directory-path.", + ); + } for dir in &import_paths { if !std::path::Path::new(dir).is_dir() { usage_error::(format!("--import-path={dir}: No such directory.")); @@ -446,7 +490,8 @@ 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, experimental) + let data_dir = data_dir.map(std::path::Path::new); + return wrangler::load(&config_file, process, options, data_dir, experimental) .unwrap_or_else(|error| config_errors(&[format!("{config_file}: {error}")], process)); } @@ -465,30 +510,42 @@ fn load_config( config_errors(&compiled.errors, process) } -/// Fills `config`'s cluster key and bucket from the environment, then adds cluster deployments to -/// `config` and records their service sources in `options`. +/// Joins `config` to a cluster with `--cluster-addr` if it has none, `can_join` (not for a +/// compiled config) and a writable disk service `do-storage`, fills its cluster key and bucket +/// from the environment ([`Config::with_cluster`]), then adds cluster deployments to `config` and +/// records their service sources in `options`. /// -/// Both happen only with `--experimental`. A public cluster address or an error in `config` found -/// during composition is a config error. A deployment that does not compose is skipped. An -/// unusable cluster environment variable, or a bucket that cannot be opened or read, ends the -/// process, even under `--watch`, because the cause lies outside the config files. See -/// `deployments.rs`. -fn with_deployments( +/// Only joining happens without `--experimental`, so that the server refuses the cluster as it +/// refuses one in the config. A public cluster address or an error in `config` found during +/// composition is a config error. A deployment that does not compose is skipped. A cluster key or +/// bucket that is missing or whose environment variable is unusable, or a bucket that cannot be +/// opened or read, ends the process, even under `--watch`, because the cause can lie outside the +/// config files. See `deployments.rs`. +fn with_cluster( config: Config, serve_or_test: &args::ServeOrTestArgs, mut options: RunOptions, process: &Process, + can_join: bool, ) -> (Config, RunOptions) { - if !serve_or_test.experimental { - return (config, options); - } + let flags = ClusterFlags { + address: options.cluster_address.as_deref(), + advertise: options.cluster_advertise.as_deref(), + can_join, + }; let var = |name: &str| std::env::var(name).ok().filter(|value| !value.is_empty()); - let config = config - .with_cluster_environment(var) - .unwrap_or_else(|error| { + let environment = serve_or_test.experimental.then_some(&var as Env<'_>); + let config = match config.with_cluster(&flags, environment) { + Ok(config) => config, + Err(ClusterError::Usage(error)) => usage_error::(error), + Err(ClusterError::Environment(error)) => { eprintln!("{error}"); std::process::exit(1); - }); + } + }; + if !serve_or_test.experimental { + return (config, options); + } let address = options.cluster_address.as_deref(); let advertise = options.cluster_advertise.as_deref(); match deployments::add(config, address, advertise) { diff --git a/src/workerd/server/cli/wrangler-test.rs b/src/workerd/server/cli/wrangler-test.rs index 6db8513df7c..7c2e63b3790 100644 --- a/src/workerd/server/cli/wrangler-test.rs +++ b/src/workerd/server/cli/wrangler-test.rs @@ -33,6 +33,8 @@ fn load_project(files: &[(&str, &str)]) -> Result { load( dir.join("wrangler.jsonc").to_str().unwrap(), &Process::new(None, None, Vec::new()), + &RunOptions::default(), + None, true, ) } @@ -191,7 +193,7 @@ fn a_deployment_holds_only_the_worker() { else { panic!("expected local disk storage") }; - assert_eq!(disk.unwrap(), DEPLOYMENT_STORAGE); + assert_eq!(disk.unwrap(), CLUSTER_STORAGE); } assert!(!dir.join(".wrangler/state").exists()); @@ -211,6 +213,375 @@ fn a_deployment_holds_only_the_worker() { assert_eq!(name, "app"); } +/// A project named `name` with a Counter Durable Object. +fn counter_project(name: &str) -> PathBuf { + project(&[ + ( + "wrangler.jsonc", + &format!( + r#"{{ "name": "{name}", "main": "index.js", "compatibility_date": "2026-01-01", + "no_bundle": true, + "durable_objects": {{ "bindings": [{{ "name": "C", "class_name": "Counter" }}] }} }}"# + ), + ), + ("index.js", "export class Counter {}"), + ]) +} + +/// The options of `serve --cluster-addr`. +fn joining() -> RunOptions { + RunOptions { + cluster_address: Some("127.0.0.1:0".to_owned()), + ..RunOptions::default() + } +} + +/// A directory for `--data-dir`, not yet created, outside any project. +fn data_dir() -> PathBuf { + std::path::absolute(project(&[]).join("data")).unwrap() +} + +/// The name and path of the disk service that the worker in `config` stores Durable Objects on. +fn storage_of(config: Config) -> (String, String) { + let message = read(config); + let config = message.get_root::().unwrap(); + let services = config.get_services().unwrap(); + let service::Which::Worker(worker) = services.get(0).which().unwrap() else { + panic!("expected a worker service") + }; + let worker::durable_object_storage::Which::LocalDisk(disk) = worker + .unwrap() + .get_durable_object_storage() + .which() + .unwrap() + else { + panic!("expected local disk storage") + }; + let storage = services.get(1); + assert_eq!(storage.get_name().unwrap(), disk.unwrap()); + let service::Which::Disk(path) = storage.which().unwrap() else { + panic!("expected a disk service") + }; + ( + storage.get_name().unwrap().to_string().unwrap(), + path.unwrap().get_path().unwrap().to_string().unwrap(), + ) +} + +#[test] +fn durable_objects_in_a_cluster_are_stored_on_do_storage() { + let dir = counter_project("counter"); + let path = dir.join("wrangler.jsonc"); + let process = Process::new(None, None, Vec::new()); + let config = load(path.to_str().unwrap(), &process, &joining(), None, true).unwrap(); + // As the translation makes it: absolute, not canonical, so on Windows not `\\?\`. + let state = std::path::absolute(&dir) + .unwrap() + .join(".wrangler/state/workerd"); + assert_eq!( + storage_of(config), + ( + CLUSTER_STORAGE.to_owned(), + state.join("do").to_string_lossy().into_owned() + ) + ); + assert!(state.join("do").is_dir()); +} + +#[test] +fn a_data_dir_holds_durable_objects_outside_the_project() { + let process = Process::new(None, None, Vec::new()); + // Joined, apart from the bundled services' directories, which a deployment's storage key could + // name. + for (options, service, dir) in [ + (joining(), CLUSTER_STORAGE, Some("do")), + (RunOptions::default(), "counter-do-storage", None), + ] { + let project = counter_project("counter"); + let path = project.join("wrangler.jsonc"); + let data = data_dir(); + let config = load( + path.to_str().unwrap(), + &process, + &options, + Some(&data), + true, + ) + .unwrap(); + let disk = dir.map_or_else(|| data.clone(), |dir| data.join(dir)); + assert_eq!( + storage_of(config), + (service.to_owned(), disk.to_string_lossy().into_owned()) + ); + assert!(disk.is_dir()); + assert!(!project.join(".wrangler").exists()); + } +} + +#[test] +fn a_relative_data_dir_is_made_absolute() { + let project = std::path::absolute(counter_project("counter")).unwrap(); + let path = project.join("wrangler.jsonc"); + let process = Process::new(None, None, Vec::new()); + // Relative to the working directory, which the crate's tests, run one at a time, may change. + let cwd = std::env::current_dir().unwrap(); + std::env::set_current_dir(&project).unwrap(); + let config = load( + path.to_str().unwrap(), + &process, + &RunOptions::default(), + Some(Path::new("data")), + true, + ); + std::env::set_current_dir(cwd).unwrap(); + assert_eq!( + storage_of(config.unwrap()).1, + project.join("data").to_string_lossy().into_owned() + ); +} + +#[test] +fn a_project_in_a_cluster_cannot_be_named_after_its_storage() { + let path = counter_project(CLUSTER_STORAGE).join("wrangler.jsonc"); + let process = Process::new(None, None, Vec::new()); + let Err(error) = load(path.to_str().unwrap(), &process, &joining(), None, true) else { + panic!("expected an error") + }; + assert_eq!( + error, + "name: \"do-storage\" is the name of the disk service that holds the Durable Objects in a \ + cluster. Choose another name." + ); + // Outside a cluster, the disk is named after the worker. + let config = load( + path.to_str().unwrap(), + &process, + &RunOptions::default(), + None, + true, + ) + .unwrap(); + assert_eq!(storage_of(config).0, "do-storage-do-storage"); +} + +/// A project named `name` without Durable Objects, with `files` besides its config and module. +fn plain_project(name: &str, files: &[(&str, &str)]) -> PathBuf { + let config = format!( + r#"{{ "name": "{name}", "main": "index.js", "compatibility_date": "2026-01-01", + "no_bundle": true }}"# + ); + let mut all = vec![ + ("wrangler.jsonc", config.as_str()), + ("index.js", "export default {}"), + ]; + all.extend_from_slice(files); + project(&all) +} + +/// The names and paths of the disk services in `config`. +fn disks_of(config: Config) -> Vec<(String, String)> { + let message = read(config); + let config = message.get_root::().unwrap(); + let services = config.get_services().unwrap(); + services + .iter() + .filter_map(|service| match service.which().unwrap() { + service::Which::Disk(disk) => Some(( + service.get_name().unwrap().to_string().unwrap(), + disk.unwrap().get_path().unwrap().to_string().unwrap(), + )), + _ => None, + }) + .collect() +} + +#[test] +fn a_project_without_durable_objects_in_a_cluster_defines_do_storage() { + let process = Process::new(None, None, Vec::new()); + let dir = plain_project("hello", &[]); + let path = dir.join("wrangler.jsonc"); + let path = path.to_str().unwrap(); + // Outside a cluster, there is no disk. Without --experimental there is no Cache API either, + // which would keep its entries in the state directory. + let config = load(path, &process, &RunOptions::default(), None, false).unwrap(); + assert_eq!(disks_of(config), []); + assert!(!dir.join(".wrangler").exists()); + // In one, the disk holds deployments' Durable Objects, in the --data-dir if given. + let data = data_dir(); + let config = load(path, &process, &joining(), Some(&data), true).unwrap(); + assert_eq!( + disks_of(config), + [( + CLUSTER_STORAGE.to_owned(), + data.join("do").to_string_lossy().into_owned() + )] + ); + assert!(!dir.join(".wrangler").exists()); + let config = load(path, &process, &joining(), None, true).unwrap(); + // As the translation makes it: absolute, not canonical, so on Windows not `\\?\`. + let state = std::path::absolute(&dir) + .unwrap() + .join(".wrangler/state/workerd"); + assert_eq!( + disks_of(config), + [( + CLUSTER_STORAGE.to_owned(), + state.join("do").to_string_lossy().into_owned() + )] + ); + assert!(state.join("do").is_dir()); + // So the worker cannot take its name. + let path = plain_project(CLUSTER_STORAGE, &[]).join("wrangler.jsonc"); + let Err(error) = load(path.to_str().unwrap(), &process, &joining(), None, true) else { + panic!("expected an error") + }; + assert!( + error.starts_with("name: \"do-storage\" is the name"), + "{error}" + ); +} + +#[test] +fn a_state_directory_that_cannot_be_created_is_an_error() { + let process = Process::new(None, None, Vec::new()); + for dir in [plain_project("hello", &[]), counter_project("counter")] { + // A file where the directory would be. + fs::write(dir.join(".wrangler"), "").unwrap(); + let path = dir.join("wrangler.jsonc"); + let Err(error) = load(path.to_str().unwrap(), &process, &joining(), None, true) else { + panic!("expected an error") + }; + assert!( + error.ends_with(". Pass --data-dir to keep state elsewhere."), + "{error}" + ); + } +} + +#[test] +fn a_data_dir_holds_the_state_of_every_bundled_service() { + let dir = project(&[ + ( + "wrangler.jsonc", + r#"{ "name": "app", "main": "index.js", "compatibility_date": "2026-01-01", + "no_bundle": true, "kv_namespaces": [{ "binding": "KV" }], + "r2_buckets": [{ "binding": "R2", "bucket_name": "files" }], + "triggers": { "crons": ["0 * * * *"] }, + "queues": { "consumers": [{ "queue": "jobs" }] }, + "workflows": [{ "binding": "R", "name": "reports", "class_name": "Report" }], + "d1_databases": [{ "binding": "DB", "database_id": "db" }] }"#, + ), + ("index.js", "export default {}"), + ]); + let path = dir.join("wrangler.jsonc"); + let data = data_dir(); + let process = Process::new(None, None, Vec::new()); + let config = load( + path.to_str().unwrap(), + &process, + &RunOptions::default(), + Some(&data), + true, + ) + .unwrap(); + let message = read(config); + let services = message + .get_root::() + .unwrap() + .get_services() + .unwrap(); + let mut paths = Vec::new(); + for service in services { + match service.which().unwrap() { + service::Which::Disk(disk) => paths.push(disk.unwrap().get_path().unwrap()), + service::Which::Cache(cache) => paths.push(cache.unwrap().get_path().unwrap()), + _ => {} + } + } + // KV's two, R2, cron, Queues, Workflows, D1, and the Cache API. + assert_eq!(paths.len(), 8); + for path in paths { + let path = path.to_str().unwrap(); + assert!(Path::new(path).starts_with(&data), "{path}"); + assert!(Path::new(path).is_dir(), "{path}"); + } + assert!(!dir.join(".wrangler").exists()); +} + +#[test] +fn a_project_in_a_cluster_cannot_have_kv_namespaces_or_queues_but_can_have_crons() { + let process = Process::new(None, None, Vec::new()); + for (field, json) in [ + ("kv_namespaces", r#""kv_namespaces": [{ "binding": "KV" }]"#), + ( + "queues", + r#""queues": { "producers": [{ "binding": "Q", "queue": "jobs" }] }"#, + ), + ] { + let dir = project(&[ + ( + "wrangler.jsonc", + format!( + r#"{{ "name": "app", "main": "index.js", "compatibility_date": "2026-01-01", + "no_bundle": true, {json} }}"# + ) + .as_str(), + ), + ("index.js", "export default {}"), + ]); + let path = dir.join("wrangler.jsonc"); + let Err(error) = load(path.to_str().unwrap(), &process, &joining(), None, true) else { + panic!("expected an error") + }; + assert_eq!( + error, + format!("A config that joins a cluster with --cluster-addr cannot have {field} yet.") + ); + } + let cron = project(&[ + ( + "wrangler.jsonc", + r#"{ "name": "app", "main": "index.js", "compatibility_date": "2026-01-01", + "no_bundle": true, "triggers": { "crons": ["0 * * * *"] } }"#, + ), + ("index.js", "export default {}"), + ]); + let path = cron.join("wrangler.jsonc"); + let data = data_dir(); + let config = load( + path.to_str().unwrap(), + &process, + &joining(), + Some(&data), + true, + ) + .unwrap(); + let names: Vec = disks_of(config).into_iter().map(|(name, _)| name).collect(); + assert_eq!(names, [CLUSTER_STORAGE, "app-cron-storage"]); + assert!(!cron.join(".wrangler").exists()); +} + +#[test] +fn a_bundle_directory_that_cannot_be_created_suggests_no_bundle() { + let error = load_project(&[ + ( + "wrangler.jsonc", + r#"{ "main": "index.js", "compatibility_date": "2026-01-01" }"#, + ), + ("index.js", "export default {}"), + (".wrangler", ""), + ]) + .err() + .unwrap(); + assert!( + error.ends_with( + ". esbuild bundles `main` there. Set \"no_bundle\": true in the wrangler config to \ + serve the modules as they are." + ), + "{error}" + ); +} + #[test] fn migrations_rename_and_delete() { let w: Wrangler = serde_json::from_str( @@ -375,7 +746,15 @@ fn kv_namespaces_require_experimental() { ]); 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(); + let error = load( + path.to_str().unwrap(), + &process, + &RunOptions::default(), + None, + 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) @@ -399,6 +778,8 @@ fn kv_namespaces_bind_the_kv_worker() { let config = load( dir.join("wrangler.jsonc").to_str().unwrap(), &Process::new(None, None, Vec::new()), + &RunOptions::default(), + None, true, ) .unwrap(); @@ -478,7 +859,16 @@ fn caches_are_served_by_the_cache_service() { let process = Process::new(None, None, Vec::new()); let path = dir.join("wrangler.jsonc"); let names = |experimental| { - let message = read(load(path.to_str().unwrap(), &process, experimental).unwrap()); + let message = read( + load( + path.to_str().unwrap(), + &process, + &RunOptions::default(), + None, + experimental, + ) + .unwrap(), + ); let conf = message.get_root::().unwrap(); let services = conf.get_services().unwrap(); let service::Which::Worker(w) = services.get(0).which().unwrap() else { @@ -523,10 +913,25 @@ fn r2_buckets_bind_the_r2_worker() { ]); let path = dir.join("wrangler.jsonc"); let process = Process::new(None, None, Vec::new()); - let error = load(path.to_str().unwrap(), &process, false).err().unwrap(); + let error = load( + path.to_str().unwrap(), + &process, + &RunOptions::default(), + None, + false, + ) + .err() + .unwrap(); assert!(error.contains("r2_buckets"), "{error}"); assert!(error.contains("--experimental"), "{error}"); - let config = load(path.to_str().unwrap(), &process, true).unwrap(); + let config = load( + path.to_str().unwrap(), + &process, + &RunOptions::default(), + None, + true, + ) + .unwrap(); let message = read(config); let conf = message.get_root::().unwrap(); let services = conf.get_services().unwrap(); @@ -596,13 +1001,30 @@ fn d1_databases_bind_the_d1_worker() { ]); 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(); + let error = load( + path.to_str().unwrap(), + &process, + &RunOptions::default(), + None, + false, + ) + .err() + .unwrap(); assert!(error.contains("d1_databases"), "{error}"); let error = load_deployment(path.to_str().unwrap(), Some("app"), &process) .err() .unwrap(); assert!(error.contains("d1_databases"), "{error}"); - let message = read(load(path.to_str().unwrap(), &process, true).unwrap()); + let message = read( + load( + path.to_str().unwrap(), + &process, + &RunOptions::default(), + None, + true, + ) + .unwrap(), + ); let services = message .get_root::() .unwrap() @@ -666,13 +1088,30 @@ fn secrets_store_secrets_bind_the_secrets_store_worker() { let dir = project(&[("wrangler.jsonc", wrangler), ("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(); + let error = load( + path.to_str().unwrap(), + &process, + &RunOptions::default(), + None, + false, + ) + .err() + .unwrap(); assert!(error.contains("secrets_store_secrets"), "{error}"); let error = load_deployment(path.to_str().unwrap(), Some("app"), &process) .err() .unwrap(); assert!(error.contains("secrets_store_secrets"), "{error}"); - let message = read(load(path.to_str().unwrap(), &process, true).unwrap()); + let message = read( + load( + path.to_str().unwrap(), + &process, + &RunOptions::default(), + None, + true, + ) + .unwrap(), + ); let services = message .get_root::() .unwrap() @@ -816,13 +1255,30 @@ fn ratelimits_bind_the_ratelimit_worker() { let dir = project(&[("wrangler.jsonc", wrangler), ("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(); + let error = load( + path.to_str().unwrap(), + &process, + &RunOptions::default(), + None, + false, + ) + .err() + .unwrap(); assert!(error.contains("ratelimits"), "{error}"); let error = load_deployment(path.to_str().unwrap(), Some("app"), &process) .err() .unwrap(); assert!(error.contains("ratelimits"), "{error}"); - let message = read(load(path.to_str().unwrap(), &process, true).unwrap()); + let message = read( + load( + path.to_str().unwrap(), + &process, + &RunOptions::default(), + None, + true, + ) + .unwrap(), + ); let services = message .get_root::() .unwrap() @@ -890,7 +1346,15 @@ fn triggers_crons_require_experimental() { ]); 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(); + let error = load( + path.to_str().unwrap(), + &process, + &RunOptions::default(), + None, + false, + ) + .err() + .unwrap(); assert!(error.contains("triggers.crons"), "{error}"); assert!(error.contains("--experimental"), "{error}"); let error = load_deployment(path.to_str().unwrap(), Some("app"), &process) @@ -911,7 +1375,15 @@ fn triggers_crons_refuse_a_worker_named_like_their_bindings() { ]); let process = Process::new(None, None, Vec::new()); let path = dir.join("wrangler.jsonc"); - let error = load(path.to_str().unwrap(), &process, true).err().unwrap(); + let error = load( + path.to_str().unwrap(), + &process, + &RunOptions::default(), + None, + true, + ) + .err() + .unwrap(); assert!(error.contains("named CRONS"), "{error}"); } @@ -928,6 +1400,8 @@ fn triggers_crons_run_on_the_cron_worker() { let config = load( dir.join("wrangler.jsonc").to_str().unwrap(), &Process::new(None, None, Vec::new()), + &RunOptions::default(), + None, true, ) .unwrap(); @@ -971,10 +1445,13 @@ fn queues_run_on_the_queues_worker() { ("index.js", ""), ]); let process = Process::new(None, None, Vec::new()); + let options = RunOptions::default(); let path = dir.join("wrangler.jsonc"); - let error = load(path.to_str().unwrap(), &process, false).err().unwrap(); + let error = load(path.to_str().unwrap(), &process, &options, None, false) + .err() + .unwrap(); assert!(error.contains("queues"), "{error}"); - let message = read(load(path.to_str().unwrap(), &process, true).unwrap()); + let message = read(load(path.to_str().unwrap(), &process, &options, None, true).unwrap()); let services = message .get_root::() .unwrap() @@ -1040,10 +1517,13 @@ fn workflows_run_on_the_workflows_worker() { ("index.js", ""), ]); let process = Process::new(None, None, Vec::new()); + let options = RunOptions::default(); let path = dir.join("wrangler.jsonc"); - let error = load(path.to_str().unwrap(), &process, false).err().unwrap(); + let error = load(path.to_str().unwrap(), &process, &options, None, false) + .err() + .unwrap(); assert!(error.contains("workflows"), "{error}"); - let message = read(load(path.to_str().unwrap(), &process, true).unwrap()); + let message = read(load(path.to_str().unwrap(), &process, &options, None, true).unwrap()); let services = message .get_root::() .unwrap() @@ -1285,7 +1765,15 @@ fn assets_require_experimental() { ]); 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(); + let error = load( + path.to_str().unwrap(), + &process, + &RunOptions::default(), + None, + false, + ) + .err() + .unwrap(); assert!(error.contains("assets"), "{error}"); assert!(error.contains("--experimental"), "{error}"); let error = load_deployment(path.to_str().unwrap(), Some("app"), &process) diff --git a/src/workerd/server/cli/wrangler.rs b/src/workerd/server/cli/wrangler.rs index b5b2fd60d27..12bbc23a4a8 100644 --- a/src/workerd/server/cli/wrangler.rs +++ b/src/workerd/server/cli/wrangler.rs @@ -14,8 +14,13 @@ //! `secrets_store_secrets`, `ratelimits`, `assets`, `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`]). +//! Durable Objects are stored on disk in the state directory, `.wrangler/state/workerd/` next to +//! the config unless `--data-dir` names another, one directory per class, named `-` by +//! its storage key (see [`do_classes`]). The disk service is named `-do-storage`, or +//! [`CLUSTER_STORAGE`] when `--cluster-addr` joins the config to a cluster, which defines it even +//! for a project without Durable Objects, in the state directory's `do/`. The bundled Workers' +//! disks and the Cache API's entries are in the state directory too. `workerd compile` translates +//! for a server that joins no cluster. //! `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 @@ -55,8 +60,8 @@ //! //! 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. A deployment cannot have `kv_namespaces`, `r2_buckets`, +//! no socket, and its Durable Objects stored on the disk service [`CLUSTER_STORAGE`], which each +//! node's own config defines. A deployment cannot have `kv_namespaces`, `r2_buckets`, //! `triggers.crons`, `queues`, `workflows`, `d1_databases`, `secrets_store_secrets`, `ratelimits` //! or `assets` yet. @@ -74,6 +79,7 @@ use workerd_capnp::config; use workerd_capnp::service; use workerd_capnp::service_designator; use workerd_capnp::worker; +use workerd_server::run::RunOptions; use crate::config::Config; use crate::config::words_from_bytes; @@ -81,10 +87,17 @@ use crate::process::Process; const DEFAULT_ADDRESS: &str = "localhost:8787"; -/// The disk service a deployment's Durable Objects are stored on: a node's, since a deployment -/// may define no disk. Each class's objects are in a directory of their own on it, named by the -/// class's storage key, which names the deployment. -pub const DEPLOYMENT_STORAGE: &str = "do-storage"; +/// The disk service that holds Durable Objects in a cluster. A deployment's are stored on the +/// node's, since a deployment may define no disk. A node that serves a wrangler config and joins a +/// cluster with `--cluster-addr` defines it, so that the node can serve deployments with Durable +/// Objects too. Each class's objects are in a directory of their own on it, named by the class's +/// storage key, which names the worker. +pub const CLUSTER_STORAGE: &str = "do-storage"; + +/// The directory of [`CLUSTER_STORAGE`] in the state directory. It is apart from the bundled +/// services' directories, such as `cache/` and `d1/`, which a deployment's storage key could +/// otherwise name. +const CLUSTER_STORAGE_DIR: &str = "do"; #[derive(Deserialize)] #[serde(deny_unknown_fields)] @@ -416,17 +429,73 @@ pub fn project_config(dir: &Path) -> Result { /// What a wrangler config is translated into. 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 { experimental: bool }, + /// A config to serve with `options`: the worker named after the config's `name`, else `main`, + /// a socket, and a disk service for Durable Objects (see [`served_storage`]). Its state is + /// under `data_dir` (`--data-dir`), else under `.wrangler/state/workerd` in the project. + Serve { + options: &'a RunOptions, + data_dir: Option<&'a Path>, + 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`]. + /// `name`, and its Durable Objects stored on the node's [`CLUSTER_STORAGE`]. Deployment { name: Option<&'a str> }, } -/// The config `workerd serve` runs for the wrangler config at `path`. -pub fn load(path: &str, process: &Process, experimental: bool) -> Result { - translate(path, process, &Target::Serve { experimental }).map(|(_, config)| config) +/// The disk service that holds the Durable Objects of the worker `name`, with `classes`, in a +/// config served with `options`, and the directory of that service if the config defines it. +/// +/// Joined to a cluster with `--cluster-addr`, the config defines [`CLUSTER_STORAGE`] even without +/// Durable Objects of its own, for deployments' ones. Otherwise the config defines +/// `-do-storage` if it has Durable Objects. The directory, created here, is +/// [`CLUSTER_STORAGE_DIR`] in `storage`, the state directory, or for `-do-storage` the +/// state directory itself, whose classes' directories are named `-`. +fn served_storage( + storage: &Path, + name: &str, + classes: &[(String, String, bool)], + options: &RunOptions, +) -> Result<(String, Option), String> { + let joining = options.cluster_address.is_some(); + let service = if joining { + CLUSTER_STORAGE.to_owned() + } else { + // Named after the worker, so it cannot collide with it. + format!("{name}-do-storage") + }; + if name == service { + return Err(format!( + "name: \"{name}\" is the name of the disk service that holds the Durable Objects in a \ + cluster. Choose another name." + )); + } + if !joining && classes.is_empty() { + return Ok((service, None)); + } + let dir = if joining { + storage.join(CLUSTER_STORAGE_DIR) + } else { + storage.to_owned() + }; + create_state_dir(&dir)?; + Ok((service, Some(dir))) +} + +/// The config `workerd serve` runs with `options` for the wrangler config at `path`, its state +/// under `data_dir` if given. +pub fn load( + path: &str, + process: &Process, + options: &RunOptions, + data_dir: Option<&Path>, + experimental: bool, +) -> Result { + let target = Target::Serve { + options, + data_dir, + experimental, + }; + translate(path, process, &target).map(|(_, config)| config) } /// The deployment `workerd deploy` publishes for the wrangler config at `path`, and its name: @@ -480,15 +549,31 @@ fn translate(path: &str, process: &Process, target: &Target) -> Result<(String, }; let workers = u32::from(wrangler.main.is_some()); - 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()))?; - } + // Durable Objects and the bundled Workers keep their state here. + let storage = match target { + Target::Serve { + data_dir: Some(dir), + .. + } => std::path::absolute(dir).map_err(|e| format!("--data-dir: {e}"))?, + _ => root.join(".wrangler/state/workerd"), + }; + let (storage_service, disk) = match target { + Target::Serve { options, .. } => served_storage(&storage, &name, &classes, options)?, + Target::Deployment { .. } => (CLUSTER_STORAGE.to_owned(), None), + }; let mut message = capnp::message::Builder::new_default(); let mut conf = message.init_root::(); - let do_storage = u32::from(serving && !classes.is_empty()); - let cache = u32::from(workers == 1 && matches!(target, Target::Serve { experimental: true })); + let do_storage = u32::from(disk.is_some()); + let cache = u32::from( + workers == 1 + && matches!( + target, + Target::Serve { + experimental: true, + .. + } + ), + ); let mut services = conf.reborrow().init_services( workers + do_storage @@ -519,20 +604,16 @@ fn translate(path: &str, process: &Process, target: &Target) -> Result<(String, if !wrangler.workflows.is_empty() { set_workflows_engine(worker.reborrow(), &name, &wrangler.workflows); } - set_durable_objects(worker, &classes, &name, serving); + set_durable_objects(worker, &classes, &name, &storage_service); } if cache == 1 { cache_service(&mut services, &name, &storage)?; } - if do_storage == 1 { - disk_service( - services.get(workers), - &format!("{name}-do-storage"), - &storage, - ); + if let Some(path) = disk { + disk_service(services.get(workers), &storage_service, &path); } - if serving { + if matches!(target, Target::Serve { .. }) { let mut socket = conf.init_sockets(1).get(0); socket.set_name("http"); socket.set_address(DEFAULT_ADDRESS); @@ -583,13 +664,12 @@ fn assets_only(wrangler: &Wrangler) -> Result<(), String> { } } -/// The Durable Object namespaces of `classes`, stored on `-do-storage` when `serving`, else -/// on [`DEPLOYMENT_STORAGE`]. +/// The Durable Object namespaces of `classes`, stored on the disk service `storage`. fn set_durable_objects( mut worker: worker::Builder<'_>, classes: &[(String, String, bool)], name: &str, - serving: bool, + storage: &str, ) { if !classes.is_empty() { let mut ns = worker @@ -601,12 +681,6 @@ fn set_durable_objects( n.set_unique_key(format!("{name}-{key}")); n.set_enable_sql(*sql); } - // Named after the worker, so it cannot collide with it. - let storage = if serving { - format!("{name}-do-storage") - } else { - DEPLOYMENT_STORAGE.to_owned() - }; worker.init_durable_object_storage().set_local_disk(storage); } } @@ -630,8 +704,24 @@ fn set_modules(worker: worker::Builder<'_>, sources: &[Source]) -> Result<(), St /// `kv_namespaces`, `r2_buckets`, `triggers.crons`, `queues`, `workflows`, `d1_databases`, /// `secrets_store_secrets`, `ratelimits` and `assets` need `--experimental`, and a deployment -/// cannot have them yet. +/// cannot have them yet. Nor can a config joined to a cluster have `kv_namespaces`, whose large +/// values would stay on the disk of the instance that wrote them, or `queues`, whose Worker this +/// translation does not set up for a cluster. fn check_experimental(wrangler: &Wrangler, target: &Target) -> Result<(), String> { + if let Target::Serve { options, .. } = target + && options.cluster_address.is_some() + { + for (used, field) in [ + (!wrangler.kv_namespaces.is_empty(), "kv_namespaces"), + (!wrangler.queues.is_empty(), "queues"), + ] { + if used { + return Err(format!( + "A config that joins a cluster with --cluster-addr cannot have {field} yet." + )); + } + } + } for (used, field) in [ (!wrangler.kv_namespaces.is_empty(), "kv_namespaces"), (!wrangler.r2_buckets.is_empty(), "r2_buckets"), @@ -648,7 +738,9 @@ fn check_experimental(wrangler: &Wrangler, target: &Target) -> Result<(), String ] { match target { _ if !used => {} - Target::Serve { experimental: true } => {} + Target::Serve { + experimental: true, .. + } => {} Target::Serve { .. } => { return Err(format!( "{field} is an experimental feature which may change or go away in the \ @@ -721,7 +813,8 @@ fn bundled_services( watch: Watch, ) -> Result<(), String> { if !wrangler.kv_namespaces.is_empty() { - kv_services(services, at, &format!("{name}-kv"), &storage.join("kv"))?; + let dir = storage.join("kv"); + kv_services(services, at, &format!("{name}-kv"), &dir)?; at += 3; } if !wrangler.r2_buckets.is_empty() { @@ -749,7 +842,8 @@ fn bundled_services( at += 2; } if !wrangler.d1_databases.is_empty() { - d1_services(services, at, &format!("{name}-d1"), &storage.join("d1"))?; + let dir = storage.join("d1"); + d1_services(services, at, &format!("{name}-d1"), &dir)?; at += 2; } if !wrangler.ratelimits.is_empty() { @@ -823,18 +917,25 @@ fn d1_services( name: &str, dir: &Path, ) -> Result<(), String> { - fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; - disk_service( - services.reborrow().get(at + 1), - &format!("{name}-storage"), - dir, - ); + let disk = format!("{name}-storage"); + create_state_dir(dir)?; + disk_service(services.reborrow().get(at + 1), &disk, dir); let service = services.reborrow().get(at); let class = Some(("DATABASE", "D1Database")); bundled_worker(service, name, "d1.js", &[], class, 1); Ok(()) } +/// Creates `dir`, a directory of the state directory. +fn create_state_dir(dir: &Path) -> Result<(), String> { + fs::create_dir_all(dir).map_err(|e| { + format!( + "{}: {e}. Pass --data-dir to keep state elsewhere.", + dir.display() + ) + }) +} + /// The KV Worker `name` at `services[at]`, then its disks under `dir`. fn kv_services( services: &mut capnp::struct_list::Builder<'_, service::Owned>, @@ -843,17 +944,11 @@ fn kv_services( dir: &Path, ) -> Result<(), String> { let blobs = dir.join("blobs"); - fs::create_dir_all(&blobs).map_err(|e| format!("{}: {e}", blobs.display()))?; - disk_service( - services.reborrow().get(at + 1), - &format!("{name}-storage"), - dir, - ); - disk_service( - services.reborrow().get(at + 2), - &format!("{name}-blobs"), - &blobs, - ); + for (i, what, path) in [(at + 1, "storage", dir), (at + 2, "blobs", &blobs)] { + let service = format!("{name}-{what}"); + create_state_dir(path)?; + disk_service(services.reborrow().get(i), &service, path); + } let service = services.reborrow().get(at); let bindings = bundled_worker( service, @@ -901,15 +996,15 @@ fn secrets_service(service: service::Builder<'_>, name: &str, secrets: &[Secrets } /// The R2 Worker `name` at `services[at]`, then its disk, `storage`, and its `BLOBS`, a bucket -/// service storing the objects in `storage/r2/`. +/// service storing the objects in `storage/r2/`, or in a cluster in the cluster's bucket. fn r2_services( services: &mut capnp::struct_list::Builder<'_, service::Owned>, at: u32, name: &str, storage: &Path, ) -> Result<(), String> { - fs::create_dir_all(storage).map_err(|e| format!("{}: {e}", storage.display()))?; let disk = format!("{name}-storage"); + create_state_dir(storage)?; disk_service(services.reborrow().get(at + 1), &disk, storage); let mut service = services.reborrow().get(at + 2); service.set_name(format!("{name}-blobs")); @@ -939,8 +1034,8 @@ fn cache_service( storage: &Path, ) -> Result<(), String> { let dir = storage.join("cache"); - fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; let cache = format!("{name}-cache"); + create_state_dir(&dir)?; let last = services.len() - 1; let mut service = services.reborrow().get(last); service.set_name(&cache); @@ -1006,8 +1101,8 @@ fn cron_services( "A Worker named {target} cannot have triggers.crons." )); } - fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; let name = format!("{target}-cron"); + create_state_dir(dir)?; disk_service( services.reborrow().get(at + 1), &format!("{name}-storage"), @@ -1195,8 +1290,8 @@ fn workflows_services( wrangler: &Wrangler, ) -> Result<(), String> { let workflows = &wrangler.workflows; - fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; let name = format!("{target}-workflows"); + create_state_dir(dir)?; disk_service( services.reborrow().get(at + 1), &format!("{name}-storage"), @@ -1271,8 +1366,8 @@ fn queues_services( dir: &Path, queues: &Queues, ) -> Result<(), String> { - fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; let name = format!("{target}-queues"); + create_state_dir(dir)?; disk_service( services.reborrow().get(at + 1), &format!("{name}-storage"), @@ -1393,7 +1488,13 @@ fn bundle(esbuild: &Path, root: &Path, main: &str, watch: Watch) -> Result { + const project = await mkdtemp(join(tmpdir(), 'workerd-wrangler-')); + try { + await writeWranglerProject(project, { name: 'counter' }); + await withCluster( + 2, + async ({ nodes, bucket, nodeKeys }) => { + const counts = []; + let id; + for (const node of nodes) { + const { status, body } = await fetchJson(node.httpPort, '/increment'); + assert.strictEqual(status, 200, JSON.stringify(body)); + counts.push(body.count); + id = body.id; + } + // One object, so one node forwarded its request to the other. + assert.deepStrictEqual(counts, [1, 2]); + const record = await bucket.get( + `${objectPrefix(id, 'counter-Counter')}/own.json` + ); + assert.notStrictEqual(record, null); + const owner = nodes.find( + (node) => nodeKeys.get(node.nodeId) === JSON.parse(record).node + ); + assert(owner !== undefined, record); + // The object is stored in `do/` where --data-dir points, and nothing + // is stored in the project. + assert( + (await readdir(join(owner.localPath, 'do'))).includes( + 'counter-Counter' + ) + ); + assert.deepStrictEqual((await readdir(project)).sort(), [ + 'index.js', + 'wrangler.jsonc', + ]); + }, + { + config: join(project, 'wrangler.jsonc'), + configName: null, + disk: null, + extraArgs: () => ['--cluster-addr=127.0.0.1:0'], + nodeEnv: async () => ({ + WORKERD_CLUSTER_KEY: 'test-cluster-shared-secret-of-32-bytes', + WORKERD_CLUSTER_BUCKET: 's3://wdtest/cluster', + AWS_ACCESS_KEY_ID: 'wdtest', + AWS_SECRET_ACCESS_KEY: 'wdtest-secret', + }), + } + ); + } finally { + await rm(project, { recursive: true, force: true }); + } +}); + +test('cluster: --cluster-addr and --data-dir are refused where they cannot apply', async () => { + const project = await mkdtemp(join(tmpdir(), 'workerd-wrangler-')); + // Spawns `binary` with `args`, and resolves to its exit code and stderr. A + // process still running after 30 s is killed, so its code is null. + const run = async (binary, args, stdout, extraEnv = {}) => { + const child = spawn(binary, args, { + stdio: ['ignore', stdout, 'pipe'], + env: { ...env, ...extraEnv }, + timeout: 30_000, + }); + let stderr = ''; + child.stderr.on('data', (d) => (stderr += d)); + const code = await new Promise((resolve, reject) => { + child.once('error', reject).once('exit', resolve); + }); + return { code, stderr }; + }; + try { + await writeWranglerProject(project, { name: 'counter' }); + const exe = process.platform === 'win32' ? '.exe' : ''; + const binary = join(project, `compiled-workerd${exe}`); + const out = await open(binary, 'w', 0o755); + try { + const compile = await run( + env.WORKERD_BINARY, + ['compile', join(project, 'wrangler.jsonc')], + out.fd + ); + assert.strictEqual(compile.code, 0, compile.stderr); + } finally { + await out.close(); + } + const { code, stderr } = await run( + binary, + [ + '--experimental', + '--socket-addr=http=127.0.0.1:0', + '--cluster-addr=127.0.0.1:0', + ], + 'ignore', + { + ...sharedLibraryPath(env.WORKERD_BINARY), + WORKERD_CLUSTER_KEY: 'test-cluster-shared-secret-of-32-bytes', + WORKERD_CLUSTER_BUCKET: 's3://wdtest/cluster', + AWS_ENDPOINT_URL: 'http://127.0.0.1:1', + } + ); + assert.notStrictEqual(code, 0); + assert.match( + stderr.replace(/\s+/g, ' '), + /the config compiled into this executable has no cluster, so it cannot join one/ + ); + + // A refusal ends the process with an error that says why. + const refused = async (binary, args, message) => { + const { code, stderr } = await run(binary, args, 'ignore', { + ...sharedLibraryPath(env.WORKERD_BINARY), + }); + assert(code !== 0 && code !== null, `${args.join(' ')}: ${code}`); + assert.match(stderr.replace(/\s+/g, ' '), message); + }; + const data = join(project, 'data'); + // The compiled binary's paths were fixed when it was compiled. + await refused( + binary, + ['--experimental', `--data-dir=${data}`], + /--data-dir: the config compiled into this executable fixed its directories/ + ); + // A Cap'n Proto config names its own directories. + await refused( + env.WORKERD_BINARY, + ['serve', env.WD_TEST_CONFIG, 'config', `--data-dir=${data}`], + /--data-dir: only a wrangler config keeps its state there/ + ); + // A config without the disk service `do-storage`, here the wrangler + // config translated for a server that joins no cluster, cannot join one: + // the cluster's deployments keep their Durable Objects on it. + const configOnly = join(project, 'config.bin'); + await writeFile( + configOnly, + await compileConfig(join(project, 'wrangler.jsonc')) + ); + await refused( + env.WORKERD_BINARY, + [ + 'serve', + '--experimental', + '--binary', + configOnly, + '--socket-addr=http=127.0.0.1:0', + '--cluster-addr=127.0.0.1:0', + ], + /--cluster-addr: the config has no writable disk service named `do-storage`/ + ); + // Joining a cluster needs --experimental, as a config's cluster does. + await refused( + env.WORKERD_BINARY, + [ + 'serve', + join(project, 'wrangler.jsonc'), + '--socket-addr=http=127.0.0.1:0', + '--cluster-addr=127.0.0.1:0', + ], + /Cluster mode is experimental; it requires --experimental/ + ); + } finally { + await rm(project, { recursive: true, force: true }); + } +}); diff --git a/src/workerd/server/workerd.capnp b/src/workerd/server/workerd.capnp index e62947b74ec..24ac676b7a0 100644 --- a/src/workerd/server/workerd.capnp +++ b/src/workerd/server/workerd.capnp @@ -96,7 +96,17 @@ struct Config { # Console and Stdio logging configuration options. cluster @7 :ClusterConfig; - # Set when this instance should join a cluster. Requires `--experimental`. + # Set when this instance should join a cluster. Requires `--experimental`. `workerd serve + # --cluster-addr=` joins a config without it, such as a wrangler config, to a cluster as if + # it were `(address = "")`: every other field at its default, so `key` and `bucket` come + # from the environment. A config compiled into a binary by `workerd compile` cannot join this + # way; compile one that sets `cluster`. Nor can a config without the writable disk service + # `do-storage`, which holds the Durable Objects of the cluster's deployments on each instance. + # + # A wrangler config joined this way defines the disk service `do-storage`, which holds its + # Durable Objects and those of the cluster's deployments, even if it has none of its own (see + # `ClusterConfig`), in `do/` of its state directory: `.wrangler/state/workerd` next to it, or + # the one that `--data-dir` names. tracing @8 :TracingOptions; # Where the spans of Worker invocations are exported.