Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(local): new run local (#4379)

teo4ae75233252c
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index aef4c4ca6c..a84c5e3dca 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -4075,6 +4075,7 @@
"workspace-hack"
],
"ses_client": [
+ "macro_env_var",
"ses_client",
"workspace-hack"
],
@@ -4612,80 +4613,11 @@
"workspace-hack"
],
"xtask": [
- "agent",
- "ai_toolset",
- "ai_usage",
- "attachment",
- "authentication_service_client",
- "bot_id",
- "call",
- "channels",
- "connection",
- "connection_gateway_client",
- "connection_gateway_models",
- "contacts",
- "cowlike",
- "crm",
- "decode_jwt",
- "document_sub_type",
- "email",
- "email_db_client",
- "email_utils",
- "entity_access",
- "entity_access_db_utils",
- "filter_ast",
- "foreign_entity",
- "frecency",
- "graphql_soup",
- "invite_email",
- "ip_extractor",
- "item_filters",
- "last_online_tracker",
- "macro_auth",
"macro_aws_config",
- "macro_db_client",
"macro_env",
"macro_env_var",
- "macro_middleware",
- "macro_service_urls",
- "macro_user_id",
- "macro_uuid",
- "mention_utils",
- "model",
- "model-entity",
- "model-error-response",
- "model_file_type",
- "model_notifications",
- "model_user",
- "models_ai_projection",
- "models_bulk_upload",
- "models_dcs",
- "models_email",
- "models_entity_access_management",
- "models_grouping",
- "models_opensearch",
- "models_pagination",
- "models_permissions",
- "models_properties",
- "models_soup",
- "models_team",
- "non_empty",
- "notification",
- "prompt",
- "properties",
- "properties_db_client",
- "rate_limit",
- "readonly_pool",
- "remote_env_var",
- "s3_key",
- "share_permission_db_utils",
- "soup",
- "sqs_client",
- "sqs_worker",
- "system_properties",
+ "macro_queues",
"tools/xtask",
- "unfurl",
- "user_quota",
"workspace-hack"
]
}
diff --git a/.gitignore b/.gitignore
index 28cccce331..602d6b8067 100644
--- a/.gitignore
+++ b/.gitignore
@@ -13,3 +13,5 @@ run-local.fish
**/result-*
.pi/plan/
.pi/plans/
+# Per-instance generated local-stack artifacts (compose override, env, kickstart, Caddyfile).
+infra/local/generated/
diff --git a/RUNNING_LOCALLY.md b/RUNNING_LOCALLY.md
index f3f3e17b85..a4d8b7dabe 100644
--- a/RUNNING_LOCALLY.md
+++ b/RUNNING_LOCALLY.md
@@ -1,80 +1,149 @@
# Running Locally
-**DISCLAIMER**: This is a work in progress and we only support running services against dev-assets at this time.
+Use `just run_local` to run the full app on your machine.
-## Prerequisites
+```bash
+just run_local
+```
+
+This starts local infra, backend services, the local proxy, and the frontend.
+When startup finishes, the command prints the frontend URL and the important
+service URLs.
+
+## Requirements
+
+The easiest path is to use the repo's Nix shell. It should provide the Rust
+toolchain, `cargo-zigbuild`, Zig, Bun, sqlx, and the other project tools.
-- sops
-- Docker
-- AWS
-- SQLX
-- Pulumi
+Outside the Nix shell, you need at least:
+
+- Docker with Compose v2
+- Doppler CLI
+- Rust toolchain
+- `cargo-zigbuild` and Zig
- Bun
-- Node
-- sqlx-cli
+- sqlx CLI
-## Local Setup
+You should also be logged in to Doppler and have access to the `local` project:
-Export the **SOPS_KMS_ARN** (you can skip if you use nix-shell)
+```bash
+doppler login
+```
+
+`run_local` pulls the `lcl_personal` Doppler config by default. If you want to
+run without Doppler, use:
```bash
-export SOPS_KMS_ARN = "arn:aws:kms:us-east-1:569036502058:key/mrk-cab29bf948044eb79005a81f48d40e93,arn:aws:kms:us-west-1:569036502058:key/mrk-cab29bf948044eb79005a81f48d40e93"
+just run_local --no-doppler --env-file ./local.env
```
-Run `just setup` to initialize your entire environment.
+## Running One Stack
+
+Start the default stack:
-Local Docker resources are intentionally frozen to the `macro` Compose project. Multiple checkouts/worktrees share the same containers, volumes, networks, LocalStack, and FusionAuth instance. Do not run two local stacks at the same time.
+```bash
+just run_local
+```
+
+Useful preflight:
-## Running
+```bash
+just doctor-local
+```
-### Backend
+While `run_local` is attached:
-You can run the services via `just run_local`.
+- Press `r` to rebuild and reload changed Rust services.
+- Press `q` to tear the stack down and exit.
-If you've updated the docker image after making changes to a service you'll need
-to provide the `--build` flag in `just run_local` to trigger docker-compose to
-update the containers.
+Prefer `q` over just closing the terminal. It stops/removes the instance's
+containers immediately, so the next startup does not have to clean up a stale
+stack first.
-By default we don't run **convert_service** or **search_processing_service**
-locally as they are not needed by the frontend when using dev assets.
+## Running Multiple Instances
-### Frontend
+Use named instances when you want multiple local stacks at once, especially
+across worktrees:
-You can run the following command to get the frontend running pointed to local
-services `cd js/app && bun i && just local`.
+```bash
+just run_local --instance agent-a
+just run_local --instance agent-b
+```
-### Local E2E smoke test
+Each named instance gets its own Compose project, volumes, networks, generated
+env files, proxy, frontend port, and backend ports. Ports are deterministic for
+the instance name, so the same name should get the same port window on every
+run.
-After `just setup`, run:
+If a generated port window conflicts with something else on your machine:
```bash
-just local-e2e
+just run_local --instance agent-a --port-base 23000
+```
+
+Generated files live at:
+
+```text
+infra/local/generated/<instance>
```
-This starts the local stack using `docker-compose.local-e2e.yml` overrides so
-services use local Postgres/LocalStack instead of shared dev assets, seeds
-deterministic smoke-test data, launches the frontend with local services and
-local bearer-token auth, and runs the Playwright smoke test.
+## What Gets Rebuilt
-The local E2E seed scenario is guarded in code: it requires `LOCAL_E2E_SEED=true`
-and refuses any `DATABASE_URL` that is not the local Docker database
-`postgres://user:...@(localhost|127.0.0.1|postgres):5432/macrodb`.
+Rust backend services are built on the host with `cargo zigbuild` and mounted
+into a shared runtime image. Docker is not compiling those Rust services during
+normal `run_local`.
-Shared fixture data lives under `rust/cloud-storage/seed_cli/seed`; local users
-are in `local_e2e/users.json`, Playwright tests can read the same data via
-`js/app/tests/e2e/fixtures/local-e2e-seed.ts`, and Rust tests can use
-`local_e2e_test_support`. The Rust helper also rejects non-local service URLs
-for mutating tests.
+Pressing `r` rebuilds the Rust binaries and restarts only the services whose
+binaries changed.
-To run the ignored Rust integration tests against the same local stack:
+The current rough edge is auxiliary Docker-built services:
+
+- `sync_service`
+- `lexical_service`
+- `websocket_service`
+
+Those are not rebuilt by default. If you change sync-service, lexical-service,
+or anything that affects their Docker images, the running stack can keep using a
+stale image.
+
+To force those services to rebuild:
+
+```bash
+just run_local --build-aux-services
+```
+
+When the stack was started with `--build-aux-services`, pressing `r` also
+rebuilds those auxiliary images and recreates their containers. That is slower,
+so leave it off unless you are actively working on those services or need to
+pick up a change there.
+
+If you already started without `--build-aux-services` and suspect a stale
+sync/lexical image, press `q` and restart with the flag.
+
+## Common Commands
+
+Run local binaries against shared dev resources instead of a fully local stack:
```bash
-just local-e2e-rust
+just run_dev
```
-To run both Rust integration tests and Playwright tests after one stack startup
-and seed pass:
+Stop an instance but keep its volumes:
```bash
-just local-e2e-all
+just stop_local --instance agent-a
```
+
+Remove an instance's containers, volumes, and named-instance networks:
+
+```bash
+just destroy_local --instance agent-a
+```
+
+Drop, recreate, and migrate an instance database:
+
+```bash
+just reset_local --instance agent-a
+```
+
+For the default instance, omit `--instance`.
diff --git a/docker-compose.yml b/docker-compose.yml
index 2802e447a3..2c401ffe2c 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -9,8 +9,12 @@ include:
- infra/stacks/fusionauth-instance/docker-compose.yml
x-common-env: &common-env
+ # The xtask orchestrator points this at a per-instance generated env file via
+ # MACRO_ENV_FILE (run-local/run-dev). Defaults to .env for any legacy/manual
+ # `docker compose` invocation, and is optional so a missing file is not fatal.
env_file:
- - .env
+ - path: ${MACRO_ENV_FILE:-.env}
+ required: false
x-rust-services-image: &rust-services-image
image: macro-local-rust-services:dev
@@ -419,6 +423,12 @@ services:
- "8096:8096"
depends_on:
- sync_service
+ # Bundle the entry before running. Executing the unbundled TS directly under
+ # Bun evaluates the circular @lexical/* ESM imports in an order that triggers
+ # a TDZ ("Cannot access 'HeadingNode'/'ElementNode' before initialization");
+ # bundling hoists/orders the declarations and resolves it (matching how the
+ # worker is run normally — wrangler/esbuild bundles it first).
+ command: ["sh", "-c", "bun build src/server.ts --target=bun --outfile=/tmp/server.js && exec bun /tmp/server.js"]
environment:
- PORT=8096
- INTERNAL_AUTH_KEY=${INTERNAL_API_SECRET_KEY}
diff --git a/js/app/packages/core/constant/servers.ts b/js/app/packages/core/constant/servers.ts
index 3befe9eeb9..4788dc81bd 100644
--- a/js/app/packages/core/constant/servers.ts
+++ b/js/app/packages/core/constant/servers.ts
@@ -41,11 +41,41 @@ const serverHostRemote = {
type Servers = Record<keyof typeof serverHostRemote, string>;
+// Single-origin local backend: when the xtask orchestrator's reverse proxy is
+// in use it sets VITE_LOCAL_BACKEND_ORIGIN to the proxy origin, and the whole
+// app talks to it via path prefixes instead of many direct host ports. Unset =>
+// direct-port behavior (unchanged). Declared BEFORE SERVER_HOSTS so it is
+// initialized before SERVER_HOSTS evaluates selectLocalServers() at module load
+// (these are consts in a temporal dead zone; the functions below are hoisted).
+const proxyOrigin: string | undefined = import.meta.env
+ .VITE_LOCAL_BACKEND_ORIGIN;
+const wsProxyOrigin = proxyOrigin?.replace(/^http/, 'ws');
+
export const SERVER_HOSTS: Servers =
import.meta.env.MODE === 'development'
? selectLocalServers()
: serverHostRemote;
+function proxyServers(): Servers | undefined {
+ if (!proxyOrigin || !wsProxyOrigin) return undefined;
+ return {
+ 'auth-service': `${proxyOrigin}/auth`,
+ 'auth-logout': serverHostLocal['auth-logout'],
+ 'pdf-service': serverHostLocal['pdf-service'], // no local container
+ 'document-storage-service': `${proxyOrigin}/dss`,
+ 'websocket-service': `${wsProxyOrigin}/websocket`,
+ 'cognition-service': `${proxyOrigin}/cognition`,
+ 'connection-gateway': `${wsProxyOrigin}/connection-gateway`,
+ 'notification-service': `${proxyOrigin}/notification`,
+ 'static-file': `${proxyOrigin}/static-file`,
+ 'unfurl-service': `${proxyOrigin}/unfurl`,
+ contacts: `${proxyOrigin}/contacts`,
+ 'email-service': `${proxyOrigin}/email`,
+ 'image-proxy-service': `${proxyOrigin}/image-proxy`,
+ 'scheduled-action': serverHostLocal['scheduled-action'], // no local container
+ };
+}
+
function selectLocalServers(): Servers {
const selectedLocalServers: string = import.meta.env.VITE_LOCAL_SERVERS;
if (!selectedLocalServers || selectedLocalServers.length === 0) {
@@ -54,7 +84,7 @@ function selectLocalServers(): Servers {
// Keyword to make running everything locally easier
if (selectedLocalServers === 'ALL') {
- return serverHostLocal;
+ return proxyServers() ?? serverHostLocal;
}
function assertValidName(name: string): name is keyof Servers {
@@ -118,6 +148,10 @@ function selectSyncServiceHost():
selectedLocalServers === 'ALL' ||
selectedLocalServers?.includes('sync-service')
) {
+ // Route sync through the single-origin proxy when it is in use.
+ if (proxyOrigin && wsProxyOrigin) {
+ return { worker: `${proxyOrigin}/sync`, ws: `${wsProxyOrigin}/sync` };
+ }
return syncServiceHostLocal;
}
return syncServiceHostRemote;
diff --git a/just/xtask.just b/just/xtask.just
new file mode 100644
index 0000000000..4958723d5f
--- /dev/null
+++ b/just/xtask.just
@@ -0,0 +1,29 @@
+# xtask owns all local/dev orchestration; these recipes are thin delegates.
+xtask := "cargo run --quiet --manifest-path rust/cloud-storage/Cargo.toml -p xtask --"
+
+# Start a fully local stack (xtask: zigbuild + runtime image + infra + proxy + frontend).
+# just run_local # default instance
+# just run_local --instance agent-a # isolated, concurrent instance
+# just run_local --no-doppler --env-file ./local.env --no-frontend --no-build
+run_local *ARGS:
+ {{ xtask }} run-local "$@"
+
+# Run local binaries against shared dev resources (no local infra).
+run_dev *ARGS:
+ {{ xtask }} run-dev "$@"
+
+# Check tools/toolchain/ports/env for the local stack.
+doctor-local *ARGS:
+ {{ xtask }} doctor-local "$@"
+
+# Reset (drop, recreate, migrate) the instance database.
+reset_local *ARGS:
+ {{ xtask }} reset-local "$@"
+
+# Remove an instance's containers, networks, and volumes.
+destroy_local *ARGS:
+ {{ xtask }} destroy-local "$@"
+
+# Stop an instance's containers, keeping volumes (xtask).
+stop_local *ARGS:
+ {{ xtask }} stop-local "$@"
diff --git a/justfile b/justfile
index c155500c71..88001a970e 100644
--- a/justfile
+++ b/justfile
@@ -40,15 +40,6 @@ docker_up *ARGS:
echo "startup docker compose"
docker compose up {{ ARGS }}
-# Run all services locally using docker-compose
-# Requires .env file (from `just get_environment`) and FusionAuth setup (from `just setup`).
-# Automatically patches .env with local FusionAuth values before starting services.
-# Uses staged output by default; set MACRO_LOCAL_VERBOSE=1 to show command output.
-run_local *ARGS:
- #!/usr/bin/env bash
- set -euo pipefail
- bash scripts/run-local.sh "$@"
-
# Reset and seed deterministic data used by local E2E tests.
local-e2e-seed:
just run_dbs -d
@@ -71,21 +62,21 @@ check-node-modules-nix:
# Start the local stack, seed deterministic data, and run the Playwright smoke suite.
local-e2e *ARGS:
AWS_ACCESS_KEY_ID=test AWS_SECRET_ACCESS_KEY=test AWS_DEFAULT_REGION=us-east-1 just setup_localstack
- COMPOSE_FILE=docker-compose.yml:docker-compose.local-e2e.yml just run_local -d --wait {{ local-e2e-services }}
+ COMPOSE_FILE=docker-compose.yml:docker-compose.local-e2e.yml bash scripts/run-local.sh -d --wait {{ local-e2e-services }}
just local-e2e-seed
cd js/app && LOCAL_E2E=true bunx playwright test {{ ARGS }}
# Start the local stack, seed deterministic data, and run ignored Rust local E2E integration tests.
local-e2e-rust *ARGS:
AWS_ACCESS_KEY_ID=test AWS_SECRET_ACCESS_KEY=test AWS_DEFAULT_REGION=us-east-1 just setup_localstack
- COMPOSE_FILE=docker-compose.yml:docker-compose.local-e2e.yml just run_local -d --wait {{ local-e2e-services }}
+ COMPOSE_FILE=docker-compose.yml:docker-compose.local-e2e.yml bash scripts/run-local.sh -d --wait {{ local-e2e-services }}
just local-e2e-seed
cd rust/cloud-storage && SQLX_OFFLINE=true cargo test -p local_e2e_integration_tests -- --ignored --nocapture {{ ARGS }}
# Start the local stack once, seed deterministic data, and run Rust + Playwright local E2E tests.
local-e2e-all *ARGS:
AWS_ACCESS_KEY_ID=test AWS_SECRET_ACCESS_KEY=test AWS_DEFAULT_REGION=us-east-1 just setup_localstack
- COMPOSE_FILE=docker-compose.yml:docker-compose.local-e2e.yml just run_local -d --wait {{ local-e2e-services }}
+ COMPOSE_FILE=docker-compose.yml:docker-compose.local-e2e.yml bash scripts/run-local.sh -d --wait {{ local-e2e-services }}
just local-e2e-seed
cd rust/cloud-storage && SQLX_OFFLINE=true cargo test -p local_e2e_integration_tests -- --ignored --nocapture
cd js/app && LOCAL_E2E=true bunx playwright test {{ ARGS }}
@@ -93,7 +84,7 @@ local-e2e-all *ARGS:
# Start the local stack, seed deterministic data, and open Playwright UI mode.
local-e2e-ui *ARGS:
AWS_ACCESS_KEY_ID=test AWS_SECRET_ACCESS_KEY=test AWS_DEFAULT_REGION=us-east-1 just setup_localstack
- COMPOSE_FILE=docker-compose.yml:docker-compose.local-e2e.yml just run_local -d --wait {{ local-e2e-services }}
+ COMPOSE_FILE=docker-compose.yml:docker-compose.local-e2e.yml bash scripts/run-local.sh -d --wait {{ local-e2e-services }}
just local-e2e-seed
cd js/app && LOCAL_E2E=true bunx playwright test --ui {{ ARGS }}
@@ -132,7 +123,7 @@ patch_local_fusionauth_env:
fi
just infra/stacks/fusionauth-instance/insert_local_fusionauth_variables
-# Stop all local services
+# Stop all local services (default project; legacy alias).
stop-local:
docker compose down
@@ -141,6 +132,7 @@ stop-databases:
# Import LocalStack recipes
import 'local_stack.just'
+import 'just/xtask.just'
# Sets up local database
setup_local_dbs:
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 049dc2bd94..3f831e2660 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -1952,6 +1952,49 @@ dependencies = [
"objc2",
]
+[[package]]
+name = "bollard"
+version = "0.21.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c9d0a013e3d3ee4edd61e779adf117944c08902d375f18630a0c5b8f95659734"
+dependencies = [
+ "base64 0.22.1",
+ "bollard-stubs",
+ "bytes",
+ "futures-core",
+ "futures-util",
+ "hex",
+ "http 1.4.0",
+ "http-body-util",
+ "hyper 1.9.0",
+ "hyper-named-pipe",
+ "hyper-util",
+ "hyperlocal",
+ "log",
+ "pin-project-lite",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "serde_urlencoded",
+ "thiserror 2.0.18",
+ "tokio",
+ "tokio-util",
+ "tower-service",
+ "url",
+ "winapi",
+]
+
+[[package]]
+name = "bollard-stubs"
+version = "1.53.1-rc.29.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce412eb6f7096743011dc3cb5c674caeb24ced61d8c498fe07cf7998a4fea889"
+dependencies = [
+ "serde",
+ "serde_json",
+ "serde_repr",
+]
+
[[package]]
name = "borsh"
version = "1.6.1"
@@ -2726,6 +2769,31 @@ dependencies = [
"workspace-hack",
]
+[[package]]
+name = "console"
+version = "0.15.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "054ccb5b10f9f2cbf51eb355ca1d05c2d279ce1804688d0db74b4733a5aeafd8"
+dependencies = [
+ "encode_unicode",
+ "libc",
+ "once_cell",
+ "unicode-width 0.2.2",
+ "windows-sys 0.59.0",
+]
+
+[[package]]
+name = "console"
+version = "0.16.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d64e8af5551369d19cf50138de61f1c42074ab970f74e99be916646777f8fc87"
+dependencies = [
+ "encode_unicode",
+ "libc",
+ "unicode-width 0.2.2",
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "console_error_panic_hook"
version = "0.1.7"
@@ -3710,6 +3778,18 @@ dependencies = [
"syn 2.0.117",
]
+[[package]]
+name = "docker-compose-types"
+version = "0.24.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bdfd601efc90644958510466e8904ca90da65a98fdfe4d21f940644a21c026b4"
+dependencies = [
+ "derive_builder",
+ "indexmap 2.14.0",
+ "serde",
+ "serde_yaml",
+]
+
[[package]]
name = "document_cognition_service"
version = "0.1.0"
@@ -4360,6 +4440,22 @@ dependencies = [
"workspace-hack",
]
+[[package]]
+name = "email-encoding"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9298e6504d9b9e780ed3f7dfd43a61be8cd0e09eb07f7706a945b0072b6670b6"
+dependencies = [
+ "base64 0.22.1",
+ "memchr",
+]
+
+[[package]]
+name = "email_address"
+version = "0.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e079f19b08ca6239f47f8ba8509c11cf3ea30095831f7fed61441475edd8c449"
+
[[package]]
name = "email_db_client"
version = "0.1.0"
@@ -4630,6 +4726,12 @@ dependencies = [
"workspace-hack",
]
+[[package]]
+name = "encode_unicode"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0"
+
[[package]]
name = "encoding_rs"
version = "0.8.35"
@@ -4752,7 +4854,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
- "windows-sys 0.61.2",
+ "windows-sys 0.52.0",
]
[[package]]
@@ -5425,6 +5527,7 @@ dependencies = [
name = "graphql_soup"
version = "0.1.0"
dependencies = [
+ "anyhow",
"async-graphql",
"async-trait",
"chrono",
@@ -6033,6 +6136,21 @@ dependencies = [
"want",
]
+[[package]]
+name = "hyper-named-pipe"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "73b7d8abf35697b81a825e386fc151e0d503e8cb5fcb93cc8669c376dfd6f278"
+dependencies = [
+ "hex",
+ "hyper 1.9.0",
+ "hyper-util",
+ "pin-project-lite",
+ "tokio",
+ "tower-service",
+ "winapi",
+]
+
[[package]]
name = "hyper-rustls"
version = "0.24.2"
@@ -6104,6 +6222,21 @@ dependencies = [
"windows-registry",
]
+[[package]]
+name = "hyperlocal"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "986c5ce3b994526b3cd75578e62554abd09f0899d6206de48b3e96ab34ccc8c7"
+dependencies = [
+ "hex",
+ "http-body-util",
+ "hyper 1.9.0",
+ "hyper-util",
+ "pin-project-lite",
+ "tokio",
+ "tower-service",
+]
+
[[package]]
name = "iana-time-zone"
version = "0.1.65"
@@ -6411,6 +6544,19 @@ dependencies = [
"serde_core",
]
+[[package]]
+name = "indicatif"
+version = "0.18.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "70a646d946d06bedbbc4cac4c218acf4bbf2d87757a784857025f4d447e4e1cd"
+dependencies = [
+ "console 0.16.3",
+ "portable-atomic",
+ "unicode-width 0.2.2",
+ "unit-prefix",
+ "web-time",
+]
+
[[package]]
name = "indoc"
version = "2.0.7"
@@ -6848,6 +6994,33 @@ version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8"
+[[package]]
+name = "lettre"
+version = "0.11.22"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0da65617f6cb926332d039cb578aad56178da86e128db6a1b09f4c94fa5b3349"
+dependencies = [
+ "async-trait",
+ "base64 0.22.1",
+ "email-encoding",
+ "email_address",
+ "fastrand 2.4.1",
+ "futures-io",
+ "futures-util",
+ "httpdate",
+ "idna",
+ "mime",
+ "nom 8.0.0",
+ "percent-encoding",
+ "quoted_printable",
+ "rustls 0.23.40",
+ "socket2 0.6.3",
+ "tokio",
+ "tokio-rustls 0.26.4",
+ "url",
+ "webpki-roots 1.0.7",
+]
+
[[package]]
name = "lexical_client"
version = "0.1.0"
@@ -8627,7 +8800,7 @@ version = "0.50.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
dependencies = [
- "windows-sys 0.61.2",
+ "windows-sys 0.59.0",
]
[[package]]
@@ -10924,7 +11097,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys 0.12.1",
- "windows-sys 0.61.2",
+ "windows-sys 0.52.0",
]
[[package]]
@@ -10946,6 +11119,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef86cd5876211988985292b91c96a8f2d298df24e75989a43a3c73f2d4d8168b"
dependencies = [
"aws-lc-rs",
+ "log",
"once_cell",
"ring",
"rustls-pki-types",
@@ -10994,7 +11168,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
- "windows-sys 0.61.2",
+ "windows-sys 0.52.0",
]
[[package]]
@@ -11699,6 +11873,19 @@ dependencies = [
"syn 2.0.117",
]
+[[package]]
+name = "serde_yaml"
+version = "0.9.34+deprecated"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47"
+dependencies = [
+ "indexmap 2.14.0",
+ "itoa",
+ "ryu",
+ "serde",
+ "unsafe-libyaml",
+]
+
[[package]]
name = "serde_yml"
version = "0.0.12"
@@ -11764,6 +11951,8 @@ version = "0.1.0"
dependencies = [
"anyhow",
"aws-sdk-sesv2",
+ "lettre",
+ "macro_env_var",
"mockall",
"tracing",
"workspace-hack",
@@ -12805,7 +12994,7 @@ dependencies = [
"getrandom 0.4.2",
"once_cell",
"rustix 1.1.4",
- "windows-sys 0.61.2",
+ "windows-sys 0.52.0",
]
[[package]]
@@ -13593,6 +13782,12 @@ version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
+[[package]]
+name = "unit-prefix"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "81e544489bf3d8ef66c953931f56617f423cd4b5494be343d9b9d3dda037b9a3"
+
[[package]]
name = "universal-hash"
version = "0.5.1"
@@ -13603,6 +13798,12 @@ dependencies = [
"subtle",
]
+[[package]]
+name = "unsafe-libyaml"
+version = "0.2.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861"
+
[[package]]
name = "unsynn"
version = "0.3.0"
@@ -14219,7 +14420,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
- "windows-sys 0.61.2",
+ "windows-sys 0.48.0",
]
[[package]]
@@ -14725,6 +14926,7 @@ dependencies = [
"hyper-rustls 0.24.2",
"hyper-rustls 0.27.9",
"hyper-util",
+ "idna",
"indexmap 2.14.0",
"ipnet",
"lazy_static",
@@ -14816,12 +15018,28 @@ name = "xtask"
version = "0.1.0"
dependencies = [
"anyhow",
+ "aws-sdk-dynamodb",
+ "aws-sdk-s3",
+ "aws-sdk-sqs",
+ "bollard",
+ "clap",
+ "console 0.15.11",
+ "docker-compose-types",
+ "dotenvy",
"gh-workflow",
- "graphql_soup",
"guppy",
"hakari",
+ "indexmap 2.14.0",
+ "indicatif",
"indoc",
+ "libc",
+ "macro_aws_config",
+ "macro_queues",
+ "serde",
"serde_json",
+ "serde_yaml",
+ "strum",
+ "tokio",
]
[[package]]
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index 2b3ee744ee..fcb788345b 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -58,7 +58,10 @@ members = [
"upload_extractor_lambda_trigger",
"user_link_cleanup_handler",
"worker_trigger",
+ "macro_config",
"macro_event_broker",
+ "macro_event_topics",
+ "macro_queues",
"prompt",
"workspace-hack",
"tools/xtask",
@@ -108,6 +111,7 @@ http = "1"
http-body-util = "0.1.2"
image = "0.25"
inquire = "0.7"
+indexmap = "2"
itertools = "0.14"
jsonwebtoken = { git = "https://github.com/whutchinson98/jsonwebtoken", features = [
"rust_crypto",
diff --git a/rust/cloud-storage/authentication_service/src/main.rs b/rust/cloud-storage/authentication_service/src/main.rs
index 80f288c163..a26ab11233 100644
--- a/rust/cloud-storage/authentication_service/src/main.rs
+++ b/rust/cloud-storage/authentication_service/src/main.rs
@@ -165,7 +165,8 @@ async fn main() -> anyhow::Result<()> {
let stripe_client = stripe::Client::new(stripe_client_secret);
tracing::trace!("initialized stripe client");
- let ses_client = ses_client::Ses::new(
+ // `from_env` routes to local SMTP (Mailpit) when SMTP_HOST is set, else SES.
+ let ses_client = ses_client::Ses::from_env(
aws_sdk_sesv2::Client::new(&macro_aws_config::get_macro_aws_config().await),
&config.environment.to_string(),
);
diff --git a/rust/cloud-storage/docker/Dockerfile.runtime b/rust/cloud-storage/docker/Dockerfile.runtime
new file mode 100644
index 0000000000..0bb2b44b14
--- /dev/null
+++ b/rust/cloud-storage/docker/Dockerfile.runtime
@@ -0,0 +1,19 @@
+# syntax=docker/dockerfile:1
+#
+# Minimal runtime image for locally-built service binaries.
+#
+# Built by `cargo x runtime-image` (xtask) and tagged `macro-local-runtime:dev`.
+# Service binaries are NOT baked in — they are bind-mounted read-only at
+# /app/out by the generated compose override, so this image never needs
+# rebuilding when Rust code changes. This is the `base` stage of Dockerfile.dev
+# with the in-Docker `cargo build` and binary COPY removed.
+FROM debian:trixie-slim
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ ca-certificates dumb-init curl \
+ && apt-get clean && rm -rf /var/lib/apt/lists/*
+WORKDIR /app
+ENV PORT=8080
+EXPOSE 8080
+# No CMD: the generated compose override supplies `command: ["/app/out/<bin>"]`
+# per service, exactly as the old services_bundle image did.
+ENTRYPOINT ["dumb-init", "--"]
diff --git a/rust/cloud-storage/graphql_soup/Cargo.toml b/rust/cloud-storage/graphql_soup/Cargo.toml
index 0dce0f2156..d23275efcc 100644
--- a/rust/cloud-storage/graphql_soup/Cargo.toml
+++ b/rust/cloud-storage/graphql_soup/Cargo.toml
@@ -5,6 +5,7 @@ edition = "2024"
publish = false
[dependencies]
+anyhow = { workspace = true }
async-graphql = { workspace = true, features = ["dataloader"] }
async-trait = { workspace = true }
chrono = { workspace = true }
diff --git a/rust/cloud-storage/graphql_soup/src/bin/graphql_soup_schema.rs b/rust/cloud-storage/graphql_soup/src/bin/graphql_soup_schema.rs
new file mode 100644
index 0000000000..3b507535b2
--- /dev/null
+++ b/rust/cloud-storage/graphql_soup/src/bin/graphql_soup_schema.rs
@@ -0,0 +1,26 @@
+use std::{fs, path::PathBuf};
+
+use anyhow::{Context, Result};
+
+fn main() -> Result<()> {
+ let output_path = std::env::args_os()
+ .nth(1)
+ .map(PathBuf::from)
+ .context("usage: graphql_soup_schema <output-path>")?;
+
+ let schema = graphql_soup::build_schema().sdl();
+
+ if let Some(parent) = output_path
+ .parent()
+ .filter(|parent| !parent.as_os_str().is_empty())
+ {
+ fs::create_dir_all(parent)
+ .with_context(|| format!("creating parent directory {}", parent.display()))?;
+ }
+
+ fs::write(&output_path, format!("{schema}\n"))
+ .with_context(|| format!("writing GraphQL Soup schema to {}", output_path.display()))?;
+
+ println!("wrote GraphQL Soup schema to {}", output_path.display());
+ Ok(())
+}
diff --git a/rust/cloud-storage/macro_aws_config/src/lib.rs b/rust/cloud-storage/macro_aws_config/src/lib.rs
index 7247e7c5f9..57e12ebb9d 100644
--- a/rust/cloud-storage/macro_aws_config/src/lib.rs
+++ b/rust/cloud-storage/macro_aws_config/src/lib.rs
@@ -31,12 +31,7 @@ pub async fn sqs_client() -> aws_sdk_sqs::Client {
/// Otherwise we load normally.
pub async fn get_macro_aws_config() -> aws_config::SdkConfig {
if let Some(local_aws_url) = LocalAwsUrl::new() {
- aws_config::defaults(aws_config::BehaviorVersion::latest())
- .region("us-east-1")
- .test_credentials()
- .endpoint_url(local_aws_url.as_ref())
- .load()
- .await
+ local_aws_config(local_aws_url.as_ref()).await
} else {
aws_config::defaults(aws_config::BehaviorVersion::latest())
.region("us-east-1")
@@ -45,6 +40,16 @@ pub async fn get_macro_aws_config() -> aws_config::SdkConfig {
}
}
+/// Creates an AWS SDK config pointed at a LocalStack endpoint.
+pub async fn local_aws_config(local_aws_url: &str) -> aws_config::SdkConfig {
+ aws_config::defaults(aws_config::BehaviorVersion::latest())
+ .region("us-east-1")
+ .test_credentials()
+ .endpoint_url(local_aws_url)
+ .load()
+ .await
+}
+
/// Returns if the aws config is local or not
pub fn is_local_aws() -> bool {
LocalAwsUrl::new().is_some()
diff --git a/rust/cloud-storage/macro_cors/src/lib.rs b/rust/cloud-storage/macro_cors/src/lib.rs
index cb9b24ddf3..8c9feafec7 100644
--- a/rust/cloud-storage/macro_cors/src/lib.rs
+++ b/rust/cloud-storage/macro_cors/src/lib.rs
@@ -59,13 +59,10 @@ fn is_allowed_origin(origin: &str) -> bool {
return true;
}
- // Check for localhost:3xxx pattern
- if origin.starts_with("http://localhost:3")
- && origin.len() == 21
- && let Some(port_str) = origin.strip_prefix("http://localhost:")
+ if let Some(port_str) = origin.strip_prefix("http://localhost:")
&& let Ok(port) = port_str.parse::<u16>()
{
- return (3000..=3999).contains(&port);
+ return (3000..=3999).contains(&port) || (20000..=60000).contains(&port);
}
false
diff --git a/rust/cloud-storage/macro_queues/src/lib.rs b/rust/cloud-storage/macro_queues/src/lib.rs
index 71cbc23920..b44a7cc96b 100644
--- a/rust/cloud-storage/macro_queues/src/lib.rs
+++ b/rust/cloud-storage/macro_queues/src/lib.rs
@@ -591,6 +591,12 @@ queue! {
dev: "bulk-upload-queue-dev",
prod: "bulk-upload-queue-prod",
},
+ /// Queue for document upload finalization events.
+ pub DocumentUploadFinalizerQueue {
+ local: "document-upload-finalizer-queue",
+ dev: "document-upload-finalizer-queue-dev",
+ prod: "document-upload-finalizer-queue-prod",
+ },
/// Queue for the organization retention handler
/// (organization_retention_trigger `ORGANIZATION_RETENTION_QUEUE`).
pub OrganizationRetentionQueue {
diff --git a/rust/cloud-storage/search_service/Cargo.toml b/rust/cloud-storage/search_service/Cargo.toml
index 6dc73fa1cf..be01c51c2b 100644
--- a/rust/cloud-storage/search_service/Cargo.toml
+++ b/rust/cloud-storage/search_service/Cargo.toml
@@ -28,7 +28,7 @@ entity_access = { path = "../entity_access", default-features = false, features
] }
futures = { workspace = true }
http-body-util = { workspace = true }
-indexmap = "2"
+indexmap = { workspace = true }
item_filters = { path = "../item_filters" }
macro_auth = { path = "../macro_auth" }
macro_db_client = { path = "../macro_db_client" }
diff --git a/rust/cloud-storage/ses_client/Cargo.toml b/rust/cloud-storage/ses_client/Cargo.toml
index 87a3bf0740..a2944de10a 100644
--- a/rust/cloud-storage/ses_client/Cargo.toml
+++ b/rust/cloud-storage/ses_client/Cargo.toml
@@ -10,6 +10,14 @@ local = []
[dependencies]
anyhow = { workspace = true }
aws-sdk-sesv2 = { workspace = true }
+# Local-mode SMTP delivery (Mailpit). rustls (no native-tls/openssl); the local
+# transport itself is plaintext via builder_dangerous.
+lettre = { version = "0.11", default-features = false, features = [
+ "builder",
+ "smtp-transport",
+ "tokio1-rustls-tls",
+] }
+macro_env_var = { path = "../macro_env_var" }
mockall = { workspace = true }
tracing = { workspace = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
diff --git a/rust/cloud-storage/ses_client/src/invite_user.rs b/rust/cloud-storage/ses_client/src/invite_user.rs
index 45330116c9..f8bda7ec5a 100644
--- a/rust/cloud-storage/ses_client/src/invite_user.rs
+++ b/rust/cloud-storage/ses_client/src/invite_user.rs
@@ -1,13 +1,7 @@
-use anyhow::Context;
-use aws_sdk_sesv2::{
- self as ses,
- types::{Body, Content, Destination, EmailContent, Message},
-};
-
-static INVITE_USER_SUBJECT: &str = "Invitation to Macro";
+pub(crate) static INVITE_USER_SUBJECT: &str = "Invitation to Macro";
/// Builds the user invite message
-fn build_user_invite_message(org_name: &str, environment: &str) -> String {
+pub(crate) fn build_user_invite_message(org_name: &str, environment: &str) -> String {
let prefix = match environment {
"prod" => "".to_string(),
_ => format!("{}.", environment),
@@ -154,50 +148,6 @@ fn build_user_invite_message(org_name: &str, environment: &str) -> String {
result.replace("{ORG_NAME}", org_name)
}
-/// Sends an invitation email to the user
-#[tracing::instrument(skip(client))]
-pub async fn invite_user(
- client: &ses::Client,
- org_name: &str,
- environment: &str,
- from_email: &str,
- to_email: &str,
-) -> anyhow::Result<()> {
- let mut dest: Destination = Destination::builder().build();
- dest.to_addresses = Some(vec![to_email.to_string()]);
-
- let subject_content = Content::builder()
- .data(INVITE_USER_SUBJECT)
- .charset("UTF-8")
- .build()
- .context("building Content")?;
-
- let body_content = Content::builder()
- .data(build_user_invite_message(org_name, environment))
- .charset("UTF-8")
- .build()
- .context("building Content")?;
-
- let body = Body::builder().html(body_content).build();
-
- let msg = Message::builder()
- .subject(subject_content)
- .body(body)
- .build();
-
- let email_content = EmailContent::builder().simple(msg).build();
-
- client
- .send_email()
- .from_email_address(from_email)
- .destination(dest)
- .content(email_content)
- .send()
- .await?;
-
- Ok(())
-}
-
#[cfg(test)]
mod tests {
diff --git a/rust/cloud-storage/ses_client/src/lib.rs b/rust/cloud-storage/ses_client/src/lib.rs
index 52003050ef..6194d709b1 100644
--- a/rust/cloud-storage/ses_client/src/lib.rs
+++ b/rust/cloud-storage/ses_client/src/lib.rs
@@ -1,31 +1,58 @@
mod invite_user;
mod send_email;
+mod send_email_smtp;
use aws_sdk_sesv2 as ses;
#[allow(unused_imports)]
use mockall::automock;
+macro_env_var::maybe_env_vars! {
+ struct SmtpHost;
+ struct SmtpPort;
+}
+
#[cfg(test)]
pub use MockSesClient as Ses;
#[cfg(not(test))]
pub use SesClient as Ses;
+/// How outbound mail is delivered. SES in dev/prod; SMTP to a local Mailpit in
+/// local mode (selected by the `SMTP_HOST` env var).
+#[derive(Clone, Debug)]
+enum Transport {
+ Ses(ses::Client),
+ Smtp { host: String, port: u16 },
+}
+
#[derive(Clone, Debug)]
pub struct SesClient {
- inner: ses::Client,
+ transport: Transport,
invite_email: Option<String>,
environment: String,
}
#[cfg_attr(test, automock)]
impl SesClient {
- pub fn new(inner: ses::Client, environment: &str) -> Self {
+ /// Construct from the environment: route to local SMTP (Mailpit) when
+ /// `SMTP_HOST` is set, otherwise SES. The SES client is still passed in (and
+ /// kept for the SES path) so callers don't branch.
+ pub fn from_env(inner: ses::Client, environment: &str) -> Self {
+ let transport = match SmtpHost::new().and_then(|host| host.value().map(str::to_string)) {
+ Some(host) if !host.is_empty() => {
+ let port = SmtpPort::new()
+ .and_then(|p| p.value().and_then(|p| p.parse().ok()))
+ .unwrap_or(1025);
+ Transport::Smtp { host, port }
+ }
+ _ => Transport::Ses(inner),
+ };
Self {
- inner,
+ transport,
invite_email: None,
environment: environment.to_string(),
}
}
+
/// Sets the invite_email
pub fn invite_email(mut self, invite_email: &str) -> Self {
self.invite_email = Some(invite_email.to_string());
@@ -35,18 +62,17 @@ impl SesClient {
/// Sends an invitation email to the user
#[tracing::instrument(skip(self))]
pub async fn invite_user(&self, organization_name: &str, email: &str) -> anyhow::Result<()> {
- if let Some(invite_email) = &self.invite_email {
- return invite_user::invite_user(
- &self.inner,
- organization_name,
- self.environment.as_str(),
- invite_email.as_str(),
- email,
- )
- .await;
- }
-
- Err(anyhow::anyhow!("invite_email is not set"))
+ let Some(invite_email) = self.invite_email.clone() else {
+ return Err(anyhow::anyhow!("invite_email is not set"));
+ };
+ let html = invite_user::build_user_invite_message(organization_name, &self.environment);
+ self.deliver(
+ &invite_email,
+ email,
+ invite_user::INVITE_USER_SUBJECT,
+ &html,
+ )
+ .await
}
/// Sends an email to the user
@@ -58,6 +84,29 @@ impl SesClient {
subject: &str,
content: &str,
) -> anyhow::Result<()> {
- send_email::send_email(&self.inner, from_email, to_email, subject, content).await
+ self.deliver(from_email, to_email, subject, content).await
+ }
+}
+
+impl SesClient {
+ /// Route a fully-rendered HTML email through the active transport.
+ async fn deliver(
+ &self,
+ from_email: &str,
+ to_email: &str,
+ subject: &str,
+ content: &str,
+ ) -> anyhow::Result<()> {
+ match &self.transport {
+ Transport::Ses(client) => {
+ send_email::send_email(client, from_email, to_email, subject, content).await
+ }
+ Transport::Smtp { host, port } => {
+ send_email_smtp::send_email_smtp(
+ host, *port, from_email, to_email, subject, content,
+ )
+ .await
+ }
+ }
}
}
diff --git a/rust/cloud-storage/ses_client/src/send_email_smtp.rs b/rust/cloud-storage/ses_client/src/send_email_smtp.rs
new file mode 100644
index 0000000000..58ecbb79e6
--- /dev/null
+++ b/rust/cloud-storage/ses_client/src/send_email_smtp.rs
@@ -0,0 +1,43 @@
+//! SMTP delivery for local mode. Sends to a plaintext SMTP sink (Mailpit) so
+//! local email flows are inspectable without SES or real credentials.
+
+use anyhow::{Context, Result};
+use lettre::message::Mailbox;
+use lettre::message::header::ContentType;
+use lettre::{Address, AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor};
+
+/// Send an HTML email over plaintext SMTP (no TLS/auth — Mailpit accepts any).
+pub async fn send_email_smtp(
+ host: &str,
+ port: u16,
+ from_email: &str,
+ to_email: &str,
+ subject: &str,
+ content: &str,
+) -> Result<()> {
+ let from = mailbox(from_email).context("parsing from address")?;
+ let to = mailbox(to_email).context("parsing to address")?;
+
+ let email = Message::builder()
+ .from(from)
+ .to(to)
+ .subject(subject)
+ .header(ContentType::TEXT_HTML)
+ .body(content.to_string())
+ .context("building SMTP message")?;
+
+ let mailer: AsyncSmtpTransport<Tokio1Executor> =
+ AsyncSmtpTransport::<Tokio1Executor>::builder_dangerous(host)
+ .port(port)
+ .build();
+
+ mailer.send(email).await.context("sending via SMTP")?;
+ Ok(())
+}
+
+fn mailbox(email: &str) -> Result<Mailbox> {
+ let address: Address = email
+ .parse()
+ .with_context(|| format!("invalid email '{email}'"))?;
+ Ok(Mailbox::new(None, address))
+}
diff --git a/rust/cloud-storage/tools/xtask/Cargo.toml b/rust/cloud-storage/tools/xtask/Cargo.toml
index db9fb02571..770a907718 100644
--- a/rust/cloud-storage/tools/xtask/Cargo.toml
+++ b/rust/cloud-storage/tools/xtask/Cargo.toml
@@ -7,7 +7,6 @@ description = "Repo automation: regenerates workspace-hack and the deploy dep-cl
[dependencies]
anyhow = { workspace = true }
-graphql_soup = { path = "../../graphql_soup" }
serde_json = { workspace = true }
# Pinned engine for the generated dependency artifacts. These versions live in
# Cargo.lock, so dev machines and CI always run the identical generator —
@@ -19,3 +18,30 @@ guppy = "0.17.24"
# xtask is excluded from hakari traversal, so these stay out of workspace-hack.
gh-workflow = "0.8"
indoc = "2"
+# Local/dev orchestration (`cargo x run-local` etc.). xtask is excluded from
+# hakari traversal, so these deps never enter workspace-hack. We reuse the
+# workspace-pinned versions so the orchestrator builds against the same crate
+# graph as the services it launches.
+clap = { workspace = true }
+serde = { workspace = true }
+tokio = { workspace = true }
+aws-sdk-sqs = { workspace = true }
+aws-sdk-dynamodb = { workspace = true }
+aws-sdk-s3 = { workspace = true }
+macro_aws_config = { path = "../../macro_aws_config" }
+macro_queues = { path = "../../macro_queues" }
+# Typed docker-compose model (build the override as structs, not strings) +
+# Docker Engine API client for the discrete container/image ops.
+docker-compose-types = { version = "0.24", features = ["indexmap"] }
+bollard = "0.21"
+indexmap = { workspace = true }
+serde_yaml = "0.9"
+indicatif = "0.18"
+console = "0.15"
+# Parse user-provided `--env-file` overlays (reading only; no crate emits the
+# docker-compose `env_file` format we generate). EnumIter derives the port list.
+dotenvy = { workspace = true }
+strum = { workspace = true, features = ["derive"] }
+# Signal the frontend dev server's whole process group on shutdown (kill bun +
+# the Vite child it spawns, not just bun).
+libc = "0.2"
diff --git a/rust/cloud-storage/tools/xtask/src/graphql_soup_schema.rs b/rust/cloud-storage/tools/xtask/src/graphql_soup_schema.rs
index 3854976594..75e1cfe4bf 100644
--- a/rust/cloud-storage/tools/xtask/src/graphql_soup_schema.rs
+++ b/rust/cloud-storage/tools/xtask/src/graphql_soup_schema.rs
@@ -1,21 +1,31 @@
-use std::{fs, path::Path};
+use std::{path::Path, process::Command};
-use anyhow::{Context, Result};
+use anyhow::{bail, Context, Result};
pub(crate) fn run(output_path: &Path) -> Result<()> {
- let schema = graphql_soup::build_schema().sdl();
+ let workspace_dir = Path::new(env!("CARGO_MANIFEST_DIR"))
+ .ancestors()
+ .nth(2)
+ .context("xtask manifest dir has no workspace root two levels up")?;
- if let Some(parent) = output_path
- .parent()
- .filter(|parent| !parent.as_os_str().is_empty())
- {
- fs::create_dir_all(parent)
- .with_context(|| format!("creating parent directory {}", parent.display()))?;
- }
+ let status = Command::new("cargo")
+ .current_dir(workspace_dir)
+ .arg("run")
+ .arg("--config")
+ .arg("env.SQLX_OFFLINE=\"true\"")
+ .arg("--quiet")
+ .arg("-p")
+ .arg("graphql_soup")
+ .arg("--bin")
+ .arg("graphql_soup_schema")
+ .arg("--")
+ .arg(output_path)
+ .status()
+ .with_context(|| format!("exporting GraphQL Soup schema to {}", output_path.display()))?;
- fs::write(output_path, format!("{schema}\n"))
- .with_context(|| format!("writing GraphQL Soup schema to {}", output_path.display()))?;
+ if !status.success() {
+ bail!("GraphQL Soup schema export failed with status {status}");
+ }
- println!("wrote GraphQL Soup schema to {}", output_path.display());
Ok(())
}
diff --git a/rust/cloud-storage/tools/xtask/src/local/arch.rs b/rust/cloud-storage/tools/xtask/src/local/arch.rs
new file mode 100644
index 0000000000..ba569451ca
--- /dev/null
+++ b/rust/cloud-storage/tools/xtask/src/local/arch.rs
@@ -0,0 +1,70 @@
+//! Host-architecture detection and the cross-compile target contract.
+//!
+//! The local orchestrator builds Linux service binaries on the developer's
+//! host with `cargo zigbuild`. We only ever build for the host's own
+//! architecture (aarch64 on Apple Silicon, x86_64 on x86 Linux) so zig only
+//! pins glibc rather than cross-compiling between architectures — a materially
+//! lower-risk use of zigbuild than full cross builds.
+
+use anyhow::{bail, Result};
+
+/// The glibc version the binaries are linked against, expressed as a
+/// `cargo zigbuild` target suffix (the same mechanism the Lambda builds use in
+/// flake.nix, where the suffix is `.2.26`). 2.36 is below the runtime image's
+/// glibc (debian:trixie ships ~2.41), so a binary linked here runs forward on
+/// the runtime image and on any host with glibc >= 2.36.
+const GLIBC_PIN: &str = "2.36";
+
+/// A resolved build target: the rust triple, the zigbuild target (triple +
+/// glibc suffix), and the Docker `--platform` for the runtime image.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Target {
+ /// e.g. `aarch64-unknown-linux-gnu`. Output binaries land in
+ /// `target/<triple>/debug/<binary>`.
+ pub triple: &'static str,
+ /// e.g. `linux/arm64`. Passed to `docker buildx --platform`.
+ pub docker_platform: &'static str,
+}
+
+/// Detect the build target from the host architecture (`std::env::consts::ARCH`).
+pub fn detect() -> Result<Target> {
+ match std::env::consts::ARCH {
+ "aarch64" => Ok(Target {
+ triple: "aarch64-unknown-linux-gnu",
+ docker_platform: "linux/arm64",
+ }),
+ "x86_64" => Ok(Target {
+ triple: "x86_64-unknown-linux-gnu",
+ docker_platform: "linux/amd64",
+ }),
+ other => bail!(
+ "unsupported host architecture '{other}' for local builds; \
+ only aarch64 and x86_64 are supported"
+ ),
+ }
+}
+
+impl Target {
+ /// The `cargo zigbuild --target` value: the rust triple plus the glibc pin
+ /// suffix (e.g. `aarch64-unknown-linux-gnu.2.36`). cargo fingerprints the
+ /// suffixed target separately from the plain triple, so this never poisons a
+ /// normal `cargo build`.
+ pub fn zig_target(&self) -> String {
+ format!("{}.{GLIBC_PIN}", self.triple)
+ }
+
+ /// The directory (relative to the cloud-storage workspace root) that
+ /// zigbuild writes binaries into. The `.2.36` glibc suffix is stripped from
+ /// the directory name by zigbuild, matching the Lambda install phase.
+ pub fn debug_dir(&self) -> String {
+ format!("target/{}/debug", self.triple)
+ }
+
+ /// Human-readable description for the env summary / doctor output.
+ pub fn describe(&self) -> String {
+ format!(
+ "{} (glibc {GLIBC_PIN}, {})",
+ self.triple, self.docker_platform
+ )
+ }
+}
diff --git a/rust/cloud-storage/tools/xtask/src/local/build/binaries_dir.rs b/rust/cloud-storage/tools/xtask/src/local/build/binaries_dir.rs
new file mode 100644
index 0000000000..c9d0a6f2f9
--- /dev/null
+++ b/rust/cloud-storage/tools/xtask/src/local/build/binaries_dir.rs
@@ -0,0 +1,81 @@
+//! Provenance-agnostic binary directory: host zigbuild output or a Nix/crane
+//! store path. The orchestrator only cares about the resulting `/app/out`
+//! mount, not how the binaries were produced.
+
+use std::path::{Path, PathBuf};
+
+use anyhow::{bail, Context, Result};
+
+/// Where the service binaries live on the host.
+#[derive(Clone, Debug)]
+pub enum BinariesDir {
+ /// A cargo target dir (host zigbuild output). Dynamically links against the
+ /// runtime image's own glibc; no `/nix/store` needed.
+ TargetDir(PathBuf),
+ /// A Nix/crane `…/bin` dir. The binaries link the nix dynamic linker, so
+ /// the host `/nix/store` must also be mounted read-only.
+ NixStore(PathBuf),
+}
+
+impl BinariesDir {
+ /// Classify a directory by whether it lives under `/nix/store`.
+ pub fn classify(dir: &Path) -> Result<Self> {
+ let canon = dir
+ .canonicalize()
+ .with_context(|| format!("binaries dir {} does not exist", dir.display()))?;
+ if canon.starts_with("/nix/store") {
+ // Accept either the `$out` dir (with a `bin/` child) or the `bin`
+ // dir directly.
+ let bin_dir = if canon.file_name().and_then(|n| n.to_str()) == Some("bin") {
+ canon
+ } else if canon.join("bin").is_dir() {
+ canon.join("bin")
+ } else {
+ canon
+ };
+ Ok(BinariesDir::NixStore(bin_dir))
+ } else {
+ Ok(BinariesDir::TargetDir(canon))
+ }
+ }
+
+ /// The directory bind-mounted to `/app/out`.
+ pub fn host_dir(&self) -> &Path {
+ match self {
+ BinariesDir::TargetDir(p) | BinariesDir::NixStore(p) => p,
+ }
+ }
+
+ fn needs_nix_store(&self) -> bool {
+ matches!(self, BinariesDir::NixStore(_))
+ }
+
+ /// The compose `volumes:` entries every Rust service needs. Always the
+ /// `/app/out` mount; plus `/nix/store` read-only when the binaries are
+ /// nix-linked.
+ pub fn compose_mounts(&self) -> Vec<String> {
+ let mut mounts = vec![format!("{}:/app/out:ro", self.host_dir().display())];
+ if self.needs_nix_store() {
+ mounts.push("/nix/store:/nix/store:ro".to_string());
+ }
+ mounts
+ }
+
+ /// Assert every expected binary exists in the directory.
+ pub fn validate(&self, binaries: &[&str]) -> Result<()> {
+ let missing: Vec<&str> = binaries
+ .iter()
+ .copied()
+ .filter(|b| !self.host_dir().join(b).exists())
+ .collect();
+ if !missing.is_empty() {
+ bail!(
+ "binaries dir {} is missing: {}\n build with `cargo x zigbuild` \
+ (or pass --binaries-dir / drop --no-build)",
+ self.host_dir().display(),
+ missing.join(", ")
+ );
+ }
+ Ok(())
+ }
+}
diff --git a/rust/cloud-storage/tools/xtask/src/local/build/mod.rs b/rust/cloud-storage/tools/xtask/src/local/build/mod.rs
new file mode 100644
index 0000000000..4bfdee8a36
--- /dev/null
+++ b/rust/cloud-storage/tools/xtask/src/local/build/mod.rs
@@ -0,0 +1,43 @@
+//! The Rust build + runtime-image contract.
+//!
+//! Binaries are built on the host with `cargo zigbuild` (or consumed from a
+//! prebuilt Nix/crane dir) and bind-mounted read-only into a minimal runtime
+//! image at `/app/out`. Docker never compiles Rust. Re-building binaries +
+//! restarting a container picks up code changes with no image rebuild.
+
+mod binaries_dir;
+mod runtime_image;
+mod zigbuild;
+
+pub use binaries_dir::BinariesDir;
+pub use runtime_image::{ensure_runtime_image, RUNTIME_IMAGE_TAG};
+
+use anyhow::Result;
+
+use super::arch::Target;
+use super::stage::Stage;
+
+/// How the caller wants binaries sourced.
+pub struct BuildOptions {
+ /// Skip building; reuse whatever is already in the default target dir.
+ pub no_build: bool,
+ /// Use this directory as the `/app/out` source instead of building.
+ pub binaries_dir: Option<std::path::PathBuf>,
+}
+
+/// Resolve a [`BinariesDir`] for the run: from `--binaries-dir`, from the
+/// existing target dir (`--no-build`), or by building with zigbuild.
+pub fn resolve(stage: &Stage, target: Target, opts: &BuildOptions) -> Result<BinariesDir> {
+ let dir = match &opts.binaries_dir {
+ Some(dir) => BinariesDir::classify(dir)?,
+ None if opts.no_build => {
+ BinariesDir::classify(&super::workspace_root().join(target.debug_dir()))?
+ }
+ None => {
+ zigbuild::run(stage, target)?;
+ BinariesDir::classify(&super::workspace_root().join(target.debug_dir()))?
+ }
+ };
+ dir.validate(&super::inventory::local_binaries())?;
+ Ok(dir)
+}
diff --git a/rust/cloud-storage/tools/xtask/src/local/build/runtime_image.rs b/rust/cloud-storage/tools/xtask/src/local/build/runtime_image.rs
new file mode 100644
index 0000000000..57ac786768
--- /dev/null
+++ b/rust/cloud-storage/tools/xtask/src/local/build/runtime_image.rs
@@ -0,0 +1,41 @@
+//! The minimal runtime image the service binaries run inside.
+//!
+//! The image contains only runtime dependencies (ca-certificates, curl,
+//! dumb-init) and *no* source or binaries — binaries arrive via the `/app/out`
+//! bind mount. It therefore never needs rebuilding when Rust code changes.
+
+use std::process::Command;
+
+use anyhow::Result;
+
+use super::super::arch::Target;
+use super::super::{stage::Stage, workspace_root};
+
+/// The shared runtime image tag. Not per-instance: the image has no
+/// instance-specific content.
+pub const RUNTIME_IMAGE_TAG: &str = "macro-local-runtime:dev";
+
+const DOCKERFILE_REL: &str = "docker/Dockerfile.runtime";
+
+/// Build the runtime image for the host arch if it is missing (or `force`).
+pub fn ensure_runtime_image(stage: &Stage, target: Target, force: bool) -> Result<()> {
+ if !force && image_exists() {
+ return Ok(());
+ }
+ let ws = workspace_root();
+ let mut cmd = Command::new("docker");
+ cmd.current_dir(&ws)
+ .args(["buildx", "build", "--platform", target.docker_platform])
+ .args(["-f", DOCKERFILE_REL])
+ .args(["-t", RUNTIME_IMAGE_TAG])
+ .arg("--load")
+ .arg(".");
+ stage.run(
+ &format!("Building runtime image {RUNTIME_IMAGE_TAG}"),
+ &mut cmd,
+ )
+}
+
+fn image_exists() -> bool {
+ super::super::docker::image_exists(RUNTIME_IMAGE_TAG)
+}
diff --git a/rust/cloud-storage/tools/xtask/src/local/build/zigbuild.rs b/rust/cloud-storage/tools/xtask/src/local/build/zigbuild.rs
new file mode 100644
index 0000000000..0687005977
--- /dev/null
+++ b/rust/cloud-storage/tools/xtask/src/local/build/zigbuild.rs
@@ -0,0 +1,119 @@
+//! Host-side cross-compile of the local service binaries via `cargo zigbuild`.
+//!
+//! Mirrors the env the Lambda builds use in flake.nix (`lambdaCommonArgs`):
+//! cleared RUSTFLAGS (zig links, so drop mold/lld), the glibc-pinned target,
+//! `AWS_LC_SYS_CMAKE_BUILDER=1` (aws-lc-sys's cc-builder rejects the zig C
+//! compiler), `SQLX_OFFLINE`, and writable zig cache dirs.
+
+use std::path::Path;
+use std::process::Command;
+
+use anyhow::{bail, Context, Result};
+
+use super::super::arch::Target;
+use super::super::inventory::RUST_SERVICES;
+use super::super::{stage::Stage, workspace_root};
+
+/// Build every non-opt-in service binary (debug profile) for `target`.
+///
+/// Most bins build together in one invocation; bins that need
+/// `--no-default-features` (e.g. `authentication_service`, to drop `rate_limit`)
+/// build in their own invocation since `--no-default-features` is package-wide.
+// xtask is host tooling; reading CARGO_BUILD_JOBS from the process env is correct.
+#[allow(clippy::disallowed_methods)]
+pub fn run(stage: &Stage, target: Target) -> Result<()> {
+ ensure_target_installed(target)?;
+
+ let ws = workspace_root();
+ let zig_cache = ws.join("target/zig-cache");
+ let jobs = std::env::var("CARGO_BUILD_JOBS")
+ .ok()
+ .filter(|j| !j.is_empty() && j != "0")
+ .unwrap_or_else(|| {
+ std::thread::available_parallelism()
+ .map(|n| n.get())
+ .unwrap_or(1)
+ .to_string()
+ });
+
+ // Group 1: default-feature bins, all in one invocation.
+ let default_bins: Vec<&str> = RUST_SERVICES
+ .iter()
+ .filter(|s| !s.is_opt_in() && !s.no_default_features)
+ .map(|s| s.cargo_bin)
+ .collect();
+ let mut cmd = base_command(&ws, &zig_cache, &jobs, target);
+ for bin in &default_bins {
+ cmd.arg("--bin").arg(bin);
+ }
+ stage.run(
+ &format!("Building service binaries ({})", target.triple),
+ &mut cmd,
+ )?;
+
+ // Group 2: each --no-default-features bin in its own package-scoped invocation.
+ for svc in RUST_SERVICES
+ .iter()
+ .filter(|s| !s.is_opt_in() && s.no_default_features)
+ {
+ let mut cmd = base_command(&ws, &zig_cache, &jobs, target);
+ cmd.arg("-p")
+ .arg(svc.package)
+ .arg("--no-default-features")
+ .arg("--bin")
+ .arg(svc.cargo_bin);
+ stage.run(
+ &format!("Building {} (no default features)", svc.cargo_bin),
+ &mut cmd,
+ )?;
+ }
+
+ Ok(())
+}
+
+/// A `cargo zigbuild` command with the shared env (mirrors flake.nix
+/// `lambdaCommonArgs`).
+fn base_command(ws: &Path, zig_cache: &Path, jobs: &str, target: Target) -> Command {
+ let mut cmd = Command::new("cargo");
+ cmd.current_dir(ws)
+ .arg("zigbuild")
+ .arg("--target")
+ .arg(target.zig_target())
+ .arg("-j")
+ .arg(jobs)
+ .env("SQLX_OFFLINE", "true")
+ .env("CARGO_PROFILE_DEV_DEBUG", "0")
+ .env("AWS_LC_SYS_CMAKE_BUILDER", "1")
+ .env("ZIG_GLOBAL_CACHE_DIR", zig_cache)
+ .env("ZIG_LOCAL_CACHE_DIR", zig_cache)
+ .env("RUSTC_WRAPPER", "sccache")
+ .env("XDG_CACHE_HOME", zig_cache);
+ cmd
+}
+
+/// Fail with an actionable hint if the rust-std for `target` is not installed.
+/// The repo's `rustup` is a no-op shim, so the only fix is adding the triple to
+/// `rust/rust-toolchain.toml` and re-entering `nix develop`.
+fn ensure_target_installed(target: Target) -> Result<()> {
+ let sysroot = Command::new("rustc")
+ .args(["--print", "sysroot"])
+ .output()
+ .context("running `rustc --print sysroot`")?;
+ if !sysroot.status.success() {
+ bail!("could not determine rustc sysroot (is the toolchain installed?)");
+ }
+ let sysroot = String::from_utf8_lossy(&sysroot.stdout).trim().to_string();
+ let std_dir = std::path::Path::new(&sysroot)
+ .join("lib/rustlib")
+ .join(target.triple);
+ if !std_dir.exists() {
+ bail!(
+ "rust target {} is not installed (no std at {}).\n \
+ Add it to rust/rust-toolchain.toml `targets` and re-enter `nix develop` \
+ (the repo's rustup is a shim and cannot install targets).",
+ target.triple,
+ std_dir.display()
+ );
+ }
+ Ok(())
+}
diff --git a/rust/cloud-storage/tools/xtask/src/local/cli.rs b/rust/cloud-storage/tools/xtask/src/local/cli.rs
new file mode 100644
index 0000000000..5f4e435952
--- /dev/null
+++ b/rust/cloud-storage/tools/xtask/src/local/cli.rs
@@ -0,0 +1,157 @@
+//! The clap-based CLI for the local/dev orchestration surface. The repo's other
+//! xtask verbs (deps/workflows/...) keep their slice-pattern match in main.rs;
+//! everything else routes here.
+
+use std::path::PathBuf;
+
+use anyhow::Result;
+use clap::{Args, Parser, Subcommand};
+
+use super::Mode;
+
+#[derive(Parser)]
+#[command(name = "cargo-x", about = "Macro local & dev orchestration")]
+struct Cli {
+ #[command(subcommand)]
+ command: Cmd,
+}
+
+#[derive(Subcommand)]
+enum Cmd {
+ /// Start a fully local stack (infra + binaries + proxy + frontend).
+ RunLocal(RunArgs),
+ /// Run local binaries against shared dev resources.
+ RunDev(RunArgs),
+ /// Cross-compile the local service binaries with cargo zigbuild.
+ Zigbuild,
+ /// Build the minimal runtime image.
+ RuntimeImage(ForceArg),
+ /// Render the per-instance compose override and print its path.
+ GenCompose(InstanceArgs),
+ /// Render merged compose and assert the no-build / runtime-image invariants.
+ ValidateLocalCompose(InstanceArgs),
+ /// Resolve env layers and assert mode-appropriate invariants.
+ ValidateLocalEnv(ValidateEnvArgs),
+ /// Preflight checks (docker, toolchain, ports, env sources, images).
+ DoctorLocal(InstanceArgs),
+ /// Stop an instance's containers (keep volumes).
+ StopLocal(InstanceArgs),
+ /// Drop, recreate, and migrate the instance database.
+ ResetLocal(InstanceArgs),
+ /// Remove an instance's containers, networks, and volumes.
+ DestroyLocal(InstanceArgs),
+}
+
+#[derive(Args, Clone, Default)]
+pub struct InstanceArgs {
+ /// Stack name. Absent (or `macro`) is the default instance.
+ #[arg(long)]
+ pub instance: Option<String>,
+ /// Override the derived port base.
+ #[arg(long)]
+ pub port_base: Option<u16>,
+}
+
+#[derive(Args, Clone, Default)]
+pub struct EnvArgs {
+ /// Skip the optional Doppler layer entirely.
+ #[arg(long)]
+ pub no_doppler: bool,
+ /// Overlay this dotenv (above defaults + Doppler, below process env).
+ #[arg(long)]
+ pub env_file: Option<PathBuf>,
+}
+
+#[derive(Args, Clone, Default)]
+pub struct BuildArgs {
+ /// Skip building; reuse whatever is in the target dir.
+ #[arg(long)]
+ pub no_build: bool,
+ /// Rebuild Docker-built auxiliary services (sync, websocket, lexical).
+ #[arg(long)]
+ pub build_aux_services: bool,
+ /// Use this dir as the `/app/out` source instead of building.
+ #[arg(long)]
+ pub binaries_dir: Option<PathBuf>,
+}
+
+#[derive(Args, Clone, Default)]
+pub struct RunArgs {
+ #[command(flatten)]
+ pub instance: InstanceArgs,
+ #[command(flatten)]
+ pub env: EnvArgs,
+ #[command(flatten)]
+ pub build: BuildArgs,
+ /// Do not start the frontend dev server.
+ #[arg(long)]
+ pub no_frontend: bool,
+ /// Stream subprocess output and show per-step timings (e.g. on `r`, the
+ /// build vs reload split instead of one folded line).
+ #[arg(long, short)]
+ pub verbose: bool,
+}
+
+#[derive(Args, Clone, Default)]
+pub struct ValidateEnvArgs {
+ #[command(flatten)]
+ pub instance: InstanceArgs,
+ #[command(flatten)]
+ pub env: EnvArgs,
+ /// Validate against dev-mode requirements instead of local.
+ #[arg(long)]
+ pub dev: bool,
+}
+
+#[derive(Args, Clone, Default)]
+pub struct ForceArg {
+ /// Rebuild even if the image already exists.
+ #[arg(long)]
+ pub force: bool,
+}
+
+/// Parse and run a local-orchestration command, or fall back to the legacy
+/// usage message on unknown input.
+pub fn dispatch(raw: &[String], legacy_usage: &str) -> Result<()> {
+ let argv = std::iter::once("cargo-x".to_string()).chain(raw.iter().cloned());
+ let cli = match Cli::try_parse_from(argv) {
+ Ok(c) => c,
+ Err(e) => {
+ // For an unrecognized subcommand, also surface the legacy verbs.
+ if e.kind() == clap::error::ErrorKind::InvalidSubcommand
+ || e.kind() == clap::error::ErrorKind::UnknownArgument
+ {
+ eprintln!("{legacy_usage}\n");
+ }
+ e.print().ok();
+ std::process::exit(e.exit_code());
+ }
+ };
+ run(cli)
+}
+
+fn run(cli: Cli) -> Result<()> {
+ match cli.command {
+ Cmd::RunLocal(args) => super::run_stack(Mode::Local, &args),
+ Cmd::RunDev(args) => super::run_stack(Mode::Dev, &args),
+ Cmd::Zigbuild => super::zigbuild_only(),
+ Cmd::RuntimeImage(a) => super::runtime_image_only(a.force),
+ Cmd::GenCompose(a) => super::gen_compose_only(&a),
+ Cmd::ValidateLocalCompose(a) => {
+ let instance = super::instance::Instance::derive(a.instance.as_deref(), a.port_base)?;
+ super::validate::local_compose(&instance, Mode::Local)
+ }
+ Cmd::ValidateLocalEnv(a) => {
+ let instance = super::instance::Instance::derive(
+ a.instance.instance.as_deref(),
+ a.instance.port_base,
+ )?;
+ let mode = if a.dev { Mode::Dev } else { Mode::Local };
+ super::validate::local_env(&instance, mode, a.env.no_doppler, a.env.env_file.as_deref())
+ }
+ Cmd::DoctorLocal(a) => super::doctor::run(&a),
+ Cmd::StopLocal(a) => super::stop(&a),
+ Cmd::ResetLocal(a) => super::reset(&a),
+ Cmd::DestroyLocal(a) => super::destroy(&a),
+ }
+}
diff --git a/rust/cloud-storage/tools/xtask/src/local/db.rs b/rust/cloud-storage/tools/xtask/src/local/db.rs
new file mode 100644
index 0000000000..41b4c1f090
--- /dev/null
+++ b/rust/cloud-storage/tools/xtask/src/local/db.rs
@@ -0,0 +1,56 @@
+//! Database lifecycle: migrate (idempotent) and reset (drop+create+migrate).
+//! Reuses the repo's sqlx recipes rather than reimplementing them. (Deterministic
+//! data seeding is a local-e2e concern, added back with that flow.)
+
+use std::process::Command;
+
+use anyhow::Result;
+
+use super::instance::{Instance, Port};
+use super::{stage::Stage, workspace_root};
+
+/// Host-side DATABASE_URL for sqlx (binaries run in-container with `postgres`,
+/// but host tooling connects via localhost:<mapped-port>).
+fn host_database_url(instance: &Instance) -> String {
+ format!(
+ "postgres://user:password@localhost:{}/macrodb",
+ instance.port(Port::Postgres)
+ )
+}
+
+/// The macro_db_client crate dir (sqlx migrations live under ./migrations).
+fn db_client_dir() -> std::path::PathBuf {
+ workspace_root().join("macro_db_client")
+}
+
+/// Create the database (idempotent) and run migrations.
+pub fn migrate(stage: &Stage, instance: &Instance) -> Result<()> {
+ let url = host_database_url(instance);
+
+ let mut create = Command::new("sqlx");
+ create
+ .arg("database")
+ .arg("create")
+ .env("DATABASE_URL", &url);
+ stage.run("Creating database (if needed)", &mut create)?;
+
+ let mut migrate = Command::new("sqlx");
+ migrate
+ .arg("migrate")
+ .arg("run")
+ .current_dir(db_client_dir())
+ .env("DATABASE_URL", &url);
+ stage.run("Running migrations", &mut migrate)
+}
+
+/// Drop + recreate + migrate the instance database.
+pub fn reset(stage: &Stage, instance: &Instance) -> Result<()> {
+ let url = host_database_url(instance);
+ let mut drop = Command::new("sqlx");
+ drop.arg("database")
+ .arg("drop")
+ .arg("-y")
+ .env("DATABASE_URL", &url);
+ let _ = stage.run("Dropping database", &mut drop);
+ migrate(stage, instance)
+}
diff --git a/rust/cloud-storage/tools/xtask/src/local/docker.rs b/rust/cloud-storage/tools/xtask/src/local/docker.rs
new file mode 100644
index 0000000000..7204e02999
--- /dev/null
+++ b/rust/cloud-storage/tools/xtask/src/local/docker.rs
@@ -0,0 +1,73 @@
+//! Thin bollard-backed helpers for the discrete Docker Engine operations the
+//! orchestrator needs outside of `docker compose` — checking whether the
+//! runtime image exists and idempotently ensuring the per-instance external
+//! networks/volumes. (Compose orchestration itself stays on the CLI; bollard
+//! has no compose support.)
+
+use anyhow::{Context, Result};
+use bollard::models::{NetworkCreateRequest, VolumeCreateRequest};
+use bollard::Docker;
+
+/// Run a future to completion on a throwaway current-thread runtime (xtask's
+/// flow is synchronous).
+fn block_on<T>(fut: impl std::future::Future<Output = Result<T>>) -> Result<T> {
+ tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .context("building tokio runtime")?
+ .block_on(fut)
+}
+
+fn connect() -> Result<Docker> {
+ Docker::connect_with_local_defaults().context("connecting to the Docker daemon")
+}
+
+/// Whether an image with `tag` exists locally.
+pub fn image_exists(tag: &str) -> bool {
+ block_on(async {
+ let docker = connect()?;
+ Ok::<_, anyhow::Error>(docker.inspect_image(tag).await.is_ok())
+ })
+ .unwrap_or(false)
+}
+
+/// Idempotently create a bridge network (no-op if it already exists).
+pub fn ensure_network(name: &str) -> Result<()> {
+ block_on(async {
+ let docker = connect()?;
+ match docker
+ .create_network(NetworkCreateRequest {
+ name: name.to_string(),
+ ..Default::default()
+ })
+ .await
+ {
+ Ok(_) => Ok(()),
+ Err(e) if already_exists(&e) => Ok(()),
+ Err(e) => Err(e).with_context(|| format!("creating network {name}")),
+ }
+ })
+}
+
+/// Idempotently create a named volume (no-op if it already exists).
+pub fn ensure_volume(name: &str) -> Result<()> {
+ block_on(async {
+ let docker = connect()?;
+ match docker
+ .create_volume(VolumeCreateRequest {
+ name: Some(name.to_string()),
+ ..Default::default()
+ })
+ .await
+ {
+ Ok(_) => Ok(()),
+ Err(e) if already_exists(&e) => Ok(()),
+ Err(e) => Err(e).with_context(|| format!("creating volume {name}")),
+ }
+ })
+}
+
+fn already_exists(e: &bollard::errors::Error) -> bool {
+ let s = e.to_string();
+ s.contains("already exists") || s.contains("409")
+}
diff --git a/rust/cloud-storage/tools/xtask/src/local/doctor.rs b/rust/cloud-storage/tools/xtask/src/local/doctor.rs
new file mode 100644
index 0000000000..1c886b62b3
--- /dev/null
+++ b/rust/cloud-storage/tools/xtask/src/local/doctor.rs
@@ -0,0 +1,150 @@
+//! `doctor-local`: preflight checks for tools, toolchain, ports, env, images.
+
+use std::process::Command;
+
+use anyhow::{bail, Result};
+
+use super::{arch, cli::InstanceArgs, instance::Instance, stage::Stage};
+
+enum Status {
+ Ok(String),
+ Warn(String),
+ Fail { msg: String, hint: Option<String> },
+}
+
+/// Run all checks, print results, and fail if any check failed.
+pub fn run(args: &InstanceArgs) -> Result<()> {
+ let stage = Stage::from_env();
+ let instance = Instance::derive(args.instance.as_deref(), args.port_base)?;
+ stage.section(&format!("doctor-local — instance {}", instance.name()));
+
+ let checks: Vec<(&str, Status)> = vec![
+ ("docker daemon", check_docker()),
+ ("docker compose", check_compose()),
+ (
+ "zig / cargo-zigbuild",
+ check_bin(
+ "cargo-zigbuild",
+ "install cargo-zigbuild + zig (in the nix dev shell)",
+ ),
+ ),
+ ("bun", check_bin("bun", "install bun")),
+ (
+ "sqlx-cli",
+ check_bin("sqlx", "cargo install sqlx-cli (in the nix dev shell)"),
+ ),
+ ("rust target", check_rust_target()),
+ ("ports", check_ports(&instance)),
+ ];
+
+ let mut failed = false;
+ for (name, status) in &checks {
+ match status {
+ Status::Ok(detail) => stage.note(&format!("✓ {name}: {detail}")),
+ Status::Warn(detail) => stage.note(&format!("! {name}: {detail}")),
+ Status::Fail { msg, hint } => {
+ failed = true;
+ stage.note(&format!("✗ {name}: {msg}"));
+ if let Some(h) = hint {
+ stage.note(&format!(" hint: {h}"));
+ }
+ }
+ }
+ }
+ if failed {
+ bail!("doctor-local found problems (see above)");
+ }
+ stage.note("all checks passed");
+ Ok(())
+}
+
+fn ok_status(out: &str) -> Status {
+ Status::Ok(out.lines().next().unwrap_or("").trim().to_string())
+}
+
+fn check_docker() -> Status {
+ match Command::new("docker")
+ .args(["info", "--format", "{{.ServerVersion}}"])
+ .output()
+ {
+ Ok(o) if o.status.success() => ok_status(&String::from_utf8_lossy(&o.stdout)),
+ _ => Status::Fail {
+ msg: "cannot reach the Docker daemon".into(),
+ hint: Some("start Docker Desktop / colima / orbstack".into()),
+ },
+ }
+}
+
+fn check_compose() -> Status {
+ match Command::new("docker")
+ .args(["compose", "version", "--short"])
+ .output()
+ {
+ Ok(o) if o.status.success() => ok_status(&String::from_utf8_lossy(&o.stdout)),
+ _ => Status::Fail {
+ msg: "`docker compose` unavailable".into(),
+ hint: Some("install the Docker Compose v2 plugin (>= 2.24.4 for !reset)".into()),
+ },
+ }
+}
+
+fn check_bin(bin: &str, hint: &str) -> Status {
+ match Command::new(bin).arg("--version").output() {
+ Ok(o) if o.status.success() => ok_status(&String::from_utf8_lossy(&o.stdout)),
+ _ => Status::Fail {
+ msg: format!("`{bin}` not found"),
+ hint: Some(hint.to_string()),
+ },
+ }
+}
+
+fn check_rust_target() -> Status {
+ let target = match arch::detect() {
+ Ok(t) => t,
+ Err(e) => {
+ return Status::Fail {
+ msg: e.to_string(),
+ hint: None,
+ }
+ }
+ };
+ let sysroot = match Command::new("rustc").args(["--print", "sysroot"]).output() {
+ Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
+ _ => {
+ return Status::Fail {
+ msg: "rustc not found".into(),
+ hint: None,
+ }
+ }
+ };
+ let std_dir = std::path::Path::new(&sysroot)
+ .join("lib/rustlib")
+ .join(target.triple);
+ if std_dir.exists() {
+ Status::Ok(target.describe())
+ } else {
+ Status::Fail {
+ msg: format!("rust target {} not installed", target.triple),
+ hint: Some(format!(
+ "add {} to rust/rust-toolchain.toml `targets` and re-enter `nix develop`",
+ target.triple
+ )),
+ }
+ }
+}
+
+fn check_ports(instance: &Instance) -> Status {
+ let busy = instance.busy_ports();
+ if busy.is_empty() {
+ Status::Ok(format!(
+ "all {} ports free",
+ super::instance::Port::all().count()
+ ))
+ } else {
+ let list: Vec<String> = busy.iter().map(|p| p.to_string()).collect();
+ Status::Warn(format!(
+ "in use: {} (may be this instance's own running containers; otherwise pass --port-base)",
+ list.join(", ")
+ ))
+ }
+}
diff --git a/rust/cloud-storage/tools/xtask/src/local/env_layer.rs b/rust/cloud-storage/tools/xtask/src/local/env_layer.rs
new file mode 100644
index 0000000000..ca1da6db7c
--- /dev/null
+++ b/rust/cloud-storage/tools/xtask/src/local/env_layer.rs
@@ -0,0 +1,249 @@
+//! Environment layering (lowest → highest precedence):
+//! - Doppler (`lcl_personal`/`dev_personal`) — the integration/secret config
+//! services require.
+//! - Local only: the typed [`local_env::LocalEnv`] overlaid on top —
+//! code is the AUTHORITATIVE source for local plumbing + the fixed FusionAuth
+//! identity (it wins over Doppler; the deleted defaults.env was the reverse,
+//! a fallback Doppler overrode).
+//! - `--env-file` < process env (existing keys only).
+//! - Dev only: overrides (pin env/project, strip local endpoints, real AWS creds).
+//!
+//! The merged map is written to a per-instance generated env file consumed by
+//! docker compose both for `${VAR}` interpolation (`--env-file`) and for
+//! injection into containers (via the `MACRO_ENV_FILE` indirection in the
+//! `x-common-env` anchor).
+
+use std::collections::BTreeMap;
+use std::path::{Path, PathBuf};
+use std::process::Command;
+
+use anyhow::{Context, Result};
+
+use super::instance::Instance;
+use super::{local_env, Mode};
+
+/// The fully resolved environment for a run.
+pub struct ResolvedEnv {
+ pub merged: BTreeMap<String, String>,
+ pub doppler_used: bool,
+ pub env_file: Option<PathBuf>,
+ pub generated_path: PathBuf,
+}
+
+/// Resolve and materialize the environment for `mode`/`instance`.
+// The process-env layer reads the host environment directly (xtask is tooling,
+// not a service reading APP_SECRETS_JSON).
+#[allow(clippy::disallowed_methods)]
+pub fn resolve(
+ mode: Mode,
+ instance: &Instance,
+ no_doppler: bool,
+ env_file: Option<&Path>,
+) -> Result<ResolvedEnv> {
+ // Base = Doppler (`lcl_personal`/`dev_personal`); it supplies the
+ // integration/secret config services require. For local we then overlay the
+ // typed `LocalEnv` ON TOP, so code is the AUTHORITATIVE source for local
+ // plumbing + the fixed FusionAuth identity (it wins over whatever Doppler
+ // has — unlike the old defaults.env, which Doppler overrode). Dev keeps
+ // Doppler as-is.
+ let spec = mode.spec();
+ let mut env = BTreeMap::new();
+ let doppler_used = if no_doppler {
+ false
+ } else {
+ pull_doppler(spec.doppler_config, &mut env)?
+ };
+ if spec.overlay_local_env {
+ for (k, v) in local_env::LocalEnv::for_instance(mode, instance).to_env() {
+ env.insert(k, v);
+ }
+ }
+
+ // `--env-file` overlay (the only dotenv we still parse).
+ if let Some(file) = env_file {
+ load_dotenv_into(file, &mut env)
+ .with_context(|| format!("loading --env-file {}", file.display()))?;
+ }
+
+ // Process env — override only keys already present, so a developer can
+ // `FOO=bar just run_local` without dumping their whole environment in.
+ for key in env.keys().cloned().collect::<Vec<_>>() {
+ if let Ok(v) = std::env::var(&key) {
+ env.insert(key, v);
+ }
+ }
+
+ // Remote-AWS modes (dev): pin ENVIRONMENT/project, strip any leaked local
+ // endpoints, and resolve the developer's real AWS credentials (incl. session
+ // token) over the dev_personal placeholders — the process-env layer can't add
+ // a key that wasn't already present. (Local owns all of this in `LocalEnv`.)
+ if spec.uses_remote_aws {
+ apply_dev_overrides(instance, &mut env);
+ pull_aws_credentials(&mut env);
+ }
+
+ let generated_path = instance.ensure_artifact_dir()?.join("local.generated.env");
+ write_dotenv(&generated_path, &env)
+ .with_context(|| format!("writing {}", generated_path.display()))?;
+
+ Ok(ResolvedEnv {
+ merged: env,
+ doppler_used,
+ env_file: env_file.map(Path::to_path_buf),
+ generated_path,
+ })
+}
+
+/// Dev-only overrides: pin the environment + project name, and strip any local
+/// infra endpoints that leaked in (from `--env-file`/process env) so services
+/// use real dev resources. Local's identity/ports/secrets are owned entirely by
+/// [`local_env::LocalEnv`], so there is no local arm here.
+fn apply_dev_overrides(instance: &Instance, env: &mut BTreeMap<String, String>) {
+ env.insert(
+ "ENVIRONMENT".to_string(),
+ Mode::Dev.environment_var().to_string(),
+ );
+ env.insert(
+ "COMPOSE_PROJECT_NAME".to_string(),
+ instance.project_name().to_string(),
+ );
+ // run-dev must not point at local infra.
+ env.remove("LOCAL_AWS_URL");
+ env.remove("SMTP_HOST");
+ env.remove("SMTP_PORT");
+}
+
+/// Resolve the developer's real AWS credentials for dev via the AWS CLI's
+/// credential chain (env, named profile / `AWS_PROFILE`, or SSO) and inject the
+/// `AWS_*` vars — crucially including `AWS_SESSION_TOKEN` for temporary/SSO
+/// creds. Non-fatal: warns loudly if it can't, since the services would then
+/// fail every AWS call with an invalid-token error.
+fn pull_aws_credentials(env: &mut BTreeMap<String, String>) {
+ let output = Command::new("aws")
+ .args([
+ "configure",
+ "export-credentials",
+ "--format",
+ "env-no-export",
+ ])
+ .output();
+ let output = match output {
+ Ok(o) if o.status.success() => o,
+ _ => {
+ eprintln!(
+ "warning: could not resolve AWS credentials for dev. Log in (e.g. `aws sso login`, \
+ set `AWS_PROFILE`) so `aws configure export-credentials` works — otherwise the \
+ services will fail AWS calls with an invalid-token error."
+ );
+ return;
+ }
+ };
+ let mut found = false;
+ for line in String::from_utf8_lossy(&output.stdout).lines() {
+ if let Some((k, v)) = line.split_once('=') {
+ let k = k.trim();
+ if k.starts_with("AWS_") {
+ env.insert(k.to_string(), v.trim().to_string());
+ found = true;
+ }
+ }
+ }
+ if !found {
+ eprintln!(
+ "warning: `aws configure export-credentials` returned no AWS_* credentials for dev."
+ );
+ }
+}
+
+/// Pull the named Doppler `local`-project config as a flat env overlay (mirrors
+/// the old `just get_environment`). Non-fatal: if Doppler is unavailable in local
+/// mode we proceed on defaults + env-file. Returns whether secrets were loaded.
+fn pull_doppler(config: &str, env: &mut BTreeMap<String, String>) -> Result<bool> {
+ let output = Command::new("doppler")
+ .args([
+ "secrets",
+ "download",
+ "--project",
+ "local",
+ "--config",
+ config,
+ ])
+ .args(["--format", "json", "--no-file"])
+ .output();
+ let output = match output {
+ Ok(o) if o.status.success() => o,
+ _ => return Ok(false),
+ };
+ let json: BTreeMap<String, serde_json::Value> =
+ serde_json::from_slice(&output.stdout).context("parsing doppler json")?;
+ for (k, v) in json {
+ let value = match v {
+ serde_json::Value::String(s) => s.trim_matches(['\r', '\n']).to_string(),
+ other => other.to_string(),
+ };
+ env.insert(k, value);
+ }
+ Ok(true)
+}
+
+/// Parse a user-provided `--env-file` into `env` via `dotenvy` (the maintained
+/// dotenv crate) — handles comments, quoting, and `export ` prefixes so we don't
+/// hand-roll a parser. Later keys win, matching our overlay semantics.
+fn load_dotenv_into(path: &Path, env: &mut BTreeMap<String, String>) -> Result<()> {
+ for item in dotenvy::from_path_iter(path)
+ .with_context(|| format!("reading env file {}", path.display()))?
+ {
+ let (key, value) = item.with_context(|| format!("parsing env file {}", path.display()))?;
+ env.insert(key, value);
+ }
+ Ok(())
+}
+
+/// Write the merged map as a docker-compose `env_file`. This is an *emitter*, not
+/// a dotenv parser: no crate writes compose's env-file format (dotenvy and
+/// friends only read), and the values come from Doppler so they can contain
+/// spaces, quotes, and newlines. Values that need it are double-quoted with
+/// escapes so compose's `env_file` parser round-trips them.
+fn write_dotenv(path: &Path, env: &BTreeMap<String, String>) -> Result<()> {
+ let mut out =
+ String::from("# GENERATED by `cargo x` — do not edit. Regenerate via run-local/run-dev.\n");
+ for (k, v) in env {
+ out.push_str(&dotenv_line(k, v));
+ out.push('\n');
+ }
+ std::fs::write(path, out).with_context(|| format!("writing {}", path.display()))?;
+ Ok(())
+}
+
+fn dotenv_line(key: &str, value: &str) -> String {
+ let needs_quote = value.is_empty()
+ || value.contains(['\n', '\t', '"', '#', ' ', '\''])
+ || value.starts_with(char::is_whitespace);
+ if needs_quote {
+ let escaped = value
+ .replace('\\', "\\\\")
+ .replace('"', "\\\"")
+ .replace('\n', "\\n")
+ .replace('\t', "\\t");
+ format!("{key}=\"{escaped}\"")
+ } else {
+ format!("{key}={value}")
+ }
+}
+
+/// A short, category-bucketed summary of the resolved env (never prints secret
+/// values).
+pub fn summarize(env: &BTreeMap<String, String>) -> String {
+ let count = |pred: fn(&str) -> bool| env.keys().filter(|k| pred(k)).count();
+ format!(
+ "{} keys (db:{} aws/buckets:{} queues:{} dynamodb:{} fusionauth:{} secrets:{} urls:{})",
+ env.len(),
+ count(|k| k.contains("DATABASE") || k.contains("REDIS") || k.contains("OPENSEARCH")),
+ count(|k| k.starts_with("AWS_") || k.contains("BUCKET") || k.contains("LOCAL_AWS")),
+ count(|k| k.contains("QUEUE")),
+ count(|k| k.contains("TABLE") || k.contains("DYNAMODB")),
+ count(|k| k.contains("FUSIONAUTH") || k.contains("FUSION_AUTH")),
+ count(|k| k.contains("SECRET") || k.contains("_KEY") || k.contains("JWT")),
+ count(|k| k.contains("URL") || k.contains("_URI")),
+ )
+}
diff --git a/rust/cloud-storage/tools/xtask/src/local/frontend.rs b/rust/cloud-storage/tools/xtask/src/local/frontend.rs
new file mode 100644
index 0000000000..886168db7b
--- /dev/null
+++ b/rust/cloud-storage/tools/xtask/src/local/frontend.rs
@@ -0,0 +1,210 @@
+//! Frontend dev-server orchestration: generate the instance env, wait for the
+//! backend to be reachable through the proxy, then launch `bun run dev` pointed
+//! at the proxy origin.
+
+use std::io::Read;
+use std::os::unix::process::CommandExt;
+use std::process::{Child, Command, Stdio};
+use std::sync::{Arc, Mutex};
+use std::thread::JoinHandle;
+
+use anyhow::{Context, Result};
+
+use super::instance::{Instance, Port};
+use super::{proxy, repo_root, stage::Stage, Mode};
+
+/// The app dir where `bun run dev` runs.
+fn app_dir() -> std::path::PathBuf {
+ repo_root().join("js/app/packages/app")
+}
+
+/// Host-facing frontend URL.
+pub fn url(instance: &Instance) -> String {
+ format!("http://localhost:{}/app", instance.port(Port::Frontend))
+}
+
+/// The env the dev server runs with. Both local and dev point the whole app at
+/// the local proxy origin (single backend origin); the modes differ only in
+/// what the *services* behind the proxy talk to (local infra vs dev resources).
+fn dev_env(instance: &Instance) -> Vec<(String, String)> {
+ vec![
+ (
+ "PORT".to_string(),
+ instance.port(Port::Frontend).to_string(),
+ ),
+ ("VITE_LOCAL_SERVERS".to_string(), "ALL".to_string()),
+ (
+ "VITE_LOCAL_BACKEND_ORIGIN".to_string(),
+ proxy::url(instance),
+ ),
+ ]
+}
+
+/// Poll the backend (auth health, through the proxy) until ready.
+pub fn wait_backend_ready(stage: &Stage, instance: &Instance) -> Result<()> {
+ let url = format!("{}/auth/health", proxy::url(instance));
+ let script = format!(
+ "for i in $(seq 1 60); do curl -fsS {url} >/dev/null 2>&1 && exit 0; sleep 2; done; echo 'backend not ready'; exit 1"
+ );
+ let mut cmd = Command::new("bash");
+ cmd.arg("-lc").arg(script);
+ stage.run("Waiting for backend (proxy /auth/health)", &mut cmd)
+}
+
+/// A running frontend dev server plus its captured output, so an unexpected
+/// exit can be explained (the output is otherwise suppressed).
+pub struct Frontend {
+ pub child: Child,
+ captured: Arc<Mutex<Vec<u8>>>,
+ drains: Vec<JoinHandle<()>>,
+}
+
+impl Frontend {
+ /// Stop the dev server and all its children. `bun run dev` spawns Vite (and
+ /// friends), which we put in their own process group at spawn — so signal the
+ /// GROUP (negative pid). SIGKILL is enough: the kernel releases the port the
+ /// moment the processes die. Then reap `bun` and join the drain threads (their
+ /// pipes close, so they exit).
+ pub fn shutdown(&mut self) {
+ let pgid = self.child.id() as i32;
+ // SAFETY: a plain `kill(2)`; an invalid/already-dead group is a harmless
+ // ESRCH. The negative pid targets the whole process group.
+ unsafe {
+ libc::kill(-pgid, libc::SIGKILL);
+ }
+ let _ = self.child.wait();
+ for h in self.drains.drain(..) {
+ let _ = h.join();
+ }
+ }
+
+ /// Join the drain threads and return the last `lines` lines of the dev
+ /// server's captured output (for diagnosing why it exited).
+ pub fn tail_output(&mut self, lines: usize) -> String {
+ for h in self.drains.drain(..) {
+ let _ = h.join();
+ }
+ let buf = self.captured.lock().unwrap_or_else(|e| e.into_inner());
+ tail_str(&String::from_utf8_lossy(&buf), lines)
+ }
+}
+
+fn tail_str(s: &str, n: usize) -> String {
+ let lines: Vec<&str> = s.lines().collect();
+ let start = lines.len().saturating_sub(n);
+ lines[start..].join("\n")
+}
+
+/// Start the frontend dev server and wait until *our* child is serving. Output
+/// is captured (suppressed — the vite banner would duplicate the summary's URL)
+/// but retained so an unexpected exit can be diagnosed. Returns `None` in
+/// dry-run mode.
+pub fn start(stage: &Stage, instance: &Instance, mode: Mode) -> Result<Option<Frontend>> {
+ if mode.spec().wait_backend_before_frontend {
+ wait_backend_ready(stage, instance)?;
+ }
+ if stage.is_dry_run() {
+ stage.note(&format!(
+ "Dry run: would start frontend at {}",
+ url(instance)
+ ));
+ return Ok(None);
+ }
+ let port = instance.port(Port::Frontend);
+ // A successful connect means something is already listening — almost
+ // certainly a stale dev server from a previous run. (A bind probe is
+ // unreliable: std's TcpListener sets SO_REUSEADDR, so it binds right
+ // alongside the squatter.) Bail clearly rather than spawn a bun that can't
+ // bind and dies with a confusing late "exited (status 1)".
+ if std::net::TcpStream::connect_timeout(
+ &([127, 0, 0, 1], port).into(),
+ std::time::Duration::from_millis(300),
+ )
+ .is_ok()
+ {
+ anyhow::bail!(
+ "frontend port {port} is already in use — likely a stale dev server from a \
+ previous run. Free it (`lsof -ti tcp:{port} | xargs kill`) and retry."
+ );
+ }
+ let mut cmd = Command::new("bun");
+ cmd.current_dir(app_dir())
+ .args(["run", "--bun", "dev"])
+ // Run bun (and the Vite child it spawns) in its OWN process group, so
+ // `shutdown` can signal the whole group — killing just `bun` would orphan
+ // Vite and leave the port held. (0 = "new group led by the child".)
+ .process_group(0)
+ // Open-but-empty stdin (piped, held open, never written): vite sees a
+ // non-TTY stdin so it won't bind its own keypress shortcuts (no fight
+ // with our hotkey loop), but it never reaches EOF — Stdio::null is EOF
+ // immediately, which makes vite shut itself down right after boot.
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+ for (k, v) in dev_env(instance) {
+ cmd.env(k, v);
+ }
+ let mut child = cmd.spawn().context("launching `bun run dev`")?;
+
+ // Drain stdout+stderr into a buffer on their own threads (a full pipe would
+ // otherwise block bun); the output stays hidden unless the server exits.
+ // stdin is intentionally NOT taken — its write end stays open so bun never
+ // sees stdin EOF.
+ let captured = Arc::new(Mutex::new(Vec::new()));
+ let mut drains = Vec::new();
+ if let Some(mut out) = child.stdout.take() {
+ let buf = Arc::clone(&captured);
+ drains.push(std::thread::spawn(move || drain_into(&mut out, &buf)));
+ }
+ if let Some(mut err) = child.stderr.take() {
+ let buf = Arc::clone(&captured);
+ drains.push(std::thread::spawn(move || drain_into(&mut err, &buf)));
+ }
+
+ // Wait until OUR child is serving: poll the port, but fail fast (with bun's
+ // output) if the child exits first. A bare port poll would mistake a stale
+ // server already on the port for "ready" while our child has died.
+ let addr: std::net::SocketAddr = ([127, 0, 0, 1], port).into();
+ let wait_buf = Arc::clone(&captured);
+ stage.run_step("Starting frontend", || {
+ for _ in 0..120 {
+ // Settle first: a failed bind (e.g. port already in use) makes vite
+ // exit near-instantly, so if the child is still alive after this it
+ // genuinely bound the port — rather than us connecting to a stale
+ // server squatting it.
+ std::thread::sleep(std::time::Duration::from_millis(300));
+ if let Some(status) = child.try_wait()? {
+ let out = tail_str(&String::from_utf8_lossy(&wait_buf.lock().unwrap()), 30);
+ anyhow::bail!(
+ "frontend dev server exited during startup ({status})\n{out}\n\
+ (if the port is in use, free it: `lsof -ti tcp:{port} | xargs kill`)"
+ );
+ }
+ if std::net::TcpStream::connect_timeout(&addr, std::time::Duration::from_millis(300))
+ .is_ok()
+ {
+ return Ok(());
+ }
+ }
+ anyhow::bail!("frontend dev server did not become ready")
+ })?;
+
+ Ok(Some(Frontend {
+ child,
+ captured,
+ drains,
+ }))
+}
+
+/// Copy a child pipe into the shared capture buffer until EOF.
+fn drain_into(reader: &mut impl Read, buf: &Mutex<Vec<u8>>) {
+ let mut chunk = [0u8; 4096];
+ while let Ok(n) = reader.read(&mut chunk) {
+ if n == 0 {
+ break;
+ }
+ if let Ok(mut b) = buf.lock() {
+ b.extend_from_slice(&chunk[..n]);
+ }
+ }
+}
diff --git a/rust/cloud-storage/tools/xtask/src/local/fusionauth.rs b/rust/cloud-storage/tools/xtask/src/local/fusionauth.rs
new file mode 100644
index 0000000000..80fa0cac3a
--- /dev/null
+++ b/rust/cloud-storage/tools/xtask/src/local/fusionauth.rs
@@ -0,0 +1,66 @@
+//! FusionAuth local bootstrap: generate the per-instance kickstart artifacts
+//! and wait for readiness. No Pulumi, no API read-back, no patch step.
+
+use std::process::Command;
+
+use anyhow::{Context, Result};
+
+use super::instance::{Instance, Port};
+use super::{gen_compose, kickstart, stage::Stage};
+
+/// The local populate-JWT lambda body, inlined into `kickstart.json`.
+///
+/// LOCAL-ONLY variant of the production populate-JWT lambda. Production enriches
+/// the JWT by calling authentication-service over HTTP, but Lambda HTTP Connect
+/// is a licensed FusionAuth feature that silently fails without a Reactor
+/// license. Local runs unlicensed, so we derive the claims instead: password
+/// users follow the `macro|<email>` convention (see `seed_cli`) and no Google
+/// IdP is configured locally, so every local user is a `macro|` user.
+/// Divergence from production: `root_macro_id` / `macro_organization_id` are
+/// never populated — org-scoped JWT flows need the licensed lambda + a license.
+///
+/// Inlined (not `include_str!`) because the canonical `.js` lives under
+/// `infra/` where a blanket `*.js` gitignore makes it untracked — a fresh
+/// checkout / CI / devcontainer wouldn't have it, breaking the build. Kept
+/// comment-free so it survives FusionAuth flattening the body to one line.
+const POPULATE_JWT_LAMBDA: &str = "function populate(jwt, user, _registration) {
+ jwt.fusion_user_id = user.id;
+ jwt.email = user.email;
+ jwt.macro_user_id = 'macro|' + user.email;
+}";
+
+/// Generate `kickstart.json` into the instance's kickstart dir, which the
+/// FusionAuth container mounts. The kickstart is pure identity-provider config:
+/// run_local pre-seeds no users — passwordless login auto-creates any user on
+/// demand.
+pub fn write_kickstart(instance: &Instance) -> Result<()> {
+ let dir = gen_compose::kickstart_dir(instance);
+ std::fs::create_dir_all(&dir)
+ .with_context(|| format!("creating kickstart dir {}", dir.display()))?;
+
+ let doc = kickstart::build(
+ instance.port(Port::Frontend),
+ instance.port(Port::Auth),
+ POPULATE_JWT_LAMBDA,
+ );
+ let json = serde_json::to_string_pretty(&doc)? + "\n";
+ std::fs::write(dir.join("kickstart.json"), json)
+ .with_context(|| format!("writing {}", dir.join("kickstart.json").display()))?;
+ Ok(())
+}
+
+/// Block until FusionAuth reports status Ok (it applies the kickstart on first
+/// boot against an empty DB, which is slow). Runs as a stage so it shows the
+/// spinner.
+pub fn wait_ready(stage: &Stage, instance: &Instance) -> Result<()> {
+ let url = format!(
+ "http://localhost:{}/api/status",
+ instance.port(Port::FusionAuth)
+ );
+ let script = format!(
+ "for i in $(seq 1 90); do curl -fsS {url} 2>/dev/null | grep -q '\"status\":\"Ok\"' && exit 0; sleep 2; done; echo 'timed out waiting for FusionAuth'; exit 1"
+ );
+ let mut cmd = Command::new("bash");
+ cmd.arg("-lc").arg(script);
+ stage.run("Waiting for FusionAuth", &mut cmd)
+}
diff --git a/rust/cloud-storage/tools/xtask/src/local/gen_compose.rs b/rust/cloud-storage/tools/xtask/src/local/gen_compose.rs
new file mode 100644
index 0000000000..17afb4c66f
--- /dev/null
+++ b/rust/cloud-storage/tools/xtask/src/local/gen_compose.rs
@@ -0,0 +1,409 @@
+//! Generates the per-instance docker-compose override.
+//!
+//! The override is built as a typed [`docker_compose_types::Compose`] model
+//! (not hand-written YAML): each Rust service is converted to the prebuilt
+//! runtime image with the host binary dir bind-mounted at `/app/out`, the
+//! companion infra services (LocalStack, Mailpit, reverse proxy) are added, and
+//! FusionAuth is repointed at the generated kickstart.
+//!
+//! The only thing the typed model can't express is Compose's `!reset` /
+//! `!override` merge tags (needed to drop the inherited `build:` and to replace
+//! inherited `ports:`/`volumes:` rather than append). Those are emitted via
+//! `serde_yaml`'s native tagged-value support — still structured data, no string
+//! munging.
+
+use std::path::PathBuf;
+use std::process::Command;
+
+use anyhow::{Context, Result};
+use docker_compose_types as dct;
+use indexmap::IndexMap;
+use serde_yaml::value::{Tag, TaggedValue};
+use serde_yaml::Value;
+
+use super::build::{BinariesDir, RUNTIME_IMAGE_TAG};
+use super::instance::{Instance, Port};
+use super::inventory::services_for_mode;
+use super::{repo_root, Mode};
+
+pub const LOCALSTACK_IMAGE: &str = "localstack/localstack:4";
+pub const MAILPIT_IMAGE: &str = "axllent/mailpit:v1.20";
+pub const CADDY_IMAGE: &str = "caddy:2-alpine";
+
+/// Base-compose services that bind fixed host ports but aren't in our inventory
+/// (reached via the proxy / container network, not the host). For named
+/// instances we drop their host-port bindings so concurrent stacks don't collide
+/// on 8787/6969/8096/8100.
+const AUX_HOST_PORT_SERVICES: &[&str] = &[
+ "sync_service",
+ "websocket_service",
+ "lexical_service",
+ "static_file_cdn",
+];
+
+/// The host directory bind-mounted into FusionAuth at
+/// `/usr/local/fusionauth/kickstart`. The kickstart writer fills it.
+pub fn kickstart_dir(instance: &Instance) -> PathBuf {
+ instance.artifact_dir().join("kickstart")
+}
+
+/// The generated Caddyfile path for this instance's reverse proxy.
+pub fn caddyfile_path(instance: &Instance) -> PathBuf {
+ instance.artifact_dir().join("proxy/Caddyfile")
+}
+
+/// Build the override (typed model), apply the merge tags, and write it.
+pub fn generate(mode: Mode, instance: &Instance, binaries: &BinariesDir) -> Result<PathBuf> {
+ let mut services: IndexMap<String, Option<dct::Service>> = IndexMap::new();
+ let mounts = binaries.compose_mounts();
+
+ // 1. Rust services → runtime image + mounted binaries.
+ for svc in services_for_mode(mode) {
+ let mut s = dct::Service {
+ image: Some(RUNTIME_IMAGE_TAG.to_string()),
+ volumes: mounts.iter().cloned().map(dct::Volumes::Simple).collect(),
+ environment: kv(&[("PORT", "8080")]),
+ ..Default::default()
+ };
+ // Named instances need their own host ports (replacing the base ports —
+ // emitted as `!override` in apply_tags). Only the self-contained local
+ // stacks remap; dev inherits the base-compose ports.
+ if mode.spec().runs_local_infra && !instance.is_default() {
+ if let Some(port) = svc.host_port {
+ s.ports = dct::Ports::Short(vec![format!("{}:8080", instance.port(port))]);
+ }
+ }
+ services.insert(svc.compose_name.to_string(), Some(s));
+ }
+
+ // The reverse proxy is the frontend's single origin in every mode, and
+ // LocalStack runs in every mode (dev's `dev_personal` notification queue
+ // lives there too).
+ add_proxy_service(&mut services, instance);
+ add_localstack_service(&mut services, instance);
+ // The rest of the local infra (FusionAuth, Mailpit, per-instance Postgres/
+ // Redis/OpenSearch port remaps) only for the self-contained local stacks.
+ if mode.spec().runs_local_infra {
+ add_local_infra(&mut services, instance);
+ }
+
+ let compose = dct::Compose {
+ services: dct::Services(services),
+ ..Default::default()
+ };
+
+ // Serialize the typed model, then layer in the merge tags + (named instance)
+ // external network/volume definitions, which the schema can't represent.
+ let mut value = serde_yaml::to_value(&compose).context("serializing compose override")?;
+ apply_tags(&mut value, mode, instance);
+ if mode.spec().runs_local_infra && !instance.is_default() {
+ set_external_networks_and_volumes(&mut value, instance);
+ }
+
+ let yaml = serde_yaml::to_string(&value).context("rendering override yaml")?;
+ let path = instance
+ .ensure_artifact_dir()?
+ .join("docker-compose.override.yml");
+ std::fs::write(
+ &path,
+ format!(
+ "# GENERATED by `cargo x` (local::gen_compose) — do not edit.\nname: {}\n{yaml}",
+ instance.project_name()
+ ),
+ )
+ .with_context(|| format!("writing {}", path.display()))?;
+ Ok(path)
+}
+
+/// LocalStack (S3/SQS/DynamoDB), reachable as `localstack` on both networks.
+/// Used by local AND dev — dev's `dev_personal` notification queue lives here.
+fn add_localstack_service(
+ services: &mut IndexMap<String, Option<dct::Service>>,
+ instance: &Instance,
+) {
+ services.insert(
+ "localstack".to_string(),
+ Some(dct::Service {
+ image: Some(LOCALSTACK_IMAGE.to_string()),
+ environment: kv(&[("SERVICES", "sqs,dynamodb,s3")]),
+ ports: dct::Ports::Short(vec![format!("{}:4566", instance.port(Port::LocalStack))]),
+ networks: net_aliases(&[
+ ("databases", &["localstack"]),
+ ("services", &["localstack"]),
+ ]),
+ ..Default::default()
+ }),
+ );
+}
+
+/// The single-origin reverse proxy (Caddy). Added in every mode — it's how the
+/// frontend reaches the local service containers.
+fn add_proxy_service(services: &mut IndexMap<String, Option<dct::Service>>, instance: &Instance) {
+ let proxy_port = instance.port(Port::Proxy);
+ services.insert(
+ "proxy".to_string(),
+ Some(dct::Service {
+ image: Some(CADDY_IMAGE.to_string()),
+ environment: kv(&[("PROXY_PORT", &proxy_port.to_string())]),
+ ports: dct::Ports::Short(vec![format!("{proxy_port}:{proxy_port}")]),
+ volumes: vec![dct::Volumes::Simple(format!(
+ "{}:/etc/caddy/Caddyfile:ro",
+ caddyfile_path(instance).display()
+ ))],
+ networks: dct::Networks::Simple(vec!["services".to_string(), "databases".to_string()]),
+ ..Default::default()
+ }),
+ );
+}
+
+/// Add the local-only companion infra services (FusionAuth override + Mailpit)
+/// and, for named instances, the remapped infra ports. LocalStack is added
+/// separately (it runs in every mode), so it is not included here.
+fn add_local_infra(services: &mut IndexMap<String, Option<dct::Service>>, instance: &Instance) {
+ // FusionAuth: repoint at the generated kickstart (volumes replaced via tag).
+ let mut fusionauth = dct::Service {
+ environment: kv(&[(
+ "FUSIONAUTH_APP_KICKSTART_FILE",
+ "/usr/local/fusionauth/kickstart/kickstart.json",
+ )]),
+ volumes: vec![
+ dct::Volumes::Simple("fusionauth_config:/usr/local/fusionauth/config".to_string()),
+ dct::Volumes::Simple(format!(
+ "{}:/usr/local/fusionauth/kickstart:ro",
+ kickstart_dir(instance).display()
+ )),
+ ],
+ ..Default::default()
+ };
+ if !instance.is_default() {
+ fusionauth.ports =
+ dct::Ports::Short(vec![format!("{}:9011", instance.port(Port::FusionAuth))]);
+ }
+ services.insert("fusionauth".to_string(), Some(fusionauth));
+
+ // Mailpit (also on `auth` so FusionAuth can deliver passwordless codes).
+ services.insert(
+ "mailpit".to_string(),
+ Some(dct::Service {
+ image: Some(MAILPIT_IMAGE.to_string()),
+ environment: kv(&[
+ ("MP_SMTP_AUTH_ACCEPT_ANY", "1"),
+ ("MP_SMTP_AUTH_ALLOW_INSECURE", "1"),
+ ]),
+ ports: dct::Ports::Short(vec![
+ format!("{}:1025", instance.port(Port::MailpitSmtp)),
+ format!("{}:8025", instance.port(Port::MailpitUi)),
+ ]),
+ networks: net_aliases(&[("services", &["mailpit"]), ("auth", &["mailpit"])]),
+ ..Default::default()
+ }),
+ );
+
+ // Named instances also remap the included infra services' host ports.
+ if !instance.is_default() {
+ services.insert(
+ "postgres".to_string(),
+ Some(ports_only(vec![format!(
+ "{}:5432",
+ instance.port(Port::Postgres)
+ )])),
+ );
+ services.insert(
+ "redis".to_string(),
+ Some(ports_only(vec![
+ format!("{}:6379", instance.port(Port::Redis)),
+ format!("{}:8001", instance.port(Port::RedisUi)),
+ ])),
+ );
+ services.insert(
+ "search".to_string(),
+ Some(ports_only(vec![
+ format!("{}:9200", instance.port(Port::OpenSearch)),
+ format!("{}:9600", instance.port(Port::OpenSearchPa)),
+ ])),
+ );
+ // The auxiliary services' host-port bindings are dropped in `apply_tags`
+ // (an empty `ports:` can't be expressed in the typed model — it needs the
+ // `!override []` merge tag).
+ }
+}
+
+/// Emit the Compose merge tags the typed schema can't represent:
+/// - every Rust service drops the inherited `build:` (`!reset null`);
+/// - in dev, services also drop `depends_on` (we start only the binaries);
+/// - named-instance `ports:` and FusionAuth `volumes:` replace rather than
+/// append (`!override`).
+fn apply_tags(value: &mut Value, mode: Mode, instance: &Instance) {
+ let Some(services) = value.get_mut("services").and_then(Value::as_mapping_mut) else {
+ return;
+ };
+ let runs_local_infra = mode.spec().runs_local_infra;
+ for svc in services_for_mode(mode) {
+ let Some(s) = services
+ .get_mut(svc.compose_name)
+ .and_then(Value::as_mapping_mut)
+ else {
+ continue;
+ };
+ s.insert("build".into(), reset_null());
+ if !runs_local_infra {
+ // Dev starts only the binaries — drop the base `depends_on` so it
+ // doesn't pull up the deployed-equivalent infra containers.
+ s.insert("depends_on".into(), reset_null());
+ } else if !instance.is_default() {
+ override_in_place(s, "ports");
+ }
+ }
+ if runs_local_infra {
+ if let Some(fa) = services
+ .get_mut("fusionauth")
+ .and_then(Value::as_mapping_mut)
+ {
+ override_in_place(fa, "volumes");
+ if !instance.is_default() {
+ override_in_place(fa, "ports");
+ }
+ }
+ if !instance.is_default() {
+ // Remapped infra ports REPLACE the inherited `ports:`.
+ for infra in ["postgres", "redis", "search"] {
+ if let Some(s) = services.get_mut(infra).and_then(Value::as_mapping_mut) {
+ override_in_place(s, "ports");
+ }
+ }
+ // Drop the aux services' fixed host ports (reached via the proxy /
+ // container network) so concurrent named stacks don't collide. An
+ // empty `ports:` can't be built in the typed model, so inject the
+ // `!override []` directly: `{ports: !override []}` merges over the
+ // base service, replacing its host-port list with nothing.
+ for name in AUX_HOST_PORT_SERVICES {
+ let entry = services
+ .entry(Value::from(*name))
+ .or_insert_with(|| Value::Mapping(serde_yaml::Mapping::new()));
+ if let Some(m) = entry.as_mapping_mut() {
+ m.insert("ports".into(), override_tag(Value::Sequence(vec![])));
+ }
+ }
+ }
+ }
+}
+
+/// Define the per-instance external networks and volumes (named-instance only).
+fn set_external_networks_and_volumes(value: &mut Value, instance: &Instance) {
+ let ext = |name: String| {
+ let mut m = serde_yaml::Mapping::new();
+ m.insert("external".into(), true.into());
+ m.insert("name".into(), name.into());
+ Value::Mapping(m)
+ };
+ let map = value.as_mapping_mut().expect("compose root is a mapping");
+ map.insert(
+ "networks".into(),
+ Value::Mapping(
+ [
+ ("databases", instance.network_databases()),
+ ("auth", instance.network_auth()),
+ ]
+ .into_iter()
+ .map(|(k, n)| (Value::from(k), ext(n)))
+ .collect(),
+ ),
+ );
+ map.insert(
+ "volumes".into(),
+ Value::Mapping(
+ [
+ ("db", instance.volume_postgres()),
+ ("cache", instance.volume_redis()),
+ ("opensearch_data", instance.volume_opensearch()),
+ ("db_data", instance.volume_fusionauth_db()),
+ ("fusionauth_config", instance.volume_fusionauth_config()),
+ ]
+ .into_iter()
+ .map(|(k, n)| (Value::from(k), ext(n)))
+ .collect(),
+ ),
+ );
+}
+
+/// `!reset null`.
+fn reset_null() -> Value {
+ Value::Tagged(Box::new(TaggedValue {
+ tag: Tag::new("!reset"),
+ value: Value::Null,
+ }))
+}
+
+/// Wrap a value in the `!override` merge tag (replace-not-merge).
+fn override_tag(value: Value) -> Value {
+ Value::Tagged(Box::new(TaggedValue {
+ tag: Tag::new("!override"),
+ value,
+ }))
+}
+
+/// Wrap an existing field value in the `!override` tag (replace-not-merge).
+fn override_in_place(service: &mut serde_yaml::Mapping, field: &str) {
+ if let Some(existing) = service.remove(field) {
+ service.insert(field.into(), override_tag(existing));
+ }
+}
+
+fn kv(pairs: &[(&str, &str)]) -> dct::Environment {
+ dct::Environment::KvPair(
+ pairs
+ .iter()
+ .map(|(k, v)| (k.to_string(), Some(dct::SingleValue::String(v.to_string()))))
+ .collect(),
+ )
+}
+
+fn net_aliases(pairs: &[(&str, &[&str])]) -> dct::Networks {
+ dct::Networks::Advanced(dct::AdvancedNetworks(
+ pairs
+ .iter()
+ .map(|(net, aliases)| {
+ (
+ net.to_string(),
+ dct::MapOrEmpty::Map(dct::AdvancedNetworkSettings {
+ aliases: aliases.iter().map(|a| a.to_string()).collect(),
+ ..Default::default()
+ }),
+ )
+ })
+ .collect(),
+ ))
+}
+
+fn ports_only(ports: Vec<String>) -> dct::Service {
+ dct::Service {
+ ports: dct::Ports::Short(ports),
+ ..Default::default()
+ }
+}
+
+/// The ordered compose file list run-local/run-dev/validate all use: the base
+/// compose then the per-instance generated override.
+pub fn compose_files(instance: &Instance) -> Vec<PathBuf> {
+ vec![
+ repo_root().join("docker-compose.yml"),
+ instance.artifact_dir().join("docker-compose.override.yml"),
+ ]
+}
+
+/// A `docker compose` command wired for this instance.
+pub fn docker_compose(
+ instance: &Instance,
+ files: &[PathBuf],
+ generated_env: &std::path::Path,
+) -> Command {
+ let mut cmd = Command::new("docker");
+ cmd.arg("compose").args(["-p", instance.project_name()]);
+ for f in files {
+ cmd.arg("-f").arg(f);
+ }
+ cmd.arg("--env-file").arg(generated_env);
+ cmd.env("COMPOSE_PROJECT_NAME", instance.project_name());
+ cmd.env("MACRO_ENV_FILE", generated_env);
+ cmd
+}
diff --git a/rust/cloud-storage/tools/xtask/src/local/identity.rs b/rust/cloud-storage/tools/xtask/src/local/identity.rs
new file mode 100644
index 0000000000..632f186135
--- /dev/null
+++ b/rust/cloud-storage/tools/xtask/src/local/identity.rs
@@ -0,0 +1,66 @@
+//! The fixed local FusionAuth/JWT identity, the shared internal-auth key, and
+//! the per-instance secret derivation.
+//!
+//! These are NOT optional defaults — they're the mandatory contract that the
+//! FusionAuth kickstart (which writes them *into* FusionAuth) and the service env
+//! (which tells the services what identity to expect) must agree on byte-for-byte.
+//! Single-sourcing them here is what prevents the kickstart↔service drift that
+//! the old Pulumi-configure-then-patch-`.env` approach kept hitting. They are
+//! deterministic, local-only, and safe to check in — never used in dev or prod.
+
+/// FusionAuth API key registered by the kickstart and used by services that
+/// call the FusionAuth admin API (auth-service).
+pub const FUSIONAUTH_API_KEY: &str = "bf69486b-4733-4954-a44e-2e1b5f2c8a91";
+
+/// HS256 signing key id imported by the kickstart and referenced by the tenant
+/// / application JWT config.
+pub const JWT_SIGNING_KEY_ID: &str = "d7d09513-a3f5-401c-9685-34ab6c552453";
+
+/// The HS256 secret. `macro_auth` reads this as `JWT_SECRET_KEY`.
+pub const JWT_SECRET: &str = "super-secret-jwt-signing-key-for-local-development-only";
+
+/// The populate-JWT lambda id (the unlicensed local variant).
+pub const POPULATE_JWT_LAMBDA_ID: &str = "a7f3e8d2-4b91-4c5a-9e6f-1a2b3c4d5e6f";
+
+/// The Macro application id. Client id == application id == JWT `aud`
+/// (`AUDIENCE`). Must NOT be FusionAuth's reserved built-in application id
+/// (`3c219e58-ed0e-4b18-ad48-f4f92793ae32`, the "FusionAuth" admin app), which
+/// already exists on every instance and would make the kickstart's
+/// create-application step fail with `[duplicate]applicationId`.
+pub const APPLICATION_ID: &str = "22222222-2222-4222-8222-222222222222";
+
+/// A fixed local tenant id (deterministic, local-only).
+pub const TENANT_ID: &str = "11111111-1111-4111-8111-111111111111";
+
+/// A fixed OAuth client secret (deterministic, local-only).
+pub const CLIENT_SECRET: &str = "c3VwZXItc2VjcmV0LWxvY2FsLWNsaWVudC1zZWNyZXQtMDE";
+
+/// The JWT issuer the tenant emits; `macro_auth` checks `iss` against this.
+pub const ISSUER: &str = "local.macro.com";
+
+/// Fixed id for the passwordless-login email template the kickstart creates.
+pub const PASSWORDLESS_EMAIL_TEMPLATE_ID: &str = "33333333-3333-4333-8333-333333333333";
+
+/// Local from-address for FusionAuth-sent mail (lands in Mailpit).
+pub const MAIL_FROM: &str = "[email protected]";
+
+/// The internal service-to-service auth key in local mode. Services read it as
+/// `INTERNAL_API_SECRET_KEY`; the FusionAuth kickstart's user webhooks send it
+/// as `x-internal-auth-key`. They MUST match (a mismatch makes the webhook's
+/// new-user registration fail), so both sides read this one constant. Local-only.
+pub const INTERNAL_AUTH_KEY: &str = "local";
+
+/// The auth-service OAuth redirect URI for an instance on `auth_port`. The
+/// FusionAuth kickstart authorizes it and services read it as
+/// `FUSIONAUTH_OAUTH_REDIRECT_URI` — build it one way so they can't drift.
+pub fn oauth_redirect_uri(auth_port: u16) -> String {
+ format!("http://localhost:{auth_port}/oauth/redirect")
+}
+
+/// Deterministically derive a local-only internal secret from a label and the
+/// instance name, so every container in one instance agrees (e.g. services and
+/// sync_service must share `INTERNAL_API_SECRET_KEY`) while different instances
+/// stay isolated. Local-only; never a real secret.
+pub fn instance_secret(label: &str, instance: &str) -> String {
+ format!("local-{instance}-{label}")
+}
diff --git a/rust/cloud-storage/tools/xtask/src/local/instance.rs b/rust/cloud-storage/tools/xtask/src/local/instance.rs
new file mode 100644
index 0000000000..6aa2108af7
--- /dev/null
+++ b/rust/cloud-storage/tools/xtask/src/local/instance.rs
@@ -0,0 +1,271 @@
+//! Per-instance isolation: names, networks, volumes, and host ports.
+//!
+//! The default instance is named `macro` and keeps the exact resource names
+//! and host ports the repo uses today, so existing worktrees and muscle memory
+//! are untouched. A named instance (`--instance agent-a`) derives a disjoint
+//! set of project name, networks, volumes, and a deterministic high port window
+//! so two stacks can run concurrently without clobbering each other.
+
+use std::net::TcpListener;
+
+use anyhow::{bail, Context, Result};
+use strum::{EnumIter, IntoEnumIterator};
+
+use super::repo_root;
+
+/// The reserved default instance name. Maps to today's frozen `macro` Compose
+/// project and the fixed base ports.
+pub const DEFAULT_NAME: &str = "macro";
+
+/// Start of the non-default port window. Each named instance gets a 1000-port
+/// stride starting here; per-port offsets (all < `STRIDE`) live within a
+/// stride, so two distinct strides can never overlap.
+const WINDOW_START: u32 = 20_000;
+const STRIDE: u32 = 1_000;
+const BUCKETS: u32 = 40; // 20000..=60000
+
+/// A validated instance name: lowercase ASCII alphanumerics, hyphen, and
+/// underscore, starting alphanumeric, non-empty, <= 40 chars. The newtype
+/// guarantees every constructed name is a legal Docker resource-name component.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct InstanceName(String);
+
+impl InstanceName {
+ pub fn parse(raw: &str) -> Result<Self> {
+ ensure_valid(raw)?;
+ Ok(InstanceName(raw.to_string()))
+ }
+
+ pub fn as_str(&self) -> &str {
+ &self.0
+ }
+}
+
+fn ensure_valid(raw: &str) -> Result<()> {
+ if raw.is_empty() {
+ bail!("instance name must not be empty");
+ }
+ if raw.len() > 40 {
+ bail!("instance name '{raw}' is too long (max 40 chars)");
+ }
+ let ok = raw.bytes().enumerate().all(|(i, b)| match b {
+ b'a'..=b'z' | b'0'..=b'9' => true,
+ b'-' | b'_' => i != 0,
+ _ => false,
+ });
+ if !ok {
+ bail!(
+ "instance name '{raw}' must be lowercase [a-z0-9_-] and start with an alphanumeric \
+ (so it yields valid Docker network/volume names)"
+ );
+ }
+ Ok(())
+}
+
+/// Every host port the orchestrator allocates. The discriminant IS the port the
+/// default `macro` instance binds (matching the values hardcoded in the compose
+/// files today); a named instance binds `port_base + offset`, where `offset` is
+/// the variant's position in declaration order. Adding a port is a single line:
+/// `NewThing = 8099,`. Offsets stay below `STRIDE`, so named windows never
+/// overlap.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, EnumIter)]
+#[repr(u16)]
+pub enum Port {
+ Postgres = 5432,
+ Redis = 6379,
+ RedisUi = 8001,
+ OpenSearch = 9200,
+ OpenSearchPa = 9600,
+ FusionAuth = 9011,
+ LocalStack = 4566,
+ MailpitSmtp = 1025,
+ MailpitUi = 8025,
+ Proxy = 8090,
+ Frontend = 3000,
+ Auth = 8080,
+ ConnGateway = 8082,
+ Contacts = 8083,
+ DocCognition = 8085,
+ DocStorage = 8086,
+ Email = 8087,
+ Notification = 8089,
+ SearchProcessing = 8092,
+ StaticFile = 8094,
+ Unfurl = 8095,
+ ImageProxy = 8097,
+}
+
+impl Port {
+ /// The port the default `macro` instance binds — the variant's discriminant.
+ pub const fn fixed(self) -> u16 {
+ self as u16
+ }
+
+ /// The per-port offset within a named instance's stride: the variant's
+ /// position in declaration order. Unique and `< STRIDE` by construction
+ /// (there are far fewer variants than the stride).
+ pub fn offset(self) -> u16 {
+ Port::iter()
+ .position(|p| p == self)
+ .expect("every Port is yielded by iter()") as u16
+ }
+
+ /// Every allocated port — used by doctor / collision probing / the env
+ /// summary.
+ pub fn all() -> impl Iterator<Item = Port> {
+ Port::iter()
+ }
+}
+
+/// A resolved instance: its identity plus the derived resource names and port
+/// base. Construct with [`Instance::derive`].
+#[derive(Clone, Debug)]
+pub struct Instance {
+ name: InstanceName,
+ project_name: String,
+ port_base: u16,
+}
+
+impl Instance {
+ /// Derive the instance from the `--instance`/`--port-base` flags. `None`
+ /// (or `--instance macro`) is the default instance.
+ pub fn derive(instance: Option<&str>, port_base: Option<u16>) -> Result<Self> {
+ let name = match instance {
+ None | Some(DEFAULT_NAME) => InstanceName(DEFAULT_NAME.to_string()),
+ Some(n) => InstanceName::parse(n)?,
+ };
+ let project_name = if name.as_str() == DEFAULT_NAME {
+ DEFAULT_NAME.to_string()
+ } else {
+ format!("macro-{}", name.0)
+ };
+ let port_base = port_base.unwrap_or_else(|| derive_port_base(&name));
+ Ok(Instance {
+ name,
+ project_name,
+ port_base,
+ })
+ }
+
+ pub fn name(&self) -> &str {
+ self.name.as_str()
+ }
+
+ pub fn is_default(&self) -> bool {
+ self.name.as_str() == DEFAULT_NAME
+ }
+
+ /// The Compose project name (`-p` / `COMPOSE_PROJECT_NAME`).
+ pub fn project_name(&self) -> &str {
+ &self.project_name
+ }
+
+ #[allow(dead_code)] // used by tests and diagnostics
+ pub fn port_base(&self) -> u16 {
+ self.port_base
+ }
+
+ /// The host port this instance binds for `port`.
+ pub fn port(&self, port: Port) -> u16 {
+ if self.is_default() {
+ port.fixed()
+ } else {
+ self.port_base + port.offset()
+ }
+ }
+
+ /// External `databases` network name.
+ pub fn network_databases(&self) -> String {
+ self.suffixed_dash("databases")
+ }
+
+ /// External `auth` network name.
+ pub fn network_auth(&self) -> String {
+ self.suffixed_dash("auth")
+ }
+
+ pub fn volume_postgres(&self) -> String {
+ self.suffixed_underscore("macro_postgres_data")
+ }
+
+ pub fn volume_redis(&self) -> String {
+ self.suffixed_underscore("macro_redis_data")
+ }
+
+ pub fn volume_opensearch(&self) -> String {
+ self.suffixed_underscore("macro_opensearch_data")
+ }
+
+ pub fn volume_fusionauth_db(&self) -> String {
+ self.suffixed_underscore("fusionauth_db_data")
+ }
+
+ pub fn volume_fusionauth_config(&self) -> String {
+ self.suffixed_underscore("fusionauth_config")
+ }
+
+ /// Where generated artifacts (compose override, env file, kickstart,
+ /// Caddyfile, frontend env) live for this instance.
+ pub fn artifact_dir(&self) -> std::path::PathBuf {
+ repo_root()
+ .join("infra/local/generated")
+ .join(self.name.as_str())
+ }
+
+ fn suffixed_dash(&self, base: &str) -> String {
+ if self.is_default() {
+ base.to_string()
+ } else {
+ format!("{base}-{}", self.name.0)
+ }
+ }
+
+ fn suffixed_underscore(&self, base: &str) -> String {
+ if self.is_default() {
+ base.to_string()
+ } else {
+ format!("{base}_{}", self.name.0)
+ }
+ }
+
+ /// Probe every allocated host port with a TCP bind. Returns the host ports
+ /// that are already in use. Advisory-only; surfaced as a warning in doctor.
+ pub fn busy_ports(&self) -> Vec<u16> {
+ Port::all()
+ .filter_map(|p| {
+ let host_port = self.port(p);
+ match TcpListener::bind(("127.0.0.1", host_port)) {
+ Ok(_) => None,
+ Err(_) => Some(host_port),
+ }
+ })
+ .collect()
+ }
+
+ /// Create the instance's generated-artifact directory.
+ pub fn ensure_artifact_dir(&self) -> Result<std::path::PathBuf> {
+ let dir = self.artifact_dir();
+ std::fs::create_dir_all(&dir)
+ .with_context(|| format!("creating artifact dir {}", dir.display()))?;
+ Ok(dir)
+ }
+}
+
+/// Deterministically derive a port base from the instance name with FNV-1a.
+/// FNV is stable across machines and Rust versions (unlike `DefaultHasher`),
+/// so two developers running `--instance agent-a` get the same ports.
+fn derive_port_base(name: &InstanceName) -> u16 {
+ (WINDOW_START + (fnv1a(name.as_str()) % BUCKETS) * STRIDE) as u16
+}
+
+fn fnv1a(s: &str) -> u32 {
+ let mut h: u32 = 0x811c_9dc5;
+ for b in s.bytes() {
+ h ^= b as u32;
+ h = h.wrapping_mul(0x0100_0193);
+ }
+ h
+}
+
+#[cfg(test)]
+mod test;
diff --git a/rust/cloud-storage/tools/xtask/src/local/instance/test.rs b/rust/cloud-storage/tools/xtask/src/local/instance/test.rs
new file mode 100644
index 0000000000..49ce841381
--- /dev/null
+++ b/rust/cloud-storage/tools/xtask/src/local/instance/test.rs
@@ -0,0 +1,65 @@
+use super::*;
+
+#[test]
+fn rejects_invalid_names() {
+ for bad in ["", "Agent-A", "-foo", "a b", "x".repeat(41).as_str()] {
+ assert!(
+ InstanceName::parse(bad).is_err(),
+ "expected '{bad}' to be rejected"
+ );
+ }
+}
+
+#[test]
+fn accepts_valid_names() {
+ for ok in ["agent-a", "feat_1", "a", "abc-123"] {
+ assert!(
+ InstanceName::parse(ok).is_ok(),
+ "expected '{ok}' to be accepted"
+ );
+ }
+}
+
+#[test]
+fn default_instance_uses_fixed_ports() {
+ let inst = Instance::derive(None, None).unwrap();
+ assert!(inst.is_default());
+ assert_eq!(inst.project_name(), "macro");
+ assert_eq!(inst.port(Port::Postgres), 5432);
+ assert_eq!(inst.port(Port::Auth), 8080);
+ assert_eq!(inst.port(Port::DocStorage), 8086);
+ assert_eq!(inst.network_databases(), "databases");
+ assert_eq!(inst.volume_postgres(), "macro_postgres_data");
+}
+
+#[test]
+fn named_instance_is_isolated_and_deterministic() {
+ let a1 = Instance::derive(Some("agent-a"), None).unwrap();
+ let a2 = Instance::derive(Some("agent-a"), None).unwrap();
+ assert_eq!(
+ a1.port_base(),
+ a2.port_base(),
+ "derivation must be deterministic"
+ );
+ assert_eq!(a1.project_name(), "macro-agent-a");
+ assert!(a1.port(Port::Postgres) >= 20_000);
+ assert_eq!(a1.network_databases(), "databases-agent-a");
+ assert_eq!(a1.volume_postgres(), "macro_postgres_data_agent-a");
+}
+
+#[test]
+fn port_offsets_are_unique() {
+ let mut seen = std::collections::HashSet::new();
+ for p in Port::all() {
+ assert!(seen.insert(p.offset()), "duplicate offset for {p:?}");
+ assert!(p.offset() < 1000, "offset must be < stride for {p:?}");
+ }
+}
+
+#[test]
+fn port_base_override_wins() {
+ let inst = Instance::derive(Some("agent-a"), Some(12000)).unwrap();
+ assert_eq!(inst.port_base(), 12000);
+ assert_eq!(inst.port(Port::Postgres), 12000);
+ assert_eq!(inst.port(Port::Auth), 12000 + Port::Auth.offset());
+}
diff --git a/rust/cloud-storage/tools/xtask/src/local/inventory.rs b/rust/cloud-storage/tools/xtask/src/local/inventory.rs
new file mode 100644
index 0000000000..2d8642daa3
--- /dev/null
+++ b/rust/cloud-storage/tools/xtask/src/local/inventory.rs
@@ -0,0 +1,241 @@
+//! The typed inventory of services the orchestrator manages.
+//!
+//! `RUST_SERVICES` is the single source of truth mapping each Compose service
+//! to its cargo binary, owning crate's package, host port, and the modes it
+//! participates in. It encodes the two non-obvious bin↔crate mappings
+//! (`document_upload_finalizer_local_worker` is built by the
+//! `document_upload_finalizer_handler` crate; `pubsub_workers` by the
+//! `email_service` crate) and makes "a port on a portless worker"
+//! unrepresentable (`host_port: None` == portless worker).
+
+use super::instance::Port;
+use super::Mode;
+
+/// A Rust service whose binary the orchestrator builds on the host and mounts
+/// into the runtime image at `/app/out/<cargo_bin>`. Several fields document
+/// the inventory and back validation/diagnostics rather than the hot path.
+#[derive(Clone, Copy, Debug)]
+pub struct RustService {
+ /// The service key in docker-compose.yml (e.g. `authentication-service`).
+ pub compose_name: &'static str,
+ /// The cargo binary name (e.g. `authentication_service`). Run as
+ /// `/app/out/<cargo_bin>`. Bin names are unique workspace-wide, so
+ /// `cargo zigbuild --bin <cargo_bin>` resolves the package automatically.
+ pub cargo_bin: &'static str,
+ /// The owning crate's package name (for documentation / `--package`).
+ pub package: &'static str,
+ /// The instance host port, or `None` for a portless worker.
+ pub host_port: Option<Port>,
+ /// The reverse-proxy path prefix the frontend reaches this service through
+ /// (e.g. `/auth`), or `None` when it isn't proxied — a portless worker, or
+ /// `static_file_service` whose route is the bespoke CDN block in `proxy`.
+ /// This is the single source for the generated Caddy routes; it must match
+ /// the matching `proxyServers()` entry in `js/.../servers.ts` (guarded by a
+ /// test).
+ pub path_prefix: Option<&'static str>,
+ /// Whether the proxy route must upgrade WebSockets (Caddy `@matcher` shape).
+ pub is_websocket: bool,
+ /// The run modes this service starts in by default. Empty for opt-in
+ /// services, which start only with an explicit profile.
+ pub modes: &'static [Mode],
+ /// Opt-in services (e.g. `search_processing_service`) only start with an
+ /// explicit profile and are never converted to the runtime image.
+ pub opt_in: bool,
+ /// Built locally with `--no-default-features` (true only for
+ /// `authentication_service`): its `rate_limit` feature is in the default
+ /// set, and dropping it removes the 1-request/minute login-code throttle
+ /// that otherwise makes local dev painful.
+ pub no_default_features: bool,
+}
+
+impl RustService {
+ /// Whether this service starts by default in the given mode.
+ pub fn in_mode(&self, mode: Mode) -> bool {
+ self.modes.contains(&mode)
+ }
+
+ /// Opt-in services (e.g. `search_processing_service`) only start with an
+ /// explicit profile and are never converted to the runtime image.
+ pub fn is_opt_in(&self) -> bool {
+ self.opt_in
+ }
+}
+
+/// The full service inventory: the 12 binaries bundled today plus the opt-in
+/// `search_processing_service`.
+pub const RUST_SERVICES: &[RustService] = &[
+ RustService {
+ compose_name: "authentication-service",
+ cargo_bin: "authentication_service",
+ package: "authentication_service",
+ host_port: Some(Port::Auth),
+ path_prefix: Some("/auth"),
+ is_websocket: false,
+ modes: &[Mode::Local, Mode::Dev],
+ opt_in: false,
+ no_default_features: true,
+ },
+ RustService {
+ compose_name: "connection_gateway",
+ cargo_bin: "connection_gateway_service",
+ package: "connection_gateway",
+ host_port: Some(Port::ConnGateway),
+ path_prefix: Some("/connection-gateway"),
+ is_websocket: true,
+ modes: &[Mode::Local, Mode::Dev],
+ opt_in: false,
+ no_default_features: false,
+ },
+ RustService {
+ compose_name: "contacts_service",
+ cargo_bin: "contacts_service",
+ package: "contacts_service",
+ host_port: Some(Port::Contacts),
+ path_prefix: Some("/contacts"),
+ is_websocket: false,
+ modes: &[Mode::Local, Mode::Dev],
+ opt_in: false,
+ no_default_features: false,
+ },
+ RustService {
+ compose_name: "document_cognition_service",
+ cargo_bin: "document_cognition_service",
+ package: "document_cognition_service",
+ host_port: Some(Port::DocCognition),
+ path_prefix: Some("/cognition"),
+ is_websocket: false,
+ modes: &[Mode::Local, Mode::Dev],
+ opt_in: false,
+ no_default_features: false,
+ },
+ RustService {
+ compose_name: "document_storage_service",
+ cargo_bin: "document_storage_service",
+ package: "document_storage_service",
+ host_port: Some(Port::DocStorage),
+ path_prefix: Some("/dss"),
+ is_websocket: false,
+ modes: &[Mode::Local, Mode::Dev],
+ opt_in: false,
+ no_default_features: false,
+ },
+ RustService {
+ compose_name: "document_upload_finalizer",
+ // Built by the document_upload_finalizer_handler crate (src/bin/local_worker.rs),
+ // NOT a crate named document_upload_finalizer.
+ cargo_bin: "document_upload_finalizer_local_worker",
+ package: "document_upload_finalizer_handler",
+ host_port: None,
+ path_prefix: None,
+ is_websocket: false,
+ modes: &[Mode::Local],
+ opt_in: false,
+ no_default_features: false,
+ },
+ RustService {
+ compose_name: "email_service",
+ cargo_bin: "email_service",
+ package: "email_service",
+ host_port: Some(Port::Email),
+ path_prefix: Some("/email"),
+ is_websocket: false,
+ modes: &[Mode::Local, Mode::Dev],
+ opt_in: false,
+ no_default_features: false,
+ },
+ RustService {
+ compose_name: "email_pubsub_workers",
+ // The pubsub_workers bin is built by the email_service crate
+ // (src/bin/pubsub_workers/pubsub_workers.rs).
+ cargo_bin: "pubsub_workers",
+ package: "email_service",
+ host_port: None,
+ path_prefix: None,
+ is_websocket: false,
+ modes: &[Mode::Local],
+ opt_in: false,
+ no_default_features: false,
+ },
+ RustService {
+ compose_name: "notification_service",
+ cargo_bin: "notification_service",
+ package: "notification_service",
+ host_port: Some(Port::Notification),
+ path_prefix: Some("/notification"),
+ is_websocket: false,
+ modes: &[Mode::Local, Mode::Dev],
+ opt_in: false,
+ no_default_features: false,
+ },
+ RustService {
+ compose_name: "static_file_service",
+ cargo_bin: "static_file_service",
+ package: "static_file_service",
+ host_port: Some(Port::StaticFile),
+ // Routed by the bespoke `/static-file` CDN block in `proxy` (S3 fan-out),
+ // not the generic generated route — so no generic prefix here.
+ path_prefix: None,
+ is_websocket: false,
+ modes: &[Mode::Local, Mode::Dev],
+ opt_in: false,
+ no_default_features: false,
+ },
+ RustService {
+ compose_name: "unfurl_service",
+ cargo_bin: "unfurl_service",
+ package: "unfurl_service",
+ host_port: Some(Port::Unfurl),
+ path_prefix: Some("/unfurl"),
+ is_websocket: false,
+ modes: &[Mode::Local, Mode::Dev],
+ opt_in: false,
+ no_default_features: false,
+ },
+ RustService {
+ compose_name: "image_proxy_service",
+ cargo_bin: "image_proxy_service",
+ package: "image_proxy_service",
+ host_port: Some(Port::ImageProxy),
+ path_prefix: Some("/image-proxy"),
+ is_websocket: false,
+ modes: &[Mode::Local, Mode::Dev],
+ opt_in: false,
+ no_default_features: false,
+ },
+ RustService {
+ compose_name: "search_processing_service",
+ cargo_bin: "search_processing_service",
+ package: "search_processing_service",
+ host_port: Some(Port::SearchProcessing),
+ path_prefix: None,
+ is_websocket: false,
+ // Opt-in: profiles:[processors], amd64-only libpdfium, separate
+ // Dockerfile. Auto-starts in no mode; never converted to the runtime
+ // image by gen-compose.
+ modes: &[],
+ opt_in: true,
+ no_default_features: false,
+ },
+];
+
+/// The Rust services that participate in `mode` (opt-in services list no modes,
+/// so they are naturally excluded).
+pub fn services_for_mode(mode: Mode) -> impl Iterator<Item = &'static RustService> {
+ RUST_SERVICES.iter().filter(move |s| s.in_mode(mode))
+}
+
+/// The cargo binaries to build for a fully local stack (every non-opt-in
+/// service's bin, deduplicated). Used by `zigbuild`.
+pub fn local_binaries() -> Vec<&'static str> {
+ let mut bins: Vec<&'static str> = RUST_SERVICES
+ .iter()
+ .filter(|s| !s.is_opt_in())
+ .map(|s| s.cargo_bin)
+ .collect();
+ bins.sort_unstable();
+ bins.dedup();
+ bins
+}
+
+#[cfg(test)]
+mod test;
diff --git a/rust/cloud-storage/tools/xtask/src/local/inventory/test.rs b/rust/cloud-storage/tools/xtask/src/local/inventory/test.rs
new file mode 100644
index 0000000000..4cfbea20d0
--- /dev/null
+++ b/rust/cloud-storage/tools/xtask/src/local/inventory/test.rs
@@ -0,0 +1,48 @@
+use super::*;
+
+#[test]
+fn local_binaries_are_unique_and_complete() {
+ let bins = local_binaries();
+ // 12 distinct binaries (the bundled set), excluding the opt-in processor.
+ assert_eq!(bins.len(), 12, "{bins:?}");
+ assert!(bins.contains(&"pubsub_workers"));
+ assert!(bins.contains(&"document_upload_finalizer_local_worker"));
+ assert!(
+ !bins.contains(&"search_processing_service"),
+ "opt-in must be excluded"
+ );
+ let mut sorted = bins.clone();
+ sorted.dedup();
+ assert_eq!(sorted.len(), bins.len(), "binaries must be deduplicated");
+}
+
+#[test]
+fn nonobvious_crate_mappings() {
+ let by_bin = |b: &str| RUST_SERVICES.iter().find(|s| s.cargo_bin == b).unwrap();
+ assert_eq!(
+ by_bin("document_upload_finalizer_local_worker").package,
+ "document_upload_finalizer_handler"
+ );
+ assert_eq!(by_bin("pubsub_workers").package, "email_service");
+}
+
+#[test]
+fn workers_are_portless() {
+ for name in ["document_upload_finalizer", "email_pubsub_workers"] {
+ let svc = RUST_SERVICES
+ .iter()
+ .find(|s| s.compose_name == name)
+ .unwrap();
+ assert!(svc.host_port.is_none());
+ }
+}
+
+#[test]
+fn dev_mode_excludes_workers_and_optin() {
+ let dev: Vec<&str> = services_for_mode(Mode::Dev)
+ .map(|s| s.compose_name)
+ .collect();
+ assert!(!dev.contains(&"email_pubsub_workers"));
+ assert!(!dev.contains(&"search_processing_service"));
+ assert!(dev.contains(&"authentication-service"));
+}
diff --git a/rust/cloud-storage/tools/xtask/src/local/kickstart.rs b/rust/cloud-storage/tools/xtask/src/local/kickstart.rs
new file mode 100644
index 0000000000..99af16ce4a
--- /dev/null
+++ b/rust/cloud-storage/tools/xtask/src/local/kickstart.rs
@@ -0,0 +1,195 @@
+//! The deterministic FusionAuth kickstart document.
+//!
+//! Replaces the Pulumi-driven local FusionAuth configuration with a single
+//! declarative kickstart that FusionAuth applies once against an empty DB:
+//! API key, HS256 signing key, the (unlicensed) populate-JWT lambda, and the
+//! tenant and Macro application with fixed ids + a fixed client secret. Every
+//! id/secret is fixed (see `identity`) so services and FusionAuth always agree
+//! without any API read-back or patch step. No users are provisioned —
+//! passwordless login auto-creates them on demand.
+
+use serde_json::{json, Value};
+
+use super::identity;
+
+/// Build the kickstart document. `lambda_body` is the JS source of
+/// `populate_jwt_local.js`; redirect URLs are templated from the instance ports.
+pub fn build(frontend_port: u16, auth_port: u16, lambda_body: &str) -> Value {
+ let app_id = identity::APPLICATION_ID;
+ let tenant_id = identity::TENANT_ID;
+ let key_id = identity::JWT_SIGNING_KEY_ID;
+ let lambda_id = identity::POPULATE_JWT_LAMBDA_ID;
+ let template_id = identity::PASSWORDLESS_EMAIL_TEMPLATE_ID;
+
+ let redirect_urls = json!([
+ format!("http://localhost:{frontend_port}/app"),
+ identity::oauth_redirect_uri(auth_port),
+ "http://authentication-service:8080/oauth/redirect",
+ "http://localhost:8085/oauth/redirect",
+ "https://mcp-server-local.macro.com/oauth/callback",
+ ]);
+
+ let requests = vec![
+ // 1. HS256 signing key.
+ json!({
+ "method": "POST",
+ "url": format!("/api/key/import/{key_id}"),
+ "body": { "key": {
+ "id": key_id,
+ "algorithm": "HS256",
+ "name": "Local JWT Signing Key",
+ "secret": identity::JWT_SECRET,
+ "type": "HMAC",
+ }}
+ }),
+ // 2. Populate-JWT lambda (unlicensed local variant).
+ json!({
+ "method": "POST",
+ "url": format!("/api/lambda/{lambda_id}"),
+ "body": { "lambda": {
+ "id": lambda_id,
+ "name": "Populate JWT (local)",
+ "type": "JWTPopulate",
+ "enabled": true,
+ "body": lambda_body,
+ }}
+ }),
+ // 3. Passwordless email template (FA sends the login code itself).
+ // `${code}` is FreeMarker, evaluated by FA at send time — it survives
+ // kickstart's `#{}`-only variable substitution untouched.
+ json!({
+ "method": "POST",
+ "url": format!("/api/email/template/{template_id}"),
+ "body": { "emailTemplate": {
+ "name": "Passwordless Login (local)",
+ "defaultSubject": "Your Macro login code",
+ "defaultHtmlTemplate": "<p>Your Macro login code:</p><h1>${code}</h1>",
+ "defaultTextTemplate": "Your Macro login code: ${code}",
+ "fromEmail": identity::MAIL_FROM,
+ }}
+ }),
+ // 4. Tenant — with SMTP pointed at Mailpit + the passwordless template,
+ // so FusionAuth-sent passwordless codes land in Mailpit.
+ json!({
+ "method": "POST",
+ "url": format!("/api/tenant/{tenant_id}"),
+ "body": { "tenant": {
+ "name": "Macro Local",
+ "issuer": identity::ISSUER,
+ // Enable the events the create/delete user webhooks consume, so
+ // FusionAuth notifies auth-service to register new users for the
+ // app (a registered user is what makes passwordless complete
+ // return 200 instead of 202).
+ "eventConfiguration": { "events": {
+ "user.create": { "enabled": true, "transactionType": "AbsoluteMajority" },
+ "user.create.complete": { "enabled": true, "transactionType": "None" },
+ "user.delete.complete": { "enabled": true, "transactionType": "None" },
+ "user.email.verified": { "enabled": true, "transactionType": "AbsoluteMajority" },
+ }},
+ "jwtConfiguration": {
+ "accessTokenKeyId": key_id,
+ "idTokenKeyId": key_id,
+ "refreshTokenTimeToLiveInMinutes": 43200,
+ "timeToLiveInSeconds": 3600,
+ },
+ "emailConfiguration": {
+ "host": "mailpit",
+ "port": 1025,
+ "security": "NONE",
+ "defaultFromEmail": identity::MAIL_FROM,
+ "defaultFromName": "Macro Local",
+ "passwordlessEmailTemplateId": template_id,
+ },
+ // Make the passwordless code a 6-digit number (matches the dev
+ // Pulumi tenant config), not FusionAuth's default long token.
+ "externalIdentifierConfiguration": {
+ "passwordlessLoginGenerator": {
+ "length": 6,
+ "type": "randomDigits",
+ },
+ },
+ }}
+ }),
+ // 4. Macro application. `tenantId` sets the X-FusionAuth-TenantId header
+ // (required for tenant-scoped ops once a second tenant exists).
+ json!({
+ "method": "POST",
+ "url": format!("/api/application/{app_id}"),
+ "tenantId": tenant_id,
+ "body": { "application": {
+ "name": "Macro",
+ "tenantId": tenant_id,
+ // The passwordless /login endpoint issues a refresh token based
+ // on loginConfiguration.generateRefreshTokens; without it FA omits
+ // refreshToken and auth-service fails to decode the response.
+ "loginConfiguration": {
+ "allowTokenRefresh": true,
+ "requireAuthentication": true,
+ "generateRefreshTokens": true,
+ },
+ "oauthConfiguration": {
+ "clientId": app_id,
+ "clientSecret": identity::CLIENT_SECRET,
+ "enabledGrants": ["authorization_code", "refresh_token"],
+ "authorizedRedirectURLs": redirect_urls,
+ "authorizedURLValidationPolicy": "AllowWildcards",
+ "logoutBehavior": "AllApplications",
+ "generateRefreshTokens": true,
+ "requireClientAuthentication": false,
+ },
+ "jwtConfiguration": {
+ "enabled": true,
+ "accessTokenKeyId": key_id,
+ "idTokenKeyId": key_id,
+ "timeToLiveInSeconds": 3600,
+ "refreshTokenTimeToLiveInMinutes": 43200,
+ "refreshTokenExpirationPolicy": "SlidingWindow",
+ },
+ "lambdaConfiguration": { "accessTokenPopulateId": lambda_id },
+ // Macro logs users in with email codes; enable passwordless.
+ "passwordlessConfiguration": { "enabled": true },
+ }}
+ }),
+ // 6. Webhooks: on user.create FusionAuth calls auth-service, which
+ // registers the new user for the Macro app (so passwordless completes
+ // with 200). `x-internal-auth-key` must equal the services'
+ // INTERNAL_API_SECRET_KEY (set to "local" in local mode).
+ json!({
+ "method": "POST",
+ "url": "/api/webhook",
+ "body": { "webhook": {
+ "description": "Create User Webhook",
+ "connectTimeout": 1000,
+ "readTimeout": 2000,
+ "url": "http://authentication-service:8080/webhooks/user",
+ "global": true,
+ "eventsEnabled": {
+ "user.create": true,
+ "user.create.complete": true,
+ "user.email.verified": true,
+ },
+ "headers": { "x-internal-auth-key": identity::INTERNAL_AUTH_KEY },
+ }}
+ }),
+ json!({
+ "method": "POST",
+ "url": "/api/webhook",
+ "body": { "webhook": {
+ "description": "Delete User Webhook",
+ "connectTimeout": 1000,
+ "readTimeout": 2000,
+ "url": "http://authentication-service:8080/webhooks/user/delete",
+ "global": true,
+ "eventsEnabled": { "user.delete.complete": true },
+ "headers": { "x-internal-auth-key": identity::INTERNAL_AUTH_KEY },
+ }}
+ }),
+ ];
+
+ json!({
+ "//": "GENERATED by xtask (cargo x run-local). Deterministic local FusionAuth bootstrap. Do not edit.",
+ "apiKeys": [ { "key": identity::FUSIONAUTH_API_KEY, "description": "Local Development API Key" } ],
+ "variables": {},
+ "requests": requests,
+ })
+}
diff --git a/rust/cloud-storage/tools/xtask/src/local/local_env.rs b/rust/cloud-storage/tools/xtask/src/local/local_env.rs
new file mode 100644
index 0000000000..debcd58aac
--- /dev/null
+++ b/rust/cloud-storage/tools/xtask/src/local/local_env.rs
@@ -0,0 +1,270 @@
+//! The typed, code-owned local-stack environment — the replacement for the
+//! checked-in `infra/local/defaults.env`.
+//!
+//! Local mode is fully code-defined: it does NOT pull Doppler. Every value here
+//! is deterministic and local-only — docker-network hostnames, LocalStack dummy
+//! creds, fixed queue/bucket names, the fixed FusionAuth kickstart identity, and
+//! per-instance internal secrets. Anything that needs a *real* secret or a real
+//! integration (Gmail, Stripe, …) is intentionally absent: that's a `run_dev`
+//! concern (Doppler), not a local one.
+//!
+//! [`LocalEnv::for_instance`] builds the struct; [`LocalEnv::to_env`] is the one
+//! boundary that flattens it to the env map. Grouping makes additions land in a
+//! named, testable place instead of a free-form dotenv file that quietly rots.
+
+use std::collections::BTreeMap;
+
+use super::instance::{Instance, Port};
+use super::{identity, resources, Mode};
+
+/// The full local environment for one instance.
+pub struct LocalEnv {
+ environment: &'static str,
+ project_name: String,
+ infra: InfraEnv,
+ storage: StorageEnv,
+ queues: QueueEnv,
+ mail: MailEnv,
+ service_auth: ServiceAuthEnv,
+ fusionauth: FusionAuthEnv,
+}
+
+impl LocalEnv {
+ /// Build the local env for `instance` in `Local` mode (dev sources its env
+ /// from Doppler, not here).
+ pub fn for_instance(mode: Mode, instance: &Instance) -> Self {
+ let name = instance.name();
+ LocalEnv {
+ // Both local flavors run against local infra (`local` env defaults).
+ environment: mode.environment_var(),
+ project_name: instance.project_name().to_string(),
+ infra: InfraEnv::local(),
+ storage: StorageEnv::local(),
+ queues: QueueEnv::local(),
+ mail: MailEnv::local(),
+ service_auth: ServiceAuthEnv::for_instance(name),
+ fusionauth: FusionAuthEnv::for_instance(instance),
+ }
+ }
+
+ /// Flatten to the env map services receive. The single struct→env boundary.
+ pub fn to_env(&self) -> BTreeMap<String, String> {
+ let mut env = BTreeMap::new();
+ env.insert("ENVIRONMENT".into(), self.environment.into());
+ env.insert("COMPOSE_PROJECT_NAME".into(), self.project_name.clone());
+ env.insert("PORT".into(), "8080".into());
+ self.infra.write(&mut env);
+ self.storage.write(&mut env);
+ self.queues.write(&mut env);
+ self.mail.write(&mut env);
+ self.service_auth.write(&mut env);
+ self.fusionauth.write(&mut env);
+ env
+ }
+}
+
+/// Databases, search, and the LocalStack/AWS endpoint (dummy creds — no real AWS
+/// locally). Hostnames are docker-network names: binaries run inside containers.
+struct InfraEnv {
+ database_url: String,
+ redis_uri: String,
+ opensearch_url: String,
+ local_aws_url: String,
+}
+
+impl InfraEnv {
+ fn local() -> Self {
+ InfraEnv {
+ database_url: "postgres://user:password@postgres:5432/macrodb".into(),
+ redis_uri: "redis://redis:6379".into(),
+ opensearch_url: "http://search:9200".into(),
+ local_aws_url: "http://localstack:4566".into(),
+ }
+ }
+
+ fn write(&self, env: &mut BTreeMap<String, String>) {
+ env.insert("DATABASE_URL".into(), self.database_url.clone());
+ env.insert("DATABASE_URL_READONLY".into(), self.database_url.clone());
+ env.insert("REDIS_URI".into(), self.redis_uri.clone());
+ env.insert(
+ "DOCUMENT_STORAGE_SERVICE_REDIS_URI".into(),
+ self.redis_uri.clone(),
+ );
+ env.insert("LAST_ONLINE_REDIS_URI".into(), self.redis_uri.clone());
+ env.insert("OPENSEARCH_URL".into(), self.opensearch_url.clone());
+ env.insert("LOCAL_AWS_URL".into(), self.local_aws_url.clone());
+ // Dummy creds: the SDK talks to LocalStack, never real AWS.
+ env.insert("AWS_ACCESS_KEY_ID".into(), "test".into());
+ env.insert("AWS_SECRET_ACCESS_KEY".into(), "test".into());
+ env.insert("AWS_REGION".into(), "us-east-1".into());
+ env.insert("AWS_DEFAULT_REGION".into(), "us-east-1".into());
+ }
+}
+
+/// S3 buckets and DynamoDB tables, emitted straight from the shared
+/// [`resources`] catalog so they can't drift from what LocalStack provisions.
+struct StorageEnv;
+
+impl StorageEnv {
+ fn local() -> Self {
+ StorageEnv
+ }
+
+ fn write(&self, env: &mut BTreeMap<String, String>) {
+ for bucket in resources::BUCKETS {
+ env.insert(bucket.env_key.into(), bucket.name.into());
+ }
+ for table in resources::TABLES {
+ env.insert(table.env_key.into(), table.name.into());
+ }
+ }
+}
+
+/// SQS queues, emitted from the shared [`resources`] catalog. Each queue knows
+/// which env key(s) point at it and whether they want the bare name or the full
+/// LocalStack URL — so adding a queue is a single catalog entry, not edits here
+/// *and* in the provisioner.
+struct QueueEnv;
+
+impl QueueEnv {
+ fn local() -> Self {
+ QueueEnv
+ }
+
+ fn write(&self, env: &mut BTreeMap<String, String>) {
+ for queue in resources::QUEUES {
+ for &(key, form) in queue.bindings {
+ env.insert(key.into(), form.value(queue.name));
+ }
+ }
+ }
+}
+
+/// Mail: SES sends are routed to Mailpit SMTP (see the `ses_client` transport).
+struct MailEnv {
+ smtp_host: &'static str,
+ smtp_port: &'static str,
+ sender_base_address: &'static str,
+}
+
+impl MailEnv {
+ fn local() -> Self {
+ MailEnv {
+ smtp_host: "mailpit",
+ smtp_port: "1025",
+ sender_base_address: "macro.local",
+ }
+ }
+
+ fn write(&self, env: &mut BTreeMap<String, String>) {
+ env.insert("SMTP_HOST".into(), self.smtp_host.into());
+ env.insert("SMTP_PORT".into(), self.smtp_port.into());
+ env.insert(
+ "SENDER_BASE_ADDRESS".into(),
+ self.sender_base_address.into(),
+ );
+ }
+}
+
+/// Internal service-to-service auth secrets. Deterministic per instance so every
+/// container (services, sync, lexical) agrees. `INTERNAL_API_SECRET_KEY` is the
+/// literal `"local"` to match the FusionAuth webhook's `x-internal-auth-key`.
+struct ServiceAuthEnv {
+ service_internal: String,
+ dss_auth: String,
+ doc_perm_jwt: String,
+ internal_call: String,
+ url_signing: String,
+}
+
+impl ServiceAuthEnv {
+ fn for_instance(name: &str) -> Self {
+ ServiceAuthEnv {
+ service_internal: identity::instance_secret("service-internal", name),
+ dss_auth: identity::instance_secret("dss-auth", name),
+ doc_perm_jwt: identity::instance_secret("doc-perm-jwt", name),
+ internal_call: identity::instance_secret("internal-call", name),
+ url_signing: identity::instance_secret("url-signing", name),
+ }
+ }
+
+ fn write(&self, env: &mut BTreeMap<String, String>) {
+ // The shared internal auth key — must match the kickstart webhook header.
+ env.insert(
+ "INTERNAL_API_SECRET_KEY".into(),
+ identity::INTERNAL_AUTH_KEY.into(),
+ );
+ env.insert(
+ "INTERNAL_AUTH_KEY".into(),
+ identity::INTERNAL_AUTH_KEY.into(),
+ );
+ env.insert(
+ "SYNC_SERVICE_AUTH_KEY".into(),
+ identity::INTERNAL_AUTH_KEY.into(),
+ );
+ env.insert(
+ "SERVICE_INTERNAL_AUTH_KEY".into(),
+ self.service_internal.clone(),
+ );
+ env.insert(
+ "DOCUMENT_STORAGE_SERVICE_AUTH_KEY".into(),
+ self.dss_auth.clone(),
+ );
+ env.insert(
+ "DOCUMENT_PERMISSION_JWT_SECRET_KEY".into(),
+ self.doc_perm_jwt.clone(),
+ );
+ env.insert("INTERNAL_CALL_SECRET".into(), self.internal_call.clone());
+ env.insert("URL_SIGNING_HMAC".into(), self.url_signing.clone());
+ }
+}
+
+/// FusionAuth identity — all fixed UUIDs/secrets shared with the deterministic
+/// kickstart (see [`identity`]). The OAuth redirect is the only per-instance bit.
+struct FusionAuthEnv {
+ oauth_redirect_uri: String,
+}
+
+impl FusionAuthEnv {
+ fn for_instance(instance: &Instance) -> Self {
+ FusionAuthEnv {
+ oauth_redirect_uri: identity::oauth_redirect_uri(instance.port(Port::Auth)),
+ }
+ }
+
+ fn write(&self, env: &mut BTreeMap<String, String>) {
+ env.insert(
+ "FUSIONAUTH_BASE_URL".into(),
+ "http://fusionauth:9011".into(),
+ );
+ env.insert(
+ "FUSIONAUTH_API_KEY".into(),
+ identity::FUSIONAUTH_API_KEY.into(),
+ );
+ // Canonical name read by auth_service (MacroConfig serde field) + seed_cli.
+ env.insert(
+ "FUSIONAUTH_API_KEY_SECRET_KEY".into(),
+ identity::FUSIONAUTH_API_KEY.into(),
+ );
+ env.insert("FUSIONAUTH_TENANT_ID".into(), identity::TENANT_ID.into());
+ env.insert(
+ "FUSIONAUTH_CLIENT_ID".into(),
+ identity::APPLICATION_ID.into(),
+ );
+ env.insert(
+ "FUSIONAUTH_CLIENT_SECRET_KEY".into(),
+ identity::CLIENT_SECRET.into(),
+ );
+ env.insert(
+ "FUSIONAUTH_OAUTH_REDIRECT_URI".into(),
+ self.oauth_redirect_uri.clone(),
+ );
+ // macro_auth JWT claim validation.
+ env.insert("AUDIENCE".into(), identity::APPLICATION_ID.into());
+ env.insert("ISSUER".into(), identity::ISSUER.into());
+ env.insert("JWT_SECRET_KEY".into(), identity::JWT_SECRET.into());
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/rust/cloud-storage/tools/xtask/src/local/local_env/test.rs b/rust/cloud-storage/tools/xtask/src/local/local_env/test.rs
new file mode 100644
index 0000000000..26daadc189
--- /dev/null
+++ b/rust/cloud-storage/tools/xtask/src/local/local_env/test.rs
@@ -0,0 +1,88 @@
+use super::*;
+use crate::local::instance::Instance;
+use crate::local::Mode;
+
+fn local_env() -> BTreeMap<String, String> {
+ let instance = Instance::derive(None, None).expect("default instance derives");
+ LocalEnv::for_instance(Mode::Local, &instance).to_env()
+}
+
+/// Every key a local service relies on must be present — this is the test that
+/// replaces "someone remembers to update defaults.env".
+#[test]
+fn emits_required_keys() {
+ let env = local_env();
+ for key in [
+ "ENVIRONMENT",
+ "PORT",
+ "DATABASE_URL",
+ "DATABASE_URL_READONLY",
+ "REDIS_URI",
+ "OPENSEARCH_URL",
+ "LOCAL_AWS_URL",
+ "AWS_ACCESS_KEY_ID",
+ "STATIC_STORAGE_BUCKET",
+ "CONNECTION_GATEWAY_TABLE",
+ "NOTIFICATION_INGRESS_QUEUE",
+ "SMTP_HOST",
+ "INTERNAL_API_SECRET_KEY",
+ "FUSIONAUTH_API_KEY_SECRET_KEY",
+ "FUSIONAUTH_OAUTH_REDIRECT_URI",
+ "JWT_SECRET_KEY",
+ ] {
+ assert!(
+ env.contains_key(key),
+ "missing required local env key: {key}"
+ );
+ }
+}
+
+/// Local must never point at real dev/prod infrastructure: endpoints are docker
+/// aliases / localhost, and creds are the LocalStack dummies. (Note `ISSUER` is
+/// the local `local.macro.com` JWT issuer — a value, not an endpoint — so we
+/// match the *deployed* markers specifically, not a bare `.macro.com`.)
+#[test]
+fn values_are_local_only() {
+ for (key, value) in local_env() {
+ for marker in ["amazonaws.com", "-dev.macro.com", ".workers.dev"] {
+ assert!(
+ !value.contains(marker),
+ "{key} points at deployed infra ({marker}): {value}"
+ );
+ }
+ }
+}
+
+#[test]
+fn aws_creds_are_dummy() {
+ let env = local_env();
+ assert_eq!(
+ env.get("AWS_ACCESS_KEY_ID").map(String::as_str),
+ Some("test")
+ );
+ assert_eq!(
+ env.get("AWS_SECRET_ACCESS_KEY").map(String::as_str),
+ Some("test")
+ );
+}
+
+/// Per-instance internal secrets must differ between instances (deterministic
+/// but instance-scoped), while the fixed FusionAuth identity stays constant.
+#[test]
+fn instance_secrets_are_scoped_but_identity_is_fixed() {
+ let default = Instance::derive(None, None).unwrap();
+ let agent_a = Instance::derive(Some("agent-a"), None).unwrap();
+ let a = LocalEnv::for_instance(Mode::Local, &default).to_env();
+ let b = LocalEnv::for_instance(Mode::Local, &agent_a).to_env();
+
+ assert_ne!(
+ a.get("SERVICE_INTERNAL_AUTH_KEY"),
+ b.get("SERVICE_INTERNAL_AUTH_KEY"),
+ "per-instance secrets should differ between instances"
+ );
+ assert_eq!(
+ a.get("FUSIONAUTH_API_KEY_SECRET_KEY"),
+ b.get("FUSIONAUTH_API_KEY_SECRET_KEY"),
+ "the fixed FusionAuth identity should be constant across instances"
+ );
+}
diff --git a/rust/cloud-storage/tools/xtask/src/local/localstack.rs b/rust/cloud-storage/tools/xtask/src/local/localstack.rs
new file mode 100644
index 0000000000..54cce20c2c
--- /dev/null
+++ b/rust/cloud-storage/tools/xtask/src/local/localstack.rs
@@ -0,0 +1,243 @@
+//! Idempotent LocalStack provisioning (S3 / SQS / DynamoDB), replacing the
+//! `local_stack.just` recipes. Uses the AWS SDK (the dev shell ships no `aws`
+//! CLI) and runs the three independent resource groups concurrently.
+
+use anyhow::{Context, Result};
+use aws_sdk_dynamodb::types as ddb_types;
+use aws_sdk_s3::types as s3_types;
+
+use super::instance::{Instance, Port};
+use super::resources;
+
+/// Provision all LocalStack resources idempotently. Blocking entry point: spins
+/// up a Tokio runtime so the orchestrator stays synchronous.
+pub fn provision(instance: &Instance) -> Result<()> {
+ let url = format!("http://localhost:{}/", instance.port(Port::LocalStack));
+ let rt = tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()
+ .context("building tokio runtime")?;
+ rt.block_on(provision_async(&url))
+}
+
+async fn provision_async(url: &str) -> Result<()> {
+ let cfg = macro_aws_config::local_aws_config(url).await;
+
+ let sqs = aws_sdk_sqs::Client::new(&cfg);
+ let ddb = aws_sdk_dynamodb::Client::new(&cfg);
+ let s3 = aws_sdk_s3::Client::from_conf(
+ aws_sdk_s3::config::Builder::from(&cfg)
+ .force_path_style(true)
+ .build(),
+ );
+
+ // The three groups are independent — run them concurrently.
+ let (q, t, b) = tokio::join!(
+ create_queues(&sqs),
+ create_tables(&ddb),
+ create_buckets(&s3)
+ );
+ q?;
+ t?;
+ b?;
+
+ // Dependent: wire doc-storage ObjectCreated -> document-upload-finalizer-queue.
+ wire_upload_finalizer(&sqs, &s3).await?;
+ Ok(())
+}
+
+async fn create_queues(sqs: &aws_sdk_sqs::Client) -> Result<()> {
+ for queue in resources::QUEUES {
+ let name = queue.name;
+ ignore_exists(
+ sqs.create_queue().queue_name(name).send().await.map(|_| ()),
+ &format!("queue {name}"),
+ )?;
+ }
+ Ok(())
+}
+
+async fn create_buckets(s3: &aws_sdk_s3::Client) -> Result<()> {
+ for bucket in resources::BUCKETS {
+ let name = bucket.name;
+ ignore_exists(
+ s3.create_bucket().bucket(name).send().await.map(|_| ()),
+ &format!("bucket {name}"),
+ )?;
+ let cors = s3_types::CorsConfiguration::builder()
+ .cors_rules(
+ s3_types::CorsRule::builder()
+ .allowed_origins("*")
+ .allowed_methods("GET")
+ .allowed_methods("PUT")
+ .allowed_methods("POST")
+ .allowed_methods("DELETE")
+ .allowed_methods("HEAD")
+ .allowed_headers("*")
+ .expose_headers("ETag")
+ .max_age_seconds(3600)
+ .build()
+ .context("building CORS rule")?,
+ )
+ .build()
+ .context("building CORS config")?;
+ s3.put_bucket_cors()
+ .bucket(name)
+ .cors_configuration(cors)
+ .send()
+ .await
+ .with_context(|| format!("setting CORS on {name}"))?;
+ }
+ Ok(())
+}
+
+async fn create_tables(ddb: &aws_sdk_dynamodb::Client) -> Result<()> {
+ use ddb_types::{
+ AttributeDefinition, BillingMode, GlobalSecondaryIndex, KeySchemaElement, KeyType,
+ Projection, ProjectionType, ScalarAttributeType,
+ };
+
+ let attr = |name: &str| {
+ AttributeDefinition::builder()
+ .attribute_name(name)
+ .attribute_type(ScalarAttributeType::S)
+ .build()
+ };
+ let key = |name: &str, kt: KeyType| {
+ KeySchemaElement::builder()
+ .attribute_name(name)
+ .key_type(kt)
+ .build()
+ };
+ let all = || {
+ Projection::builder()
+ .projection_type(ProjectionType::All)
+ .build()
+ };
+
+ // bulk-upload (PK HASH, SK RANGE; GSI DocumentPkIndex on SK).
+ ignore_exists(
+ ddb.create_table()
+ .table_name(resources::BULK_UPLOAD_TABLE)
+ .attribute_definitions(attr("PK")?)
+ .attribute_definitions(attr("SK")?)
+ .key_schema(key("PK", KeyType::Hash)?)
+ .key_schema(key("SK", KeyType::Range)?)
+ .billing_mode(BillingMode::PayPerRequest)
+ .global_secondary_indexes(
+ GlobalSecondaryIndex::builder()
+ .index_name("DocumentPkIndex")
+ .key_schema(key("SK", KeyType::Hash)?)
+ .projection(all())
+ .build()
+ .context("bulk-upload GSI")?,
+ )
+ .send()
+ .await
+ .map(|_| ()),
+ "table bulk-upload",
+ )?;
+
+ // connection-gateway-table (PK HASH, SK RANGE; GSI ConnectionPkIndex SK HASH + PK RANGE).
+ ignore_exists(
+ ddb.create_table()
+ .table_name(resources::CONNECTION_GATEWAY_TABLE)
+ .attribute_definitions(attr("PK")?)
+ .attribute_definitions(attr("SK")?)
+ .key_schema(key("PK", KeyType::Hash)?)
+ .key_schema(key("SK", KeyType::Range)?)
+ .billing_mode(BillingMode::PayPerRequest)
+ .global_secondary_indexes(
+ GlobalSecondaryIndex::builder()
+ .index_name("ConnectionPkIndex")
+ .key_schema(key("SK", KeyType::Hash)?)
+ .key_schema(key("PK", KeyType::Range)?)
+ .projection(all())
+ .build()
+ .context("connection-gateway GSI")?,
+ )
+ .send()
+ .await
+ .map(|_| ()),
+ "table connection-gateway-table",
+ )?;
+
+ // static-file-metadata (file_id HASH).
+ ignore_exists(
+ ddb.create_table()
+ .table_name(resources::STATIC_FILE_TABLE)
+ .attribute_definitions(attr("file_id")?)
+ .key_schema(key("file_id", KeyType::Hash)?)
+ .billing_mode(BillingMode::PayPerRequest)
+ .send()
+ .await
+ .map(|_| ()),
+ "table static-file-metadata",
+ )?;
+
+ Ok(())
+}
+
+/// Configure doc-storage S3 ObjectCreated events to publish to the upload
+/// finalizer SQS queue (mirrors local_stack.just).
+async fn wire_upload_finalizer(sqs: &aws_sdk_sqs::Client, s3: &aws_sdk_s3::Client) -> Result<()> {
+ let queue_url = resources::queue_url(resources::UPLOAD_FINALIZER_QUEUE);
+ let queue_arn = resources::queue_arn(resources::UPLOAD_FINALIZER_QUEUE);
+ let source_arn = format!("arn:aws:s3:::{}", resources::DOC_STORAGE_BUCKET);
+
+ let policy = serde_json::json!({
+ "Version": "2012-10-17",
+ "Statement": [{
+ "Effect": "Allow",
+ "Principal": "*",
+ "Action": "sqs:SendMessage",
+ "Resource": queue_arn,
+ "Condition": { "ArnEquals": { "aws:SourceArn": source_arn } },
+ }],
+ })
+ .to_string();
+
+ sqs.set_queue_attributes()
+ .queue_url(&queue_url)
+ .attributes(aws_sdk_sqs::types::QueueAttributeName::Policy, policy)
+ .send()
+ .await
+ .context("setting upload-finalizer queue policy")?;
+
+ let config = s3_types::NotificationConfiguration::builder()
+ .queue_configurations(
+ s3_types::QueueConfiguration::builder()
+ .id("document-upload-finalizer")
+ .queue_arn(&queue_arn)
+ .events(s3_types::Event::from("s3:ObjectCreated:*"))
+ .build()
+ .context("building queue notification config")?,
+ )
+ .build();
+ s3.put_bucket_notification_configuration()
+ .bucket(resources::DOC_STORAGE_BUCKET)
+ .notification_configuration(config)
+ .send()
+ .await
+ .context("configuring doc-storage notifications")?;
+ Ok(())
+}
+
+/// Map "already exists" service errors to success; propagate everything else.
+fn ignore_exists<E: std::fmt::Debug>(result: Result<(), E>, what: &str) -> Result<()> {
+ match result {
+ Ok(()) => Ok(()),
+ Err(e) => {
+ let s = format!("{e:?}");
+ if s.contains("AlreadyExists")
+ || s.contains("ResourceInUseException")
+ || s.contains("BucketAlreadyOwnedByYou")
+ || s.contains("QueueNameExists")
+ {
+ Ok(())
+ } else {
+ anyhow::bail!("creating {what} failed: {s}")
+ }
+ }
+ }
+}
diff --git a/rust/cloud-storage/tools/xtask/src/local/mailpit.rs b/rust/cloud-storage/tools/xtask/src/local/mailpit.rs
new file mode 100644
index 0000000000..5a86bf91b5
--- /dev/null
+++ b/rust/cloud-storage/tools/xtask/src/local/mailpit.rs
@@ -0,0 +1,10 @@
+//! Mailpit endpoints for the run summary. The container itself is defined by
+//! the compose override; mail is routed to it via the `ses_client` SMTP
+//! transport (`SMTP_HOST=mailpit`).
+
+use super::instance::{Instance, Port};
+
+/// The Mailpit web UI URL (host-facing).
+pub fn ui_url(instance: &Instance) -> String {
+ format!("http://localhost:{}", instance.port(Port::MailpitUi))
+}
diff --git a/rust/cloud-storage/tools/xtask/src/local/mod.rs b/rust/cloud-storage/tools/xtask/src/local/mod.rs
new file mode 100644
index 0000000000..48c2dff9e3
--- /dev/null
+++ b/rust/cloud-storage/tools/xtask/src/local/mod.rs
@@ -0,0 +1,775 @@
+//! xtask-owned local & dev orchestration.
+//!
+//! `just run_local`, `just run_dev`, and the supporting
+//! `doctor`/`validate`/`stop`/`reset`/`destroy` recipes all delegate here.
+//! This module owns: building Linux service binaries on the host (zigbuild),
+//! the minimal runtime image, the typed service inventory, per-instance
+//! isolation, environment layering, generated docker-compose overrides, local
+//! infra (FusionAuth via kickstart, Mailpit, LocalStack, Postgres/Redis, DB
+//! migrate), the single-origin reverse proxy, and the frontend dev server.
+//!
+//! Design invariant: Docker never compiles Rust. Binaries are built on the host
+//! and bind-mounted read-only into the runtime image at `/app/out`.
+
+use std::path::{Path, PathBuf};
+
+pub mod arch;
+pub mod build;
+pub mod cli;
+pub mod db;
+pub mod docker;
+pub mod doctor;
+pub mod env_layer;
+pub mod frontend;
+pub mod fusionauth;
+pub mod gen_compose;
+pub mod identity;
+pub mod instance;
+pub mod inventory;
+pub mod kickstart;
+pub mod local_env;
+pub mod localstack;
+pub mod mailpit;
+pub mod proxy;
+pub mod resources;
+pub mod stage;
+pub mod summary;
+pub mod validate;
+
+#[cfg(test)]
+mod test;
+
+/// What flavor of stack we are bringing up. The mode drives which infra runs,
+/// which env applies, and which service subset starts.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Mode {
+ /// Fully local: local Postgres/Redis/FusionAuth/Mailpit/LocalStack + app
+ /// services + proxy + frontend. No Pulumi, no real AWS, no SES.
+ Local,
+ /// Local binaries pointed at shared dev resources. No local infra.
+ Dev,
+}
+
+/// The per-mode behavior table. Each [`Mode`] resolves to exactly one
+/// `ModeSpec`, and the orchestration code reads these fields instead of matching
+/// on the enum — so a mode's behavior lives in one place and adding a mode is one
+/// new [`Mode::spec`] arm rather than a hunt through ten files.
+#[derive(Clone, Copy, Debug)]
+pub struct ModeSpec {
+ /// Human-facing label (`local` / `dev`).
+ pub label: &'static str,
+ /// The Doppler `local`-project config pulled as the secret base.
+ pub doppler_config: &'static str,
+ /// Overlay the code-owned [`local_env::LocalEnv`] on top of Doppler (local
+ /// plumbing is authoritative). Off for dev, which runs against Doppler's
+ /// dev values.
+ pub overlay_local_env: bool,
+ /// Resolve the developer's real AWS credentials and strip any local-only
+ /// endpoints — dev talks to real AWS/RDS, not LocalStack/Postgres.
+ pub uses_remote_aws: bool,
+ /// Run the local-only infra: the FusionAuth kickstart, Mailpit, and the
+ /// per-instance Postgres/Redis/OpenSearch isolation. Off for dev, which
+ /// shares the deployed resources (LocalStack + Redis still run either way).
+ pub runs_local_infra: bool,
+ /// Migrate the local DB after bring-up. Off for dev — `DATABASE_URL` is the
+ /// shared dev RDS and must never be migrated from here.
+ pub migrates_db: bool,
+ /// Route `/static-file` through LocalStack S3 (vs. the dev-pointed service).
+ pub static_files_via_localstack: bool,
+ /// Wait for the backend (proxy `/auth/health`) before starting the frontend.
+ pub wait_backend_before_frontend: bool,
+ /// Show the local infra endpoints (proxy/FusionAuth/Mailpit/…) in the
+ /// summary.
+ pub show_infra_in_summary: bool,
+}
+
+impl Mode {
+ /// The behavior table for this mode (see [`ModeSpec`]).
+ pub const fn spec(self) -> ModeSpec {
+ match self {
+ Mode::Local => ModeSpec {
+ label: "local",
+ doppler_config: "lcl_personal",
+ overlay_local_env: true,
+ uses_remote_aws: false,
+ runs_local_infra: true,
+ migrates_db: true,
+ static_files_via_localstack: true,
+ wait_backend_before_frontend: true,
+ show_infra_in_summary: true,
+ },
+ Mode::Dev => ModeSpec {
+ label: "dev",
+ doppler_config: "dev_personal",
+ overlay_local_env: false,
+ uses_remote_aws: true,
+ runs_local_infra: false,
+ migrates_db: false,
+ static_files_via_localstack: false,
+ wait_backend_before_frontend: false,
+ show_infra_in_summary: false,
+ },
+ }
+ }
+
+ pub fn label(self) -> &'static str {
+ self.spec().label
+ }
+
+ /// The value of the `ENVIRONMENT` variable services read (`macro_env`).
+ /// Always `local`, including dev. In the `dev`/`prod` macro_env environments
+ /// the `remote_env_var` layer treats each config var's env value as the NAME
+ /// of a Secrets Manager secret to fetch; only `local` reads the env value as
+ /// the value itself. The Doppler `dev_personal` config ships real values (a
+ /// postgres URL, keys), not secret names, so `run_dev` must run as `local`
+ /// and gets its "dev-ness" from those values (dev DB + real AWS), not from
+ /// switching macro_env to `dev`.
+ pub fn environment_var(self) -> &'static str {
+ "local"
+ }
+}
+
+/// The cloud-storage cargo workspace root (`rust/cloud-storage`). Anchored on
+/// the crate manifest dir rather than the invocation cwd so the orchestrator
+/// works from anywhere, exactly like `main::build_graph`.
+pub fn workspace_root() -> PathBuf {
+ Path::new(env!("CARGO_MANIFEST_DIR"))
+ .ancestors()
+ .nth(2)
+ .expect("xtask manifest dir has no workspace root two levels up")
+ .to_owned()
+}
+
+/// The repository root (two levels above the cloud-storage workspace:
+/// `<repo>/rust/cloud-storage`). This is where `docker-compose.yml`,
+/// `infra/`, `js/`, and the root `justfile` live.
+pub fn repo_root() -> PathBuf {
+ workspace_root()
+ .ancestors()
+ .nth(2)
+ .expect("cloud-storage workspace has no repo root two levels up")
+ .to_owned()
+}
+
+use std::process::Command;
+
+use anyhow::Result;
+
+use instance::Instance;
+use stage::Stage;
+
+const AUX_SERVICE_IMAGES: &[&str] = &["websocket_service", "sync_service", "lexical_service"];
+
+/// Bring up a Local or Dev stack and (unless `--no-frontend`) the frontend.
+pub fn run_stack(mode: Mode, args: &cli::RunArgs) -> Result<()> {
+ let stage = Stage::from_env_cli(args.verbose);
+ let instance = Instance::derive(args.instance.instance.as_deref(), args.instance.port_base)?;
+ stage.section(&format!(
+ "macro {} stack — instance {}",
+ mode.label(),
+ instance.name()
+ ));
+
+ // `run_local`/`run_dev` are full delete + full create: tear the previous
+ // stack and ALL its stateful volumes down so the bring-up is always from a
+ // clean slate. That makes the command unconditionally idempotent — no
+ // persisted state (a stale FusionAuth DB, an old migration) can poison a
+ // later run. (Unclean exits skip the quit-time teardown, so this is also the
+ // idempotency safety net.) Run it in the BACKGROUND: tearing the old stack
+ // down is independent of the host-side build, so the two overlap instead of
+ // summing (stopping ~20 containers is otherwise the slow part of a re-run).
+ let teardown = (!stage.is_dry_run()).then(|| {
+ let instance = instance.clone();
+ std::thread::spawn(move || teardown_commands(&instance))
+ });
+
+ // Foreground: resolve env, build binaries + runtime image, generate the
+ // compose override / Caddyfile / kickstart. None of this touches the volumes
+ // or containers the teardown is removing, so it's safe to overlap.
+ let (env, target) = prepare(&stage, mode, &instance, args)?;
+
+ // Join the background teardown before we (re)create volumes + bring infra up,
+ // surfaced as a live spinner so it's clear what we're blocked on. It
+ // overlapped the build above, so this is just whatever's left of stopping the
+ // old containers — instant if it already finished.
+ if let Some(handle) = teardown {
+ stage.run_step("Tearing down previous stack", move || {
+ let _ = handle.join();
+ Ok(())
+ })?;
+ }
+ if mode.spec().runs_local_infra {
+ ensure_external_resources(&stage, &instance)?;
+ }
+
+ // Bring the backend infra up and fully ready — DB created + migrated,
+ // LocalStack provisioned, FusionAuth kickstarted — BEFORE the app services
+ // start. The teardown means everything is freshly created each run, so
+ // otherwise the services race their backends on startup (no `macrodb`,
+ // DynamoDB/OpenSearch connection refused).
+ bring_up_infra(&stage, mode, &instance, &env)?;
+ bring_up_app(&stage, mode, &instance, &env)?;
+
+ // No restart-to-reload step: the teardown means `up` always creates fresh
+ // containers, which start on the just-built binaries bind-mounted at
+ // `/app/out`. (Reloading binaries into an already-running stack is the `r`
+ // hotkey's job — see `restart_services`.)
+
+ // Start the frontend (readiness-gated, output suppressed) BEFORE the
+ // summary so the summary is the last thing printed; then block on the dev
+ // server so `just run_local` stays attached (Ctrl-C stops it while the
+ // backend containers keep running).
+ let frontend = if args.no_frontend {
+ stage.note("frontend disabled (--no-frontend)");
+ None
+ } else {
+ frontend::start(&stage, &instance, mode)?
+ };
+
+ summary::print(mode, &instance, &env);
+
+ match frontend {
+ // Interactive terminal: stay attached with a hotkey loop.
+ Some(mut fe) if stage.is_tty() => {
+ interact(
+ &stage,
+ mode,
+ &instance,
+ &env,
+ target,
+ args.build.build_aux_services,
+ &mut fe,
+ )?;
+ }
+ // Non-interactive (piped/CI): just hold the dev server until it exits.
+ Some(mut fe) => {
+ let status = fe.child.wait()?;
+ if !status.success() {
+ let out = fe.tail_output(40);
+ if !out.trim().is_empty() {
+ eprintln!("{out}");
+ }
+ anyhow::bail!("frontend dev server exited with {status}");
+ }
+ }
+ None => {}
+ }
+ Ok(())
+}
+
+/// Print the hotkey legend shown while attached to a running stack.
+fn print_hotkeys(stage: &Stage) {
+ stage.note(" [r] rebuild & reload services [q] quit (tears the stack down)");
+}
+
+/// Re-build the service binaries on the host and restart only the containers
+/// whose binary actually changed — the body of the `r` hotkey. The binaries are
+/// bind-mounted at `/app/out`, so a rebuild updates them in-place; the container
+/// just needs to re-exec. We snapshot binary mtimes around the build so a small
+/// change relinks (and restarts) one or two services, not all twelve — and a
+/// no-op build restarts nothing. Runs under a single parent spinner (quiet
+/// sub-stage) so a reload is one resolving line.
+fn rebuild_and_reload(
+ stage: &Stage,
+ mode: Mode,
+ instance: &Instance,
+ env: &env_layer::ResolvedEnv,
+ target: arch::Target,
+ build_aux_services: bool,
+) -> Result<()> {
+ if stage.is_verbose() {
+ // Run each step on the parent stage so the build (per group) and the
+ // reload each show their own `Done <elapsed>` — the build-vs-reload
+ // split — rather than folding into one line.
+ run_rebuild(stage, mode, instance, env, target, build_aux_services)
+ } else {
+ stage.run_step("Rebuilding & reloading services", || {
+ run_rebuild(
+ &stage.quiet(),
+ mode,
+ instance,
+ env,
+ target,
+ build_aux_services,
+ )
+ })
+ }
+}
+
+/// Snapshot binary mtimes, rebuild, and restart only the services whose binary
+/// the build rewrote. Runs on a quiet sub-stage when folded, or the parent stage
+/// under `--verbose` so each step times itself.
+fn run_rebuild(
+ stage: &Stage,
+ mode: Mode,
+ instance: &Instance,
+ env: &env_layer::ResolvedEnv,
+ target: arch::Target,
+ build_aux_services: bool,
+) -> Result<()> {
+ let before: Vec<Option<std::time::SystemTime>> = inventory::services_for_mode(mode)
+ .map(|svc| binary_mtime(target, svc))
+ .collect();
+ if build_aux_services {
+ std::thread::scope(|scope| {
+ let rust_build = scope.spawn(|| {
+ build::resolve(
+ stage,
+ target,
+ &build::BuildOptions {
+ no_build: false,
+ binaries_dir: None,
+ },
+ )
+ });
+ let aux_build = scope.spawn(|| build_aux_service_images(stage, instance, env));
+ let binaries = rust_build
+ .join()
+ .map_err(|_| anyhow::anyhow!("Rust service build panicked"))?;
+ let aux = aux_build
+ .join()
+ .map_err(|_| anyhow::anyhow!("auxiliary service build panicked"))?;
+ binaries?;
+ aux
+ })?;
+ } else {
+ build::resolve(
+ stage,
+ target,
+ &build::BuildOptions {
+ no_build: false,
+ binaries_dir: None,
+ },
+ )?;
+ }
+ let changed: Vec<&inventory::RustService> = inventory::services_for_mode(mode)
+ .zip(before)
+ .filter(|(svc, was)| binary_mtime(target, svc) != *was)
+ .map(|(svc, _)| svc)
+ .collect();
+ if build_aux_services {
+ recreate_aux_service_containers(stage, instance, env)?;
+ }
+ if !changed.is_empty() {
+ reload_services(stage, instance, &changed)?;
+ }
+ Ok(())
+}
+
+/// Modification time of a service's built binary (`None` if absent). Used to tell
+/// which binaries a rebuild rewrote.
+fn binary_mtime(
+ target: arch::Target,
+ svc: &inventory::RustService,
+) -> Option<std::time::SystemTime> {
+ let path = workspace_root()
+ .join(target.debug_dir())
+ .join(svc.cargo_bin);
+ std::fs::metadata(path).and_then(|m| m.modified()).ok()
+}
+
+/// Stay attached to the running stack, handling hotkeys until the user quits or
+/// the frontend exits. `r` rebuilds + reloads the services; `q`/Esc/Ctrl-C stops
+/// the frontend and tears the whole stack down (so the next run starts clean and
+/// fast). An unexpected frontend exit just returns, leaving the stack up for
+/// inspection — the next run's start-of-run teardown will reclaim it.
+fn interact(
+ stage: &Stage,
+ mode: Mode,
+ instance: &Instance,
+ env: &env_layer::ResolvedEnv,
+ target: arch::Target,
+ build_aux_services: bool,
+ fe: &mut frontend::Frontend,
+) -> Result<()> {
+ use console::Key;
+
+ let term = console::Term::stdout();
+ print_hotkeys(stage);
+ loop {
+ // Noticed on the next keypress; the frontend running silently is fine.
+ if let Some(status) = fe.child.try_wait()? {
+ let out = fe.tail_output(40);
+ if !out.trim().is_empty() {
+ stage.note("frontend output (last lines):");
+ for line in out.lines() {
+ println!(" {line}");
+ }
+ }
+ stage.note(&format!("frontend dev server exited ({status})"));
+ return Ok(());
+ }
+ match term.read_key() {
+ Ok(Key::Char('r' | 'R')) => {
+ // Drop the legend so the rebuild's single resolved line slots in
+ // above a freshly reprinted legend (pinned to the bottom) rather
+ // than the whole block stacking on each press.
+ let _ = term.clear_last_lines(1);
+ // run_step renders ✗ + the captured build error on failure; keep
+ // the loop alive so the user can fix and press `r` again.
+ let _ = rebuild_and_reload(stage, mode, instance, env, target, build_aux_services);
+ print_hotkeys(stage);
+ }
+ Ok(Key::Char('q' | 'Q') | Key::Escape | Key::CtrlC) | Err(_) => {
+ // Kill the frontend's whole process group (bun + Vite), not just
+ // bun — otherwise Vite is orphaned and keeps holding the port.
+ fe.shutdown();
+ // Tear the stack down on quit, while the user is already leaving:
+ // stopping the running containers now is the slow part of
+ // teardown, so doing it here makes the *next* `run_local` skip it
+ // (its start-of-run teardown then has nothing to stop). Best-effort
+ // — we're exiting regardless.
+ let _ = teardown(stage, instance);
+ return Ok(());
+ }
+ _ => {}
+ }
+ }
+}
+
+/// The shared front half of every stack flow: resolve the env, ensure the
+/// runtime image + service binaries, and generate the compose override /
+/// Caddyfile / kickstart. Deliberately does NOT create the external
+/// networks/volumes — that's done after the background teardown joins, since
+/// teardown removes them. Returns the resolved env + build target.
+fn prepare(
+ stage: &Stage,
+ mode: Mode,
+ instance: &Instance,
+ args: &cli::RunArgs,
+) -> Result<(env_layer::ResolvedEnv, arch::Target)> {
+ let env = env_layer::resolve(
+ mode,
+ instance,
+ args.env.no_doppler,
+ args.env.env_file.as_deref(),
+ )?;
+ stage.note(&format!("env: {}", env_layer::summarize(&env.merged)));
+
+ // Build the runtime image (idempotent) and the service binaries.
+ let target = arch::detect()?;
+ build::ensure_runtime_image(stage, target, false)?;
+ let binaries = build::resolve(
+ stage,
+ target,
+ &build::BuildOptions {
+ no_build: args.build.no_build,
+ binaries_dir: args.build.binaries_dir.clone(),
+ },
+ )?;
+
+ // Generate the override + the Caddyfile (the frontend reaches the services
+ // through the proxy in every mode), and — for the self-contained local
+ // stacks — the FusionAuth kickstart. (External networks/volumes are created
+ // by the caller after the background teardown joins.)
+ gen_compose::generate(mode, instance, &binaries)?;
+ proxy::write_caddyfile(instance, mode)?;
+ if mode.spec().runs_local_infra {
+ fusionauth::write_kickstart(instance)?;
+ }
+ if args.build.build_aux_services {
+ build_aux_service_images(stage, instance, &env)?;
+ }
+ Ok((env, target))
+}
+
+/// A `docker compose` command wired for this instance's full file set + the
+/// generated env. Shared by bring-up and the binary-reload restart.
+fn compose_cmd(instance: &Instance, env: &env_layer::ResolvedEnv) -> Command {
+ let files = gen_compose::compose_files(instance);
+ gen_compose::docker_compose(instance, &files, &env.generated_path)
+}
+
+fn build_aux_service_images(
+ stage: &Stage,
+ instance: &Instance,
+ env: &env_layer::ResolvedEnv,
+) -> Result<()> {
+ let mut build = compose_cmd(instance, env);
+ build.arg("build").args(AUX_SERVICE_IMAGES);
+ stage.run("Building auxiliary service images", &mut build)
+}
+
+fn recreate_aux_service_containers(
+ stage: &Stage,
+ instance: &Instance,
+ env: &env_layer::ResolvedEnv,
+) -> Result<()> {
+ let mut up = compose_cmd(instance, env);
+ up.args(["up", "-d", "--force-recreate", "--no-deps"])
+ .args(AUX_SERVICE_IMAGES);
+ stage.run("Recreating auxiliary service containers", &mut up)
+}
+
+/// Bring up the backend infra the app services connect to at startup, and get it
+/// fully ready before any of them start. The clean-slate teardown means
+/// everything is freshly created each run, so this ordering is what stops the
+/// services racing their backends (missing `macrodb`, DynamoDB/OpenSearch
+/// refused). Dev points Postgres/OpenSearch/FusionAuth at shared dev resources,
+/// so it only runs Redis + LocalStack locally.
+fn bring_up_infra(
+ stage: &Stage,
+ mode: Mode,
+ instance: &Instance,
+ env: &env_layer::ResolvedEnv,
+) -> Result<()> {
+ if stage.is_dry_run() {
+ return Ok(());
+ }
+ use instance::Port;
+ let spec = mode.spec();
+
+ // `--wait` gates on each service's healthcheck. Postgres (`pg_isready`) and
+ // OpenSearch (HTTP) have patient ones, so this blocks until they genuinely
+ // accept connections — not just an open port (Docker's proxy accepts before
+ // the server is ready, which is why a plain TCP probe let sqlx hit a
+ // not-ready Postgres). Redis + LocalStack have no healthcheck, so `--wait`
+ // only confirms "running"; LocalStack readiness is polled below. FusionAuth
+ // is deliberately excluded — its healthcheck gives up (5 retries) long before
+ // its ~minute kickstart finishes, so it's started + polled separately.
+ let waited: &[&str] = if spec.runs_local_infra {
+ &["postgres", "redis", "search", "localstack"]
+ } else {
+ &["redis", "localstack"]
+ };
+ let mut up = compose_cmd(instance, env);
+ up.arg("up").arg("-d").arg("--wait").args(waited);
+ stage.run("Starting infra (docker compose up -d --wait)", &mut up)?;
+
+ // LocalStack has no healthcheck: poll its API, then provision S3/SQS/DynamoDB.
+ let localstack_health = format!(
+ "http://localhost:{}/_localstack/health",
+ instance.port(Port::LocalStack)
+ );
+ wait_http(stage, "Waiting for LocalStack", &localstack_health)?;
+ stage.run_step("Provisioning LocalStack", || {
+ localstack::provision(instance)
+ })?;
+
+ if spec.migrates_db {
+ // Postgres is ready (`--wait`); create + migrate the freshly-wiped DB.
+ db::migrate(stage, instance)?;
+ }
+ if spec.runs_local_infra {
+ // Start FusionAuth on its own (impatient healthcheck → no `--wait`) and
+ // poll it patiently until the kickstart has applied.
+ let mut fa = compose_cmd(instance, env);
+ fa.arg("up").arg("-d").arg("fusionauth");
+ stage.run("Starting FusionAuth", &mut fa)?;
+ fusionauth::wait_ready(stage, instance)?;
+ }
+ Ok(())
+}
+
+/// Bring up the app (Rust) services once the infra is ready. For local, `up`
+/// with no service args starts everything — the app services plus the auxiliary
+/// containers (sync/websocket/lexical/mailpit/proxy/…) — with the already-running
+/// infra a no-op, so inter-service start order is unchanged from before. Dev
+/// starts only the binaries + proxy (its local infra is already up).
+fn bring_up_app(
+ stage: &Stage,
+ mode: Mode,
+ instance: &Instance,
+ env: &env_layer::ResolvedEnv,
+) -> Result<()> {
+ let mut up = compose_cmd(instance, env);
+ up.arg("up").arg("-d").arg("--remove-orphans");
+ if !mode.spec().runs_local_infra {
+ for svc in inventory::services_for_mode(mode) {
+ up.arg(svc.compose_name);
+ }
+ up.arg("proxy");
+ }
+ stage.run("Starting services (docker compose up -d)", &mut up)
+}
+
+/// Restart the given services' containers so they re-exec their freshly built
+/// binaries (bind-mounted at `/app/out`). Uses plain `docker restart -t 0` by
+/// container name — no `docker compose` config parse, no graceful-stop grace,
+/// and only the changed containers — so a reload after a small change is ~1s
+/// rather than bouncing all twelve. Restarting only the changed subset also
+/// avoids the `depends_on` race a full restart hits (a service coming back
+/// before a peer it depends on).
+fn reload_services(
+ stage: &Stage,
+ instance: &Instance,
+ services: &[&inventory::RustService],
+) -> Result<()> {
+ if stage.is_dry_run() {
+ return Ok(());
+ }
+ let mut cmd = Command::new("docker");
+ cmd.arg("restart").arg("-t").arg("0");
+ for svc in services {
+ // Compose names containers `<project>-<service>-1`.
+ cmd.arg(format!(
+ "{}-{}-1",
+ instance.project_name(),
+ svc.compose_name
+ ));
+ }
+ let names = services
+ .iter()
+ .map(|s| s.compose_name)
+ .collect::<Vec<_>>()
+ .join(", ");
+ stage.run(&format!("Reloading {names}"), &mut cmd)
+}
+
+/// Every Docker volume an instance owns: the app DB/cache/search plus the
+/// FusionAuth DB/config. The single list `teardown`, `ensure_external_resources`,
+/// and `destroy` share.
+fn instance_volumes(instance: &Instance) -> [String; 5] {
+ [
+ instance.volume_postgres(),
+ instance.volume_redis(),
+ instance.volume_opensearch(),
+ instance.volume_fusionauth_db(),
+ instance.volume_fusionauth_config(),
+ ]
+}
+
+/// The instance's external Docker networks.
+fn instance_networks(instance: &Instance) -> [String; 2] {
+ [instance.network_databases(), instance.network_auth()]
+}
+
+/// The docker teardown work: stop + remove the instance's stack and ALL its
+/// stateful volumes — the basis of `run_local`'s full-delete/full-create
+/// idempotency, the quit hotkey, and `destroy-local`. Containers + project
+/// networks come down with `down -v`; the data volumes are then removed
+/// explicitly, because FusionAuth's (and named instances' infra) volumes are
+/// declared `external`, which `down -v` leaves behind. Output is captured (this
+/// is best-effort and noisy) so callers surface it as a single line; absent
+/// containers/volumes are ignored.
+fn teardown_commands(instance: &Instance) {
+ let project = instance.project_name();
+ // `-t 0`: SIGKILL immediately, no graceful-shutdown grace. The default 10s
+ // SIGTERM timeout per container (Postgres' smart shutdown, OpenSearch, …)
+ // dominates teardown — and we're wiping the volumes anyway, so a clean
+ // shutdown buys nothing.
+ let _ = Command::new("docker")
+ .args([
+ "compose",
+ "-p",
+ project,
+ "down",
+ "-v",
+ "--remove-orphans",
+ "-t",
+ "0",
+ ])
+ .output();
+ for vol in instance_volumes(instance) {
+ let _ = Command::new("docker")
+ .args(["volume", "rm", "-f", &vol])
+ .output();
+ }
+}
+
+/// [`teardown_commands`] shown as a single progress row (for the quit hotkey and
+/// `destroy-local`). `run_local` instead runs it in the background — see
+/// `run_stack`.
+fn teardown(stage: &Stage, instance: &Instance) -> Result<()> {
+ if stage.is_dry_run() {
+ return Ok(());
+ }
+ stage.run_step("Tearing down stack", || {
+ teardown_commands(instance);
+ Ok(())
+ })
+}
+
+/// Create the per-instance external networks and volumes the compose files
+/// reference (idempotent — replaces the old `just create_networks`).
+fn ensure_external_resources(stage: &Stage, instance: &Instance) -> Result<()> {
+ let networks = instance_networks(instance);
+ let volumes = instance_volumes(instance);
+ stage.run_step("Ensuring networks & volumes", || {
+ for n in &networks {
+ docker::ensure_network(n)?;
+ }
+ for v in &volumes {
+ docker::ensure_volume(v)?;
+ }
+ Ok(())
+ })
+}
+
+fn wait_http(stage: &Stage, label: &str, url: &str) -> Result<()> {
+ let script = format!(
+ "for i in $(seq 1 60); do curl -fsS {url} >/dev/null 2>&1 && exit 0; sleep 2; done; echo 'not ready: {url}'; exit 1"
+ );
+ let mut cmd = Command::new("bash");
+ cmd.arg("-lc").arg(script);
+ stage.run(label, &mut cmd)
+}
+
+/// `cargo x zigbuild`.
+pub fn zigbuild_only() -> Result<()> {
+ let stage = Stage::from_env();
+ let target = arch::detect()?;
+ let binaries = build::resolve(
+ &stage,
+ target,
+ &build::BuildOptions {
+ no_build: false,
+ binaries_dir: None,
+ },
+ )?;
+ stage.note(&format!("binaries at {}", binaries.host_dir().display()));
+ Ok(())
+}
+
+/// `cargo x runtime-image`.
+pub fn runtime_image_only(force: bool) -> Result<()> {
+ let stage = Stage::from_env();
+ build::ensure_runtime_image(&stage, arch::detect()?, force)
+}
+
+/// `cargo x gen-compose`.
+pub fn gen_compose_only(args: &cli::InstanceArgs) -> Result<()> {
+ let instance = Instance::derive(args.instance.as_deref(), args.port_base)?;
+ let target = arch::detect()?;
+ let binaries = build::BinariesDir::TargetDir(workspace_root().join(target.debug_dir()));
+ let path = gen_compose::generate(Mode::Local, &instance, &binaries)?;
+ println!("{}", path.display());
+ Ok(())
+}
+
+/// `cargo x stop-local` — stop the instance's containers (keep volumes).
+pub fn stop(args: &cli::InstanceArgs) -> Result<()> {
+ let stage = Stage::from_env();
+ let instance = Instance::derive(args.instance.as_deref(), args.port_base)?;
+ let mut cmd = Command::new("docker");
+ cmd.args(["compose", "-p", instance.project_name(), "stop"]);
+ stage.run(&format!("Stopping {}", instance.project_name()), &mut cmd)
+}
+
+/// `cargo x reset-local` — drop, recreate, and migrate the instance DB.
+pub fn reset(args: &cli::InstanceArgs) -> Result<()> {
+ let stage = Stage::from_env();
+ let instance = Instance::derive(args.instance.as_deref(), args.port_base)?;
+ db::reset(&stage, &instance)
+}
+
+/// `cargo x destroy-local` — remove the instance's containers, volumes, and
+/// (named instances) external networks.
+pub fn destroy(args: &cli::InstanceArgs) -> Result<()> {
+ let stage = Stage::from_env();
+ let instance = Instance::derive(args.instance.as_deref(), args.port_base)?;
+ // Containers + all volumes (incl. FusionAuth's external ones, which `down -v`
+ // leaves behind — the same teardown run_local does for its clean slate).
+ teardown(&stage, &instance)?;
+ // The per-instance external networks only exist for named instances; the
+ // default instance's are shared base-compose networks we leave in place.
+ if !instance.is_default() {
+ stage.run_step("Removing instance networks", || {
+ for n in instance_networks(&instance) {
+ let _ = Command::new("docker").args(["network", "rm", &n]).status();
+ }
+ Ok(())
+ })?;
+ }
+ Ok(())
+}
diff --git a/rust/cloud-storage/tools/xtask/src/local/proxy.rs b/rust/cloud-storage/tools/xtask/src/local/proxy.rs
new file mode 100644
index 0000000000..8f6c2f6ef8
--- /dev/null
+++ b/rust/cloud-storage/tools/xtask/src/local/proxy.rs
@@ -0,0 +1,142 @@
+//! The per-instance single-origin reverse proxy (Caddy).
+//!
+//! One backend origin the frontend points at via `VITE_LOCAL_BACKEND_ORIGIN`.
+//! Path prefixes mirror the `serverHostLocal` keys in `servers.ts`; Caddy
+//! `reverse_proxy` upgrades WebSockets transparently (connection-gateway,
+//! websocket-service, sync-service). The `/static-file/*` block reproduces the
+//! nginx CDN fan-out (S3 via LocalStack + the static-file service).
+
+use std::path::PathBuf;
+
+use anyhow::{Context, Result};
+
+use super::gen_compose::caddyfile_path;
+use super::instance::{Instance, Port};
+use super::{inventory, Mode};
+
+/// The host-facing proxy origin.
+pub fn url(instance: &Instance) -> String {
+ format!("http://localhost:{}", instance.port(Port::Proxy))
+}
+
+/// Write the instance Caddyfile and return its path. Both local and dev route
+/// the frontend through this single origin to the local service containers; the
+/// only difference is the static-file block (dev has no local LocalStack).
+pub fn write_caddyfile(instance: &Instance, mode: Mode) -> Result<PathBuf> {
+ let path = caddyfile_path(instance);
+ if let Some(dir) = path.parent() {
+ std::fs::create_dir_all(dir)
+ .with_context(|| format!("creating proxy dir {}", dir.display()))?;
+ }
+ std::fs::write(&path, caddyfile(mode))
+ .with_context(|| format!("writing {}", path.display()))?;
+ Ok(path)
+}
+
+/// Assemble the Caddyfile: the listener head, the generated per-service routes
+/// (from the inventory), the special non-inventory routes, the mode's
+/// static-file block, then the tail. Service routes are identical across modes
+/// (they hit the local containers); only the static-file block differs.
+fn caddyfile(mode: Mode) -> String {
+ let static_block = if mode.spec().static_files_via_localstack {
+ STATIC_FILE_LOCAL
+ } else {
+ STATIC_FILE_DEV
+ };
+ format!(
+ "{CADDY_HEAD}{routes}{SPECIAL_ROUTES}{static_block}{CADDY_TAIL}",
+ routes = service_routes()
+ )
+}
+
+/// Generate the reverse-proxy routes for every inventoried service that exposes
+/// a path prefix. The inventory is the single source, so adding a service's
+/// proxy route is one field there — not a hand-edit here that can drift.
+fn service_routes() -> String {
+ let mut out = String::new();
+ for svc in inventory::RUST_SERVICES {
+ if let Some(prefix) = svc.path_prefix {
+ out.push_str(&route_block(prefix, svc.compose_name, svc.is_websocket));
+ }
+ }
+ out
+}
+
+/// One Caddy route to a service container (always on `:8080`). HTTP uses
+/// `handle_path` (which strips the prefix); WebSocket needs the bare-prefix
+/// `@matcher` + explicit strip so the frontend's trailing-slash-less connect URL
+/// still matches. The target is the canonical compose service name, which always
+/// resolves on the proxy's networks.
+fn route_block(prefix: &str, target: &str, is_websocket: bool) -> String {
+ if is_websocket {
+ let m = matcher_name(prefix);
+ format!(
+ " {m} path {prefix} {prefix}/*\n handle {m} {{\n uri strip_prefix {prefix}\n reverse_proxy {target}:8080\n }}\n"
+ )
+ } else {
+ format!(" handle_path {prefix}/* {{\n reverse_proxy {target}:8080\n }}\n")
+ }
+}
+
+/// A Caddy named-matcher token from a path prefix (drop the slash; hyphens →
+/// underscores so it's a single bare token).
+fn matcher_name(prefix: &str) -> String {
+ format!("@{}", prefix.trim_start_matches('/').replace('-', "_"))
+}
+
+/// Caddy listens on `{$PROXY_PORT}` (set in the compose service env). Static
+/// content, plaintext HTTP, automatic WebSocket upgrade. The per-service routes
+/// (generated from the inventory), the special routes, the static-file block,
+/// and the closing brace follow.
+const CADDY_HEAD: &str = r#"# GENERATED by `cargo x` — do not edit.
+{
+ auto_https off
+ admin off
+}
+
+:{$PROXY_PORT} {
+ # Caddy requires the block body on its own lines (no single-line `{ ... }`).
+"#;
+
+/// Routes for services that aren't in the Rust inventory (external / base-compose
+/// services on their own ports), so they can't be generated from it. The
+/// WebSocket routes match the bare prefix too (the frontend connects without a
+/// trailing slash, which `handle_path /x/*` would miss).
+const SPECIAL_ROUTES: &str = r#" @websocket path /websocket /websocket/*
+ handle @websocket {
+ uri strip_prefix /websocket
+ reverse_proxy websocket-service:6969
+ }
+ @sync path /sync /sync/*
+ handle @sync {
+ uri strip_prefix /sync
+ reverse_proxy sync-service:8787
+ }
+
+"#;
+
+/// Local: /api and /internal go to the service, everything else to the S3 bucket
+/// via LocalStack (mirrors infra/local/nginx/static-file-cdn.conf).
+const STATIC_FILE_LOCAL: &str = r#" route /static-file/* {
+ uri strip_prefix /static-file
+ @svc path /api/* /internal/*
+ reverse_proxy @svc static-file-service:8080
+ rewrite * /static-file-storage{uri}
+ reverse_proxy localstack:4566
+ }
+"#;
+
+/// Dev: no local LocalStack — route all static-file paths through the local
+/// static-file-service (which is pointed at dev S3).
+const STATIC_FILE_DEV: &str = r#" handle_path /static-file/* {
+ reverse_proxy static-file-service:8080
+ }
+"#;
+
+const CADDY_TAIL: &str = r#"
+ respond "macro local proxy" 200
+}
+"#;
+
+#[cfg(test)]
+mod test;
diff --git a/rust/cloud-storage/tools/xtask/src/local/proxy/test.rs b/rust/cloud-storage/tools/xtask/src/local/proxy/test.rs
new file mode 100644
index 0000000000..75b825419f
--- /dev/null
+++ b/rust/cloud-storage/tools/xtask/src/local/proxy/test.rs
@@ -0,0 +1,69 @@
+use super::*;
+use crate::local::{inventory, repo_root};
+
+/// Every inventoried service that declares a path prefix must get a route in the
+/// generated Caddyfile, targeting its canonical compose service name. This is
+/// the guarantee that replaces the old hand-maintained route list.
+#[test]
+fn generates_a_route_for_every_prefixed_service() {
+ let caddy = caddyfile(Mode::Local);
+ for svc in inventory::RUST_SERVICES {
+ let Some(prefix) = svc.path_prefix else {
+ continue;
+ };
+ assert!(
+ caddy.contains(&format!("reverse_proxy {}:8080", svc.compose_name)),
+ "Caddyfile is missing a route to {}",
+ svc.compose_name
+ );
+ assert!(
+ caddy.contains(&format!("{prefix}/*")),
+ "Caddyfile is missing the {prefix} prefix"
+ );
+ }
+}
+
+/// WebSocket services use the bare-prefix `@matcher` + explicit strip; HTTP
+/// services use `handle_path`.
+#[test]
+fn websocket_services_use_a_matcher() {
+ let caddy = caddyfile(Mode::Local);
+ // connection-gateway is the inventoried WebSocket service.
+ assert!(caddy.contains("@connection_gateway path /connection-gateway /connection-gateway/*"));
+ assert!(caddy.contains("uri strip_prefix /connection-gateway"));
+ // A plain HTTP service uses handle_path.
+ assert!(caddy.contains("handle_path /auth/* {"));
+}
+
+/// The static-file block is the one route that differs by mode: LocalStack S3
+/// fan-out locally, the dev-pointed service in dev.
+#[test]
+fn static_file_block_is_mode_specific() {
+ assert!(caddyfile(Mode::Local).contains("/static-file-storage"));
+ assert!(caddyfile(Mode::Dev).contains("handle_path /static-file/*"));
+ assert!(!caddyfile(Mode::Dev).contains("/static-file-storage"));
+}
+
+/// Drift gate across the Rust↔TypeScript seam: every proxied service's prefix
+/// must be wired into `proxyServers()` in `servers.ts`, or the frontend can't
+/// reach it through the single-origin proxy. servers.ts can't be derived from
+/// Rust, so this test is what keeps the two in sync.
+#[test]
+fn frontend_wires_every_inventory_prefix() {
+ let servers = repo_root().join("js/app/packages/core/constant/servers.ts");
+ let src = std::fs::read_to_string(&servers)
+ .unwrap_or_else(|e| panic!("reading {}: {e}", servers.display()));
+ for svc in inventory::RUST_SERVICES {
+ let Some(prefix) = svc.path_prefix else {
+ continue;
+ };
+ let http = format!("${{proxyOrigin}}{prefix}");
+ let ws = format!("${{wsProxyOrigin}}{prefix}");
+ assert!(
+ src.contains(&http) || src.contains(&ws),
+ "servers.ts proxyServers() is missing prefix {prefix} (for {}); \
+ the frontend can't reach it through the proxy",
+ svc.compose_name
+ );
+ }
+}
diff --git a/rust/cloud-storage/tools/xtask/src/local/resources.rs b/rust/cloud-storage/tools/xtask/src/local/resources.rs
new file mode 100644
index 0000000000..9f96de1175
--- /dev/null
+++ b/rust/cloud-storage/tools/xtask/src/local/resources.rs
@@ -0,0 +1,228 @@
+//! The single catalog of local AWS resources (SQS queues, S3 buckets, DynamoDB
+//! tables).
+//!
+//! Two places need these names: [`localstack`](super::localstack) *creates* the
+//! resources, and [`local_env`](super::local_env) emits the env vars services
+//! use to *find* them. Before this catalog the lists lived in both files and
+//! could silently drift — a queue created but not exported (or vice-versa) is a
+//! service that can't reach a queue that exists. Here they share one list, so
+//! adding a resource in one place is impossible: creation and env both follow
+//! from a single entry.
+//!
+//! Rule of thumb: a name is a `const` only when something *outside* the catalog
+//! iteration also references it (the upload-finalizer wiring, the seed env);
+//! everything else is an inline literal in its entry.
+
+/// LocalStack's fixed account id, used in queue URLs and ARNs.
+const ACCOUNT_ID: &str = "000000000000";
+
+/// The doc-storage bucket — referenced by the upload-finalizer wiring and the
+/// seed env, so it is named rather than inlined.
+pub const DOC_STORAGE_BUCKET: &str = "doc-storage";
+
+/// The queue doc-storage ObjectCreated events publish to — referenced by the
+/// upload-finalizer wiring, so it is named.
+pub const UPLOAD_FINALIZER_QUEUE: &str = macro_queues::DocumentUploadFinalizerQueue::LOCAL;
+
+// DynamoDB table names: referenced both by their bespoke create-table schema in
+// `localstack` and by the env binding below, so they are named.
+/// The bulk-upload requests table.
+pub const BULK_UPLOAD_TABLE: &str = "bulk-upload";
+/// The connection-gateway (websocket) table.
+pub const CONNECTION_GATEWAY_TABLE: &str = "connection-gateway-table";
+/// The static-file metadata table.
+pub const STATIC_FILE_TABLE: &str = "static-file-metadata";
+
+/// The full LocalStack URL for `queue` (docker-network host — services run in
+/// containers and reach LocalStack by its compose alias).
+pub fn queue_url(queue: &str) -> String {
+ format!("http://localstack:4566/{ACCOUNT_ID}/{queue}")
+}
+
+/// The ARN for `queue`.
+pub fn queue_arn(queue: &str) -> String {
+ format!("arn:aws:sqs:us-east-1:{ACCOUNT_ID}:{queue}")
+}
+
+/// How an env var refers to a queue: the bare name, or the full LocalStack URL.
+#[derive(Clone, Copy)]
+pub enum QueueForm {
+ /// The env value is the bare queue name.
+ Name,
+ /// The env value is the full LocalStack queue URL.
+ Url,
+}
+
+impl QueueForm {
+ /// Resolve the env value for `queue` in this form.
+ pub fn value(self, queue: &str) -> String {
+ match self {
+ QueueForm::Name => queue.to_string(),
+ QueueForm::Url => queue_url(queue),
+ }
+ }
+}
+
+/// An SQS queue: the name created in LocalStack plus the env vars that point at
+/// it. A queue may be referenced by several keys in different forms (e.g. the
+/// backfill queue is exported both as a bare name and as a URL).
+pub struct Queue {
+ /// The queue name created in LocalStack.
+ pub name: &'static str,
+ /// `(env key, value form)` pairs the env builder emits for this queue.
+ pub bindings: &'static [(&'static str, QueueForm)],
+}
+
+/// An S3 bucket: the name created in LocalStack and the env var pointing at it.
+pub struct Bucket {
+ /// The bucket name created in LocalStack.
+ pub name: &'static str,
+ /// The env var services read to find this bucket.
+ pub env_key: &'static str,
+}
+
+/// A DynamoDB table: the name and its env var. The table *schema* lives with the
+/// provisioner (it is bespoke per table); only the name is shared here.
+pub struct Table {
+ /// The table name created in LocalStack.
+ pub name: &'static str,
+ /// The env var services read to find this table.
+ pub env_key: &'static str,
+}
+
+use QueueForm::{Name, Url};
+
+/// Every local SQS queue and the env var(s) that reference it.
+pub const QUEUES: &[Queue] = &[
+ Queue {
+ name: macro_queues::NotificationQueue::LOCAL,
+ bindings: &[("NOTIFICATION_QUEUE", Url)],
+ },
+ Queue {
+ name: macro_queues::NotificationIngressQueue::LOCAL,
+ bindings: &[("NOTIFICATION_INGRESS_QUEUE", Url)],
+ },
+ Queue {
+ name: macro_queues::PushNotificationEventHandlerQueue::LOCAL,
+ bindings: &[("PUSH_NOTIFICATION_EVENT_HANDLER_QUEUE", Name)],
+ },
+ Queue {
+ name: macro_queues::EmailBackfillQueue::LOCAL,
+ bindings: &[("BACKFILL_QUEUE", Name), ("EMAIL_BACKFILL_QUEUE", Url)],
+ },
+ Queue {
+ name: macro_queues::ChatDeleteQueue::LOCAL,
+ bindings: &[("CHAT_DELETE_QUEUE", Name)],
+ },
+ Queue {
+ name: macro_queues::ContactsQueue::LOCAL,
+ bindings: &[("CONTACTS_QUEUE", Name)],
+ },
+ Queue {
+ name: macro_queues::ConvertQueue::LOCAL,
+ bindings: &[("CONVERT_QUEUE", Name)],
+ },
+ Queue {
+ name: macro_queues::DocumentDeleteQueue::LOCAL,
+ bindings: &[("DOCUMENT_DELETE_QUEUE", Name)],
+ },
+ Queue {
+ name: UPLOAD_FINALIZER_QUEUE,
+ bindings: &[("DOCUMENT_UPLOAD_FINALIZER_QUEUE_URL", Url)],
+ },
+ Queue {
+ name: macro_queues::DocumentTextExtractorQueue::LOCAL,
+ bindings: &[("DOCUMENT_TEXT_EXTRACTOR_QUEUE", Name)],
+ },
+ Queue {
+ name: macro_queues::EmailScheduledQueue::LOCAL,
+ bindings: &[("EMAIL_SCHEDULED_QUEUE", Name)],
+ },
+ Queue {
+ name: macro_queues::GmailInboxSyncQueue::LOCAL,
+ bindings: &[("GMAIL_INBOX_SYNC_QUEUE", Name)],
+ },
+ Queue {
+ name: macro_queues::GmailInboxSyncRetryQueue::LOCAL,
+ bindings: &[("GMAIL_INBOX_SYNC_RETRY_QUEUE", Name)],
+ },
+ Queue {
+ name: macro_queues::GmailOpsQueue::LOCAL,
+ bindings: &[("GMAIL_OPS_QUEUE", Name)],
+ },
+ Queue {
+ name: macro_queues::GmailOpsRetryQueue::LOCAL,
+ bindings: &[("GMAIL_OPS_RETRY_QUEUE", Name)],
+ },
+ Queue {
+ name: macro_queues::LinkManagerQueue::LOCAL,
+ bindings: &[("LINK_MANAGER_QUEUE", Name)],
+ },
+ Queue {
+ name: macro_queues::SearchEventQueue::LOCAL,
+ bindings: &[("SEARCH_EVENT_QUEUE", Name)],
+ },
+ Queue {
+ name: macro_queues::AiProjectionQueue::LOCAL,
+ bindings: &[("AI_PROJECTION_QUEUE", Url)],
+ },
+ Queue {
+ name: macro_queues::SfsDeleteQueue::LOCAL,
+ bindings: &[("SFS_DELETE_QUEUE", Name)],
+ },
+ Queue {
+ name: macro_queues::SfsUploaderQueue::LOCAL,
+ bindings: &[("SFS_UPLOADER_QUEUE", Name)],
+ },
+ Queue {
+ name: macro_queues::StaticFileServiceS3EventQueueUrl::LOCAL,
+ bindings: &[("STATIC_FILE_SERVICE_S3_EVENT_QUEUE_URL", Url)],
+ },
+];
+
+/// Every local S3 bucket and the env var that references it.
+pub const BUCKETS: &[Bucket] = &[
+ Bucket {
+ name: "macro-email-attachments",
+ env_key: "ATTACHMENT_BUCKET",
+ },
+ Bucket {
+ name: DOC_STORAGE_BUCKET,
+ env_key: "DOCUMENT_STORAGE_BUCKET",
+ },
+ Bucket {
+ name: "docx-upload",
+ env_key: "DOCX_DOCUMENT_UPLOAD_BUCKET",
+ },
+ Bucket {
+ name: "static-file-storage",
+ env_key: "STATIC_STORAGE_BUCKET",
+ },
+ Bucket {
+ name: "bulk-upload-staging",
+ env_key: "UPLOAD_STAGING_BUCKET",
+ },
+ Bucket {
+ name: "macro-call-recording-local",
+ env_key: "CALL_RECORDING_BUCKET_NAME",
+ },
+];
+
+/// Every local DynamoDB table and the env var that references it.
+pub const TABLES: &[Table] = &[
+ Table {
+ name: BULK_UPLOAD_TABLE,
+ env_key: "BULK_UPLOAD_REQUESTS_TABLE",
+ },
+ Table {
+ name: CONNECTION_GATEWAY_TABLE,
+ env_key: "CONNECTION_GATEWAY_TABLE",
+ },
+ Table {
+ name: STATIC_FILE_TABLE,
+ env_key: "STATIC_FILE_SERVICE_DYNAMODB_TABLE_NAME",
+ },
+];
+
+#[cfg(test)]
+mod test;
diff --git a/rust/cloud-storage/tools/xtask/src/local/resources/test.rs b/rust/cloud-storage/tools/xtask/src/local/resources/test.rs
new file mode 100644
index 0000000000..38493fedf8
--- /dev/null
+++ b/rust/cloud-storage/tools/xtask/src/local/resources/test.rs
@@ -0,0 +1,49 @@
+use super::*;
+use std::collections::HashSet;
+
+/// Every env key across queues, buckets, and tables must be unique — a collision
+/// means one resource's value silently clobbers another's.
+#[test]
+fn env_keys_are_unique() {
+ let mut seen = HashSet::new();
+ let keys = QUEUES
+ .iter()
+ .flat_map(|q| q.bindings.iter().map(|(k, _)| *k))
+ .chain(BUCKETS.iter().map(|b| b.env_key))
+ .chain(TABLES.iter().map(|t| t.env_key));
+ for key in keys {
+ assert!(seen.insert(key), "duplicate env key in catalog: {key}");
+ }
+}
+
+/// Resource names must be unique within each kind — a duplicate is almost
+/// certainly a copy-paste mistake (LocalStack would just no-op the second
+/// create, masking it).
+#[test]
+fn resource_names_are_unique() {
+ let mut queues = HashSet::new();
+ for q in QUEUES {
+ assert!(queues.insert(q.name), "duplicate queue name: {}", q.name);
+ }
+ let mut buckets = HashSet::new();
+ for b in BUCKETS {
+ assert!(buckets.insert(b.name), "duplicate bucket name: {}", b.name);
+ }
+ let mut tables = HashSet::new();
+ for t in TABLES {
+ assert!(tables.insert(t.name), "duplicate table name: {}", t.name);
+ }
+}
+
+/// A queue with no bindings is created in LocalStack but unreachable by any
+/// service — almost always a mistake.
+#[test]
+fn every_queue_is_bound() {
+ for q in QUEUES {
+ assert!(
+ !q.bindings.is_empty(),
+ "queue {} has no env binding",
+ q.name
+ );
+ }
+}
diff --git a/rust/cloud-storage/tools/xtask/src/local/stage.rs b/rust/cloud-storage/tools/xtask/src/local/stage.rs
new file mode 100644
index 0000000000..4d6770426f
--- /dev/null
+++ b/rust/cloud-storage/tools/xtask/src/local/stage.rs
@@ -0,0 +1,377 @@
+//! Staged-progress UI, mirroring `scripts/lib/stage-ui.sh`.
+//!
+//! A bold `[+]` section header, then per-stage lines: an `indicatif` spinner
+//! that *resolves in place* into `✓ Done <elapsed>` / `✗ Failed <elapsed>` via
+//! the bar's own finish state (no clear-and-reprint), a captured-output dump on
+//! failure, and respect for `MACRO_LOCAL_VERBOSE`, `MACRO_LOCAL_DRY_RUN`, and
+//! `NO_COLOR`.
+//!
+//! Only the subprocess capture is hand-rolled, on purpose: stdout and stderr
+//! are drained on dedicated threads so a chatty child (e.g. `cargo zigbuild`)
+//! cannot deadlock by filling a pipe buffer while we wait. `indicatif` only
+//! animates — it never reads the child's pipes.
+
+use std::io::Read;
+use std::process::{Command, Stdio};
+use std::time::{Duration, Instant};
+
+use anyhow::{bail, Result};
+use console::Style;
+use indicatif::{ProgressBar, ProgressDrawTarget, ProgressStyle};
+
+const WIDTH: usize = 48;
+/// Braille spinner frames + a trailing space (indicatif's "final" tick, which
+/// we never show — stages resolve via `finish_with_message`).
+const TICK_CHARS: &str = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏ ";
+
+/// Drives staged output. Construct once with [`Stage::from_env`] and reuse.
+pub struct Stage {
+ is_tty: bool,
+ verbose: bool,
+ dry_run: bool,
+ /// When set, this stage's own ✓/✗ lines, spinners, section headers, and
+ /// notes are suppressed (commands still run + capture). Used to fold a
+ /// multi-step action under a single parent spinner.
+ quiet: bool,
+}
+
+impl Stage {
+ pub fn from_env() -> Self {
+ let is_tty = console::Term::stdout().is_term();
+ // Disable coloring globally when not a TTY or NO_COLOR is set; every
+ // `console::Style` and indicatif template color then becomes a no-op.
+ let no_color = std::env::var_os("NO_COLOR").is_some() || !is_tty;
+ console::set_colors_enabled(!no_color);
+ Stage {
+ is_tty,
+ verbose: env_flag("MACRO_LOCAL_VERBOSE"),
+ dry_run: env_flag("MACRO_LOCAL_DRY_RUN"),
+ quiet: false,
+ }
+ }
+
+ /// Like [`Stage::from_env`], plus an explicit `--verbose` flag OR-ed with the
+ /// `MACRO_LOCAL_VERBOSE` env var.
+ pub fn from_env_cli(verbose: bool) -> Self {
+ let mut s = Self::from_env();
+ s.verbose = s.verbose || verbose;
+ s
+ }
+
+ pub fn is_dry_run(&self) -> bool {
+ self.dry_run
+ }
+
+ /// Whether verbose mode is on: stream subprocess output, and show every
+ /// sub-step's own timing instead of folding it under a parent spinner.
+ pub fn is_verbose(&self) -> bool {
+ self.verbose
+ }
+
+ /// Whether stdout is an interactive terminal (drives the hotkey loop).
+ pub fn is_tty(&self) -> bool {
+ self.is_tty
+ }
+
+ /// A child stage that suppresses its own output, so a multi-step action can
+ /// be folded under a single parent spinner. Commands still run and capture;
+ /// a failure surfaces via the returned error (with the captured output) so
+ /// the parent can show it after its spinner clears.
+ pub fn quiet(&self) -> Stage {
+ Stage {
+ is_tty: self.is_tty,
+ verbose: self.verbose,
+ dry_run: self.dry_run,
+ quiet: true,
+ }
+ }
+
+ /// A `[+] <label>` section header.
+ pub fn section(&self, label: &str) {
+ if self.quiet {
+ return;
+ }
+ println!(
+ "\n{}",
+ Style::new().green().bold().apply_to(format!("[+] {label}"))
+ );
+ }
+
+ /// A dim hint line.
+ pub fn note(&self, text: &str) {
+ if self.quiet {
+ return;
+ }
+ println!("{}", Style::new().dim().apply_to(text));
+ }
+
+ /// Print a labeled, shell-quoted command (dry-run preview / failure dump).
+ pub fn print_command(&self, label: &str, program: &str, args: &[String]) {
+ let mut line = Style::new().bold().apply_to(label).to_string();
+ line.push(' ');
+ line.push_str(&shell_quote(program));
+ for a in args {
+ line.push(' ');
+ line.push_str(&shell_quote(a));
+ }
+ println!("{line}");
+ }
+
+ /// Format a ` <marker> <label> <status>` stage line with one color.
+ fn line(&self, marker: &str, label: &str, status: &str, style: &Style) -> String {
+ format!(
+ " {} {label:<WIDTH$} {}",
+ style.apply_to(marker),
+ style.apply_to(status)
+ )
+ }
+
+ /// A steady-ticking spinner for `label`, or `None` when not a TTY (then
+ /// stages just print their resolved line, no animation).
+ fn spinner(&self, label: &str) -> Option<ProgressBar> {
+ if !self.is_tty {
+ return None;
+ }
+ let pb = ProgressBar::with_draw_target(None, ProgressDrawTarget::stdout());
+ pb.set_style(
+ ProgressStyle::with_template(" {spinner:.cyan} {prefix} {msg:.cyan}")
+ .expect("valid spinner template")
+ .tick_chars(TICK_CHARS),
+ );
+ pb.set_prefix(format!("{label:<WIDTH$}"));
+ pb.set_message("Running");
+ pb.enable_steady_tick(Duration::from_millis(80));
+ Some(pb)
+ }
+
+ /// Settle a stage to its final line: resolved in place if a spinner is live
+ /// (TTY), else printed plainly (non-TTY).
+ fn resolve(&self, spinner: Option<ProgressBar>, line: String) {
+ match spinner {
+ Some(pb) => {
+ pb.set_style(ProgressStyle::with_template("{msg}").expect("valid template"));
+ pb.finish_with_message(line);
+ }
+ None => println!("{line}"),
+ }
+ }
+
+ /// Run `cmd` as a single stage. In dry-run mode the command is printed, not
+ /// executed. In verbose mode output streams live. Otherwise output is
+ /// captured and a spinner animates until completion; on failure the
+ /// captured output is dumped and the error propagated (fail-fast).
+ pub fn run(&self, label: &str, cmd: &mut Command) -> Result<()> {
+ let program = cmd.get_program().to_string_lossy().to_string();
+ let args: Vec<String> = cmd
+ .get_args()
+ .map(|a| a.to_string_lossy().to_string())
+ .collect();
+
+ if self.dry_run {
+ println!("{}", self.line("•", label, "Dry run", &Style::new().dim()));
+ self.print_command(" ", &program, &args);
+ return Ok(());
+ }
+
+ let start = Instant::now();
+
+ if self.verbose {
+ println!("{}", self.line("-", label, "Running", &Style::new().cyan()));
+ let status = cmd.status();
+ return self.finish(
+ None,
+ label,
+ start,
+ status.map(|s| (s, Vec::new())),
+ &program,
+ &args,
+ );
+ }
+
+ // Default mode: capture output, animate a spinner. stdout/stderr are
+ // drained on their own threads so the child can't deadlock on a full
+ // pipe while the spinner ticks and we wait. The spinner only animates;
+ // it never touches the child's pipes.
+ cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
+ let mut child = cmd.spawn().map_err(anyhow::Error::from)?;
+ let mut stdout = child.stdout.take();
+ let mut stderr = child.stderr.take();
+ let out_handle = std::thread::spawn(move || drain(stdout.as_mut()));
+ let err_handle = std::thread::spawn(move || drain(stderr.as_mut()));
+
+ let spinner = if self.quiet {
+ None
+ } else {
+ self.spinner(label)
+ };
+ let status = child.wait();
+ let mut captured = out_handle.join().unwrap_or_default();
+ captured.extend(err_handle.join().unwrap_or_default());
+ if self.quiet {
+ // Silent on success; on failure bubble the captured output up in the
+ // error so the parent stage can show it after its spinner clears.
+ return match status {
+ Ok(s) if s.success() => Ok(()),
+ Ok(s) => {
+ let out = String::from_utf8_lossy(&captured);
+ bail!("`{program}` exited with {s}\n{}", out.trim_end());
+ }
+ Err(e) => Err(anyhow::Error::from(e)),
+ };
+ }
+ self.finish(
+ spinner,
+ label,
+ start,
+ status.map(|s| (s, captured)),
+ &program,
+ &args,
+ )
+ }
+
+ /// Run an in-process closure as a stage (for work that isn't a subprocess,
+ /// e.g. async LocalStack provisioning). The spinner ticks on its own thread
+ /// while the closure blocks this one, with the same ✓/✗ contract and
+ /// dry-run handling.
+ pub fn run_step<F: FnOnce() -> Result<()>>(&self, label: &str, f: F) -> Result<()> {
+ if self.dry_run {
+ println!("{}", self.line("•", label, "Dry run", &Style::new().dim()));
+ return Ok(());
+ }
+ if self.quiet {
+ return f();
+ }
+ let start = Instant::now();
+ let spinner = self.spinner(label);
+ let result = f();
+ let elapsed = format_elapsed(start.elapsed());
+ match result {
+ Ok(()) => {
+ self.resolve(
+ spinner,
+ self.line(
+ "✓",
+ label,
+ &format!("Done {elapsed}"),
+ &Style::new().green(),
+ ),
+ );
+ Ok(())
+ }
+ Err(e) => {
+ self.resolve(
+ spinner,
+ self.line(
+ "✗",
+ label,
+ &format!("Failed {elapsed}"),
+ &Style::new().red(),
+ ),
+ );
+ eprintln!(" {e:?}");
+ Err(e)
+ }
+ }
+ }
+
+ fn finish(
+ &self,
+ spinner: Option<ProgressBar>,
+ label: &str,
+ start: Instant,
+ outcome: std::io::Result<(std::process::ExitStatus, Vec<u8>)>,
+ program: &str,
+ args: &[String],
+ ) -> Result<()> {
+ let elapsed = format_elapsed(start.elapsed());
+ match outcome {
+ Ok((status, _captured)) if status.success() => {
+ self.resolve(
+ spinner,
+ self.line(
+ "✓",
+ label,
+ &format!("Done {elapsed}"),
+ &Style::new().green(),
+ ),
+ );
+ Ok(())
+ }
+ Ok((status, captured)) => {
+ self.resolve(
+ spinner,
+ self.line(
+ "✗",
+ label,
+ &format!("Failed {elapsed}"),
+ &Style::new().red(),
+ ),
+ );
+ self.print_command("Command failed:", program, args);
+ if !captured.is_empty() {
+ println!("{}", Style::new().bold().apply_to("Output:"));
+ for line in String::from_utf8_lossy(&captured).lines() {
+ println!(" {line}");
+ }
+ }
+ bail!("`{program}` exited with {status}");
+ }
+ Err(e) => {
+ self.resolve(
+ spinner,
+ self.line(
+ "✗",
+ label,
+ &format!("Failed {elapsed}"),
+ &Style::new().red(),
+ ),
+ );
+ self.print_command("Command failed:", program, args);
+ Err(anyhow::Error::from(e))
+ }
+ }
+ }
+}
+
+fn drain(reader: Option<&mut impl Read>) -> Vec<u8> {
+ let mut buf = Vec::new();
+ if let Some(r) = reader {
+ let _ = r.read_to_end(&mut buf);
+ }
+ buf
+}
+
+// xtask is host tooling, not a service reading APP_SECRETS_JSON, so reading the
+// process environment directly is correct here.
+#[allow(clippy::disallowed_methods)]
+fn env_flag(name: &str) -> bool {
+ std::env::var(name).map(|v| v == "1").unwrap_or(false)
+}
+
+fn format_elapsed(d: Duration) -> String {
+ let secs = d.as_secs();
+ if secs >= 60 {
+ format!("{}m{}s", secs / 60, secs % 60)
+ } else {
+ format!("{secs}s")
+ }
+}
+
+/// Minimal POSIX shell quoting for the command-echo lines (stand-in for bash's
+/// `printf %q`). Bare tokens pass through; anything with shell-special
+/// characters is single-quoted.
+fn shell_quote(s: &str) -> String {
+ if !s.is_empty()
+ && s.bytes().all(|b| {
+ b.is_ascii_alphanumeric()
+ || matches!(
+ b,
+ b'_' | b'-' | b'.' | b'/' | b':' | b'=' | b',' | b'@' | b'+'
+ )
+ })
+ {
+ s.to_string()
+ } else {
+ format!("'{}'", s.replace('\'', "'\\''"))
+ }
+}
diff --git a/rust/cloud-storage/tools/xtask/src/local/summary.rs b/rust/cloud-storage/tools/xtask/src/local/summary.rs
new file mode 100644
index 0000000000..934cba7b17
--- /dev/null
+++ b/rust/cloud-storage/tools/xtask/src/local/summary.rs
@@ -0,0 +1,91 @@
+//! The final startup summary (the spec's Output Contract).
+
+use console::Style;
+
+use super::env_layer::ResolvedEnv;
+use super::instance::{Instance, Port};
+use super::{frontend, mailpit, proxy, Mode};
+
+/// Print the mode/instance/endpoints block after a successful startup.
+pub fn print(mode: Mode, instance: &Instance, env: &ResolvedEnv) {
+ let key = Style::new().dim();
+ let link = Style::new().cyan();
+ let row = |k: &str, v: String| {
+ // Tint anything that looks like a clickable endpoint.
+ let v =
+ if v.starts_with("http") || v.starts_with("redis://") || v.starts_with("postgres://") {
+ link.apply_to(v).to_string()
+ } else {
+ v
+ };
+ println!(" {}{v}", key.apply_to(format!("{k:<16}")));
+ };
+ println!();
+ println!(
+ "{}",
+ Style::new()
+ .green()
+ .bold()
+ .apply_to(format!("✓ macro {} stack ready", mode.label()))
+ );
+ row("mode", mode.label().to_string());
+ row(
+ "instance",
+ format!("{} (project {})", instance.name(), instance.project_name()),
+ );
+ row(
+ "env source",
+ if mode.spec().overlay_local_env {
+ "code (LocalEnv)".to_string()
+ } else if env.doppler_used {
+ format!("Doppler {}", mode.spec().doppler_config)
+ } else {
+ "--env-file / process env".to_string()
+ },
+ );
+ row(
+ "env file",
+ env.env_file
+ .as_ref()
+ .map(|p| p.display().to_string())
+ .unwrap_or_else(|| "(none)".into()),
+ );
+ row("generated env", env.generated_path.display().to_string());
+ row("frontend", frontend::url(instance));
+
+ if mode.spec().show_infra_in_summary {
+ row("proxy", proxy::url(instance));
+ row(
+ "fusionauth",
+ format!("http://localhost:{}", instance.port(Port::FusionAuth)),
+ );
+ row("mailpit", mailpit::ui_url(instance));
+ row(
+ "localstack",
+ format!("http://localhost:{}", instance.port(Port::LocalStack)),
+ );
+ row(
+ "postgres",
+ format!(
+ "postgres://user:password@localhost:{}/macrodb",
+ instance.port(Port::Postgres)
+ ),
+ );
+ row(
+ "redis",
+ format!("redis://localhost:{}", instance.port(Port::Redis)),
+ );
+ }
+
+ row(
+ "logs",
+ format!("docker compose -p {} logs -f", instance.project_name()),
+ );
+ let stop = if instance.is_default() {
+ "just stop_local".to_string()
+ } else {
+ format!("just stop_local --instance {}", instance.name())
+ };
+ row("stop", stop);
+ println!();
+}
diff --git a/rust/cloud-storage/tools/xtask/src/local/test.rs b/rust/cloud-storage/tools/xtask/src/local/test.rs
new file mode 100644
index 0000000000..99d6812947
--- /dev/null
+++ b/rust/cloud-storage/tools/xtask/src/local/test.rs
@@ -0,0 +1,27 @@
+use super::*;
+
+/// Every mode whose spec we assert invariants over.
+const MODES: &[Mode] = &[Mode::Local, Mode::Dev];
+
+/// Cross-field design rules every [`ModeSpec`] must satisfy. These encode what
+/// makes a mode *coherent* — a new mode that trips one of these is a bug, not a
+/// new policy — so they're the real guard on the table, not a restatement of it.
+#[test]
+fn mode_specs_are_coherent() {
+ for &mode in MODES {
+ let s = mode.spec();
+ // You either own the local plumbing (LocalEnv: dummy creds + localstack
+ // endpoint) or you point at deployed AWS and strip those — never both.
+ assert!(
+ !(s.overlay_local_env && s.uses_remote_aws),
+ "{}: overlay_local_env and uses_remote_aws are mutually exclusive",
+ s.label
+ );
+ // Migrations only make sense against a database this mode runs itself.
+ assert!(
+ !s.migrates_db || s.runs_local_infra,
+ "{}: migrates_db requires runs_local_infra",
+ s.label
+ );
+ }
+}
diff --git a/rust/cloud-storage/tools/xtask/src/local/validate.rs b/rust/cloud-storage/tools/xtask/src/local/validate.rs
new file mode 100644
index 0000000000..ab27c98c55
--- /dev/null
+++ b/rust/cloud-storage/tools/xtask/src/local/validate.rs
@@ -0,0 +1,196 @@
+//! `validate-local-compose` and `validate-local-env`.
+//!
+//! These are the durable guards behind the spec's hard invariants: no Rust
+//! service builds in Docker for the local path, and local mode never requires
+//! Pulumi / real AWS / real SES.
+
+use anyhow::{bail, Context, Result};
+use serde_json::Value;
+
+use super::build::{BinariesDir, RUNTIME_IMAGE_TAG};
+use super::inventory::services_for_mode;
+use super::{arch, env_layer, gen_compose, instance::Instance, workspace_root, Mode};
+
+/// Required non-Rust services that must be present in the rendered local
+/// compose.
+const REQUIRED_NON_RUST: &[&str] = &["postgres", "redis", "fusionauth", "localstack", "mailpit"];
+
+/// Render the merged compose config and assert every Rust service is a
+/// runtime-image container with no `build:` and an `/app/out` mount, and that
+/// the required non-Rust services exist.
+pub fn local_compose(instance: &Instance, mode: Mode) -> Result<()> {
+ // Generate the override against the expected (possibly not-yet-built)
+ // target dir — config rendering does not need the binaries to exist.
+ let target = arch::detect()?;
+ let binaries = BinariesDir::TargetDir(workspace_root().join(target.debug_dir()));
+ gen_compose::generate(mode, instance, &binaries)?;
+ let resolved = env_layer::resolve(mode, instance, true, None)?;
+
+ let files = gen_compose::compose_files(instance);
+ let mut cmd = gen_compose::docker_compose(instance, &files, &resolved.generated_path);
+ cmd.args(["config", "--format", "json"]);
+ let out = cmd.output().context("running `docker compose config`")?;
+ if !out.status.success() {
+ bail!(
+ "`docker compose config` failed:\n{}",
+ String::from_utf8_lossy(&out.stderr)
+ );
+ }
+ let cfg: Value = serde_json::from_slice(&out.stdout).context("parsing compose config json")?;
+ let services = cfg.get("services").and_then(Value::as_object);
+ let Some(services) = services else {
+ bail!("rendered compose has no services");
+ };
+
+ let mut failures: Vec<String> = Vec::new();
+ for svc in services_for_mode(mode) {
+ let Some(node) = services.get(svc.compose_name) else {
+ failures.push(format!(
+ "Rust service '{}' is missing from the rendered compose",
+ svc.compose_name
+ ));
+ continue;
+ };
+ if node.get("build").map(|b| !b.is_null()).unwrap_or(false) {
+ failures.push(format!(
+ "'{}' still has a build: stanza — the local path must mount prebuilt binaries, not build in Docker",
+ svc.compose_name
+ ));
+ }
+ match node.get("image").and_then(Value::as_str) {
+ Some(img) if img == RUNTIME_IMAGE_TAG => {}
+ other => failures.push(format!(
+ "'{}' image is {:?}, expected {RUNTIME_IMAGE_TAG}",
+ svc.compose_name, other
+ )),
+ }
+ if !has_app_out_mount(node) {
+ failures.push(format!(
+ "'{}' is missing the /app/out bind mount",
+ svc.compose_name
+ ));
+ }
+ }
+ for required in REQUIRED_NON_RUST {
+ if !services.contains_key(*required) {
+ failures.push(format!("required non-Rust service '{required}' is absent"));
+ }
+ }
+
+ if !failures.is_empty() {
+ bail!(
+ "validate-local-compose failed:\n - {}",
+ failures.join("\n - ")
+ );
+ }
+ println!(
+ "validate-local-compose: OK ({} Rust services)",
+ services_for_mode(mode).count()
+ );
+ Ok(())
+}
+
+fn has_app_out_mount(service: &Value) -> bool {
+ let Some(volumes) = service.get("volumes").and_then(Value::as_array) else {
+ return false;
+ };
+ volumes.iter().any(|v| match v {
+ // Normalized form: { type, source, target, ... }.
+ Value::Object(map) => map.get("target").and_then(Value::as_str) == Some("/app/out"),
+ // Short form: "src:/app/out:ro".
+ Value::String(s) => s.split(':').nth(1) == Some("/app/out"),
+ _ => false,
+ })
+}
+
+/// Resolve the env layers and assert mode-appropriate invariants.
+pub fn local_env(
+ instance: &Instance,
+ mode: Mode,
+ no_doppler: bool,
+ env_file: Option<&std::path::Path>,
+) -> Result<()> {
+ let resolved = env_layer::resolve(mode, instance, no_doppler, env_file)?;
+ let env = &resolved.merged;
+ let mut failures: Vec<String> = Vec::new();
+
+ let require = |failures: &mut Vec<String>, key: &str| {
+ if !env.contains_key(key) {
+ failures.push(format!("missing required env '{key}'"));
+ }
+ };
+
+ match mode {
+ Mode::Local => {
+ for key in [
+ "DATABASE_URL",
+ "REDIS_URI",
+ "LOCAL_AWS_URL",
+ "FUSIONAUTH_BASE_URL",
+ "FUSIONAUTH_CLIENT_ID",
+ "JWT_SECRET_KEY",
+ "DOCUMENT_STORAGE_BUCKET",
+ ] {
+ require(&mut failures, key);
+ }
+ // No real AWS creds locally.
+ if env.get("AWS_ACCESS_KEY_ID").map(String::as_str) != Some("test") {
+ failures.push(
+ "AWS_ACCESS_KEY_ID is not the local dummy 'test' — refusing real AWS creds locally".into(),
+ );
+ }
+ // Endpoints must be local docker hosts.
+ for (key, host) in [
+ ("FUSIONAUTH_BASE_URL", "fusionauth"),
+ ("LOCAL_AWS_URL", "localstack"),
+ ("DATABASE_URL", "postgres"),
+ ("REDIS_URI", "redis"),
+ ] {
+ if let Some(v) = env.get(key) {
+ if !v.contains(host) && !v.contains("localhost") {
+ failures.push(format!(
+ "{key}={v} is not a local endpoint (expected host '{host}')"
+ ));
+ }
+ }
+ }
+ }
+ Mode::Dev => {
+ // run-dev runs as macro_env `local` *on purpose*: dev_personal ships
+ // real values, not Secrets-Manager names, so a `dev`/`develop`
+ // macro_env would make services try to fetch each value as a secret.
+ // Its "dev-ness" comes from the values (dev DB, real AWS), not this.
+ if env.get("ENVIRONMENT").map(String::as_str) != Some("local") {
+ failures.push(
+ "run-dev resolves ENVIRONMENT=local (dev values, local macro_env)".into(),
+ );
+ }
+ if env.get("LOCAL_AWS_URL").is_some() {
+ failures.push(
+ "run-dev must not set LOCAL_AWS_URL (would point SES/S3 at LocalStack)".into(),
+ );
+ }
+ match env.get("DATABASE_URL") {
+ None => failures.push("run-dev requires a dev DATABASE_URL (none found)".into()),
+ Some(v) if v.contains("@postgres:") || v.contains("localhost") => {
+ failures.push(format!("run-dev DATABASE_URL={v} points at local infra; expected a shared-dev host"));
+ }
+ Some(_) => {}
+ }
+ }
+ }
+
+ if !failures.is_empty() {
+ bail!(
+ "validate-local-env ({}) failed:\n - {}",
+ mode.label(),
+ failures.join("\n - ")
+ );
+ }
+ println!(
+ "validate-local-env ({}): OK — {}",
+ mode.label(),
+ env_layer::summarize(env)
+ );
+ Ok(())
+}
diff --git a/rust/cloud-storage/tools/xtask/src/main.rs b/rust/cloud-storage/tools/xtask/src/main.rs
index 86da062717..11adf13d25 100644
--- a/rust/cloud-storage/tools/xtask/src/main.rs
+++ b/rust/cloud-storage/tools/xtask/src/main.rs
@@ -19,6 +19,7 @@ mod closures;
mod doppler_bins;
mod graphql_soup_schema;
mod hakari_ops;
+mod local;
mod nextest_filter;
mod workflows;
@@ -44,12 +45,19 @@ fn main() -> Result<()> {
["graphql-soup-schema", output_path] => graphql_soup_schema::run(Path::new(output_path)),
["workflows"] => workflows::generate(),
["workflows", "--check"] => workflows::check(),
- _ => bail!(
- "usage (from rust/cloud-storage):\n cargo x deps [--check]\n cargo x nextest-filter <changed-files-path>\n cargo x doppler-bins <changed-files-path>\n cargo x graphql-soup-schema <output-path>\n cargo x workflows [--check]"
- ),
+ // Everything else is the local/dev orchestration surface. It has many
+ // subcommands each with several flags, so it uses a real (clap) parser
+ // rather than fixed-arity slice patterns. Unknown input falls through
+ // to a combined usage message inside `local::cli::dispatch`.
+ _ => local::cli::dispatch(&args, LEGACY_USAGE),
}
}
+/// Usage for the repo-automation verbs handled by the slice match above. The
+/// local orchestration parser appends its own usage and prints both on an
+/// unrecognized command.
+const LEGACY_USAGE: &str = "repo automation (from rust/cloud-storage):\n cargo x deps [--check]\n cargo x nextest-filter <changed-files-path>\n cargo x doppler-bins <changed-files-path>\n cargo x graphql-soup-schema <output-path>\n cargo x workflows [--check]";
+
fn run_deps(check: bool) -> Result<()> {
let graph = build_graph(check)?;
diff --git a/rust/cloud-storage/workspace-hack/Cargo.toml b/rust/cloud-storage/workspace-hack/Cargo.toml
index 2e9758b5ff..3947421dc0 100644
--- a/rust/cloud-storage/workspace-hack/Cargo.toml
+++ b/rust/cloud-storage/workspace-hack/Cargo.toml
@@ -68,6 +68,7 @@ hyper-582f2526e08bb6a0 = { package = "hyper", version = "0.14", default-features
hyper-dff4ba8e3ae991db = { package = "hyper", version = "1", features = ["client", "http1", "http2", "server"] }
hyper-rustls-adf3d7031871b0af = { package = "hyper-rustls", version = "0.24", default-features = false, features = ["acceptor", "http1", "http2", "logging", "tls12", "webpki-tokio"] }
hyper-util = { version = "0.1", features = ["client-legacy", "client-proxy", "http1", "http2", "server", "service"] }
+idna = { version = "1" }
indexmap = { version = "2", features = ["serde"] }
lazy_static = { version = "1", default-features = false, features = ["spin_no_std"] }
libc = { version = "0.2", features = ["extra_traits"] }
@@ -93,7 +94,7 @@ rig-core = { git = "https://github.com/macro-inc/rig", branch = "feat/responses-
rmcp = { version = "1", features = ["auth", "client", "transport-streamable-http-client-reqwest", "transport-streamable-http-server"] }
rsa = { version = "0.9", features = ["getrandom", "sha1"] }
rustc-hash = { version = "2" }
-rustls-2b5c6dc72f624058 = { package = "rustls", version = "0.23", default-features = false, features = ["prefer-post-quantum", "ring", "std", "tls12"] }
+rustls-2b5c6dc72f624058 = { package = "rustls", version = "0.23", default-features = false, features = ["logging", "prefer-post-quantum", "ring", "std", "tls12"] }
rustls-647d43efb71741da = { package = "rustls", version = "0.21" }
rustls-webpki = { version = "0.103", default-features = false, features = ["aws-lc-rs", "ring", "std"] }
schemars = { version = "1", features = ["chrono04", "uuid1"] }
@@ -116,7 +117,7 @@ subtle = { version = "2" }
sync_wrapper = { version = "1", default-features = false, features = ["futures"] }
time = { version = "0.3", features = ["formatting", "macros", "parsing"] }
tokio = { version = "1", features = ["fs", "io-util", "macros", "net", "parking_lot", "process", "rt-multi-thread", "signal", "test-util"] }
-tokio-rustls = { version = "0.26", default-features = false, features = ["tls12"] }
+tokio-rustls = { version = "0.26", default-features = false, features = ["logging", "tls12"] }
tokio-stream = { version = "0.1", features = ["fs"] }
tokio-util = { version = "0.7", features = ["codec", "compat", "io"] }
tower = { version = "0.5", default-features = false, features = ["balance", "buffer", "limit", "load-shed", "log"] }
@@ -185,6 +186,7 @@ hyper-582f2526e08bb6a0 = { package = "hyper", version = "0.14", default-features
hyper-dff4ba8e3ae991db = { package = "hyper", version = "1", features = ["client", "http1", "http2", "server"] }
hyper-rustls-adf3d7031871b0af = { package = "hyper-rustls", version = "0.24", default-features = false, features = ["acceptor", "http1", "http2", "logging", "tls12", "webpki-tokio"] }
hyper-util = { version = "0.1", features = ["client-legacy", "client-proxy", "http1", "http2", "server", "service"] }
+idna = { version = "1" }
indexmap = { version = "2", features = ["serde"] }
lazy_static = { version = "1", default-features = false, features = ["spin_no_std"] }
libc = { version = "0.2", features = ["extra_traits"] }
@@ -213,7 +215,7 @@ rig-core = { git = "https://github.com/macro-inc/rig", branch = "feat/responses-
rmcp = { version = "1", features = ["auth", "client", "transport-streamable-http-client-reqwest", "transport-streamable-http-server"] }
rsa = { version = "0.9", features = ["getrandom", "sha1"] }
rustc-hash = { version = "2" }
-rustls-2b5c6dc72f624058 = { package = "rustls", version = "0.23", default-features = false, features = ["prefer-post-quantum", "ring", "std", "tls12"] }
+rustls-2b5c6dc72f624058 = { package = "rustls", version = "0.23", default-features = false, features = ["logging", "prefer-post-quantum", "ring", "std", "tls12"] }
rustls-647d43efb71741da = { package = "rustls", version = "0.21" }
rustls-webpki = { version = "0.103", default-features = false, features = ["aws-lc-rs", "ring", "std"] }
schemars = { version = "1", features = ["chrono04", "uuid1"] }
@@ -238,7 +240,7 @@ syn-f595c2ba2a3f28df = { package = "syn", version = "2", features = ["extra-trai
sync_wrapper = { version = "1", default-features = false, features = ["futures"] }
time = { version = "0.3", features = ["formatting", "macros", "parsing"] }
tokio = { version = "1", features = ["fs", "io-util", "macros", "net", "parking_lot", "process", "rt-multi-thread", "signal", "test-util"] }
-tokio-rustls = { version = "0.26", default-features = false, features = ["tls12"] }
+tokio-rustls = { version = "0.26", default-features = false, features = ["logging", "tls12"] }
tokio-stream = { version = "0.1", features = ["fs"] }
tokio-util = { version = "0.7", features = ["codec", "compat", "io"] }
tower = { version = "0.5", default-features = false, features = ["balance", "buffer", "limit", "load-shed", "log"] }
diff --git a/rust/rust-toolchain.toml b/rust/rust-toolchain.toml
index 50b1500173..0fb4ad2dc1 100644
--- a/rust/rust-toolchain.toml
+++ b/rust/rust-toolchain.toml
@@ -1,4 +1,12 @@
[toolchain]
channel = "1.94.0"
components = ["clippy", "rustfmt", "rust-analyzer", "rust-src"]
-targets = ["wasm32-unknown-unknown"]
+# The linux-gnu targets are required by `cargo x zigbuild` (the local
+# orchestrator cross-compiles service binaries for the runtime image). They
+# don't affect the fenix channel-manifest hash in nix/cloud-storage.nix (targets
+# are selected after the manifest is fetched), so adding one needs no hash bump.
+targets = [
+ "wasm32-unknown-unknown",
+ "aarch64-unknown-linux-gnu",
+ "x86_64-unknown-linux-gnu",
+]
diff --git a/rust/sync-service/src/durable_object.rs b/rust/sync-service/src/durable_object.rs
index c68546ecc4..619ca86540 100644
--- a/rust/sync-service/src/durable_object.rs
+++ b/rust/sync-service/src/durable_object.rs
@@ -1008,15 +1008,6 @@ pub struct PeerResponse {
pub static ALLOWED_ORIGINS: &[&str] = &[
"http://localhost:5173",
"http://localhost:3000",
- "http://localhost:3001",
- "http://localhost:3002",
- "http://localhost:3003",
- "http://localhost:3004",
- "http://localhost:3005",
- "http://localhost:3006",
- "http://localhost:3007",
- "http://localhost:3008",
- "http://localhost:3009",
"http://host.local:3000",
"https://dev.macro.com",
"https://staging.macro.com",
@@ -1030,6 +1021,11 @@ pub fn is_origin_allowed(origin: &str) -> bool {
if ALLOWED_ORIGINS.contains(&origin) {
return true;
}
+ if let Some(port) = origin.strip_prefix("http://localhost:")
+ && let Ok(port) = port.parse::<u16>()
+ {
+ return (3000..=3999).contains(&port) || (20000..=60000).contains(&port);
+ }
// Allow feature branch previews: https://{subdomain}.preview.macro.com
if let Some(host) = origin.strip_prefix("https://")
&& let Some(subdomain) = host.strip_suffix(".preview.macro.com")
diff --git a/rust/sync-service/tests/cors.test.ts b/rust/sync-service/tests/cors.test.ts
index 21c3aff068..db6c3c650d 100644
--- a/rust/sync-service/tests/cors.test.ts
+++ b/rust/sync-service/tests/cors.test.ts
@@ -13,15 +13,9 @@ describe('CORS middleware tests', async () => {
const allowedOrigins = [
'http://localhost:5173',
'http://localhost:3000',
- 'http://localhost:3001',
- 'http://localhost:3002',
- 'http://localhost:3003',
- 'http://localhost:3004',
- 'http://localhost:3005',
- 'http://localhost:3006',
- 'http://localhost:3007',
- 'http://localhost:3008',
- 'http://localhost:3009',
+ 'http://localhost:3999',
+ 'http://localhost:20010',
+ 'http://localhost:60000',
'http://host.local:3000',
'https://dev.macro.com',
'https://staging.macro.com',