From 9d9477193f1ce43f8b3e2cb5f6d69122566d8976 Mon Sep 17 00:00:00 2001 From: Raphael Amorim Date: Wed, 2 Dec 2026 22:10:42 +0000 Subject: [PATCH 1/3] Oj store: shared build cache across worktrees, with a wire A shared per-user content store (`$OJ_STORE_DIR`, which `oj dev --store` sets to a DIR or the user's cache dir; off otherwise) for the cache entries whose keys and artifacts are worktree-independent, so a second worktree of an app, a second app on the same dependencies or a fresh sandbox starts warm: the persistent module cache, back under `oj dev --store` after #669 removed it with nothing to turn it on, the V8 code cache, Start codegen and the Start client bundle. `oj store serve` is an HTTP substituter dev servers read through and push to. Entries are path-free: the compiler names an in-root module by its served path, metadata and `?importer=` params encode root- or workspace-relative, files outside the root but in the workspace serve at `/@fs/@mono/`, and Start's dev asset URLs are `/@oj-start/fs/@ws/`. A module's key covers the dependency epoch, the config graph, tsconfig, the resolver settings, the defines, the JSX runtime and the asset URL settings. A cached module records the side files a plugin read (node:fs interposition and a TracingFs under the engine's fs ops) and its `import.meta.glob` listings, re-verified on a hit. An entry is served only under the HMR import stamps it baked in; a stamped compile is never persisted, nor is an app module where a plugin collects state from transforms (UnoCSS, by name). A read from the shared directory refuses an entry that still names a checkout; a file outside the root but in the workspace is named by its `/@fs/@mono/` url in its debug info. The wire's write-once links a per-request temp file into place, and a substituter that does not answer is given up on for the session. Dep URL versions are content-derived through a write-once ledger salted with its epoch, so worktrees and restarts over the same bytes mint the same URLs, and other bytes under a served URL move every URL and reload. The Start bundle store keeps generations and blobs in the shared directory with per-root pointers and pins, keys closures and the inputs outside them root-relative, probes recent generations for a cold worktree, and carries a generation's StyleX rules and generated-sheet mark as attachments. Tests cover the store under abuse: racing writers of one key, torn and poisoned entries, racing bundle persists and a restore against another root's eviction, racing ledger records, a read-only or deleted store under a live server, two servers on one store, a config edit between sessions, and an e2e with two `oj dev --store` processes where one is killed mid-burst. --- .github/workflows/ci.yml | 10 + CHANGELOG.md | 16 + Cargo.lock | 1 + README.md | 23 +- crates/oj/src/main.rs | 167 ++- crates/oj/src/ssr_dev.rs | 1 + crates/oj/src/start_bundle/assets.rs | 6 +- crates/oj/src/start_bundle/dev.rs | 9 +- crates/oj/src/start_bundle/tests.rs | 15 +- crates/oj/src/start_dev.rs | 135 ++- crates/oj/src/start_host.rs | 52 +- crates/oj/src/stylex_plugin.rs | 202 +++- crates/oj_cache/src/lib.rs | 1055 ++++++++++++++++- crates/oj_cache/src/start_bundle/memo.rs | 46 +- crates/oj_cache/src/start_bundle/mod.rs | 456 ++++++- crates/oj_cache/src/start_bundle/persist.rs | 70 +- crates/oj_cache/src/start_bundle/prune.rs | 86 +- crates/oj_cache/src/start_bundle/tests.rs | 721 ++++++++++- crates/oj_cache/src/start_codegen.rs | 249 +++- crates/oj_cache/src/store.rs | 173 +++ crates/oj_compiler/src/compile.rs | 24 +- crates/oj_compiler/tests/path_independence.rs | 151 +++ crates/oj_env/src/knobs.rs | 61 + crates/oj_js/Cargo.toml | 1 + crates/oj_js/src/code_cache.rs | 417 ++++++- crates/oj_js/src/lib.rs | 6 + crates/oj_js/src/tracing_fs.rs | 510 ++++++++ crates/oj_js/src/worker.rs | 25 +- crates/oj_server/Cargo.toml | 2 +- crates/oj_server/src/assets/plugin-host.mjs | 97 +- crates/oj_server/src/crawl.rs | 2 +- crates/oj_server/src/css_engine.rs | 12 +- crates/oj_server/src/lib.rs | 280 ++++- crates/oj_server/src/module_pipeline.rs | 378 +++++- crates/oj_server/src/optimize.rs | 394 +++++- crates/oj_server/src/plugin_routes.rs | 2 +- crates/oj_server/src/plugins/extract.rs | 29 +- crates/oj_server/src/plugins/host.rs | 74 +- crates/oj_server/src/plugins/static_config.rs | 2 +- crates/oj_server/src/rewrite.rs | 121 +- crates/oj_server/src/serve.rs | 9 +- crates/oj_server/src/store_remote.rs | 310 +++++ crates/oj_server/src/store_server.rs | 567 +++++++++ crates/oj_server/src/style_file.rs | 25 +- crates/oj_server/src/tests.rs | 590 +++++++++ crates/oj_server/src/watch.rs | 11 +- crates/oj_server/tests/dev/determinism.rs | 536 +++++++++ .../tests/dev/hmr_stamp_persistent.rs | 342 ++++++ crates/oj_server/tests/dev/main.rs | 21 +- crates/oj_server/tests/dev/optimize_plan.rs | 53 +- crates/oj_server/tests/dev/store.rs | 792 +++++++++++++ crates/oj_server/tests/dev/stylex.rs | 125 ++ .../tests/dev/warm_transform_virtual.rs | 155 +++ crates/oj_stylex/src/options.rs | 41 +- crates/oj_stylex/src/plugin.rs | 72 +- e2e/cross-worktree-cache.mjs | 184 +++ e2e/start-css-modules.mjs | 20 +- e2e/store-concurrent.mjs | 169 +++ e2e/store-flag.mjs | 116 ++ e2e/store-remote.mjs | 203 ++++ e2e/trace-staleness.mjs | 163 +++ 61 files changed, 10148 insertions(+), 437 deletions(-) create mode 100644 crates/oj_cache/src/store.rs create mode 100644 crates/oj_compiler/tests/path_independence.rs create mode 100644 crates/oj_js/src/tracing_fs.rs create mode 100644 crates/oj_server/src/store_remote.rs create mode 100644 crates/oj_server/src/store_server.rs create mode 100644 crates/oj_server/tests/dev/determinism.rs create mode 100644 crates/oj_server/tests/dev/hmr_stamp_persistent.rs create mode 100644 crates/oj_server/tests/dev/store.rs create mode 100644 crates/oj_server/tests/dev/warm_transform_virtual.rs create mode 100644 e2e/cross-worktree-cache.mjs create mode 100644 e2e/store-concurrent.mjs create mode 100644 e2e/store-flag.mjs create mode 100644 e2e/store-remote.mjs create mode 100644 e2e/trace-staleness.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5569ff91f..06e08ba6c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -152,6 +152,16 @@ jobs: run: node e2e/run.mjs - name: wasm playground (editor, preview, error strip) run: node e2e/wasm-playground.mjs + - name: cross-worktree shared module store + run: node e2e/cross-worktree-cache.mjs + - name: oj store flag + run: node e2e/store-flag.mjs + - name: two servers on one store, one killed mid-burst + run: node e2e/store-concurrent.mjs + - name: constructive trace staleness + run: node e2e/trace-staleness.mjs + - name: remote store wire + run: node e2e/store-remote.mjs - name: warm-cache plugin side effects run: node e2e/warm-cache.mjs - name: ssr dev + hydration diff --git a/CHANGELOG.md b/CHANGELOG.md index ccafe60de..f0c22bdc5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,9 +7,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- The oj store: a shared per-user content store (`OJ_STORE_DIR`, versioned `v1`) for cache entries whose keys and artifacts are worktree-independent, so a second worktree of an app, or a second app on the same dependencies, starts warm. It is off unless `OJ_STORE_DIR` is set, which `oj dev --store` does for itself and every child process, to the given DIR or to `$XDG_CACHE_HOME/oj/store` (else `~/.cache/oj/store`); a plain `oj dev` writes nothing outside the tree. It holds the V8 code cache, relocatable module-cache entries, Start codegen entries and Start client-bundle generations. +- `oj dev --store[=DIR]`: the one switch for the oj store. It turns the store on (and, given a DIR, says where) and the persistent module cache with it, which 0.4.x removed with `--enable-cache`. A plugin that collects state from every module's transform and serves it from a virtual (UnoCSS, WindiCSS, by name) keeps app modules out of the persistent cache: they compile each session, dependencies still serve from the store. The persistent cache is the dev server's memory cache written through to disk: entries whose stored form is worktree-independent go to the store's `modules/` directory, entries that still pin a checkout (absolute `/@fs/` imports, absolute metadata) stay in the app's own cache, and an entry is served only under the HMR import stamps it baked in, as the memory cache serves one. Its key covers everything that shapes compiled output: the dependency epoch (lockfiles, patches, package.json), the config graph (vite/oj config plus every file it imports), tsconfig.json, the resolver settings with alias targets hashed root- or workspace-relative, the defines, the JSX runtime and the asset URL settings. A config, lockfile, tsconfig or resolver edit is a clean miss instead of a possible stale hit. +- `oj store serve --dir DIR --port N` serves a store directory as an HTTP substituter (`GET/PUT /v1/ac/{ns}/{key}` write-once with 409 on conflict, `GET/HEAD/PUT /v1/cas/{blake3}` checked against the digest, `POST /v1/cas/missing`), with split bearer tokens: `OJ_STORE_READ_TOKEN` (unset = public reads) and `OJ_STORE_WRITE_TOKEN` (unset = writes refused). Dev servers read through it with `OJ_STORE_REMOTE=` (+ `OJ_STORE_TOKEN`): local store first, remote on a miss with a local back-fill, and a fetched entry passes the same admission checks as a local hit (relocatability, import stamps, plugin virtuals, trace verification). `OJ_STORE_PUSH=1` pushes relocatable entries from a dedicated queue thread, never blocking compiles on the network. A substituter that does not answer (a 2 s connect, a 5 s fetch) three times in a row is not asked again for the session. +- Constructive traces: a cached module records every side file a plugin `transform` read, with a blake3 digest, and a warm hit re-verifies them; any mismatch is a clean miss instead of a stale serve. Reads are seen by the plugin host's `node:fs` interposition (per hook, through AsyncLocalStorage) and by TracingFs, a recorder under the engine's fs ops layer that also catches named `node:fs` imports. `import.meta.glob` expansions are traced too. `OJ_VERIFY_HITS=<0..1>` recompiles that share of persistent hits and logs any divergence. + ### Changed - The goldens and the TanStack Start fixture (`e2e/fixtures/start-app`) are recorded from Vite 8.4.0, the release, in place of 8.4.0-beta.1; rolldown stays 1.3.2, the crate oj builds with (8.4.0 declares `~1.3.2`; 8.4.1 declares `~1.3.4`, whose Rust crates are not published, and its build import analysis hands rolldown a field 1.3.2 rejects). Recorded from `/tmp`, so a recording carries no path depth of the machine it was made on. +- Compiled modules are path-free: the compiler names an in-root module by its served path (`/src/App.tsx`) in the jsx dev `__source` and the sourcemap `sources` entry, so the bytes are identical in every worktree. `fs_allow`/`watch_files` metadata and `/@id/...?importer=` params encode `ws:`/`mono:`-relative and decode against the serving worktree. Sourcemaps from earlier transforms (StyleX, plugins) name in-root files by served path too. +- Files outside the app root but inside the workspace (hoisted node_modules, monorepo packages) are served at `/@fs/@mono/`, which each server resolves against its own workspace root, so cached artifacts that import them share across worktrees. +- The V8 code cache keys modules by their root-relative identity instead of the absolute `file://` URL and lives in the shared store, so worktrees of one app share every entry and `node_modules` bytecode is shared across apps with the same layout. Old per-app `code-cache` directories can be deleted. +- The Start client-bundle store is shared across worktrees (bundle format 6, rebuilt once): closure keys, the stored closure, the inputs outside the closure (the route trees, the config and its imports) and the bundle's `import.meta.glob` patterns are root-relative, and dev asset URLs are `/@oj-start/fs/@ws/`, resolved against the serving root. A generation whose globs reach outside the root stays keyed to the root that built it. `current` and the memo stay per root; each root mirrors its `current` into `pins/`, and eviction never removes a generation (or its blobs) a fresh pin protects; pins unrefreshed for 7 days stop protecting. A worktree with no `current` probes the most recently used shared generations, so the first `oj dev` in a new worktree restores the bundle another one built. A generation's StyleX rules and its plugin-served-stylesheet mark travel with it as attachments. +- Start codegen entries (route tree, server fns) live in the shared store; the mtime memo stays per root. +- StyleX apps share across worktrees too: the plugin's fingerprint, which keys every compiled module, hashes its options with paths under the app root spelled root-relative (the default `rootDir` is the app root). +- The deps prebundle key hashes `resolve.alias` targets root- or workspace-relative, so one vite.config in two worktrees yields one prebundle key. +- Dep URL versions are content-derived instead of per session. Each `/@oj-deps/` URL is recorded write-once with its file's content hash in a ledger (in the oj store, else the app's cache), and versions are salted with the ledger's epoch instead of a per-process timestamp. Restarts and worktrees that bundle the same bytes mint the same URLs, so modules compiled against them are shared. Other bytes under a URL an earlier session served move every URL to a version of the new bytes and reload the page, so an `immutable` URL never names two bundles. Wiping the ledger starts a new epoch, which moves every URL. +- The dev server records the config's imported files per config file instead of in one process-wide slot, so two apps in one process never hash or watch each other's config imports. ### Fixed diff --git a/Cargo.lock b/Cargo.lock index 4e4249e4a..9126778ff 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6623,6 +6623,7 @@ dependencies = [ name = "oj_js" version = "0.5.3" dependencies = [ + "async-trait", "deno_config", "deno_core", "deno_error", diff --git a/README.md b/README.md index 2b60cad8b..e2f3bec95 100644 --- a/README.md +++ b/README.md @@ -120,6 +120,26 @@ oj lint --fix src # oxlint's own flags pass through oxlint comes from the project (`node_modules/.bin/oxlint`, from the current directory up; `OJ_OXLINT_PATH` names another). A project that runs oxlint itself can point it at oj instead: `OXLINT_TSGOLINT_PATH=$(which oj) oxlint --type-aware`. +## The oj store + +`oj dev --store` keeps what a dev server builds in a per-user store, so a second worktree of the app, a second app on the same dependencies or a fresh sandbox starts warm instead of compiling what already exists on the machine. The idea, and why a per-user content-addressed store is the right shape for ephemeral sandboxes and agents, is in [JavaScript tooling for a world of ephemeral sandboxes](https://rapha.land/javascript-tooling-for-a-world-of-ephemeral-sandboxes/). + +```sh +oj dev --store # the store at $XDG_CACHE_HOME/oj/store (else ~/.cache/oj/store) +oj dev --store=/srv/oj-store # a directory of your choosing (also OJ_STORE_DIR) +oj store serve --dir /srv/oj-store --port 5399 # an HTTP substituter over a store +OJ_STORE_REMOTE=http://host:5399 oj dev --store # read through to it; OJ_STORE_PUSH=1 also pushes +``` + +How it works: + +- The store is off unless `OJ_STORE_DIR` is set, which `--store` does for the server and every child process. A plain `oj dev` writes nothing outside the app. +- An entry is named by content, never by path: the module's source and every input that shapes its output (the compile mode and import stamps, the lockfiles, every `tsconfig*.json`, the config file and the files it imports, the PostCSS config, the env it inlines) hashed under a worktree-independent key. Paths inside an artifact are root-relative (`/src/App.tsx`) or workspace-relative (`/@fs/@mono/`), so two checkouts compute the same name and serve the same bytes, sourcemaps included. An artifact that still names a checkout (an import from outside the workspace) stays in that app's own cache. +- A warm hit is verified before it is served: the side files a plugin read while transforming (recorded through `node:fs` and the engine's file system) and the files an `import.meta.glob` expanded to are digested again, and a mismatch, a file that appeared or one that moved is a miss, never a stale serve. Plugins that collect state from every transform (UnoCSS's shape) keep app modules out of the store for the session. +- It holds the compiled module cache, the V8 bytecode cache of the plugin host, the TanStack Start client bundle (a cold worktree restores the generation its sources hash to) and the dependency URL ledger, so two checkouts bundling the same dependency bytes mint the same `/@oj-deps/...?v=` URLs. +- Writes are atomic and write-once: two servers on one store, or two pushers of one key, leave one whole entry and never a torn one. A store that cannot be written costs sharing, not correctness. A corrupt or foreign entry is dropped on read. +- `oj store serve` publishes a store over HTTP with read and write bearer tokens (`OJ_STORE_READ_TOKEN`, `OJ_STORE_WRITE_TOKEN`; a dev server sends `OJ_STORE_TOKEN`). A dev server asks it only on a local miss, with a 2 s connect and 5 s fetch timeout, and stops asking for the session after three failures in a row. + ## Quickstart Install the CLI from crates.io, then run `oj` in any app: @@ -189,6 +209,7 @@ Production builds (`oj build` vs `vite build`) produce the same output on the 10 - [vitejs/vite-plugin-react](https://github.com/vitejs/vite-plugin-react): the Fast Refresh glue semantics oj replicates - [vite/packages/vite/src/node/server](https://github.com/vitejs/vite/tree/main/packages/vite/src/node/server): HMR propagation, `import.meta.hot` protocol - [rolldown/rolldown](https://github.com/rolldown/rolldown): plugin hook filters, the prod linker oj embeds +- [JavaScript tooling for a world of ephemeral sandboxes](https://rapha.land/javascript-tooling-for-a-world-of-ephemeral-sandboxes/): the design brief for the oj store ## Misc @@ -234,4 +255,4 @@ gaps. MIT, see [LICENSE](LICENSE). -OJ was created by [Raphael Amorim](https://rapha.land/introducing-oj/) and has since migrated to [Lovable](https://lovable.dev), which now maintains the project. \ No newline at end of file +OJ was created by [Raphael Amorim](https://rapha.land/introducing-oj/) and has since migrated to [Lovable](https://lovable.dev), which now maintains the project. diff --git a/crates/oj/src/main.rs b/crates/oj/src/main.rs index 6d42f41f5..535d7ad09 100644 --- a/crates/oj/src/main.rs +++ b/crates/oj/src/main.rs @@ -67,6 +67,20 @@ fn debug_with_scopes(debug: Option<&str>, scopes: &str) -> String { names.join(",") } +#[derive(Subcommand)] +enum StoreCommand { + /// Serve DIR as a remote oj store (the six-endpoint substituter). + Serve { + /// Directory holding the served entries (created if missing). + #[arg(long, default_value = "oj-store")] + dir: PathBuf, + #[arg(long, default_value_t = 5399)] + port: u16, + #[arg(long, default_value = "127.0.0.1")] + host: String, + }, +} + #[derive(Subcommand)] enum Command { Dev { @@ -82,6 +96,13 @@ enum Command { /// Vite's `--mode` for the dev server (default `development`). #[arg(long)] mode: Option, + /// Use the oj store: compiled modules persist, and build output (the + /// Start client bundle, codegen, V8 bytecode, dep URLs) is shared across + /// worktrees through the per-user store at `$XDG_CACHE_HOME/oj/store` + /// (else `~/.cache/oj/store`). An optional DIR relocates it (also + /// `OJ_STORE_DIR`, which `--store` exports for every child process). + #[arg(long, value_name = "DIR", num_args = 0..=1, require_equals = true)] + store: Option>, /// Compile modules on demand instead of eagerly crawling the whole graph /// on boot. Opt-in: the eager crawl pre-compiles in parallel and warms /// HMR, which is usually the faster default; --lazy suits apps that @@ -98,6 +119,14 @@ enum Command { #[arg(long)] prod: bool, }, + /// The oj store's wire: serve a store directory over HTTP so worktrees, + /// CI, and sandboxes share one substituter. Reads are public unless + /// OJ_STORE_READ_TOKEN is set; writes require OJ_STORE_WRITE_TOKEN. + #[command(name = "store")] + Store { + #[command(subcommand)] + action: StoreCommand, + }, /// Internal: run an ES module on the embedded JS engine and print its /// default export as JSON. Used by oj's own tests (the napi symbols the /// engine needs are only exported from this binary, so a cargo test @@ -484,6 +513,33 @@ fn sniffed_manager_version(path: &std::path::Path, manager: &str, default_versio } } +/// The store `--store` turns on: its DIR when given, else the `OJ_STORE_DIR` +/// already in the environment (a CI job, a test harness pointing every oj at +/// one store), else the user's cache dir. +fn store_dir_for( + flag: Option<&std::path::Path>, + env: Option, + default: Option, +) -> Option { + let non_empty = |p: PathBuf| (!p.as_os_str().is_empty()).then_some(p); + flag.map(std::path::Path::to_path_buf) + .and_then(non_empty) + .or_else(|| env.and_then(non_empty)) + .or(default) +} + +/// Where `--store` keeps the shared store when neither a DIR nor +/// `OJ_STORE_DIR` says: `$XDG_CACHE_HOME/oj/store`, else +/// `$HOME/.cache/oj/store`. Read before the env snapshot, like the other +/// startup env access in `main`. +fn default_store_dir() -> Option { + let non_empty = |name: &str| std::env::var_os(name).filter(|v| !v.is_empty()); + if let Some(xdg) = non_empty("XDG_CACHE_HOME") { + return Some(PathBuf::from(xdg).join("oj/store")); + } + non_empty("HOME").map(|home| PathBuf::from(home).join(".cache/oj/store")) +} + /// The root when none is named: the current directory, as in Vite /// (`config.root ? path.resolve(config.root) : process.cwd()`). A folder the /// app happens to hold, `playground/` say, is never picked in its place. @@ -578,6 +634,26 @@ fn main() -> anyhow::Result<()> { reap_on_parent_death(); std::env::remove_var(PARENT_PID_ENV); } + // `--store` turns the oj store on for this process and every child (the + // engine, the plugin host, one-shot builders all read OJ_STORE_DIR), so + // the store's dir is exported before the snapshot below: the given DIR, + // else the user's cache dir. + if let Command::Dev { + store: Some(store), .. + } = &cli.command + { + let dir = store_dir_for( + store.as_deref(), + std::env::var_os("OJ_STORE_DIR").map(PathBuf::from), + default_store_dir(), + ); + match dir { + Some(dir) => std::env::set_var("OJ_STORE_DIR", dir), + None => eprintln!( + "oj: --store: no store directory (set OJ_STORE_DIR, XDG_CACHE_HOME or HOME)" + ), + } + } // The startup writes above are oj's only direct process-env access. Snapshot // the env now, still single-threaded: everything after reads `oj_env::get()`. oj_env::init(); @@ -633,6 +709,7 @@ async fn run(cli: Cli, rolldown: tokio::runtime::Handle) -> anyhow::Result<()> { host, config, mode, + store, lazy, typecheck, } => { @@ -648,7 +725,17 @@ async fn run(cli: Cli, rolldown: tokio::runtime::Handle) -> anyhow::Result<()> { if runtime_env.is_some() { eprintln!("oj: OJ_RUNTIME_ENV_KEYS is not applied to a TanStack Start app yet; the keys keep their literals"); } - start_dev::start_dev(root, port, host, config, mode, typecheck, rolldown).await + start_dev::start_dev( + root, + port, + host, + config, + mode, + typecheck, + store.is_some(), + rolldown, + ) + .await } else { oj_server::DevServer { root, @@ -658,6 +745,7 @@ async fn run(cli: Cli, rolldown: tokio::runtime::Handle) -> anyhow::Result<()> { lazy, typecheck, mode, + store: store.is_some(), runtime_env, rolldown, } @@ -721,6 +809,15 @@ async fn run(cli: Cli, rolldown: tokio::runtime::Handle) -> anyhow::Result<()> { .context("engine-job result write")?; Ok(()) } + Command::Store { action } => match action { + StoreCommand::Serve { dir, port, host } => { + if let Err(e) = oj_server::store_server::serve(dir, &host, port).await { + eprintln!("oj store: {e}"); + std::process::exit(1); + } + Ok(()) + } + }, Command::Compile { file, prod } => { let source = std::fs::read_to_string(&file) .with_context(|| format!("cannot read {}", file.display()))?; @@ -930,6 +1027,74 @@ fn resolve_config_arg(root: &std::path::Path, config: Option) -> Option }) } +#[cfg(test)] +mod store_flag_tests { + use super::*; + use clap::Parser; + use std::path::Path; + + fn parse_dev(args: &[&str]) -> (Option>, Option) { + let cli = Cli::try_parse_from(args).expect("parse"); + match cli.command { + Command::Dev { store, root, .. } => (store, root), + _ => panic!("expected dev"), + } + } + + #[test] + fn bare_store_enables_without_eating_the_root() { + let (store, root) = parse_dev(&["oj", "dev", "--store", "app"]); + assert_eq!(store, Some(None), "bare --store carries no dir"); + assert_eq!( + root.as_deref(), + Some(Path::new("app")), + "the positional stays the root" + ); + } + + #[test] + fn store_with_a_dir_requires_equals_and_carries_it() { + let (store, root) = parse_dev(&["oj", "dev", "--store=/shared/oj", "app"]); + assert_eq!(store, Some(Some(PathBuf::from("/shared/oj")))); + assert_eq!(root.as_deref(), Some(Path::new("app"))); + } + + #[test] + fn absent_store_stays_none() { + let (store, _) = parse_dev(&["oj", "dev"]); + assert_eq!(store, None); + } + + #[test] + fn the_store_dir_is_the_flags_then_the_environments_then_the_default() { + let p = |s: &str| Some(PathBuf::from(s)); + let env = p("/env/store"); + let default = p("/home/u/.cache/oj/store"); + assert_eq!( + store_dir_for(Some(Path::new("/flag")), env.clone(), default.clone()), + p("/flag") + ); + assert_eq!( + store_dir_for(None, env.clone(), default.clone()), + p("/env/store"), + "a bare --store keeps the store the environment names" + ); + assert_eq!( + store_dir_for(Some(Path::new("")), env, default.clone()), + p("/env/store") + ); + assert_eq!(store_dir_for(None, p(""), default.clone()), default); + assert_eq!(store_dir_for(None, None, None), None); + } + + #[test] + fn the_old_cache_flags_are_gone() { + for flag in ["--enable-cache", "--no-cache"] { + assert!(Cli::try_parse_from(["oj", "dev", flag]).is_err(), "{flag}"); + } + } +} + #[cfg(test)] mod preview_tests { use super::*; diff --git a/crates/oj/src/ssr_dev.rs b/crates/oj/src/ssr_dev.rs index c276fafc9..2fc4ca3a8 100644 --- a/crates/oj/src/ssr_dev.rs +++ b/crates/oj/src/ssr_dev.rs @@ -41,6 +41,7 @@ pub async fn ssr_dev( lazy: false, typecheck, mode: None, + store: false, runtime_env: None, rolldown, } diff --git a/crates/oj/src/start_bundle/assets.rs b/crates/oj/src/start_bundle/assets.rs index 05be15533..50408a507 100644 --- a/crates/oj/src/start_bundle/assets.rs +++ b/crates/oj/src/start_bundle/assets.rs @@ -2766,7 +2766,7 @@ fn module_order(outputs: &[rolldown_common::Output]) -> HashMap<&str, usize> { /// Where the asset modules point. pub(crate) enum AssetMode { - /// The dev server's files: `/@oj-start/fs/`, workers on the dev + /// The dev server's files (`oj_server::start_dev_file_url`), workers on the dev /// pipeline. `css_urls` collects the linked stylesheets. Dev { css_urls: Arc>, @@ -2785,8 +2785,6 @@ pub(crate) enum AssetMode { }, } -pub(crate) const DEV_FS_BASE: &str = "/@oj-start/fs"; - /// The client's numeric `build.assetsInlineLimit` (its environment's own /// first; Vite's default 4096), the limit Vite's `shouldInline` reads. pub(crate) fn client_inline_limit(config: &oj_config::OjConfig) -> u64 { @@ -2944,7 +2942,7 @@ impl StartAssetsPlugin { async fn url_for(&self, path: &Path) -> Result { match &self.mode { AssetMode::Dev { url_base, .. } => { - Ok(format!("{url_base}{DEV_FS_BASE}{}", path.display())) + Ok(oj_server::start_dev_file_url(url_base, &self.root, path)) } AssetMode::Build { emitter, .. } => emitter.emit(path).await, } diff --git a/crates/oj/src/start_bundle/dev.rs b/crates/oj/src/start_bundle/dev.rs index 4a0e8b601..de477c3bd 100644 --- a/crates/oj/src/start_bundle/dev.rs +++ b/crates/oj/src/start_bundle/dev.rs @@ -218,8 +218,13 @@ impl DevBundler { /// `configFileDependencies`, on which Vite restarts), which the store's /// epoch cannot name. pub(crate) fn cache_key_files(&self) -> Vec { - let mut config: Vec = oj_server::plugins::config_dependencies().to_vec(); - config.extend(self.config_file.clone()); + let vite = + oj_server::plugins::vite_config_file(&self.start.root, self.config_file.as_deref()); + let mut config: Vec = vite + .as_deref() + .map(oj_server::plugins::config_dependencies_of) + .unwrap_or_default(); + config.extend(vite); // A cached extraction lists the config itself and sorted, a fresh one // only what it imported, in import order: the same set keys the same. config.sort(); diff --git a/crates/oj/src/start_bundle/tests.rs b/crates/oj/src/start_bundle/tests.rs index f3b2893fb..2ab129ea8 100644 --- a/crates/oj/src/start_bundle/tests.rs +++ b/crates/oj/src/start_bundle/tests.rs @@ -184,10 +184,7 @@ console.log(raw, url, inline, icon, kept, sprite, worker, styles.card); "?raw exports the text:\n{code}" ); assert!( - code.contains(&format!( - "\"/@oj-start/fs{}\"", - src.join("logo.png").display() - )), + code.contains("\"/@oj-start/fs/@ws/src/logo.png\""), "{code}" ); assert!( @@ -202,17 +199,11 @@ console.log(raw, url, inline, icon, kept, sprite, worker, styles.card); "a small svg is inlined in dev, as in the build:\n{code}" ); assert!( - code.contains(&format!( - "\"/@oj-start/fs{}\"", - src.join("icon.svg").display() - )), + code.contains("\"/@oj-start/fs/@ws/src/icon.svg\""), "`?no-inline` keeps the served url:\n{code}" ); assert!( - code.contains(&format!( - "\"/@oj-start/fs{}\"", - src.join("sprite.svg").display() - )), + code.contains("\"/@oj-start/fs/@ws/src/sprite.svg\""), "an svg over the inline limit keeps the served url:\n{code}" ); let rel = src diff --git a/crates/oj/src/start_dev.rs b/crates/oj/src/start_dev.rs index afe2e4568..e4ab33f33 100644 --- a/crates/oj/src/start_dev.rs +++ b/crates/oj/src/start_dev.rs @@ -71,6 +71,8 @@ struct StartState { /// How often a page socket sends [`PING_FRAME`] (`OJ_HMR_PING_MS`); none /// turns the keepalive and the client's watchdog off. hmr_ping: Option, + /// The app root: `/@oj-start/fs/@ws/` asset URLs resolve against it. + root: PathBuf, workspace_root: PathBuf, /// Vite's `publicDir` (`None` when disabled): its files answer ahead of /// the router and the SSR handler, see [`public_file`]. @@ -328,6 +330,7 @@ async fn watcher_covers(timing: &crate::start_reloads::FlushTiming) -> bool { } } +#[allow(clippy::too_many_arguments)] pub async fn start_dev( root: PathBuf, port: Option, @@ -335,6 +338,7 @@ pub async fn start_dev( config: Option, mode: Option, typecheck: bool, + store: bool, rolldown: tokio::runtime::Handle, ) -> anyhow::Result<()> { let root = root @@ -374,6 +378,7 @@ pub async fn start_dev( lazy: false, typecheck, mode: Some(mode.clone()), + store, runtime_env: None, rolldown: rolldown.clone(), }; @@ -762,6 +767,7 @@ pub async fn start_dev( hmr_overlay, csp_nonce, hmr_ping: hmr_ping(oj_env::get().knobs.hmr_ping_ms), + root: root.clone(), workspace_root: workspace_root(&root), public_dir, dev_headers: Arc::clone(&built.dev_headers), @@ -1205,15 +1211,7 @@ fn list_files_under(dir: &Path) -> Vec { } fn workspace_root(app: &Path) -> PathBuf { - let mut best = app.to_path_buf(); - let mut cur = app; - while let Some(parent) = cur.parent() { - if parent.join("node_modules").is_dir() { - best = parent.to_path_buf(); - } - cur = parent; - } - best + oj_cache::store::workspace_root(app) } /// The content type of a served file: the kinds this server serves that @@ -1505,10 +1503,11 @@ fn load_client_glob_importers(cache: &Path) -> Vec<(PathBuf, oj_compiler::glob:: /// the closure check still rebundles for every known input, and the /// bundle-ok flag for every failed one. fn load_glob_calls(file: &Path) -> Vec { - let Some(entries) = std::fs::read_to_string(file) - .ok() - .and_then(|s| serde_json::from_str::>(&s).ok()) - else { + std::fs::read_to_string(file).map_or_else(|_| Vec::new(), |s| parse_glob_calls(&s)) +} + +fn parse_glob_calls(json: &str) -> Vec { + let Ok(entries) = serde_json::from_str::>(json) else { return Vec::new(); }; entries @@ -1636,13 +1635,13 @@ impl KnownFiles { } } -/// The files a stored generation's globs expand to today that its closure -/// could hold: the client bundle leaves the generated route tree and its own -/// directory (`cache`) out of closure.json, so a glob reaching them has not -/// grown, or every restore of such an app would miss. -fn restorable_glob_members(scopes: &Path, cache: &Path) -> Vec { +/// The files a stored generation's globs (its glob-scopes.json) expand to +/// today that its closure could hold: the client bundle leaves the generated +/// route tree and its own directory (`cache`) out of closure.json, so a glob +/// reaching them has not grown, or every restore of such an app would miss. +fn restorable_glob_members(scopes: &str, cache: &Path) -> Vec { let left_out = crate::start_bundle::dev::left_out_of_closure(cache); - load_glob_calls(scopes) + parse_glob_calls(scopes) .iter() .flat_map(oj_compiler::glob::GlobCall::files) .filter(|f| !left_out(f)) @@ -1681,7 +1680,8 @@ fn boot_changes( .client_glob_scopes .read() .unwrap_or_else(std::sync::PoisonError::into_inner); - let added = restorable_glob_members(&cache.join("glob-scopes.json"), cache) + let stored_scopes = std::fs::read_to_string(cache.join("glob-scopes.json")).unwrap_or_default(); + let added = restorable_glob_members(&stored_scopes, cache) .into_iter() .filter(|f| added_to_glob(&scopes, &inputs, f)) .collect(); @@ -1814,11 +1814,7 @@ fn spawn_start_watcher( // module changes and never flip this. let watch_root = root.clone(); let boot_entry = crate::start_host::app_start_entry(&watch_root); - rt.spawn(refresh_worker( - root.clone(), - cache.clone(), - Arc::clone(&state), - )); + rt.spawn(refresh_worker(cache.clone(), Arc::clone(&state))); rt.spawn(rebundle_worker( root, cache, @@ -2208,7 +2204,7 @@ async fn rebundle_worker( let outcome = match bundling.then(|| bundler.bundle(&inputs, false)) { None => ClientRun::Skipped, Some(Ok(true)) => ClientRun::Hot, - Some(Ok(false)) => match pinned_output(&bundler, &r, &c, &m) { + Some(Ok(false)) => match pinned_output(&bundler, &c, &m) { Some(pinned) => ClientRun::Fresh(pinned), None => ClientRun::Failed("the bundle left no output to serve".into()), }, @@ -2577,53 +2573,63 @@ enum ClientRun { /// The output a successful bundle wrote, cached for the next boot. fn pinned_output( bundler: &ClientBundler, - root: &Path, cache: &Path, mode: &str, ) -> Option { if !bundler.cacheable() { return oj_cache::start_bundle::PinnedBundle::from_build_dir(cache); } - match persist_as_built(bundler, &keyed_bundle_store(bundler, root, mode), cache) { + let store = keyed_bundle_store(bundler, bundler.root(), mode); + match persist_as_built(bundler, &store, cache) { Some((key, pinned)) => { - save_stylex_rules(bundler, cache, &key); - save_generated_sheets(bundler, cache, &key); + save_stylex_rules(bundler, &store, &key); + save_generated_sheets(bundler, &store, &key); Some(pinned) } None => oj_cache::start_bundle::PinnedBundle::from_build_dir(cache), } } -/// The StyleX rules of the bundle just cached under `key`, saved beside it -/// so a restore of it serves a complete sheet. /// Marks the bundle cached under `key` as holding a stylesheet a plugin /// serves (UnoCSS's): its CSS comes from what the plugin collects as modules /// transform, which a restored bundle never does, so it is rebuilt instead. +/// Kept with the generation, so a worktree that restores it knows too; the +/// key names one bundle, so the mark never needs taking back. const GENERATED_SHEETS: &str = "client-generated-sheets.json"; -fn save_generated_sheets(bundler: &ClientBundler, cache: &Path, key: &str) { - let file = cache.join(GENERATED_SHEETS); +fn save_generated_sheets( + bundler: &ClientBundler, + store: &oj_cache::start_bundle::StartBundleStore, + key: &str, +) { let generated = bundler .bundle_modules() .iter() .any(|id| crate::start_bundle::host::is_served_stylesheet(id)); if generated { - let _ = std::fs::write(file, serde_json::json!({ "key": key }).to_string()); - } else { - let _ = std::fs::remove_file(file); + store.attach(key, GENERATED_SHEETS, b"{}"); } } -fn has_generated_sheets(cache: &Path, key: &str) -> bool { - std::fs::read(cache.join(GENERATED_SHEETS)) - .ok() - .and_then(|b| serde_json::from_slice::(&b).ok()) - .is_some_and(|v| v["key"] == key) +fn has_generated_sheets(store: &oj_cache::start_bundle::StartBundleStore, key: &str) -> bool { + store.attachment(key, GENERATED_SHEETS).is_some() } -fn save_stylex_rules(bundler: &ClientBundler, cache: &Path, key: &str) { +/// The StyleX rules of the bundle just cached under `key`, kept with its +/// generation so a restore of it (in any worktree) serves a complete sheet. +fn save_stylex_rules( + bundler: &ClientBundler, + store: &oj_cache::start_bundle::StartBundleStore, + key: &str, +) { if let Some(plugin) = bundler.stylex() { - crate::stylex_plugin::save_rules(plugin, cache, key, &bundler.bundle_modules()); + crate::stylex_plugin::save_rules( + plugin, + store, + bundler.root(), + key, + &bundler.bundle_modules(), + ); } } @@ -2700,7 +2706,7 @@ async fn refresh_pause>( /// Brings the client output current after hot updates, once edits pause or /// as soon as a document or a page's reload needs it. -async fn refresh_worker(root: PathBuf, cache: PathBuf, state: Arc) { +async fn refresh_worker(cache: PathBuf, state: Arc) { use std::sync::atomic::Ordering::SeqCst; loop { state.refresh_wake.notified().await; @@ -2716,12 +2722,11 @@ async fn refresh_worker(root: PathBuf, cache: PathBuf, state: Arc) { } let generation = state.bundler.hot.generation(); let started = state.refreshes.fetch_add(1, SeqCst) + 1; - let (r, c, m) = (root.clone(), cache.clone(), state.mode.clone()); + let (c, m) = (cache.clone(), state.mode.clone()); let bundler = Arc::clone(&state.bundler); let pinned = tokio::task::spawn_blocking(move || { bundler.bundle(&[], true)?; - pinned_output(&bundler, &r, &c, &m) - .ok_or_else(|| anyhow::anyhow!("no client chunk index")) + pinned_output(&bundler, &c, &m).ok_or_else(|| anyhow::anyhow!("no client chunk index")) }) .await .map_err(anyhow::Error::from) @@ -2971,7 +2976,10 @@ fn codegen_store( // resolves keys the output; its content does not. if kind == "route-tree" { if let Some(entry) = crate::start_host::app_start_entry(root) { - extra.extend_from_slice(entry.to_string_lossy().as_bytes()); + // Root-relative, so worktrees share the tree. + let rel = oj_cache::store::rel_key(root, &entry) + .unwrap_or_else(|| entry.to_string_lossy().into_owned()); + extra.extend_from_slice(rel.as_bytes()); } extra.push(0); } @@ -3997,12 +4005,13 @@ fn bundle_client_entry_cached( // A restored bundle never ran the StyleX transform: its modules' // rules come from the sidecar saved with it, or it is rebuilt. Ok((stats, _)) - if stylex - .is_some_and(|p| !crate::stylex_plugin::restore_rules(p, cache, &stats.key)) => + if stylex.is_some_and(|p| { + !crate::stylex_plugin::restore_rules(p, &store, root, &stats.key) + }) => { println!(" oj start: client bundle cache miss (no StyleX rules saved for it)") } - Ok((stats, _)) if has_generated_sheets(cache, &stats.key) => println!( + Ok((stats, _)) if has_generated_sheets(&store, &stats.key) => println!( " oj start: client bundle cache miss (a plugin generates a stylesheet from its modules)" ), Ok((stats, pinned)) => { @@ -4026,8 +4035,8 @@ fn bundle_client_entry_cached( if !bundler.cacheable() { println!(" oj start: client bundle not cached (built without the app's plugin host)"); } else if let Some((key, pinned)) = persist_as_built(bundler, &store, cache) { - save_stylex_rules(bundler, cache, &key); - save_generated_sheets(bundler, cache, &key); + save_stylex_rules(bundler, &store, &key); + save_generated_sheets(bundler, &store, &key); println!( " oj start: client bundle cached (key {}…, {} chunks)", key.get(..8).unwrap_or(&key), @@ -5584,7 +5593,13 @@ fn css_response(body: Result) -> Response { async fn serve_fs_asset(state: &StartState, abs: &str) -> Response { let decoded = percent_decode(abs); - let path = PathBuf::from(&decoded); + // `@ws/` is the worktree-independent form the bundle emits for + // in-root assets: resolve it against THIS server's root, so a restored + // bundle can never point into another checkout. + let path = match decoded.strip_prefix("/@ws/") { + Some(rel) => state.root.join(rel), + None => PathBuf::from(&decoded), + }; let canon = match tokio::fs::canonicalize(&path).await { Ok(c) => c, Err(e) => return (StatusCode::NOT_FOUND, format!("oj start: asset: {e}")).into_response(), @@ -7564,14 +7579,9 @@ mod tests { file("src/.oj/start/manifest.ts"); let kept = file("src/routeTree.generated.ts"); let cache = app.join("src/.oj/start"); - let scopes = app.join("glob-scopes.json"); let a = app.to_string_lossy().replace('\\', "/"); - std::fs::write( - &scopes, - serde_json::json!([{"patterns": [format!("{a}/src/**/*.ts")], "exhaustive": true, "caseSensitive": true}]) - .to_string(), - ) - .unwrap(); + let scopes = serde_json::json!([{"patterns": [format!("{a}/src/**/*.ts")], "exhaustive": true, "caseSensitive": true}]) + .to_string(); let mut got = restorable_glob_members(&scopes, &cache); got.sort(); assert_eq!(got, [member, kept]); @@ -7611,6 +7621,7 @@ mod tests { .to_string(), ) .unwrap(); + let scopes = std::fs::read_to_string(&scopes).unwrap(); assert_eq!(restorable_glob_members(&scopes, &cache), [member]); let _ = std::fs::remove_dir_all(&app); } diff --git a/crates/oj/src/start_host.rs b/crates/oj/src/start_host.rs index 6c61fcf13..58fdedc6d 100644 --- a/crates/oj/src/start_host.rs +++ b/crates/oj/src/start_host.rs @@ -544,6 +544,11 @@ pub(crate) fn app_start_entry(root: &Path) -> Option { start_file(root) } +/// A Start dev asset's served URL; the client bundle builds the same one. +fn fs_asset_url(url_base: &str, root: &Path, abs: &str) -> String { + oj_server::start_dev_file_url(url_base, root, Path::new(abs)) +} + /// `entries`: the router and start entries as Start resolved them /// ([`crate::start_bundle::StartEntries`]). The `#tanstack-start-entry` /// target is the app's file when it has one, else the bundled stub: upstream @@ -1164,7 +1169,7 @@ impl StartHost { id, self.inline_limit, ) - .unwrap_or_else(|| format!("{}/@oj-start/fs{clean}", self.bridge.start_url_base())); + .unwrap_or_else(|| fs_asset_url(&self.bridge.start_url_base(), &self.root, &clean)); format!("export default {};", json_str(&value)) }); return Ok(js(code)); @@ -1411,16 +1416,17 @@ impl StartHost { &format!("{path}?url"), self.inline_limit, ) - .unwrap_or_else(|| format!("{}/@oj-start/fs{path}", self.bridge.start_url_base())); + .unwrap_or_else(|| fs_asset_url(&self.bridge.start_url_base(), &self.root, path)); Ok(format!("export default {};", json_str(&value))) } // "no-inline", "asset" and anything unrecognized: the served-URL // module. _ => Ok(format!( "export default {};", - json_str(&format!( - "{}/@oj-start/fs{path}", - self.bridge.start_url_base() + json_str(&fs_asset_url( + &self.bridge.start_url_base(), + &self.root, + path )) )), } @@ -1914,6 +1920,42 @@ fn spawn_engine(root: &Path, host: &Arc) -> Result anyhow::Result` (ids +/// are the bundler's realpaths, so against the canonical root), anything +/// else as is. An out-of-root id is the same path in every worktree whose +/// bundle shares the generation, since the bundle key covers it. +fn stored_id(canonical_root: &Path, id: &str) -> String { + match Path::new(id).strip_prefix(canonical_root) { + Ok(rel) if !rel.as_os_str().is_empty() => format!("ws:{}", rel.to_string_lossy()), + _ => id.to_string(), + } +} + +fn canonical(root: &Path) -> std::path::PathBuf { + std::fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf()) +} /// Saves the rules of `modules`, the bundle cached under `key`: only its /// own, so a restore brings back no other environment's (or a gone module's). -pub(crate) fn save_rules(plugin: &StylexPlugin, dir: &Path, key: &str, modules: &[String]) { +pub(crate) fn save_rules( + plugin: &StylexPlugin, + store: &oj_cache::start_bundle::StartBundleStore, + root: &Path, + key: &str, + modules: &[String], +) { + let root = canonical(root); let modules: std::collections::HashSet<&str> = modules.iter().map(String::as_str).collect(); let rules: Vec<_> = plugin .module_rules() .into_iter() .filter(|(id, _)| modules.contains(id.as_str())) + .map(|(id, rules)| (stored_id(&root, &id), rules)) .collect(); - let sidecar = serde_json::json!({ - "key": key, + let saved = serde_json::json!({ "fingerprint": plugin.fingerprint(), "modules": rules, }); - let _ = std::fs::write(dir.join(RULES_SIDECAR), sidecar.to_string()); + store.attach(key, RULES_ATTACHMENT, saved.to_string().as_bytes()); } -/// Restores the rules saved for the bundle cached under `key`; false when -/// none were saved for it (or for these options), and the bundle must be -/// rebuilt for its modules to compile. -pub(crate) fn restore_rules(plugin: &StylexPlugin, dir: &Path, key: &str) -> bool { - let Some(sidecar) = std::fs::read(dir.join(RULES_SIDECAR)) - .ok() +/// Restores the rules saved with the bundle cached under `key`, rehomed onto +/// this root; false when none were saved for it (or for these options), and +/// the bundle must be rebuilt for its modules to compile. +pub(crate) fn restore_rules( + plugin: &StylexPlugin, + store: &oj_cache::start_bundle::StartBundleStore, + root: &Path, + key: &str, +) -> bool { + let Some(saved) = store + .attachment(key, RULES_ATTACHMENT) .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) else { return false; }; - let saved_for = - |field: &str, want: &str| sidecar.get(field).and_then(|v| v.as_str()) == Some(want); - if !saved_for("key", key) || !saved_for("fingerprint", plugin.fingerprint()) { + if saved.get("fingerprint").and_then(|v| v.as_str()) != Some(plugin.fingerprint()) { return false; } - let Some(modules) = sidecar.get("modules").cloned().and_then(|m| { + let Some(modules) = saved.get("modules").cloned().and_then(|m| { serde_json::from_value::)>>(m).ok() }) else { return false; }; + let root = canonical(root); for (id, rules) in modules { + let id = match id.strip_prefix("ws:") { + Some(rel) => root.join(rel).to_string_lossy().into_owned(), + None => id, + }; plugin.set_module_rules(&id, rules); } true @@ -222,39 +254,145 @@ mod tests { const SRC: &str = "import * as stylex from \"@stylexjs/stylex\";\n\ export const s = stylex.create({ a: { color: \"olive\" } });\n"; - fn plugin(options: serde_json::Value) -> StylexPlugin { - StylexPlugin::new(&options, Path::new("/app"), false, true).unwrap() + /// A bundle store over `dir` holding one generation for `root`, and its key. + fn store_with_generation( + dir: &Path, + root: &Path, + ) -> (oj_cache::start_bundle::StartBundleStore, String) { + let start = dir.join(format!( + "start-{}", + root.display().to_string().replace('/', "_") + )); + std::fs::create_dir_all(start.join("client-chunks")).unwrap(); + std::fs::create_dir_all(root.join("src")).unwrap(); + std::fs::write(root.join("src/a.ts"), SRC).unwrap(); + std::fs::write( + start.join("closure.json"), + serde_json::to_vec(&[root.join("src/a.ts")]).unwrap(), + ) + .unwrap(); + std::fs::write(start.join("client-chunks/entry.js"), "x").unwrap(); + std::fs::write( + start.join("client-chunks.json"), + r#"{"entry":"entry.js","files":[{"name":"entry.js","size":1}]}"#, + ) + .unwrap(); + for name in [ + "client-entry.modules", + "manifest.ts", + "glob-scopes.json", + "css-urls.json", + "client-modules.json", + ] { + std::fs::write( + start.join(name), + match name { + "client-modules.json" => "{}", + n if n.ends_with(".json") => "[]", + _ => "", + }, + ) + .unwrap(); + } + let store = oj_cache::start_bundle::StartBundleStore::at_dirs( + root, + dir.join("shared"), + root.join(".oj-cache/start-bundle"), + 8, + "0.0.1-test", + oj_cache::integrity::VerifyMode::Standard, + "development", + ); + let (key, _) = store.persist(&start).unwrap(); + (store, key) + } + + // The rules travel with the generation: another worktree restoring the + // same bundle gets them under its own module ids. + #[test] + fn saved_rules_restore_in_another_worktree_under_its_ids() { + let dir = std::env::temp_dir().join(format!("oj-stylex-share-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let (a, b) = (dir.join("wt-a"), dir.join("wt-b")); + let (store_a, key) = store_with_generation(&dir, &a); + let (store_b, key_b) = store_with_generation(&dir, &b); + assert_eq!(key, key_b, "same content, one generation"); + let id = |root: &Path| { + canonical(root) + .join("src/a.ts") + .to_string_lossy() + .into_owned() + }; + let cold = StylexPlugin::new(&serde_json::json!({}), &a, false, true).unwrap(); + let rules = cold + .transform_source(Path::new(&id(&a)), SRC) + .unwrap() + .unwrap() + .rules; + cold.set_module_rules(&id(&a), rules); + save_rules(&cold, &store_a, &a, &key, &[id(&a)]); + + let warm = StylexPlugin::new(&serde_json::json!({}), &b, false, true).unwrap(); + assert_eq!( + warm.fingerprint(), + cold.fingerprint(), + "one fingerprint per app" + ); + assert!(restore_rules(&warm, &store_b, &b, &key)); + assert_eq!( + warm.module_rules() + .iter() + .map(|(id, _)| id.clone()) + .collect::>(), + [id(&b)] + ); + let _ = std::fs::remove_dir_all(&dir); } #[test] fn saved_rules_restore_only_for_their_bundle_and_options() { let dir = std::env::temp_dir().join(format!("oj-stylex-sidecar-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let cold = plugin(serde_json::json!({})); + let _ = std::fs::remove_dir_all(&dir); + let app = dir.join("app"); + let (store, key) = store_with_generation(&dir, &app); + let id = |rel: &str| canonical(&app).join(rel).to_string_lossy().into_owned(); + let cold = StylexPlugin::new(&serde_json::json!({}), &app, false, true).unwrap(); let rules = cold - .transform_source(Path::new("/app/src/a.ts"), SRC) + .transform_source(Path::new(&id("src/a.ts")), SRC) .unwrap() .unwrap() .rules; - cold.set_module_rules("/app/src/a.ts", rules.clone()); + cold.set_module_rules(&id("src/a.ts"), rules.clone()); // Another environment's module, not the bundle's: never saved. - cold.set_module_rules("/app/src/ssr-only.ts", rules); - save_rules(&cold, &dir, "k1", &["/app/src/a.ts".to_string()]); + cold.set_module_rules(&id("src/ssr-only.ts"), rules); + save_rules(&cold, &store, &app, &key, &[id("src/a.ts")]); - let warm = plugin(serde_json::json!({})); - assert!(!restore_rules(&warm, &dir, "k2"), "another bundle's key"); + let warm = StylexPlugin::new(&serde_json::json!({}), &app, false, true).unwrap(); + assert!( + !restore_rules(&warm, &store, &app, "0000"), + "another bundle's key" + ); assert_eq!(warm.stylesheet().unwrap(), None); - assert!(restore_rules(&warm, &dir, "k1")); + assert!(restore_rules(&warm, &store, &app, &key)); assert_eq!( warm.module_rules() .iter() - .map(|(id, _)| id.as_str()) + .map(|(id, _)| id.clone()) .collect::>(), - ["/app/src/a.ts"] + [id("src/a.ts")] ); - let other_options = plugin(serde_json::json!({ "classNamePrefix": "q" })); - assert!(!restore_rules(&other_options, &dir, "k1"), "other options"); + let other_options = StylexPlugin::new( + &serde_json::json!({ "classNamePrefix": "q" }), + &app, + false, + true, + ) + .unwrap(); + assert!( + !restore_rules(&other_options, &store, &app, &key), + "other options" + ); let _ = std::fs::remove_dir_all(&dir); } } diff --git a/crates/oj_cache/src/lib.rs b/crates/oj_cache/src/lib.rs index b4676dcc2..0f8b560ca 100644 --- a/crates/oj_cache/src/lib.rs +++ b/crates/oj_cache/src/lib.rs @@ -3,10 +3,12 @@ use std::fs; use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; pub mod config_extract; pub mod integrity; pub mod start_bundle; +pub mod store; use serde::{Deserialize, Serialize}; @@ -134,7 +136,7 @@ pub(crate) fn hash_nul_joined(fields: &[&[u8]]) -> blake3::Hash { hasher.finalize() } -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] pub struct CachedModule { pub code: String, /// Raw sourcemap JSON; encoded to a data URL at serve time (Vite's @@ -165,6 +167,126 @@ pub struct CachedModule { /// its part of the stylesheet without recompiling. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub stylex_rules: Vec, + /// Constructive trace (pulp P2): files a plugin hook actually READ while + /// producing this entry, beyond the module source the key already covers. + /// A warm hit re-verifies every row; any mismatch (edited, deleted) is a + /// miss, never a stale serve. Empty for the vast majority of modules, so + /// verification costs nothing where plugins did nothing. + #[serde(default)] + pub trace: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct TraceRow { + /// The file's identity: absolute in memory, `ws:`/`mono:`-relative in the + /// stored form (see `relocated_for_store`). + pub id: String, + /// blake3 of the file's content at build time. + pub digest: String, +} + +impl CachedModule { + /// The on-disk form: absolute paths under `root` become `ws:` so the + /// stored artifact means the same thing in every worktree. Fields it + /// covers are the metadata paths oj itself consumes (`fs_allow`, + /// `watch_files`); anything not under the root stays absolute, which + /// keeps the entry correct and merely non-shareable. `rehome` is the + /// inverse, applied on read against the reading worktree's root. + pub fn relocated_for_store(&self, root: &Path, workspace: &Path) -> CachedModule { + let mut out = self.clone(); + let relocate = |entry: &mut String| { + // Glob rows carry their pattern behind a `glob:` tag; the inner + // pattern relocates like a path. + let (prefix, inner) = match entry.strip_prefix("glob:") { + Some(inner) => ("glob:", inner.to_string()), + None => ("", entry.clone()), + }; + if let Some(rel) = crate::store::rel_key(root, Path::new(&inner)) { + *entry = format!("{prefix}ws:{rel}"); + } else if let Some(rel) = crate::store::rel_key(workspace, Path::new(&inner)) { + *entry = format!("{prefix}mono:{rel}"); + } + }; + for list in [&mut out.fs_allow, &mut out.watch_files] { + for entry in list.iter_mut() { + relocate(entry); + } + } + for row in &mut out.trace { + relocate(&mut row.id); + } + out + } + + /// Expand `ws:` metadata paths against this worktree's root: the + /// read-side inverse of `relocated_for_store`. + pub fn rehomed(&self, root: &Path, workspace: &Path) -> CachedModule { + let mut out = self.clone(); + let rehome = |entry: &mut String| { + let (prefix, inner) = match entry.strip_prefix("glob:") { + Some(inner) => ("glob:", inner.to_string()), + None => ("", entry.clone()), + }; + if let Some(rel) = inner.strip_prefix("ws:") { + *entry = format!("{prefix}{}", root.join(rel).to_string_lossy()); + } else if let Some(rel) = inner.strip_prefix("mono:") { + *entry = format!("{prefix}{}", workspace.join(rel).to_string_lossy()); + } + }; + for list in [&mut out.fs_allow, &mut out.watch_files] { + for entry in list.iter_mut() { + rehome(entry); + } + } + for row in &mut out.trace { + rehome(&mut row.id); + } + out + } + + /// True when nothing in the stored form still points into a specific + /// worktree: the admission test for a shared store. Checks the metadata + /// paths and the rewritten import URLs (`/@fs/` pins an artifact to + /// one checkout; `importer=` hex params are covered by their own `ws:` + /// encoding at generation time). + pub fn is_relocatable(&self) -> bool { + let path_free = |s: &str| { + let s = s.strip_prefix("glob:").unwrap_or(s); + s.starts_with("ws:") || s.starts_with("mono:") || !Path::new(s).is_absolute() + }; + // Served-URL fields: /@fs/ and /@oj-pkg/ pin an entry + // to one checkout (the latter hex-encodes an absolute entry path). + // /@fs/@mono/ is the workspace-relative form: the serving + // worktree resolves it against its OWN workspace root, so it does + // not pin. + let pinned_url = |s: &str| { + (s.starts_with("/@fs/") && !s.starts_with("/@fs/@mono/")) || s.starts_with("/@oj-pkg/") + }; + self.fs_allow.iter().all(|p| path_free(p)) + && self.watch_files.iter().all(|p| path_free(p)) + && self.trace.iter().all(|row| path_free(&row.id)) + && !self.imports.iter().any(|i| pinned_url(i)) + && !self + .require_map + .iter() + .any(|(_, target)| pinned_url(target)) + && !code_pins(&self.code) + && !self.code.contains("/@oj-pkg/") + } +} + +/// True when `code` contains a worktree-pinning `/@fs/` reference: any +/// occurrence NOT in the workspace-relative `/@fs/@mono/` form. +fn code_pins(code: &str) -> bool { + let mut rest = code; + while let Some(i) = rest.find("/@fs/") { + let after = &rest[i + "/@fs/".len()..]; + if !after.starts_with("@mono/") { + return true; + } + rest = after; + } + false } #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] @@ -178,10 +300,171 @@ pub struct HotMeta { pub accepted_exports: Option>, } +/// The persistent module cache: the dev server's compiled modules on disk, +/// so a restart, a second worktree or a fresh sandbox serves what an earlier +/// process compiled (see [`store`]). An entry is written under its memory key +/// ([`module_key`]) salted with everything else that shapes compiled output +/// (the tool version, the defines, the config graph), so a stale entry is a +/// miss, never a wrong hit. +pub struct PersistentCache { + /// The per-app home: entries whose stored form still pins a worktree + /// (`/@fs/` imports, absolute metadata) live here and nowhere else. + dir: PathBuf, + /// The shared per-user modules directory. Entries that pass + /// [`CachedModule::is_relocatable`] are written here, where every + /// worktree (and every app whose salted key matches) can hit them. + shared: Option, + salt: String, +} + +/// Bumped whenever the meaning of a stored [`CachedModule`] changes, so an +/// older entry is never deserialized with the new meaning. +pub const CACHE_FORMAT: u32 = 9; + +impl PersistentCache { + pub fn new(dir: PathBuf, tool_version: &str) -> Self { + Self { + dir, + shared: None, + salt: format!("{tool_version}:{CACHE_FORMAT}"), + } + } + + /// Attaches the shared modules directory. Callers hand entries to `put` + /// in their stored (`ws:`-relative) form; `put` admits them to the shared + /// directory only when nothing in that form still points into a specific + /// worktree. + pub fn with_shared(mut self, shared: Option) -> Self { + self.shared = shared; + self + } + + /// Compiled modules embed inlined `import.meta.env` values, so anything + /// that changes the defines (dotenv edits, process env, plugin config() + /// mutations) must land in the salt or warm restarts serve stale env. + pub fn with_salt_extra(mut self, extra: &str) -> Self { + self.salt.push(':'); + self.salt.push_str(extra); + self + } + + /// The name an entry is stored under: its memory key under this cache's + /// salt, as hex. Two processes agree on it when they agree on every + /// input the salt covers, which is what lets a worktree hit another's + /// entry. + pub fn disk_key(&self, key: &ModuleKey) -> String { + hash_nul_joined(&[self.salt.as_bytes(), key]) + .to_hex() + .to_string() + } + + pub fn get(&self, key: &str) -> Option { + // Shared first: relocatable entries (most of a typical app) are + // written there. A corrupt entry is removed from whichever directory + // held it and reads fall through. + if let Some(path) = self.shared.as_deref().and_then(|s| Self::path_in(s, key)) { + let found: Option = integrity::read_json_or_remove(&path); + if let Some(module) = found { + // The shared directory is every worktree's: an entry that still + // points into one checkout (another oj's write, a damaged + // store) is dropped, never served, whatever `put` admitted. + if module.is_relocatable() { + return Some(module); + } + let _ = fs::remove_file(&path); + } + } + integrity::read_json_or_remove(&Self::path_in(&self.dir, key)?) + } + + pub fn put(&self, key: &str, module: &CachedModule) { + // Admission control for the shared store: only an entry whose stored + // form carries no worktree-specific path may leave this app's cache. + // Everything else stays correct and local. + let bytes = serde_json::to_vec(module).unwrap_or_default(); + if let Some(shared) = self.shared.as_deref().filter(|_| module.is_relocatable()) { + if Self::write_in(shared, key, &bytes) { + return; + } + // A store that cannot be written (another user's, a read-only + // mount) costs sharing, never this app's own warm restarts. + } + Self::write_in(&self.dir, key, &bytes); + } + + /// Writes the entry to this app's own cache only, whatever its stored + /// form admits: for an entry the caller knows names the checkout where + /// [`CachedModule::is_relocatable`] cannot see it (its debug info). + pub fn put_local(&self, key: &str, module: &CachedModule) { + let bytes = serde_json::to_vec(module).unwrap_or_default(); + Self::write_in(&self.dir, key, &bytes); + } + + /// Writes the entry under `dir`, through a temp file and a rename, so a + /// reader never sees a partial one. False when nothing landed. + fn write_in(dir: &Path, key: &str, bytes: &[u8]) -> bool { + let Some(path) = Self::path_in(dir, key) else { + return false; + }; + let Some(parent) = path.parent() else { + return false; + }; + if fs::create_dir_all(parent).is_err() { + return false; + } + // Per-write sequence: threads of one process may put the same key + // concurrently and must not share a temp file. + let seq = TEMP_SEQ.fetch_add(1, Ordering::Relaxed); + let tmp = path.with_extension(format!("tmp-{}-{seq}", std::process::id())); + integrity::write_via_tmp(&tmp, &path, bytes).is_ok() + } + + /// `//.json`; `None` for anything but a lowercase + /// blake3 hex digest, so a key can never escape the cache dir. + fn path_in(dir: &Path, key: &str) -> Option { + if key.len() != 64 || !is_lower_hex(key) { + return None; + } + Some(dir.join(&key[..2]).join(format!("{key}.json"))) + } +} + +static TEMP_SEQ: AtomicU64 = AtomicU64::new(0); + #[cfg(test)] mod tests { use super::*; + fn temp_cache(label: &str) -> PersistentCache { + let dir = + std::env::temp_dir().join(format!("oj-cache-test-{}-{label}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + PersistentCache::new(dir, "0.0.1-test") + } + + /// A disk key for `source` at `url`, under `cache`'s salt. + fn disk_key(cache: &PersistentCache, source: &[u8], url: &str, mode: &str) -> String { + cache.disk_key(&module_key(&source_hash(source), url, mode)) + } + + fn sample() -> CachedModule { + CachedModule { + code: "export const x = 1;".into(), + map_json: Some("data:application/json;base64,e30=".into()), + imports: vec!["/node_modules/react/index.js".into()], + is_boundary: true, + kind: "esm".into(), + require_map: vec![("react".into(), "/node_modules/react/index.js".into())], + css_exports: Vec::new(), + fs_allow: Vec::new(), + watch_files: Vec::new(), + import_bindings: Vec::new(), + hot: None, + stylex_rules: Vec::new(), + trace: Vec::new(), + } + } + #[test] fn module_key_changes_with_every_input_and_keeps_field_boundaries() { let hash = source_hash(b"source"); @@ -201,6 +484,101 @@ mod tests { assert_ne!(module_key(&hash, "a", "bc"), module_key(&hash, "ab", "c")); } + #[test] + fn the_disk_key_moves_with_the_version_and_every_salt() { + let cache = temp_cache("keys"); + let base = disk_key(&cache, b"source", "/src/App.tsx", "dev"); + assert_eq!(base, disk_key(&cache, b"source", "/src/App.tsx", "dev")); + assert_ne!( + base, + disk_key(&cache, b"source2", "/src/App.tsx", "dev"), + "content" + ); + assert_ne!( + base, + disk_key(&cache, b"source", "/src/Other.tsx", "dev"), + "url" + ); + assert_ne!( + base, + disk_key(&cache, b"source", "/src/App.tsx", "prod"), + "mode" + ); + let other_version = PersistentCache::new(std::env::temp_dir(), "9.9.9"); + assert_ne!( + base, + disk_key(&other_version, b"source", "/src/App.tsx", "dev"), + "version" + ); + let salted = PersistentCache::new(std::env::temp_dir(), "9.9.9").with_salt_extra("env-a"); + let resalted = PersistentCache::new(std::env::temp_dir(), "9.9.9").with_salt_extra("env-b"); + assert_ne!( + disk_key(&salted, b"source", "/src/App.tsx", "dev"), + disk_key(&resalted, b"source", "/src/App.tsx", "dev"), + "env defines salt" + ); + // Two caches with one salt agree on the name: the sharing contract. + let twin = PersistentCache::new(std::env::temp_dir(), "0.0.1-test"); + assert_eq!(base, disk_key(&twin, b"source", "/src/App.tsx", "dev")); + } + + #[test] + fn roundtrip() { + let cache = temp_cache("roundtrip"); + let key = disk_key(&cache, b"source", "/src/App.tsx", "dev"); + assert_eq!(cache.get(&key), None); + cache.put(&key, &sample()); + assert_eq!(cache.get(&key), Some(sample())); + } + + #[test] + fn corrupt_entries_are_dropped_not_served() { + let cache = temp_cache("corrupt"); + let key = disk_key(&cache, b"s", "/u", "dev"); + cache.put(&key, &sample()); + let path = PersistentCache::path_in(&cache.dir, &key).unwrap(); + std::fs::write(&path, b"{ not json").unwrap(); + assert_eq!(cache.get(&key), None); + assert!(!path.exists(), "corrupt entry must be removed"); + } + + #[test] + fn shards_by_key_prefix_and_leaves_no_temp_file() { + let cache = temp_cache("shard"); + let key = disk_key(&cache, b"s", "/u", "dev"); + cache.put(&key, &sample()); + let path = PersistentCache::path_in(&cache.dir, &key).unwrap(); + assert_eq!( + path.parent() + .unwrap() + .file_name() + .unwrap() + .to_str() + .unwrap(), + &key[..2] + ); + assert!(path.exists()); + let shard = path.parent().unwrap(); + let leftovers: Vec<_> = std::fs::read_dir(shard) + .unwrap() + .flatten() + .map(|e| e.file_name().to_string_lossy().into_owned()) + .filter(|name| name.contains(".tmp")) + .collect(); + assert!( + leftovers.is_empty(), + "temp files must be renamed away: {leftovers:?}" + ); + } + + #[test] + fn a_key_that_is_no_digest_names_no_file() { + let cache = temp_cache("escape"); + cache.put("../../etc/passwd", &sample()); + assert_eq!(cache.get("../../etc/passwd"), None); + assert!(!cache.dir.exists(), "nothing written for a bad key"); + } + #[test] fn cache_root_is_versioned() { let root = cache_root_in(Path::new("/app"), None); @@ -248,6 +626,286 @@ mod tests { ); } + fn shared_pair(label: &str) -> (PersistentCache, PersistentCache, PathBuf) { + let base = + std::env::temp_dir().join(format!("oj-shared-cache-{}-{label}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let shared = base.join("store/modules"); + let a = PersistentCache::new(base.join("wt-a/.oj-cache/v1"), "0.0.1-test") + .with_shared(Some(shared.clone())); + let b = PersistentCache::new(base.join("wt-b/.oj-cache/v1"), "0.0.1-test") + .with_shared(Some(shared.clone())); + (a, b, base) + } + + #[test] + fn relocatable_entries_are_shared_across_worktrees() { + let (a, b, base) = shared_pair("hit"); + let module = CachedModule { + code: "export const x = 1;".into(), + fs_allow: vec!["ws:node_modules/dep".into()], + ..Default::default() + }; + let key = disk_key(&a, b"src", "/src/App.tsx", "dev"); + a.put(&key, &module); + assert_eq!( + b.get(&key).as_ref(), + Some(&module), + "worktree B reads what worktree A compiled" + ); + // It lives in the shared directory, not in either app's cache. + assert!(base + .join("store/modules") + .join(&key[..2]) + .join(format!("{key}.json")) + .is_file()); + assert!(!base.join("wt-a/.oj-cache/v1").join(&key[..2]).exists()); + } + + #[test] + fn pinned_entries_stay_in_their_own_worktree() { + let (a, b, base) = shared_pair("pin"); + let pinned = CachedModule { + code: "import u from \"/@fs//work/wt-a/pkg/u.ts\";".into(), + imports: vec!["/@fs//work/wt-a/pkg/u.ts".into()], + ..Default::default() + }; + let key = disk_key(&a, b"src", "/src/uses-sibling.ts", "dev"); + a.put(&key, &pinned); + assert_eq!( + a.get(&key).as_ref(), + Some(&pinned), + "A still hits its own entry" + ); + assert_eq!( + b.get(&key), + None, + "B must never receive an entry that points into A's checkout" + ); + assert!(!base.join("store/modules").join(&key[..2]).exists()); + } + + #[test] + fn without_a_shared_dir_everything_stays_local() { + let cache = temp_cache("no-shared"); + let module = sample(); + let key = disk_key(&cache, b"src", "/src/a.ts", "dev"); + cache.put(&key, &module); + assert_eq!(cache.get(&key).as_ref(), Some(&module)); + } + + #[test] + fn corrupt_shared_entry_is_removed_and_misses() { + let (a, b, base) = shared_pair("corrupt"); + let key = disk_key(&a, b"src", "/src/App.tsx", "dev"); + let shard = base.join("store/modules").join(&key[..2]); + std::fs::create_dir_all(&shard).unwrap(); + let path = shard.join(format!("{key}.json")); + std::fs::write(&path, b"{ not json").unwrap(); + assert_eq!(b.get(&key), None); + assert!(!path.exists(), "corrupt shared entry deleted on read"); + let _ = a; + } + + #[test] + fn relocatability_covers_require_map_and_pkg_bundle_urls() { + let clean = CachedModule { + code: "require(\"react\");".into(), + require_map: vec![("react".into(), "/node_modules/react/index.js".into())], + ..Default::default() + }; + assert!(clean.is_relocatable()); + let fs_require = CachedModule { + require_map: vec![("sib".into(), "/@fs//work/wt-a/sib/index.js".into())], + ..clean.clone() + }; + assert!(!fs_require.is_relocatable(), "/@fs require target pins"); + let pkg_import = CachedModule { + imports: vec!["/@oj-pkg/6162".into()], + ..clean.clone() + }; + assert!( + !pkg_import.is_relocatable(), + "/@oj-pkg hex-encodes an absolute path" + ); + } + + #[test] + fn cached_module_relocates_metadata_and_rehomes_in_another_worktree() { + let root_a = Path::new("/work/wt-a/mono/app"); + let ws_a = Path::new("/work/wt-a/mono"); + let root_b = Path::new("/elsewhere/wt-b/mono/app"); + let ws_b = Path::new("/elsewhere/wt-b/mono"); + let module = CachedModule { + code: "export {}".into(), + fs_allow: vec![ + "/work/wt-a/mono/app/node_modules/dep".into(), + "/work/wt-a/mono/packages/common".into(), + "/outside/sibling".into(), + ], + watch_files: vec!["/work/wt-a/mono/app/tailwind.config.js".into()], + ..Default::default() + }; + let stored = module.relocated_for_store(root_a, ws_a); + assert_eq!( + stored.fs_allow, + vec![ + "ws:node_modules/dep".to_string(), + "mono:packages/common".to_string(), + "/outside/sibling".to_string() + ], + "root-relative, workspace-relative, and external forms" + ); + assert_eq!( + stored.watch_files, + vec!["ws:tailwind.config.js".to_string()] + ); + // Reading worktree B expands against ITS root and workspace. + let rehomed = stored.rehomed(root_b, ws_b); + assert_eq!( + rehomed.fs_allow, + vec![ + "/elsewhere/wt-b/mono/app/node_modules/dep".to_string(), + "/elsewhere/wt-b/mono/packages/common".to_string(), + "/outside/sibling".to_string() + ] + ); + assert_eq!( + rehomed.watch_files, + vec!["/elsewhere/wt-b/mono/app/tailwind.config.js".to_string()] + ); + // The roundtrip in one worktree is the identity. + assert_eq!( + module + .relocated_for_store(root_a, ws_a) + .rehomed(root_a, ws_a), + module + ); + } + + #[test] + fn trace_rows_relocate_rehome_and_gate_admission() { + let root_a = Path::new("/wt-a/mono/app"); + let ws_a = Path::new("/wt-a/mono"); + let module = CachedModule { + code: "export {}".into(), + trace: vec![ + TraceRow { + id: "/wt-a/mono/app/extra.txt".into(), + digest: "d1".into(), + }, + TraceRow { + id: "/wt-a/mono/packages/tokens.json".into(), + digest: "d2".into(), + }, + TraceRow { + id: "/etc/hosts".into(), + digest: "d3".into(), + }, + ], + ..Default::default() + }; + let stored = module.relocated_for_store(root_a, ws_a); + assert_eq!(stored.trace[0].id, "ws:extra.txt"); + assert_eq!(stored.trace[1].id, "mono:packages/tokens.json"); + assert_eq!(stored.trace[2].id, "/etc/hosts"); + assert!( + !stored.is_relocatable(), + "a trace row outside the workspace pins the entry" + ); + let in_ws = CachedModule { + trace: stored.trace[..2].to_vec(), + ..stored.clone() + }; + assert!(in_ws.is_relocatable(), "ws:/mono: trace rows do not pin"); + // B rehomes against its own roots; digests travel untouched. + let rehomed = in_ws.rehomed(Path::new("/b/mono/app"), Path::new("/b/mono")); + assert_eq!(rehomed.trace[0].id, "/b/mono/app/extra.txt"); + assert_eq!(rehomed.trace[1].id, "/b/mono/packages/tokens.json"); + assert_eq!(rehomed.trace[1].digest, "d2"); + } + + #[test] + fn glob_trace_rows_relocate_behind_their_tag() { + let module = CachedModule { + trace: vec![TraceRow { + id: "glob:/wt-a/mono/app/globbed/*.ts".into(), + digest: "d".into(), + }], + ..Default::default() + }; + let stored = + module.relocated_for_store(Path::new("/wt-a/mono/app"), Path::new("/wt-a/mono")); + assert_eq!(stored.trace[0].id, "glob:ws:globbed/*.ts"); + assert!(stored.is_relocatable()); + let rehomed = stored.rehomed(Path::new("/b/app"), Path::new("/b")); + assert_eq!(rehomed.trace[0].id, "glob:/b/app/globbed/*.ts"); + // Out-of-workspace glob pins. + let pinned = CachedModule { + trace: vec![TraceRow { + id: "glob:/elsewhere/*.ts".into(), + digest: "d".into(), + }], + ..Default::default() + }; + assert!(!pinned + .relocated_for_store(Path::new("/wt-a/app"), Path::new("/wt-a")) + .is_relocatable()); + } + + #[test] + fn relocatability_is_judged_on_the_stored_form() { + let clean = CachedModule { + code: "import x from \"/src/a.js\";".into(), + imports: vec!["/src/a.js".into()], + fs_allow: vec!["ws:node_modules/dep".into()], + watch_files: vec![], + ..Default::default() + }; + assert!(clean.is_relocatable()); + + let abs_allow = CachedModule { + fs_allow: vec!["/work/wt-a/node_modules/dep".into()], + ..clean.clone() + }; + assert!( + !abs_allow.is_relocatable(), + "absolute fs_allow pins the entry" + ); + + let fs_import = CachedModule { + imports: vec!["/@fs//work/wt-a/pkg/util.ts".into()], + ..clean.clone() + }; + assert!(!fs_import.is_relocatable(), "/@fs import pins the entry"); + + let fs_in_code = CachedModule { + code: "import u from \"/@fs//work/wt-a/pkg/util.ts\";".into(), + ..clean.clone() + }; + assert!(!fs_in_code.is_relocatable()); + + // The workspace-relative /@fs/@mono form does NOT pin: the serving + // worktree resolves it against its own workspace root. + let mono_import = CachedModule { + code: "import r from \"/@fs/@mono/node_modules/react/index.js?v=1\";".into(), + imports: vec!["/@fs/@mono/node_modules/react/index.js?v=1".into()], + fs_allow: vec!["mono:node_modules/react".into()], + ..clean.clone() + }; + assert!( + mono_import.is_relocatable(), + "@mono urls are worktree-independent" + ); + // But one pinning occurrence among mono ones still pins. + let mixed = CachedModule { + code: "import a from \"/@fs/@mono/x.js\"; import b from \"/@fs//work/wt-a/y.js\";" + .into(), + ..clean.clone() + }; + assert!(!mixed.is_relocatable(), "one absolute /@fs still pins"); + } + #[test] fn cache_root_is_relocatable_and_stays_versioned() { let app = Path::new("/srv/app"); @@ -272,4 +930,399 @@ mod tests { assert_eq!(cache_base_in(app, out), Path::new("/out/oj")); assert!(cache_root_in(app, out).starts_with(cache_base_in(app, out))); } + + // A disk key is a lowercase blake3 hex digest, the same for the same + // inputs under the same salt, and distinct over a corpus of near inputs: + // sources a byte apart, urls that are prefixes of one another, modes + // that shift a character across the field boundary. + #[test] + fn disk_keys_are_digests_and_distinct_over_a_corpus_of_near_inputs() { + let cache = temp_cache("corpus"); + let twin = PersistentCache::new(std::env::temp_dir().join("twin"), "0.0.1-test"); + let mut seen = std::collections::HashSet::new(); + let sources: Vec> = (0..8u8) + .map(|i| { + let mut s = b"export const x = 1;".to_vec(); + if i > 0 { + s.push(i); + } + s + }) + .collect(); + let urls = [ + "/src/a.ts", + "/src/a.tsx", + "/src/a.ts?raw", + "/src/a.ts?url", + "/src/a", + "/src/a/", + "/src/aa.ts", + "/@fs/@mono/src/a.ts", + "/node_modules/a/index.js", + ]; + let modes = [ + "dev", + "dev@1", + "dev@12", + "dev@1+setcf", + "dev+setcf", + "server", + "dev+deps01", + "dev+deps0", + "de", + "dev+vms", + "dev+esm", + "dev+cjs", + ]; + for source in &sources { + for url in urls { + for mode in modes { + let key = disk_key(&cache, source, url, mode); + assert_eq!(key.len(), 64); + assert!(is_lower_hex(&key), "{key}"); + assert_eq!( + key, + disk_key(&twin, source, url, mode), + "same salt, same name" + ); + assert!(seen.insert(key), "{url} {mode} collided"); + } + } + } + // Mode and url meet at a NUL: a character shifted across it is + // another key. + assert_ne!( + disk_key(&cache, b"s", "/x", "dev+a"), + disk_key(&cache, b"s", "a/x", "dev+") + ); + // Salt extras are fields in order: the same extras in another order + // name another entry. + let ab = PersistentCache::new(std::env::temp_dir(), "1") + .with_salt_extra("a") + .with_salt_extra("b"); + let ba = PersistentCache::new(std::env::temp_dir(), "1") + .with_salt_extra("b") + .with_salt_extra("a"); + assert_ne!( + disk_key(&ab, b"s", "/x", "dev"), + disk_key(&ba, b"s", "/x", "dev") + ); + } + + // Relative identity follows path components, never string prefixes: a + // sibling that shares the root's spelling is outside, a trailing + // separator on the root is the same root, the root itself is the empty + // key. A `..` is kept as spelled (`ws:../x` means the same place + // relative to every root); a `.` is no component. + #[test] + fn rel_key_follows_components_not_string_prefixes() { + use crate::store::rel_key; + let root = Path::new("/work/app"); + assert_eq!(rel_key(root, Path::new("/work/app2/x.ts")), None); + assert_eq!(rel_key(root, Path::new("/work/app.bak/x.ts")), None); + assert_eq!(rel_key(root, Path::new("/work/ap/x.ts")), None); + assert_eq!(rel_key(root, Path::new("work/app/x.ts")), None); + assert_eq!( + rel_key(Path::new("/work/app/"), Path::new("/work/app/x.ts")).as_deref(), + Some("x.ts") + ); + assert_eq!(rel_key(root, Path::new("/work/app/")).as_deref(), Some("")); + assert_eq!( + rel_key(root, Path::new("/work/app/a b/\u{fc}.ts")).as_deref(), + Some("a b/\u{fc}.ts") + ); + assert_eq!( + rel_key(root, Path::new("/work/app/./x.ts")).as_deref(), + Some("x.ts") + ); + assert_eq!( + rel_key(root, Path::new("/work/app/../x.ts")).as_deref(), + Some("../x.ts") + ); + } +} + +#[cfg(test)] +mod store_stress_tests { + //! The shared store is written by every oj on the machine at once and + //! read by servers that trust it: these pin what must hold under races, + //! torn files and entries another process put there. + use super::*; + + fn base(label: &str) -> PathBuf { + let dir = + std::env::temp_dir().join(format!("oj-store-stress-{}-{label}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + dir + } + + fn worktree(base: &Path, name: &str) -> PersistentCache { + PersistentCache::new(base.join(name).join(".oj-cache/v1"), "0.0.1-test") + .with_shared(Some(base.join("store/modules"))) + } + + fn module(code: &str) -> CachedModule { + CachedModule { + code: code.to_string(), + kind: "esm".into(), + ..Default::default() + } + } + + fn files_in_shard(base: &Path, key: &str) -> Vec { + std::fs::read_dir(base.join("store/modules").join(&key[..2])) + .into_iter() + .flatten() + .flatten() + .map(|e| e.file_name().to_string_lossy().into_owned()) + .collect() + } + + // Many threads of one process, and two worktrees' caches on one shared + // directory, write one key at once while readers poll it: a reader sees + // nothing or one whole entry some writer wrote, and the shard ends with + // the one file and no temp file. + #[test] + fn racing_writers_of_one_key_leave_one_whole_entry() { + let base = base("race"); + let a = worktree(&base, "wt-a"); + let b = worktree(&base, "wt-b"); + let key = a.disk_key(&module_key(&source_hash(b"src"), "/src/App.tsx", "dev")); + assert_eq!( + key, + b.disk_key(&module_key(&source_hash(b"src"), "/src/App.tsx", "dev")) + ); + let bodies: Vec = (0..64) + .map(|i| format!("export const x = {i}; // {}", "x".repeat(2000 + i))) + .collect(); + let torn = std::sync::atomic::AtomicUsize::new(0); + let reads = std::sync::atomic::AtomicUsize::new(0); + std::thread::scope(|s| { + for (i, body) in bodies.iter().enumerate() { + let cache = if i % 2 == 0 { &a } else { &b }; + let key = &key; + s.spawn(move || { + for _ in 0..8 { + cache.put(key, &module(body)); + } + }); + } + for reader in [&a, &b] { + let (key, bodies, torn, reads) = (&key, &bodies, &torn, &reads); + s.spawn(move || { + for _ in 0..400 { + if let Some(seen) = reader.get(key) { + reads.fetch_add(1, Ordering::Relaxed); + if !bodies.contains(&seen.code) { + torn.fetch_add(1, Ordering::Relaxed); + } + } + std::thread::yield_now(); + } + }); + } + }); + assert_eq!(torn.into_inner(), 0, "a reader saw bytes no writer wrote"); + assert!(reads.into_inner() > 0, "the readers never saw an entry"); + let last = a.get(&key).expect("an entry survives"); + assert!(bodies.contains(&last.code)); + let files = files_in_shard(&base, &key); + assert_eq!(files, vec![format!("{key}.json")], "{files:?}"); + } + + // A crash mid-write of another oj (one that wrote in place rather than + // via a temp file): a valid prefix of a real entry is a corrupt entry, + // removed on read and never served. + #[test] + fn a_torn_entry_is_removed_and_misses() { + let base = base("torn"); + let a = worktree(&base, "wt-a"); + let key = a.disk_key(&module_key(&source_hash(b"src"), "/src/a.ts", "dev")); + a.put(&key, &module("export const whole = 1;")); + let path = base + .join("store/modules") + .join(&key[..2]) + .join(format!("{key}.json")); + let bytes = std::fs::read(&path).unwrap(); + for cut in [1, bytes.len() / 3, bytes.len() - 1] { + std::fs::write(&path, &bytes[..cut]).unwrap(); + assert_eq!(a.get(&key), None, "a prefix of {cut} bytes served"); + assert!(!path.exists(), "the torn file stays after a cut at {cut}"); + } + } + + // An entry in the shared directory that names a checkout (put there by + // another oj version, or a copied store) is poison for every other + // worktree: a read refuses it and removes it, whatever wrote it. + #[test] + fn a_shared_entry_that_pins_a_checkout_is_refused_on_read() { + let base = base("poison"); + let a = worktree(&base, "wt-a"); + let key = a.disk_key(&module_key(&source_hash(b"src"), "/src/a.ts", "dev")); + let shard = base.join("store/modules").join(&key[..2]); + std::fs::create_dir_all(&shard).unwrap(); + let path = shard.join(format!("{key}.json")); + let poison = CachedModule { + imports: vec!["/@fs//work/wt-zzz/pkg/u.ts".into()], + ..module("import u from \"/@fs//work/wt-zzz/pkg/u.ts\";") + }; + std::fs::write(&path, serde_json::to_vec(&poison).unwrap()).unwrap(); + assert_eq!(a.get(&key), None, "a pinned shared entry was served"); + assert!(!path.exists(), "the poison stays in the store"); + // The same entry in the worktree's own cache is its own business. + a.put(&key, &poison); + assert_eq!(a.get(&key).as_ref(), Some(&poison)); + assert!(!path.exists(), "a pinned put never lands in the shared dir"); + } + + // Every path shape under the root relocates to `ws:` and comes back + // whole; anything outside stays as it was and keeps the entry local. + #[test] + fn relocation_round_trips_every_path_shape_and_admits_only_path_free_entries() { + let root = Path::new("/work/wt-a/mono/app"); + let ws = Path::new("/work/wt-a/mono"); + let other_root = Path::new("/elsewhere/b/mono/app"); + let other_ws = Path::new("/elsewhere/b/mono"); + let under_root = [ + "src/App.tsx", + "src/deep/er/path/x.ts", + "node_modules/dep/index.js", + "with space/ü.ts", + ".oj-cache/v1/x.json", + "src/App.tsx?import&t=5", + ]; + let under_ws = ["node_modules/react/index.js", "packages/ui/Button.tsx"]; + let outside = [ + "/opt/other/x.ts", + "/work/wt-a/mono2/x.ts", + "/work/wt-a/monoapp/x.ts", + ]; + let mut seed = 7u64; + let mut pick = |n: usize| { + seed = seed + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407); + (seed >> 33) as usize % n + }; + for _ in 0..500 { + let mut fs_allow = Vec::new(); + let mut watch = Vec::new(); + let mut trace = Vec::new(); + let mut has_outside = false; + for _ in 0..pick(4) + 1 { + let (entry, out) = match pick(3) { + 0 => (root.join(under_root[pick(under_root.len())]), false), + 1 => (ws.join(under_ws[pick(under_ws.len())]), false), + _ => (PathBuf::from(outside[pick(outside.len())]), true), + }; + has_outside |= out; + let entry = entry.to_string_lossy().into_owned(); + match pick(3) { + 0 => fs_allow.push(entry), + 1 => watch.push(entry), + _ => trace.push(TraceRow { + id: entry, + digest: "d".into(), + }), + } + } + let module = CachedModule { + code: "export {}".into(), + fs_allow, + watch_files: watch, + trace, + ..Default::default() + }; + let stored = module.relocated_for_store(root, ws); + assert_eq!( + stored.is_relocatable(), + !has_outside, + "admission for {module:?}" + ); + assert_eq!(stored.rehomed(root, ws), module, "round trip"); + if !has_outside { + let moved = stored.rehomed(other_root, other_ws); + for entry in moved.fs_allow.iter().chain(&moved.watch_files) { + assert!( + entry.starts_with("/elsewhere/b/mono"), + "{entry} did not move with the worktree" + ); + } + assert_eq!( + moved.relocated_for_store(other_root, other_ws), + stored, + "the stored form is the same from either worktree" + ); + } + } + } +} + +#[cfg(all(test, unix))] +mod store_permission_tests { + //! A shared store another user owns, or a read-only mount: sharing is + //! lost, the app's own cache is not, and nothing panics. + use super::*; + use std::os::unix::fs::PermissionsExt; + + #[test] + fn an_unwritable_shared_dir_keeps_entries_local() { + // Root writes anywhere; the test means nothing there. + if unsafe { libc_geteuid() } == 0 { + return; + } + let base = std::env::temp_dir().join(format!("oj-store-perm-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let shared = base.join("store/modules"); + std::fs::create_dir_all(&shared).unwrap(); + std::fs::set_permissions(&shared, std::fs::Permissions::from_mode(0o555)).unwrap(); + let cache = PersistentCache::new(base.join("wt-a/.oj-cache/v1"), "0.0.1-test") + .with_shared(Some(shared.clone())); + let key = cache.disk_key(&module_key(&source_hash(b"src"), "/src/a.ts", "dev")); + let module = CachedModule { + code: "export const x = 1;".into(), + ..Default::default() + }; + cache.put(&key, &module); + let got = cache.get(&key); + let shared_has = shared.join(&key[..2]).exists(); + std::fs::set_permissions(&shared, std::fs::Permissions::from_mode(0o755)).unwrap(); + assert!(!shared_has, "written into a read-only store"); + assert_eq!(got.as_ref(), Some(&module), "the app's own cache took it"); + } + + extern "C" { + #[link_name = "geteuid"] + fn libc_geteuid() -> u32; + } +} + +#[cfg(test)] +mod store_removal_tests { + use super::*; + + // The store directory disappears under a running server (a cache clean, + // a sandbox reset): reads miss, the next write recreates it, nothing + // panics. + #[test] + fn a_shared_dir_removed_underneath_is_recreated_by_the_next_write() { + let base = std::env::temp_dir().join(format!("oj-store-removed-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let shared = base.join("store/modules"); + let cache = PersistentCache::new(base.join("wt-a/.oj-cache/v1"), "0.0.1-test") + .with_shared(Some(shared.clone())); + let module = CachedModule { + code: "export const x = 1;".into(), + ..Default::default() + }; + let key = cache.disk_key(&module_key(&source_hash(b"src"), "/src/a.ts", "dev")); + cache.put(&key, &module); + assert_eq!(cache.get(&key).as_ref(), Some(&module)); + std::fs::remove_dir_all(base.join("store")).unwrap(); + assert_eq!(cache.get(&key), None, "a removed store misses"); + let other = cache.disk_key(&module_key(&source_hash(b"src"), "/src/b.ts", "dev")); + cache.put(&other, &module); + assert_eq!(cache.get(&other).as_ref(), Some(&module)); + assert!(shared.is_dir(), "the write recreated the store"); + } } diff --git a/crates/oj_cache/src/start_bundle/memo.rs b/crates/oj_cache/src/start_bundle/memo.rs index 357f2029e..a8cf5107a 100644 --- a/crates/oj_cache/src/start_bundle/memo.rs +++ b/crates/oj_cache/src/start_bundle/memo.rs @@ -1,8 +1,8 @@ // SPDX-License-Identifier: MIT // Copyright (c) 2026 Raphael Amorim -//! Per-generation (size, mtime) -> digest memo, so a restore rehashes only -//! closure files whose stat changed. +//! Per-root (size, mtime) -> digest memo, keyed by closure id, so a restore +//! rehashes only closure files whose stat changed. use serde::{Deserialize, Serialize}; use std::collections::HashMap; @@ -32,8 +32,8 @@ struct MemoFile { } /// An unparseable memo is deleted so the next write starts clean. -pub(super) fn read_memo(entry: &Path) -> Option { - let path = entry.join(MEMO_FILE); +pub(super) fn read_memo(dir: &Path) -> Option { + let path = dir.join(MEMO_FILE); let bytes = fs::read(&path).ok()?; match serde_json::from_slice(&bytes) { Ok(memo) => Some(memo), @@ -44,30 +44,32 @@ pub(super) fn read_memo(entry: &Path) -> Option { } } -pub(super) fn write_memo(entry: &Path, memo: &Memo) { +pub(super) fn write_memo(dir: &Path, memo: &Memo) { let Ok(bytes) = serde_json::to_vec(memo) else { return; }; - let _ = integrity::atomic_write(&entry.join(MEMO_FILE), &bytes); + // A cold worktree's first restore may be the first write to its dir. + let _ = fs::create_dir_all(dir); + let _ = integrity::atomic_write(&dir.join(MEMO_FILE), &bytes); } -/// The memo of a [`verified_digests`] pass: each file under the stat it had -/// before it was read. A stat taken after (once the persist's blob copies are -/// done) would pair an edit made meanwhile with the digest of the bytes -/// before it, and every later persist would take that digest as settled. -pub(super) fn build_memo(files: &[PathBuf], digests: &Digests) -> Memo { +/// The memo of a [`verified_digests`] pass: each file, by its closure id, +/// under the stat it had before it was read. A stat taken after (once the +/// persist's blob copies are done) would pair an edit made meanwhile with +/// the digest of the bytes before it, and every later persist would take +/// that digest as settled. +pub(super) fn build_memo(ids: &[String], digests: &Digests) -> Memo { let written_at_ns = digests.statted_at_ns; let mut map = HashMap::new(); - for ((path, digest), stat) in files.iter().zip(&digests.hashes).zip(&digests.stats) { - let (Some(digest), Some((size, mtime_ns)), Some(path)) = (digest, stat, path.to_str()) - else { + for ((id, digest), stat) in ids.iter().zip(&digests.hashes).zip(&digests.stats) { + let (Some(digest), Some((size, mtime_ns))) = (digest, stat) else { continue; }; if mtime_ns.saturating_add(MEMO_FRESHNESS_SLACK_NS) > written_at_ns { continue; } map.insert( - path.to_string(), + id.clone(), MemoFile { size: *size, mtime_ns: *mtime_ns, @@ -91,17 +93,19 @@ pub(super) struct Digests { pub(super) rehashed: usize, } -/// Digests for `files`, taken from the memo when size and mtime still match. -pub(super) fn verified_digests(files: &[PathBuf], memo: Option<&Memo>) -> Digests { +/// Digests for `files` (each named by the id in `ids`), taken from the memo +/// when size and mtime still match. +pub(super) fn verified_digests(files: &[PathBuf], ids: &[String], memo: Option<&Memo>) -> Digests { let statted_at_ns = now_ns(); let rehashed = AtomicUsize::new(0); - let both = par_map(files, |p| { + let pairs: Vec<(&PathBuf, &String)> = files.iter().zip(ids).collect(); + let both = par_map(&pairs, |&(p, id)| { let stat = fs::metadata(p) .ok() .and_then(|meta| Some((meta.len(), mtime_ns(&meta)?))); if let Some(digest) = memo .zip(stat) - .and_then(|(m, stat)| memoized_digest(m, p, stat)) + .and_then(|(m, stat)| memoized_digest(m, id, stat)) { return Some((stat, Some(digest))); } @@ -141,8 +145,8 @@ impl Digests { } } -fn memoized_digest(memo: &Memo, p: &Path, (size, mtime_ns): (u64, u64)) -> Option { - let known = memo.files.get(p.to_str()?)?; +fn memoized_digest(memo: &Memo, id: &str, (size, mtime_ns): (u64, u64)) -> Option { + let known = memo.files.get(id)?; if size != known.size || mtime_ns != known.mtime_ns { return None; } diff --git a/crates/oj_cache/src/start_bundle/mod.rs b/crates/oj_cache/src/start_bundle/mod.rs index 5c112bdbb..67a9de220 100644 --- a/crates/oj_cache/src/start_bundle/mod.rs +++ b/crates/oj_cache/src/start_bundle/mod.rs @@ -4,12 +4,18 @@ //! The Start client-bundle store: generations keyed by the module closure, //! chunk bytes deduplicated in a content-addressed blob store, a `current` //! pointer, and pinning so a served bundle survives later eviction. +//! +//! Generations and blobs live in the shared oj store when there is one, so +//! worktree B restores the bundle worktree A built: closure keys and stored +//! closures are root-relative (`ws:`), and so are the stored globs. +//! `current` and the memo stay per-root; each root mirrors its `current` +//! into `pins/`, which every store's eviction honors. use serde::{Deserialize, Serialize}; -use std::collections::{BTreeMap, HashMap}; +use std::collections::{BTreeMap, HashMap, HashSet}; use std::fs; use std::path::{Path, PathBuf}; -use std::time::{Instant, SystemTime, UNIX_EPOCH}; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use crate::integrity::{self, ExpectedFile, VerifyMode}; @@ -20,7 +26,7 @@ mod prune; use epoch::epoch; pub use memo::MEMO_FRESHNESS_SLACK_NS; -use memo::{build_memo, read_memo, verified_digests, write_memo}; +use memo::{build_memo, read_memo, verified_digests, write_memo, Digests}; pub const START_BUNDLE_FORMAT: u32 = 6; pub const DEFAULT_PRUNE_BUDGET_BYTES: u64 = 1024 * 1024 * 1024; @@ -29,6 +35,12 @@ pub const DEFAULT_PRUNE_BUDGET_BYTES: u64 = 1024 * 1024 * 1024; /// recency window so reverting to a just-seen closure restores warm, while a /// long editing session cannot accumulate one generation per save. pub const KEEP_GENERATIONS: usize = 8; +/// The shared store serves every worktree and app on the machine, so its +/// generation window is wider than a single app's. +pub const SHARED_KEEP_GENERATIONS: usize = 32; +/// Cold-worktree probe: with no per-root `current`, try this many of the most +/// recently used shared generations' closures as key predictions. +const PROBE_CANDIDATES: usize = 4; /// glob-scopes.json is the generation's `import.meta.glob` calls, which a /// restore re-expands (see [`StartBundleStore::restore`]). @@ -45,6 +57,16 @@ const CLOSURE_FILE: &str = "closure.json"; const MEMO_FILE: &str = "memo.json"; const MANIFEST_FILE: &str = "manifest.json"; const CURRENT_FILE: &str = "current"; +/// Per-root pin files inside the shared dir: `pins/` names the +/// generation that root currently serves, so one worktree's eviction can +/// never delete blobs another running server reads live. +const PINS_DIR: &str = "pins"; +/// A pin whose file has not been refreshed for this long belongs to a +/// worktree that is gone (deleted checkout, abandoned sandbox): eviction may +/// ignore it, and the next prune removes the pin file itself. +const PIN_MAX_AGE: Duration = Duration::from_secs(7 * 24 * 60 * 60); +/// What an in-root glob pattern's root prefix is stored as. +const GLOB_ROOT_TOKEN: &str = "\0ws/"; const LEGACY_POINTER_FILE: &str = "latest"; const TOUCH_FILE: &str = "last-used"; const BLOBS_DIR: &str = "blobs"; @@ -53,6 +75,16 @@ const CHUNK_INDEX_FILE: &str = "client-chunks.json"; const CSS_URLS_FILE: &str = "css-urls.json"; pub struct StartBundleStore { + /// The canonical root: closure ids relativize against it. + root: PathBuf, + /// The root as the caller spells it, which the bundle's glob patterns use. + root_spelled: PathBuf, + /// Per-root pointer state: `current` and `memo.json`. Never shared. + local: PathBuf, + /// This root's pin file name in the shared dir (hash of the canonical root). + pin_id: String, + keep_generations: usize, + /// Generation entries and blobs (the shared store's, when there is one). dir: PathBuf, salt: String, verify: VerifyMode, @@ -160,6 +192,11 @@ impl PinnedBundle { #[serde(rename_all = "camelCase")] struct GenerationManifest { format: u32, + /// The store salt this generation was keyed under (see + /// [`StartBundleStore::salt_id`]): the cold probe tries only the + /// generations a key of this store could name. + #[serde(default)] + salt_id: String, entry: String, css_urls: Vec, files: BTreeMap, @@ -260,8 +297,39 @@ impl StartBundleStore { /// import.meta.env, so `oj dev --mode staging` must not restore a bundle /// built for `development` (or the other way round). pub fn for_mode(root: &Path, tool_version: &str, verify: VerifyMode, mode: &str) -> Self { + let local = crate::cache_root(root).join("start-bundle"); + let (dir, keep) = match crate::store::store_root() { + Some(store) => (store.join("start-bundle"), SHARED_KEEP_GENERATIONS), + None => (local.clone(), KEEP_GENERATIONS), + }; + Self::at_dirs(root, dir, local, keep, tool_version, verify, mode) + } + + /// The explicit layout `for_mode` resolves into: generation entries and + /// blobs at `dir` (shareable), `current` and the memo at `local` + /// (per-root). Tests and embedders that must not touch the user's shared + /// store build through this. + pub fn at_dirs( + root: &Path, + dir: PathBuf, + local: PathBuf, + keep_generations: usize, + tool_version: &str, + verify: VerifyMode, + mode: &str, + ) -> Self { + // Canonical, so rolldown's realpath ids and macOS /var symlink + // spellings both relativize. + let root_canon = fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf()); + let pin_id = + blake3::hash(root_canon.as_os_str().as_encoded_bytes()).to_hex()[..16].to_string(); Self { - dir: crate::cache_root(root).join("start-bundle"), + root: root_canon, + root_spelled: root.to_path_buf(), + local, + pin_id, + keep_generations, + dir, salt: format!( "{tool_version}:{START_BUNDLE_FORMAT}:start-bundle:{mode}:{}", epoch(root, mode) @@ -273,11 +341,13 @@ impl StartBundleStore { /// This store with the contents of `files` in its key: inputs of the /// bundle that no closure lists (a missing one keys as missing). A - /// generation built from other contents is then no restore's match. + /// generation built from other contents is then no restore's match. The + /// files are named by their closure id (root-relative under the root), + /// so two worktrees with the same inputs key the same. pub fn keyed_by_files(mut self, files: &[PathBuf]) -> Self { let mut hasher = blake3::Hasher::new(); for file in files { - hasher.update(file.as_os_str().as_encoded_bytes()); + hasher.update(self.closure_id(file).as_bytes()); match fs::read(file) { Ok(bytes) => { hasher.update(&[1]); @@ -305,38 +375,121 @@ impl StartBundleStore { self } + /// Keeps `bytes` as `name` with the generation `key`: state a caller + /// derives from that bundle (the StyleX rules its modules compiled to) + /// travels with it to every worktree that restores it. False when there + /// is no such generation (or `name` is not a plain file name). + pub fn attach(&self, key: &str, name: &str, bytes: &[u8]) -> bool { + self.attachment_path(key, name) + .is_some_and(|path| integrity::atomic_write(&path, bytes).is_ok()) + } + + /// What [`Self::attach`] kept as `name` with the generation `key`. + pub fn attachment(&self, key: &str, name: &str) -> Option> { + fs::read(self.attachment_path(key, name)?).ok() + } + + fn attachment_path(&self, key: &str, name: &str) -> Option { + let plain = |s: &str| { + !s.is_empty() + && s.bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.')) + && !s.starts_with('.') + }; + let entry = self.dir.join(key); + (plain(key) && plain(name) && entry.is_dir()).then(|| entry.join(format!("attach-{name}"))) + } + + /// Folds `extra` into the key salt: bundle inputs only the caller knows. + /// Hash them worktree-independently, or nothing is shared. + pub fn with_extra_salt(mut self, extra: &[u8]) -> Self { + self.salt.push(':'); + self.salt.push_str(&blake3::hash(extra).to_hex()); + self + } + /// The generation `current` names, when its closure still hashes to a /// stored key. The key covers every file the bundle read, but a file an /// `import.meta.glob` would expand to now and the bundle never read (one /// added while no server watched) is in no closure: `glob_members` maps - /// the generation's glob-scopes.json to the files its calls expand to - /// today, and any one outside the closure is a miss, as Vite expands - /// every glob anew on each start. + /// the generation's glob-scopes.json (rehomed onto this root) to the + /// files its calls expand to today, and any one outside the closure is a + /// miss, as Vite expands every glob anew on each start. + /// + /// A cold worktree has no `current`, so the most recently used shared + /// generations stand in as predictions: their closures are root-relative, + /// so this worktree's own files decide whether one holds. pub fn restore( &self, start_dir: &Path, - glob_members: impl Fn(&Path) -> Vec, + glob_members: impl Fn(&str) -> Vec, ) -> Result<(RestoreStats, PinnedBundle), Miss> { let started = Instant::now(); - let current = read_current(&self.dir).ok_or(Miss::NoPreviousBuild)?; - let current_dir = self.dir.join(¤t); - let Some(files) = read_closure(¤t_dir.join(CLOSURE_FILE)) else { - let _ = fs::remove_dir_all(¤t_dir); + let predictions: Vec<(String, bool)> = match read_current(&self.local) { + Some(current) => vec![(current, true)], + None => self + .recent_generation_keys(PROBE_CANDIDATES) + .into_iter() + .map(|k| (k, false)) + .collect(), + }; + let mut last = Miss::NoPreviousBuild; + for (candidate, own) in predictions { + match self.restore_candidate(start_dir, &candidate, own, &glob_members) { + Ok((key, files, digests, manifest)) => { + // Always rewritten: the pin file's freshness is what + // protects this generation's blobs from another + // worktree's eviction. + self.write_current(&key); + let stats = RestoreStats { + key, + files: files.len(), + chunks: manifest.files.len(), + rehashed: digests.rehashed, + elapsed_ms: started.elapsed().as_millis(), + inputs: digests.inputs(&files), + }; + return Ok((stats, self.pin(&manifest))); + } + Err(miss) if own => return Err(miss), + Err(miss) => last = miss, + } + } + Err(last) + } + + /// One prediction: the generation `candidate`'s closure, rehomed and + /// hashed here, must name a stored entry. + fn restore_candidate( + &self, + start_dir: &Path, + candidate: &str, + own: bool, + glob_members: &impl Fn(&str) -> Vec, + ) -> Result<(String, Vec, Digests, GenerationManifest), Miss> { + let candidate_dir = self.dir.join(candidate); + let Some((ids, files)) = self.read_closure_rehomed(&candidate_dir.join(CLOSURE_FILE)) + else { + // Only this root's own generation is known broken; a probed one + // may just be from a store another oj writes. + if own { + let _ = fs::remove_dir_all(&candidate_dir); + } return Err(Miss::ClosureUnreadable); }; - let read: std::collections::HashSet<&Path> = files.iter().map(PathBuf::as_path).collect(); - if let Some(added) = glob_members(¤t_dir.join(GLOB_SCOPES_FILE)) - .into_iter() - .find(|f| { - !read.contains(f.as_path()) - && fs::canonicalize(f).map_or(true, |real| !read.contains(real.as_path())) - }) - { + let stored_globs = fs::read_to_string(candidate_dir.join(GLOB_SCOPES_FILE)) + .unwrap_or_else(|_| "[]".into()); + let globs = self.rehome_globs(&stored_globs); + let read: HashSet<&Path> = files.iter().map(PathBuf::as_path).collect(); + if let Some(added) = glob_members(&globs).into_iter().find(|f| { + !read.contains(f.as_path()) + && fs::canonicalize(f).map_or(true, |real| !read.contains(real.as_path())) + }) { return Err(Miss::GlobGrew(added)); } - let memo = read_memo(¤t_dir); - let digests = verified_digests(&files, memo.as_ref()); - let key = self.key_from(&files, &digests.hashes)?; + let memo = read_memo(&self.local); + let digests = verified_digests(&files, &ids, memo.as_ref()); + let key = self.key_from(&files, &ids, &digests.hashes, globs_pin_root(&stored_globs))?; let entry = self.dir.join(&key); if !entry.is_dir() { return Err(Miss::NoEntryForKey(key)); @@ -349,23 +502,14 @@ impl StartBundleStore { let _ = fs::remove_dir_all(&entry); return Err(Miss::ChunkCorrupt { key, name, detail }); } - restore_artifacts(&entry, start_dir, &manifest, &key)?; - if digests.rehashed > 0 || !entry.join(MEMO_FILE).is_file() { - write_memo(&entry, &build_memo(&files, &digests)); + restore_artifacts(&entry, start_dir, &manifest, &key, &globs)?; + restore_build_view(start_dir, &manifest, &files) + .map_err(|_| Miss::ArtifactWriteFailed(CHUNK_INDEX_FILE.to_string()))?; + if digests.rehashed > 0 || !self.local.join(MEMO_FILE).is_file() { + write_memo(&self.local, &build_memo(&ids, &digests)); } touch(&entry); - if key != current { - self.write_current(&key); - } - let stats = RestoreStats { - key, - files: files.len(), - chunks: manifest.files.len(), - rehashed: digests.rehashed, - elapsed_ms: started.elapsed().as_millis(), - inputs: digests.inputs(&files), - }; - Ok((stats, self.pin(&manifest))) + Ok((key, files, digests, manifest)) } fn pin(&self, manifest: &GenerationManifest) -> PinnedBundle { @@ -424,28 +568,210 @@ impl StartBundleStore { Ok(()) } + /// The closure's hash under the store salt. Files key by their + /// worktree-independent id, so two worktrees with the same content + /// compute one key; `pin_root` (a generation whose globs reach outside + /// the root) mixes the root in, keeping that generation to this root. fn key_from( &self, files: &[PathBuf], + ids: &[String], digests: &[Option], + pin_root: bool, ) -> Result { let mut hasher = blake3::Hasher::new(); hasher.update(self.salt.as_bytes()); - for (path, digest) in files.iter().zip(digests) { + if pin_root { + hasher.update(b"\0root="); + hasher.update(self.root.as_os_str().as_encoded_bytes()); + } + for ((path, id), digest) in files.iter().zip(ids).zip(digests) { let Some(digest) = digest else { return Err(Miss::ClosureFileUnreadable(path.clone())); }; hasher.update(&[0]); - hasher.update(path.as_os_str().as_encoded_bytes()); + hasher.update(id.as_bytes()); hasher.update(&[0]); hasher.update(digest.as_bytes()); } Ok(hasher.finalize().to_hex().to_string()) } + /// The worktree-independent identity of a closure file: `ws:` under + /// the (canonical) root, the canonical absolute path otherwise. It keys + /// the bundle hash, the stored closure and the memo alike. + fn closure_id(&self, path: &Path) -> String { + let canon = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()); + match crate::store::rel_key(&self.root, &canon) { + Some(rel) => format!("ws:{rel}"), + None => canon.to_string_lossy().into_owned(), + } + } + + /// A stored closure, rehomed against this root: the ids stay the + /// identity, the paths are where this checkout reads the bytes. + fn read_closure_rehomed(&self, path: &Path) -> Option<(Vec, Vec)> { + let bytes = fs::read(path).ok()?; + let mut ids: Vec = serde_json::from_slice(&bytes).ok()?; + if ids.is_empty() { + return None; + } + ids.sort(); + ids.dedup(); + let files = ids + .iter() + .map(|id| match id.strip_prefix("ws:") { + Some(rel) => self.root.join(rel), + None => PathBuf::from(id), + }) + .collect(); + Some((ids, files)) + } + + /// glob-scopes.json as stored: every pattern's root prefix (either + /// spelling) becomes [`GLOB_ROOT_TOKEN`]. + fn relocate_globs(&self, json: &str) -> String { + let roots: Vec = [&self.root_spelled, &self.root] + .iter() + .map(|r| format!("{}/", r.display())) + .collect(); + map_glob_strings(json, |s| { + let (neg, body) = s.strip_prefix('!').map_or(("", s), |b| ("!", b)); + match roots.iter().find_map(|r| body.strip_prefix(r.as_str())) { + Some(rest) => format!("{neg}{GLOB_ROOT_TOKEN}{rest}"), + None => s.to_string(), + } + }) + } + + /// A stored glob-scopes.json with this root put back in. + fn rehome_globs(&self, json: &str) -> String { + let root = format!("{}/", self.root_spelled.display()); + map_glob_strings(json, |s| s.replacen(GLOB_ROOT_TOKEN, &root, 1)) + } + fn write_current(&self, key: &str) { - let _ = integrity::atomic_write(&self.dir.join(CURRENT_FILE), key.as_bytes()); + let _ = fs::create_dir_all(&self.local); + let _ = integrity::atomic_write(&self.local.join(CURRENT_FILE), key.as_bytes()); + // The pin mirrors `current` into the shared dir, where every store's + // eviction sees it; rewritten, not touched, so its mtime is its + // freshness. + let pins = self.dir.join(PINS_DIR); + let _ = fs::create_dir_all(&pins); + let _ = integrity::atomic_write(&pins.join(&self.pin_id), key.as_bytes()); + } + + /// Generation keys eviction must not remove: this root's `current` plus + /// every fresh pin. A pin older than [`PIN_MAX_AGE`] belongs to a dead + /// worktree and is deleted instead of honored. + fn protected_keys(&self) -> HashSet { + let mut keys: HashSet = read_current(&self.local).into_iter().collect(); + let Ok(entries) = fs::read_dir(self.dir.join(PINS_DIR)) else { + return keys; + }; + for e in entries.flatten() { + let stale = e + .metadata() + .and_then(|m| m.modified()) + .ok() + .and_then(|m| m.elapsed().ok()) + .is_some_and(|age| age > PIN_MAX_AGE); + if stale { + let _ = fs::remove_file(e.path()); + } else if let Ok(key) = fs::read_to_string(e.path()) { + keys.insert(key.trim().to_string()); + } + } + keys + } + + /// Whether a fresh pin of another root names `key`: that root serves the + /// generation from its blobs right now. + fn pinned_by_another_root(&self, key: &str) -> bool { + let Ok(entries) = fs::read_dir(self.dir.join(PINS_DIR)) else { + return false; + }; + entries.flatten().any(|e| { + e.file_name().to_string_lossy() != self.pin_id + && e.metadata() + .and_then(|m| m.modified()) + .ok() + .and_then(|m| m.elapsed().ok()) + .is_some_and(|age| age <= PIN_MAX_AGE) + && fs::read_to_string(e.path()).is_ok_and(|k| k.trim() == key) + }) + } + + /// A short digest of this store's salt, what every key of this store + /// hashes under: a generation of another app, mode, tool version or + /// config (the shared dir holds them all) is told apart by it before + /// its closure is hashed. + fn salt_id(&self) -> String { + blake3::hash(self.salt.as_bytes()).to_hex()[..16].to_string() } + + /// The most recently used generations under this store's salt, newest + /// first, for the cold probe. One under another salt can never match a + /// key of this store, and would only take a candidate's place. + fn recent_generation_keys(&self, cap: usize) -> Vec { + let Ok(entries) = fs::read_dir(&self.dir) else { + return Vec::new(); + }; + let salt_id = self.salt_id(); + let mut gens: Vec<(SystemTime, String)> = entries + .flatten() + .filter(is_generation_dir) + .map(|e| { + ( + prune::generation_stamp(&e.path()), + e.file_name().to_string_lossy().into_owned(), + ) + }) + .collect(); + gens.sort_by_key(|(stamp, _)| std::cmp::Reverse(*stamp)); + gens.into_iter() + .map(|(_, k)| k) + .filter(|k| read_manifest(&self.dir.join(k)).is_some_and(|m| m.salt_id == salt_id)) + .take(cap) + .collect() + } +} + +/// A generation dir: anything in the store dir but the blob store, the pins +/// and `.tmp-` staging. +fn is_generation_dir(e: &fs::DirEntry) -> bool { + let name = e.file_name(); + let name = name.to_string_lossy(); + name != BLOBS_DIR && name != PINS_DIR && !name.starts_with(".tmp-") && e.path().is_dir() +} + +/// Whether stored globs still name an absolute path (a pattern outside the +/// root), which pins the generation to the root that built it. +fn globs_pin_root(stored: &str) -> bool { + let mut absolute = false; + map_glob_strings(stored, |s| { + absolute |= s.trim_start_matches('!').starts_with('/'); + s.to_string() + }); + absolute +} + +/// glob-scopes.json with every string inside `patterns` mapped. Anything +/// unparseable passes through as is (the restore treats it as no globs). +fn map_glob_strings(json: &str, mut f: impl FnMut(&str) -> String) -> String { + let Ok(mut calls) = serde_json::from_str::>(json) else { + return json.to_string(); + }; + for call in &mut calls { + if let Some(patterns) = call.get_mut("patterns").and_then(|p| p.as_array_mut()) { + for p in patterns { + if let Some(s) = p.as_str() { + *p = serde_json::Value::String(f(s)); + } + } + } + } + serde_json::to_string(&calls).unwrap_or_else(|_| json.to_string()) } /// Copies the generation's artifacts and css urls into the build dir. A @@ -455,11 +781,16 @@ fn restore_artifacts( start_dir: &Path, manifest: &GenerationManifest, key: &str, + globs: &str, ) -> Result<(), Miss> { - // The closure list too: the dev server's rebundle gate reads it, and the - // restored bundle's own inputs are the ones that can move under it. - for name in ARTIFACTS.into_iter().chain([CLOSURE_FILE]) { - let Ok(bytes) = fs::read(entry.join(name)) else { + // The closure list is written by `restore_build_view`, rehomed onto this + // root; the stored globs come rehomed too. + for name in ARTIFACTS { + let bytes = match name { + GLOB_SCOPES_FILE => Ok(globs.as_bytes().to_vec()), + _ => fs::read(entry.join(name)), + }; + let Ok(bytes) = bytes else { let _ = fs::remove_dir_all(entry); return Err(Miss::EntryCorrupt(key.to_string())); }; @@ -474,6 +805,37 @@ fn restore_artifacts( Ok(()) } +/// The small files a fresh bundle leaves in the build dir besides the +/// artifacts: the chunk index and the closure, rehomed onto this root. A +/// restore from the shared store lands in a build dir that never built, so +/// without them the dev rebundle gate has no closure to consult. The chunks +/// themselves stay in the blob store, served from there (no per-boot copy +/// of the chunk set; see [`StartBundleStore::restore`]). +fn restore_build_view( + start_dir: &Path, + manifest: &GenerationManifest, + files: &[PathBuf], +) -> std::io::Result<()> { + let index: Vec = manifest + .files + .iter() + .map(|(name, f)| serde_json::json!({ "name": name, "size": f.size })) + .collect(); + let index = serde_json::json!({ "entry": manifest.entry, "files": index }); + integrity::atomic_write( + &start_dir.join(CHUNK_INDEX_FILE), + index.to_string().as_bytes(), + )?; + let closure: Vec = files + .iter() + .map(|f| f.to_string_lossy().into_owned()) + .collect(); + integrity::atomic_write( + &start_dir.join(CLOSURE_FILE), + &serde_json::to_vec(&closure).unwrap_or_default(), + ) +} + /// The trimmed generation key `current` points at. fn read_current(dir: &Path) -> Option { fs::read_to_string(dir.join(CURRENT_FILE)) diff --git a/crates/oj_cache/src/start_bundle/persist.rs b/crates/oj_cache/src/start_bundle/persist.rs index a62afc71f..5f9bcaf69 100644 --- a/crates/oj_cache/src/start_bundle/persist.rs +++ b/crates/oj_cache/src/start_bundle/persist.rs @@ -7,10 +7,9 @@ use std::path::{Path, PathBuf}; use super::memo::{build_memo, read_memo, verified_digests, write_memo}; use super::{ - hash_file, par_map, read_chunk_index, read_closure, read_css_urls, read_current, read_manifest, - touch, ChunkIndexFile, GenerationManifest, ManifestFile, PinnedBundle, StartBundleStore, - ARTIFACTS, BLOBS_DIR, CHUNKS_DIR, CLOSURE_FILE, KEEP_GENERATIONS, MANIFEST_FILE, - START_BUNDLE_FORMAT, + hash_file, par_map, read_chunk_index, read_closure, read_css_urls, read_manifest, touch, + ChunkIndexFile, GenerationManifest, ManifestFile, PinnedBundle, StartBundleStore, ARTIFACTS, + BLOBS_DIR, CHUNKS_DIR, CLOSURE_FILE, GLOB_SCOPES_FILE, MANIFEST_FILE, START_BUNDLE_FORMAT, }; impl StartBundleStore { @@ -30,13 +29,28 @@ impl StartBundleStore { start_dir: &Path, as_built: impl FnOnce() -> bool, ) -> Option<(String, PinnedBundle)> { - let files = read_closure(&start_dir.join(CLOSURE_FILE))?; - // A dev rebundle persists after every edit: files the current - // generation's memo still vouches for (same size and mtime, settled - // past its freshness window) keep their digest unread. - let memo = read_current(&self.dir).and_then(|key| read_memo(&self.dir.join(key))); - let digests = verified_digests(&files, memo.as_ref()); - let key = self.key_from(&files, &digests.hashes).ok()?; + // Ordered and deduplicated by id, exactly as a restore reads the + // stored closure back: a file outside the root (a symlinked package) + // ids by its canonical path, which sorts apart from its in-root + // spelling, and two spellings of one file are one id. + let mut pairs: Vec<(String, PathBuf)> = read_closure(&start_dir.join(CLOSURE_FILE))? + .into_iter() + .map(|p| (self.closure_id(&p), p)) + .collect(); + pairs.sort_by(|a, b| a.0.cmp(&b.0)); + pairs.dedup_by(|a, b| a.0 == b.0); + let (ids, files): (Vec, Vec) = pairs.into_iter().unzip(); + // A dev rebundle persists after every edit: files this root's memo + // still vouches for (same size and mtime, settled past its freshness + // window) keep their digest unread. + let memo = read_memo(&self.local); + let digests = verified_digests(&files, &ids, memo.as_ref()); + let globs = + self.relocate_globs(&fs::read_to_string(start_dir.join(GLOB_SCOPES_FILE)).ok()?); + let pin_root = super::globs_pin_root(&globs); + let key = self + .key_from(&files, &ids, &digests.hashes, pin_root) + .ok()?; if !as_built() { return None; } @@ -47,6 +61,7 @@ impl StartBundleStore { let manifest_files = store_chunk_blobs(&index.files, &chunk_dir, &blobs)?; let manifest = GenerationManifest { format: START_BUNDLE_FORMAT, + salt_id: self.salt_id(), entry: index.entry, css_urls, files: manifest_files, @@ -58,6 +73,14 @@ impl StartBundleStore { // Renamed aside before it is deleted: a restore in another process // finds the generation whole or not at all. if entry.is_dir() && read_manifest(&entry).as_ref() != Some(&manifest) { + // Another root serves the stored generation live, from its blobs: + // replacing it would sweep the chunks from under that server. This + // build serves from its own dir; the next boot restores the stored + // one, built from the same sources. + if self.pinned_by_another_root(&key) { + self.write_current(&key); + return PinnedBundle::from_build_dir(start_dir).map(|pinned| (key, pinned)); + } let aside = self.dir.join(format!( ".tmp-replaced-{}-{}", key.get(..16)?, @@ -70,15 +93,15 @@ impl StartBundleStore { let _ = fs::remove_dir_all(&aside); } if !entry.is_dir() { - self.commit_generation(start_dir, &key, &manifest, &entry)?; + self.commit_generation(start_dir, &key, &manifest, &entry, &ids, &globs)?; } - write_memo(&entry, &build_memo(&files, &digests)); + write_memo(&self.local, &build_memo(&ids, &digests)); touch(&entry); self.write_current(&key); // Enforce the window at write time like Vite's dep-cache commit: // constant work here, deletion and blob accounting in the background. // The full budget prune stays a boot-only pass. - self.enforce_window(KEEP_GENERATIONS); + self.enforce_window(self.keep_generations); // Another instance's prune can sweep a blob this persist dedup-skipped, // between the existence check and the generation rename (its scan saw // no generation referencing it yet). The chunk sources are still in @@ -98,23 +121,32 @@ impl StartBundleStore { /// Stages the generation dir under `.tmp-` and renames it into place. A /// failed rename is fine when a racing writer committed the same key. + /// The closure is stored as ids and the globs relocated, so the entry + /// means the same in every worktree. fn commit_generation( &self, start_dir: &Path, key: &str, manifest: &GenerationManifest, entry: &Path, + ids: &[String], + globs: &str, ) -> Option<()> { let tmp = self .dir .join(format!(".tmp-{}-{}", key.get(..16)?, std::process::id())); let _ = fs::remove_dir_all(&tmp); fs::create_dir_all(&tmp).ok()?; - for name in ARTIFACTS.into_iter().chain([CLOSURE_FILE]) { - if fs::copy(start_dir.join(name), tmp.join(name)).is_err() { - let _ = fs::remove_dir_all(&tmp); - return None; - } + let staged = ARTIFACTS + .into_iter() + .filter(|name| *name != GLOB_SCOPES_FILE) + .all(|name| fs::copy(start_dir.join(name), tmp.join(name)).is_ok()) + && fs::write(tmp.join(GLOB_SCOPES_FILE), globs).is_ok() + && serde_json::to_vec(ids) + .is_ok_and(|bytes| fs::write(tmp.join(CLOSURE_FILE), bytes).is_ok()); + if !staged { + let _ = fs::remove_dir_all(&tmp); + return None; } let bytes = serde_json::to_vec(manifest).ok()?; if fs::write(tmp.join(MANIFEST_FILE), bytes).is_err() { diff --git a/crates/oj_cache/src/start_bundle/prune.rs b/crates/oj_cache/src/start_bundle/prune.rs index 6669a3fd4..9d1b6356d 100644 --- a/crates/oj_cache/src/start_bundle/prune.rs +++ b/crates/oj_cache/src/start_bundle/prune.rs @@ -2,9 +2,9 @@ // Copyright (c) 2026 Raphael Amorim //! Eviction: the save-path generation window (background) and the boot-time -//! budget prune. Both evict oldest-first by last-use stamp, never touch the -//! `current` generation, and only delete blobs no surviving generation -//! references. +//! budget prune. Both evict oldest-first by last-use stamp, never touch a +//! protected generation (this root's `current`, any root's fresh pin), and +//! only delete blobs no surviving generation references. use std::collections::{HashMap, HashSet}; use std::fs; @@ -12,8 +12,8 @@ use std::path::{Path, PathBuf}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use super::{ - entry_size, read_current, read_manifest, StartBundleStore, BLOBS_DIR, KEEP_GENERATIONS, - LEGACY_POINTER_FILE, TOUCH_FILE, + entry_size, is_generation_dir, read_manifest, StartBundleStore, BLOBS_DIR, LEGACY_POINTER_FILE, + PINS_DIR, TOUCH_FILE, }; /// A `.tmp-` entry younger than this is presumed live (a persist mid-copy, @@ -30,7 +30,7 @@ fn tmp_is_stale(path: &Path) -> bool { } /// Last-use time of a generation: its touch file, else the dir's own mtime. -fn generation_stamp(path: &Path) -> SystemTime { +pub(super) fn generation_stamp(path: &Path) -> SystemTime { fs::metadata(path.join(TOUCH_FILE)) .or_else(|_| fs::metadata(path)) .and_then(|m| m.modified()) @@ -46,13 +46,13 @@ fn manifest_hashes(entry: &Path) -> Vec { impl StartBundleStore { pub fn prune(&self, budget_bytes: u64) { - self.prune_with(budget_bytes, KEEP_GENERATIONS) + self.prune_with(budget_bytes, self.keep_generations) } /// The save-path half of eviction. Like Vite's dep-cache commit (rename + /// background rm), but the whole pass (listing, renames-aside, blob /// sweep) runs on a detached thread so the save path pays one spawn. - /// Safe because: it never touches `current`, a mid-sweep crash strands + /// Safe because: it never touches a protected generation, a mid-sweep crash strands /// only `.tmp-` dirs the boot prune age-gates away, and a sweep racing the /// next persist is covered by persist's post-commit blob re-check. Each /// thread joins its predecessor first, so sweeps never stack and @@ -60,11 +60,12 @@ impl StartBundleStore { pub(super) fn enforce_window(&self, max_generations: usize) { let prev = self.sweeper.lock().ok().and_then(|mut s| s.take()); let dir = self.dir.clone(); + let protected = self.protected_keys(); let handle = std::thread::spawn(move || { if let Some(prev) = prev { let _ = prev.join(); } - enforce_window_blocking(&dir, max_generations); + enforce_window_blocking(&dir, max_generations, &protected); }); if let Ok(mut slot) = self.sweeper.lock() { *slot = Some(handle); @@ -80,15 +81,15 @@ impl StartBundleStore { } /// Boot-time prune: sweeps stale `.tmp-` leftovers, evicts the oldest - /// non-current generations until both the byte budget and the window + /// unprotected generations until both the byte budget and the window /// hold, then deletes every blob no remaining generation references. fn prune_with(&self, budget_bytes: u64, max_generations: usize) { let _ = fs::remove_file(self.dir.join(LEGACY_POINTER_FILE)); let Ok(entries) = fs::read_dir(&self.dir) else { return; }; - let keep = read_current(&self.dir).unwrap_or_default(); - let mut gens = scan_generations(entries, &keep); + let protected = self.protected_keys(); + let mut gens = scan_generations(entries, &protected); let blobs_dir = self.dir.join(BLOBS_DIR); let blob_sizes = scan_blobs(&blobs_dir); let mut refcount: HashMap = HashMap::new(); @@ -109,9 +110,10 @@ impl StartBundleStore { .filter(|&(_, c)| c > 0) .map(|(h, _)| h) .collect(); - // `current` may have moved since the scan (a concurrent persist). - if let Some(now_current) = read_current(&self.dir) { - live.extend(manifest_hashes(&self.dir.join(now_current))); + // Protection may have moved since the scan (a concurrent persist or + // another root's restore). + for key in self.protected_keys() { + live.extend(manifest_hashes(&self.dir.join(key))); } for hash in blob_sizes.keys() { if !live.contains(hash) { @@ -126,16 +128,16 @@ struct Generation { stamp: SystemTime, own_size: u64, refs: Vec, - is_current: bool, + protected: bool, } /// Lists generation dirs, deleting stale `.tmp-` dirs along the way. -fn scan_generations(entries: fs::ReadDir, keep: &str) -> Vec { +fn scan_generations(entries: fs::ReadDir, protected: &HashSet) -> Vec { let mut gens = Vec::new(); for e in entries.flatten() { let path = e.path(); let name = e.file_name().to_string_lossy().into_owned(); - if name == BLOBS_DIR || !path.is_dir() { + if name == BLOBS_DIR || name == PINS_DIR || !path.is_dir() { continue; } if name.starts_with(".tmp-") { @@ -148,7 +150,7 @@ fn scan_generations(entries: fs::ReadDir, keep: &str) -> Vec { let stamp = generation_stamp(&path); gens.push(Generation { own_size: entry_size(&path), - is_current: name == keep, + protected: protected.contains(&name), path, stamp, refs, @@ -177,7 +179,7 @@ fn scan_blobs(blobs_dir: &Path) -> HashMap { blob_sizes } -/// Removes generations oldest-first (skipping current) until the total size +/// Removes generations oldest-first (skipping protected ones) until the total size /// (generation dirs plus referenced blobs) fits the budget and at most /// `max_generations` remain. Decrements `refcount` for each eviction. fn evict_oldest( @@ -199,7 +201,7 @@ fn evict_oldest( if total <= budget_bytes && kept <= max_generations { break; } - if g.is_current { + if g.protected { continue; } // A dir already gone (another process's prune won the race) is an @@ -222,13 +224,12 @@ fn evict_oldest( } } -fn enforce_window_blocking(dir: &Path, max_generations: usize) { - let keep = read_current(dir).unwrap_or_default(); - let evicted = rename_aside_overflow(dir, &keep, max_generations); +fn enforce_window_blocking(dir: &Path, max_generations: usize, protected: &HashSet) { + let evicted = rename_aside_overflow(dir, protected, max_generations); if evicted.is_empty() { return; } - // Blobs still referenced by a surviving generation (or current) stay; + // Blobs still referenced by a surviving generation stay; // everything the evicted generations uniquely owned goes. let live = live_blob_hashes(dir); let blobs = dir.join(BLOBS_DIR); @@ -243,22 +244,30 @@ fn enforce_window_blocking(dir: &Path, max_generations: usize) { } /// Renames the oldest generations beyond the window to `.tmp-evict-` dirs -/// and returns them. `current` is never a candidate. -fn rename_aside_overflow(dir: &Path, keep: &str, max_generations: usize) -> Vec { +/// and returns them. A protected generation is never a candidate. +fn rename_aside_overflow( + dir: &Path, + protected: &HashSet, + max_generations: usize, +) -> Vec { let Ok(entries) = fs::read_dir(dir) else { return Vec::new(); }; let mut gens: Vec<(SystemTime, PathBuf)> = Vec::new(); + let mut kept = 0; for e in entries.flatten() { - let name = e.file_name().to_string_lossy().into_owned(); - let path = e.path(); - if name == BLOBS_DIR || name == keep || name.starts_with(".tmp-") || !path.is_dir() { + if !is_generation_dir(&e) { + continue; + } + if protected.contains(e.file_name().to_string_lossy().as_ref()) { + kept += 1; continue; } - gens.push((generation_stamp(&path), path)); + gens.push((generation_stamp(&e.path()), e.path())); } - // `keep` was skipped above, so the window is current + max-1 others. - let overflow = (gens.len() + 1).saturating_sub(max_generations); + // Protected generations count toward the window (at least one: the + // generation this persist just made current). + let overflow = (gens.len() + kept.max(1)).saturating_sub(max_generations); if overflow == 0 { return Vec::new(); } @@ -280,17 +289,12 @@ fn rename_aside_overflow(dir: &Path, keep: &str, max_generations: usize) -> Vec< evicted } -/// Every blob hash referenced by a generation dir (including current). +/// Every blob hash referenced by a generation dir (protected ones included). fn live_blob_hashes(dir: &Path) -> HashSet { let mut live = HashSet::new(); if let Ok(entries) = fs::read_dir(dir) { - for e in entries.flatten() { - let name = e.file_name().to_string_lossy().into_owned(); - let path = e.path(); - if name == BLOBS_DIR || name.starts_with(".tmp-") || !path.is_dir() { - continue; - } - live.extend(manifest_hashes(&path)); + for e in entries.flatten().filter(is_generation_dir) { + live.extend(manifest_hashes(&e.path())); } } live diff --git a/crates/oj_cache/src/start_bundle/tests.rs b/crates/oj_cache/src/start_bundle/tests.rs index 2ef99b9c1..b3acf7d0a 100644 --- a/crates/oj_cache/src/start_bundle/tests.rs +++ b/crates/oj_cache/src/start_bundle/tests.rs @@ -27,12 +27,33 @@ impl Fixture { fx } + /// The single-directory layout, pinned to fixture-local paths so no + /// test reaches the developer's real shared store. + fn store_with(&self, verify: VerifyMode, mode: &str) -> StartBundleStore { + let local = crate::cache_root(&self.root).join("start-bundle"); + StartBundleStore::at_dirs( + &self.root, + local.clone(), + local, + KEEP_GENERATIONS, + "0.0.1-test", + verify, + mode, + ) + } + fn store(&self) -> StartBundleStore { - StartBundleStore::new(&self.root, "0.0.1-test", VerifyMode::Standard) + self.store_with(VerifyMode::Standard, "development") } fn full_store(&self) -> StartBundleStore { - StartBundleStore::new(&self.root, "0.0.1-test", VerifyMode::Full) + self.store_with(VerifyMode::Full, "development") + } + + fn memo_path(&self) -> PathBuf { + crate::cache_root(&self.root) + .join("start-bundle") + .join(MEMO_FILE) } fn module(&self, name: &str) -> PathBuf { @@ -128,7 +149,7 @@ fn set_mtime(path: &Path, t: SystemTime) { f.set_times(fs::FileTimes::new().set_modified(t)).unwrap(); } -fn no_globs(_: &Path) -> Vec { +fn no_globs(_: &str) -> Vec { Vec::new() } @@ -146,8 +167,8 @@ fn a_file_new_to_a_bundled_glob_misses_the_restore() { fx.store().persist(&fx.start).unwrap(); fx.clear_start_dir(); let src = fx.root.join("src"); - let members = |scopes: &Path| { - assert!(fs::read_to_string(scopes).unwrap().contains("src/*.tsx")); + let members = |scopes: &str| { + assert!(scopes.contains("src/*.tsx")); let mut files: Vec = fs::read_dir(&src) .unwrap() .map(|e| e.unwrap().path()) @@ -157,8 +178,11 @@ fn a_file_new_to_a_bundled_glob_misses_the_restore() { }; assert!(fx.store().restore(&fx.start, members).is_ok()); assert_eq!( - fs::read_to_string(fx.start.join(GLOB_SCOPES_FILE)).unwrap(), - r#"[{"patterns":["src/*.tsx"]}]"#, + serde_json::from_str::( + &fs::read_to_string(fx.start.join(GLOB_SCOPES_FILE)).unwrap() + ) + .unwrap(), + serde_json::json!([{"patterns":["src/*.tsx"]}]), "the restore brings the calls back for the dev gate" ); fx.write_module("c.tsx", "export const c = 3;"); @@ -453,8 +477,17 @@ fn epoch_input_changes_the_key() { Err(Miss::NoEntryForKey(k)) => assert_ne!(k, key), other => panic!("expected key miss, got {other:?}"), } - let other_version = - StartBundleStore::new(&fx.root, "9.9.9", VerifyMode::Standard).persist(&fx.start); + let local = crate::cache_root(&fx.root).join("start-bundle"); + let other_version = StartBundleStore::at_dirs( + &fx.root, + local.clone(), + local, + KEEP_GENERATIONS, + "9.9.9", + VerifyMode::Standard, + "development", + ) + .persist(&fx.start); assert_ne!(other_version.unwrap().0, key, "tool version salts the key"); } @@ -491,9 +524,7 @@ fn files_outside_the_closure_key_the_generation_by_content() { #[test] fn dev_mode_and_its_env_file_change_the_key() { let fx = Fixture::new("mode"); - let staging = |root: &Path| { - StartBundleStore::for_mode(root, "0.0.1-test", VerifyMode::Standard, "staging") - }; + let staging = |_: &Path| fx.store_with(VerifyMode::Standard, "staging"); let (dev_key, _) = fx.store().persist(&fx.start).unwrap(); let (staging_key, _) = staging(&fx.root).persist(&fx.start).unwrap(); assert_ne!(staging_key, dev_key, "the mode salts the key"); @@ -655,6 +686,7 @@ fn persist_enforces_the_generation_window() { .filter(|e| { e.path().is_dir() && e.file_name() != "blobs" + && e.file_name() != "pins" && !e.file_name().to_string_lossy().starts_with(".tmp-") }) .count() @@ -763,14 +795,15 @@ fn an_edit_after_the_hash_is_rehashed_next_time() { let fx = Fixture::new("memo-edit-after-hash"); fx.settle_modules(); let files = vec![fx.module("a.tsx")]; - let digests = memo::verified_digests(&files, None); + let ids = vec!["ws:src/a.tsx".to_string()]; + let digests = memo::verified_digests(&files, &ids, None); fx.write_module("a.tsx", "export const a = 7;"); set_mtime( &fx.module("a.tsx"), SystemTime::now() - Duration::from_secs(60), ); - let memo = memo::build_memo(&files, &digests); - let again = memo::verified_digests(&files, Some(&memo)); + let memo = memo::build_memo(&ids, &digests); + let again = memo::verified_digests(&files, &ids, Some(&memo)); assert_eq!( again.rehashed, 1, "the memo vouched for the pre-edit digest" @@ -816,7 +849,7 @@ fn missing_memo_falls_back_to_full_hash_and_heals() { let fx = Fixture::new("memo-fallback"); fx.settle_modules(); let (key, _) = fx.store().persist(&fx.start).unwrap(); - let memo_path = fx.entry_dir(&key).join(MEMO_FILE); + let memo_path = fx.memo_path(); fs::remove_file(&memo_path).unwrap(); let (stats, _) = fx.store().restore(&fx.start, no_globs).unwrap(); assert_eq!(stats.key, key); @@ -831,9 +864,663 @@ fn corrupt_memo_is_dropped_and_falls_back() { let fx = Fixture::new("memo-corrupt"); fx.settle_modules(); let (key, _) = fx.store().persist(&fx.start).unwrap(); - let memo_path = fx.entry_dir(&key).join(MEMO_FILE); + let memo_path = fx.memo_path(); fs::write(&memo_path, b"{ not json").unwrap(); let (stats, _) = fx.store().restore(&fx.start, no_globs).unwrap(); assert_eq!(stats.key, key); assert_eq!(stats.rehashed, 2); } + +#[test] +fn identical_worktrees_compute_one_bundle_key() { + let a = Fixture::new("xwt-key-a"); + let b = Fixture::new("xwt-key-b"); + let (key_a, _) = a.store().persist(&a.start).unwrap(); + let (key_b, _) = b.store().persist(&b.start).unwrap(); + assert_eq!(key_a, key_b, "same content in two roots keys identically"); +} + +#[test] +fn an_edit_still_changes_the_key_across_worktrees() { + let a = Fixture::new("xwt-edit-a"); + let b = Fixture::new("xwt-edit-b"); + b.write_module("a.tsx", "export const a = 999;"); + let (key_a, _) = a.store().persist(&a.start).unwrap(); + let (key_b, _) = b.store().persist(&b.start).unwrap(); + assert_ne!(key_a, key_b); +} + +#[test] +fn the_stored_closure_is_root_relative() { + let fx = Fixture::new("rel-closure"); + let (key, _) = fx.store().persist(&fx.start).unwrap(); + let stored: Vec = + serde_json::from_slice(&fs::read(fx.entry_dir(&key).join(CLOSURE_FILE)).unwrap()).unwrap(); + assert!(!stored.is_empty()); + for entry in &stored { + assert!(entry.starts_with("ws:"), "stored relative, got {entry}"); + assert!( + !entry.contains("oj-start-bundle-test"), + "no root leak: {entry}" + ); + } +} + +#[test] +fn memo_survives_path_spelling_differences() { + // macOS temp_dir is /var/..., canonical is /private/var/...: the memo is + // keyed by closure id, so either spelling hits it. + let fx = Fixture::new("memo-spelling"); + fx.settle_modules(); + let (key, _) = fx.store().persist(&fx.start).unwrap(); + let (stats, _) = fx.store().restore(&fx.start, no_globs).unwrap(); + assert_eq!(stats.key, key); + assert_eq!(stats.rehashed, 0); +} + +/// Generations and blobs in `shared`, pointers under each app. +fn split_store_at(root: &Path, shared: &Path, keep: usize) -> StartBundleStore { + StartBundleStore::at_dirs( + root, + shared.join("start-bundle"), + crate::cache_root(root).join("start-bundle"), + keep, + "0.0.1-test", + VerifyMode::Standard, + "development", + ) +} + +fn shared_base(label: &str) -> PathBuf { + let base = std::env::temp_dir().join(format!( + "oj-start-bundle-shared-{}-{label}", + std::process::id() + )); + let _ = fs::remove_dir_all(&base); + base +} + +#[test] +fn cold_worktree_restores_through_the_probe() { + let shared = shared_base("probe"); + let a = Fixture::new("split-probe-a"); + let b = Fixture::new("split-probe-b"); + let (key_a, _) = split_store_at(&a.root, &shared, SHARED_KEEP_GENERATIONS) + .persist(&a.start) + .unwrap(); + + // B is cold: no current, no memo, empty start dir. + b.clear_start_dir(); + let (stats, pinned) = split_store_at(&b.root, &shared, SHARED_KEEP_GENERATIONS) + .restore(&b.start, no_globs) + .unwrap(); + assert_eq!( + stats.key, key_a, + "the probe predicted A's closure and B's files agreed" + ); + assert!(!pinned.is_empty()); + assert!(b.start.join("manifest.ts").is_file()); + let local = crate::cache_root(&b.root).join("start-bundle"); + assert!(local.join(CURRENT_FILE).is_file(), "current is per-root"); + assert!(local.join(MEMO_FILE).is_file(), "memo is per-root"); + let pins = fs::read_dir(shared.join("start-bundle").join(PINS_DIR)) + .unwrap() + .count(); + assert_eq!(pins, 2, "one pin per root"); +} + +#[test] +fn an_edited_cold_worktree_misses_instead_of_taking_the_wrong_bundle() { + let shared = shared_base("probe-miss"); + let a = Fixture::new("split-miss-a"); + let b = Fixture::new("split-miss-b"); + split_store_at(&a.root, &shared, SHARED_KEEP_GENERATIONS) + .persist(&a.start) + .unwrap(); + b.write_module("a.tsx", "export const a = 999;"); + let err = split_store_at(&b.root, &shared, SHARED_KEEP_GENERATIONS) + .restore(&b.start, no_globs) + .unwrap_err(); + assert!(matches!(err, Miss::NoEntryForKey(_)), "{err:?}"); +} + +#[test] +fn another_roots_pin_survives_eviction() { + let shared = shared_base("pin-protect"); + let a = Fixture::new("split-pin-a"); + let b = Fixture::new("split-pin-b"); + let (key_a, _) = split_store_at(&a.root, &shared, 2) + .persist(&a.start) + .unwrap(); + + // B churns generations through a window of 2, which without pins would + // evict A's generation and its blobs. + let store_b = split_store_at(&b.root, &shared, 2); + for i in 0..4 { + b.write_module("a.tsx", &format!("export const a = {i};")); + b.write_build(&format!("bundle-b{i}")); + store_b.persist(&b.start).unwrap(); + std::thread::sleep(Duration::from_millis(20)); + } + store_b.join_eviction(); + store_b.prune(DEFAULT_PRUNE_BUDGET_BYTES); + + assert!(shared.join("start-bundle").join(&key_a).is_dir()); + let (stats, _) = split_store_at(&a.root, &shared, 2) + .restore(&a.start, no_globs) + .unwrap(); + assert_eq!(stats.key, key_a, "A still restores, blobs included"); +} + +#[test] +fn stale_pins_stop_protecting_and_are_removed() { + let shared = shared_base("pin-stale"); + let a = Fixture::new("split-stale-a"); + let b = Fixture::new("split-stale-b"); + let store_a = split_store_at(&a.root, &shared, 2); + let (key_a, _) = store_a.persist(&a.start).unwrap(); + // A's checkout is gone: its pointers with it, its pin and its + // generation's recency aged past the freshness window. + let _ = fs::remove_dir_all(&a.root); + let old = SystemTime::now() - Duration::from_secs(8 * 24 * 60 * 60); + let pin = shared + .join("start-bundle") + .join(PINS_DIR) + .join(&store_a.pin_id); + set_mtime(&pin, old); + set_mtime( + &shared.join("start-bundle").join(&key_a).join(TOUCH_FILE), + old, + ); + + let store_b = split_store_at(&b.root, &shared, 2); + for i in 0..4 { + b.write_module("a.tsx", &format!("export const a = {i};")); + b.write_build(&format!("bundle-b{i}")); + store_b.persist(&b.start).unwrap(); + std::thread::sleep(Duration::from_millis(20)); + } + store_b.join_eviction(); + + assert!( + !shared.join("start-bundle").join(&key_a).is_dir(), + "a dead worktree's generation is evictable" + ); + assert!(!pin.is_file(), "the stale pin file itself is cleaned up"); +} + +/// glob-scopes.json for one call over `patterns`. +fn glob_scopes(patterns: &[String]) -> String { + serde_json::json!([{ "patterns": patterns, "exhaustive": true, "caseSensitive": true }]) + .to_string() +} + +// The bundle's glob patterns are absolute: a shared generation stores them +// root-relative and hands each worktree its own, or B would expand A's +// checkout and its dev gate would watch A's files. +#[test] +fn in_root_globs_rehome_onto_the_restoring_worktree() { + let shared = shared_base("glob-rehome"); + let a = Fixture::new("split-glob-a"); + let b = Fixture::new("split-glob-b"); + let pattern = |fx: &Fixture| vec![format!("{}/src/*.tsx", fx.root.display())]; + fs::write(a.start.join(GLOB_SCOPES_FILE), glob_scopes(&pattern(&a))).unwrap(); + let (key_a, _) = split_store_at(&a.root, &shared, SHARED_KEEP_GENERATIONS) + .persist(&a.start) + .unwrap(); + let stored = fs::read_to_string( + shared + .join("start-bundle") + .join(&key_a) + .join(GLOB_SCOPES_FILE), + ) + .unwrap(); + assert!( + !stored.contains("split-glob-a"), + "stored without A's root: {stored}" + ); + + b.clear_start_dir(); + let seen = std::cell::RefCell::new(String::new()); + let (stats, _) = split_store_at(&b.root, &shared, SHARED_KEEP_GENERATIONS) + .restore(&b.start, |scopes: &str| { + *seen.borrow_mut() = scopes.to_string(); + Vec::new() + }) + .unwrap(); + assert_eq!(stats.key, key_a); + let expect: serde_json::Value = serde_json::from_str(&glob_scopes(&pattern(&b))).unwrap(); + assert_eq!( + serde_json::from_str::(&seen.borrow()).unwrap(), + expect + ); + let restored = fs::read_to_string(b.start.join(GLOB_SCOPES_FILE)).unwrap(); + assert_eq!( + serde_json::from_str::(&restored).unwrap(), + expect + ); +} + +// A glob reaching outside the root cannot be rehomed, so its generation is +// keyed to the root that built it: it still restores there, never elsewhere. +#[test] +fn an_out_of_root_glob_keeps_the_generation_to_its_root() { + let shared = shared_base("glob-pin"); + let a = Fixture::new("split-globpin-a"); + let b = Fixture::new("split-globpin-b"); + let outside = vec!["/elsewhere/shared/*.ts".to_string()]; + fs::write(a.start.join(GLOB_SCOPES_FILE), glob_scopes(&outside)).unwrap(); + let store_a = split_store_at(&a.root, &shared, SHARED_KEEP_GENERATIONS); + let (key_a, _) = store_a.persist(&a.start).unwrap(); + a.clear_start_dir(); + assert_eq!(store_a.restore(&a.start, no_globs).unwrap().0.key, key_a); + + b.clear_start_dir(); + let err = split_store_at(&b.root, &shared, SHARED_KEEP_GENERATIONS) + .restore(&b.start, no_globs) + .unwrap_err(); + assert!( + matches!(&err, Miss::NoEntryForKey(k) if *k != key_a), + "{err:?}" + ); +} + +// Inputs only the caller knows (the config the app was started with) key +// the bundle: a generation persisted under one never restores under another. +#[test] +fn the_extra_salt_keys_the_bundle() { + let fx = Fixture::new("extra-salt"); + let (key, _) = fx + .store() + .with_extra_salt(b"config-a") + .persist(&fx.start) + .unwrap(); + let (again, _) = fx + .store() + .with_extra_salt(b"config-a") + .persist(&fx.start) + .unwrap(); + assert_eq!(key, again); + match fx + .store() + .with_extra_salt(b"config-b") + .restore(&fx.start, no_globs) + { + Err(Miss::NoEntryForKey(k)) => assert_ne!(k, key), + other => panic!("expected key miss, got {other:?}"), + } +} + +// A closure file reached through a symlink out of the root (a linked +// package, a symlinked node_modules) ids by its canonical path, which sorts +// apart from its in-root spelling, and may appear under both spellings. The +// key a persist computes must be the one a restore recomputes from the +// stored closure, or every boot misses. +#[cfg(unix)] +#[test] +fn a_closure_reaching_out_of_the_root_restores_under_its_own_key() { + let fx = Fixture::new("symlinked"); + let outside = fx + .root + .with_file_name(format!("oj-start-bundle-outside-{}", std::process::id())); + let _ = fs::remove_dir_all(&outside); + fs::create_dir_all(&outside).unwrap(); + fs::write(outside.join("z.tsx"), "export const z = 1;").unwrap(); + std::os::unix::fs::symlink(outside.join("z.tsx"), fx.module("link.tsx")).unwrap(); + let closure = vec![ + fx.module("a.tsx").display().to_string(), + fx.module("b.tsx").display().to_string(), + fx.module("link.tsx").display().to_string(), + outside.join("z.tsx").display().to_string(), + ]; + fs::write( + fx.start.join(CLOSURE_FILE), + serde_json::to_vec(&closure).unwrap(), + ) + .unwrap(); + let (key, _) = fx.store().persist(&fx.start).unwrap(); + fx.clear_start_dir(); + let (stats, _) = fx.store().restore(&fx.start, no_globs).unwrap(); + assert_eq!(stats.key, key); + assert_eq!( + stats.files, 3, + "one id for both spellings of the linked file" + ); + let _ = fs::remove_dir_all(&outside); +} + +// A restore into a build dir that never built (another worktree's +// generation) leaves the chunk index a consumer reads and the closure the +// dev rebundle gate consults; the chunks stay in the blob store. +#[test] +fn a_restore_leaves_the_build_dirs_index_and_closure() { + let shared = shared_base("build-view"); + let a = Fixture::new("view-a"); + let b = Fixture::new("view-b"); + split_store_at(&a.root, &shared, SHARED_KEEP_GENERATIONS) + .persist(&a.start) + .unwrap(); + b.clear_start_dir(); + let _ = fs::remove_file(b.start.join(CHUNK_INDEX_FILE)); + let _ = fs::remove_file(b.start.join(CLOSURE_FILE)); + let (_, pinned) = split_store_at(&b.root, &shared, SHARED_KEEP_GENERATIONS) + .restore(&b.start, no_globs) + .unwrap(); + let index: serde_json::Value = + serde_json::from_slice(&fs::read(b.start.join(CHUNK_INDEX_FILE)).unwrap()).unwrap(); + assert_eq!(index["entry"], "client-entry.js"); + let names: Vec<&str> = index["files"] + .as_array() + .unwrap() + .iter() + .map(|f| f["name"].as_str().unwrap()) + .collect(); + assert!(names.iter().all(|n| pinned.chunk(n).is_some()), "{names:?}"); + let closure: Vec = + serde_json::from_slice(&fs::read(b.start.join(CLOSURE_FILE)).unwrap()).unwrap(); + assert_eq!(closure.len(), 2); + assert!( + closure.iter().all(|f| f.contains("view-b")), + "the closure names this worktree's files: {closure:?}" + ); + assert!(!b.start.join(CHUNKS_DIR).exists(), "no chunk bytes copied"); +} + +// An attachment travels with its generation: another worktree restoring +// the generation reads it back; another key, a gone generation, or a name +// that is not a plain file name has none. +#[test] +fn attachments_travel_with_their_generation() { + let shared = shared_base("attach"); + let a = Fixture::new("attach-a"); + let b = Fixture::new("attach-b"); + let store_a = split_store_at(&a.root, &shared, SHARED_KEEP_GENERATIONS); + let (key, _) = store_a.persist(&a.start).unwrap(); + assert!(store_a.attach(&key, "rules.json", b"[1]")); + assert!( + !store_a.attach("0000", "rules.json", b"[1]"), + "no such generation" + ); + assert!(!store_a.attach(&key, "../escape", b"x"), "not a plain name"); + let store_b = split_store_at(&b.root, &shared, SHARED_KEEP_GENERATIONS); + b.clear_start_dir(); + let (stats, _) = store_b.restore(&b.start, no_globs).unwrap(); + assert_eq!(stats.key, key); + assert_eq!( + store_b.attachment(&key, "rules.json").as_deref(), + Some(&b"[1]"[..]) + ); + assert_eq!(store_b.attachment(&key, "other.json"), None); +} + +// Two worktrees of one app bundle the same closure at the same time (two +// sandboxes booting from one scaffold): both persist the one key at once, +// repeatedly. One generation comes out of it, whole, with every blob its +// manifest names, and either worktree restores it afterwards. +#[test] +fn racing_persists_of_one_closure_commit_one_whole_generation() { + let shared = shared_base("race-persist"); + let a = Fixture::new("race-persist-a"); + let b = Fixture::new("race-persist-b"); + let keys: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + std::thread::scope(|s| { + for fx in [&a, &b] { + let (shared, keys) = (&shared, &keys); + s.spawn(move || { + let store = split_store_at(&fx.root, shared, SHARED_KEEP_GENERATIONS); + for _ in 0..6 { + let (key, pinned) = store.persist(&fx.start).expect("persist"); + assert!(!pinned.is_empty()); + keys.lock().unwrap().push(key); + } + store.join_eviction(); + }); + } + }); + let keys = keys.into_inner().unwrap(); + assert_eq!(keys.len(), 12); + assert!(keys.iter().all(|k| *k == keys[0]), "{keys:?}"); + let key = &keys[0]; + let entry = shared.join("start-bundle").join(key); + let manifest = read_manifest(&entry).expect("a whole manifest"); + for f in manifest.files.values() { + assert!( + shared + .join("start-bundle") + .join(BLOBS_DIR) + .join(&f.hash) + .is_file(), + "blob {} of the racing generation is missing", + f.hash + ); + } + let leftovers: Vec = fs::read_dir(shared.join("start-bundle")) + .unwrap() + .flatten() + .map(|e| e.file_name().to_string_lossy().into_owned()) + .filter(|n| n.starts_with(".tmp-")) + .collect(); + assert!(leftovers.is_empty(), "{leftovers:?}"); + for fx in [&a, &b] { + fx.clear_start_dir(); + let (stats, _) = split_store_at(&fx.root, &shared, SHARED_KEEP_GENERATIONS) + .restore(&fx.start, no_globs) + .unwrap(); + assert_eq!(&stats.key, key); + } +} + +// One worktree restores its bundle over and over while another churns +// generations through a window of two, evicting as it goes: the pin the +// restoring root holds keeps its generation and blobs, so no restore ever +// finds a half-evicted entry. +#[test] +fn a_restore_never_loses_to_another_roots_eviction() { + let shared = shared_base("race-evict"); + let a = Fixture::new("race-evict-a"); + let b = Fixture::new("race-evict-b"); + let (key_a, _) = split_store_at(&a.root, &shared, 2) + .persist(&a.start) + .unwrap(); + let stop = std::sync::atomic::AtomicBool::new(false); + std::thread::scope(|s| { + s.spawn(|| { + let store_b = split_store_at(&b.root, &shared, 2); + // Never A's sources: a shared key is another story (see below). + for i in 0..40 { + b.write_module("a.tsx", &format!("export const a = {i} + 100;")); + b.write_build(&format!("bundle-b{i}")); + store_b.persist(&b.start).unwrap(); + store_b.prune(DEFAULT_PRUNE_BUDGET_BYTES); + } + store_b.join_eviction(); + stop.store(true, std::sync::atomic::Ordering::SeqCst); + }); + s.spawn(|| { + let store_a = split_store_at(&a.root, &shared, 2); + let mut restores = 0; + while !stop.load(std::sync::atomic::Ordering::SeqCst) || restores == 0 { + a.clear_start_dir(); + let (stats, pinned) = store_a + .restore(&a.start, no_globs) + .unwrap_or_else(|miss| panic!("restore {restores} lost to eviction: {miss}")); + assert_eq!(stats.key, key_a); + for (name, chunk) in pinned.chunks() { + assert!(chunk.path.is_file(), "blob of {name} swept under a pin"); + } + restores += 1; + } + }); + }); +} + +// Two roots with the same sources bundle to other chunks (a plugin that is +// not deterministic, another machine): the second must not replace the +// generation the first serves live, or the first's chunks vanish from under +// its running server. The second serves its own build dir; a later boot of +// either restores the stored generation, built from the same sources. +#[test] +fn a_generation_another_root_serves_is_not_replaced_from_under_it() { + let shared = shared_base("no-replace"); + let a = Fixture::new("no-replace-a"); + let b = Fixture::new("no-replace-b"); + let store_a = split_store_at(&a.root, &shared, SHARED_KEEP_GENERATIONS); + let (key, pinned_a) = store_a.persist(&a.start).unwrap(); + b.write_build("bundle-other-chunks"); + let store_b = split_store_at(&b.root, &shared, SHARED_KEEP_GENERATIONS); + let (key_b, pinned_b) = store_b.persist(&b.start).unwrap(); + assert_eq!(key_b, key, "same sources, one key"); + for (name, chunk) in pinned_a.chunks() { + assert!(chunk.path.is_file(), "A's chunk {name} was swept"); + } + assert_eq!( + fs::read_to_string(pinned_b.chunk("client-entry.js").unwrap().path.as_path()).unwrap(), + "bundle-other-chunks", + "B serves what it built" + ); + assert!( + pinned_b + .chunk("client-entry.js") + .unwrap() + .path + .starts_with(&b.start), + "from its own build dir" + ); + let entry = + fs::read_to_string(pinned_a.chunk("client-entry.js").unwrap().path.as_path()).unwrap(); + assert_eq!(entry, "bundle-v1", "the stored generation is A's"); + // Either root restores the stored generation afterwards. + for fx in [&a, &b] { + fx.clear_start_dir(); + let (stats, pinned) = split_store_at(&fx.root, &shared, SHARED_KEEP_GENERATIONS) + .restore(&fx.start, no_globs) + .unwrap(); + assert_eq!(stats.key, key); + assert_eq!( + fs::read_to_string(pinned.chunk("client-entry.js").unwrap().path.as_path()).unwrap(), + "bundle-v1" + ); + } + // With A gone (its pin stale), B's rebuild takes the key. + let old = SystemTime::now() - Duration::from_secs(8 * 24 * 60 * 60); + set_mtime( + &shared + .join("start-bundle") + .join(PINS_DIR) + .join(&store_a.pin_id), + old, + ); + b.write_build("bundle-other-chunks"); + let (_, pinned_b) = store_b.persist(&b.start).unwrap(); + assert!(pinned_b + .chunk("client-entry.js") + .unwrap() + .path + .starts_with(shared.join("start-bundle"))); + assert_eq!( + fs::read_to_string(pinned_b.chunk("client-entry.js").unwrap().path.as_path()).unwrap(), + "bundle-other-chunks" + ); +} + +// The inputs outside the closure (the config and the files it imports) key +// the bundle by their root-relative name and content: two worktrees with +// the same config agree on the key, other content or a missing file does not. +#[test] +fn files_outside_the_closure_key_the_bundle_worktree_independently() { + let shared = shared_base("keyed-files"); + let a = Fixture::new("keyed-files-a"); + let b = Fixture::new("keyed-files-b"); + for fx in [&a, &b] { + fs::write( + fx.root.join("vite.config.ts"), + "export default { plugins: [one()] }", + ) + .unwrap(); + } + let keyed = |fx: &Fixture| { + split_store_at(&fx.root, &shared, SHARED_KEEP_GENERATIONS) + .keyed_by_files(&[fx.root.join("vite.config.ts")]) + }; + let (key_a, _) = keyed(&a).persist(&a.start).unwrap(); + let (key_b, _) = keyed(&b).persist(&b.start).unwrap(); + assert_eq!(key_a, key_b, "same config in two worktrees"); + b.clear_start_dir(); + assert_eq!(keyed(&b).restore(&b.start, no_globs).unwrap().0.key, key_a); + fs::write( + b.root.join("vite.config.ts"), + "export default { plugins: [two()] }", + ) + .unwrap(); + assert!( + matches!(keyed(&b).restore(&b.start, no_globs), Err(Miss::NoEntryForKey(k)) if k != key_a), + "other config content" + ); + fs::remove_file(b.root.join("vite.config.ts")).unwrap(); + assert!( + matches!(keyed(&b).restore(&b.start, no_globs), Err(Miss::NoEntryForKey(k)) if k != key_a), + "a missing file keys as missing" + ); +} + +// The shared dir holds every app's generations: a cold worktree's probe +// tries only those keyed under its own salt (its app, mode, tool and +// config), however many another app's crowd the recency window, and still +// restores its own. +#[test] +fn the_cold_probe_skips_generations_of_other_salts() { + let shared = shared_base("probe-salts"); + let a = Fixture::new("probe-salts-a"); + let (key_a, _) = split_store_at(&a.root, &shared, SHARED_KEEP_GENERATIONS) + .persist(&a.start) + .unwrap(); + // Another app's generations, newer than A's, more than the probe tries. + let other = Fixture::new("probe-salts-other"); + for i in 0..(PROBE_CANDIDATES + 2) { + other.write_module("a.tsx", &format!("export const a = {i};")); + other.write_build(&format!("other-{i}")); + split_store_at(&other.root, &shared, SHARED_KEEP_GENERATIONS) + .keyed_by("app", "other") + .persist(&other.start) + .unwrap(); + } + let b = Fixture::new("probe-salts-b"); + b.clear_start_dir(); + let store = split_store_at(&b.root, &shared, SHARED_KEEP_GENERATIONS); + assert_eq!( + store.recent_generation_keys(PROBE_CANDIDATES), + vec![key_a.clone()], + "only generations under this store's salt are candidates" + ); + let (stats, _) = store.restore(&b.start, no_globs).unwrap(); + assert_eq!(stats.key, key_a); +} + +// The files outside the closure key the bundle by identity, length and +// content: a missing file is not an empty one, and two files' contents do +// not run together (`ab`+`c` against `a`+`bc`). +#[test] +fn keyed_by_files_tells_missing_from_empty_and_keeps_file_boundaries() { + let fx = Fixture::new("keyed-files-boundaries"); + let (x, y) = (fx.root.join("x.txt"), fx.root.join("y.txt")); + let files = [x.clone(), y.clone()]; + let key = || { + fx.store() + .keyed_by_files(&files) + .persist(&fx.start) + .unwrap() + .0 + }; + let missing = key(); + fs::write(&x, b"").unwrap(); + let empty = key(); + assert_ne!(missing, empty, "missing and empty are two inputs"); + fs::write(&x, b"ab").unwrap(); + fs::write(&y, b"c").unwrap(); + let ab_c = key(); + fs::write(&x, b"a").unwrap(); + fs::write(&y, b"bc").unwrap(); + let a_bc = key(); + assert_ne!(ab_c, a_bc, "contents keep their file boundaries"); + assert_eq!(a_bc, key(), "the same inputs key the same"); +} diff --git a/crates/oj_cache/src/start_codegen.rs b/crates/oj_cache/src/start_codegen.rs index f87a65e5a..c0880df16 100644 --- a/crates/oj_cache/src/start_codegen.rs +++ b/crates/oj_cache/src/start_codegen.rs @@ -12,6 +12,9 @@ use std::time::{Instant, SystemTime, UNIX_EPOCH}; pub const START_CODEGEN_FORMAT: u32 = 4; pub const DEFAULT_KEEP_ENTRIES: usize = 8; +/// The shared store serves every worktree and app on the machine, so its +/// per-kind entry budget is wider than a single app's. +pub const SHARED_KEEP_ENTRIES: usize = 32; const MEMO_FILE: &str = "memo.json"; const TOUCH_FILE: &str = "last-used"; @@ -21,9 +24,17 @@ const MEMO_FRESHNESS_SLACK_NS: u64 = 2_000_000_000; pub struct StartCodegenStore { root: PathBuf, + /// Entry directories (content, keyed root-relative): the shared per-user + /// store when one is available, so worktree B restores what worktree A + /// generated; the per-app cache otherwise. dir: PathBuf, + /// The memo (mtime fast-path) is per-root pointer state: its relative + /// paths mean nothing outside this worktree and its mtimes are this + /// checkout's, so it always stays under the app, split from the entries. + memo_dir: PathBuf, salt: String, marker: Option, + keep_entries: usize, } #[derive(Debug, PartialEq)] @@ -88,15 +99,48 @@ impl StartCodegenStore { tool_version: &str, extra_salt: &[u8], marker: Option<&str>, + ) -> Self { + let local = crate::cache_root(root).join("start-codegen").join(kind); + let (dir, keep_entries) = match crate::store::store_root() { + Some(store) => (store.join("start-codegen").join(kind), SHARED_KEEP_ENTRIES), + None => (local.clone(), DEFAULT_KEEP_ENTRIES), + }; + Self::at_dirs( + root, + dir, + local, + keep_entries, + kind, + tool_version, + extra_salt, + marker, + ) + } + + /// The explicit-layout constructor `new` resolves into: entries at `dir` + /// (shareable), memo at `memo_dir` (per-root). Tests and embedders that + /// must not touch the user's shared store build through this. + #[allow(clippy::too_many_arguments)] + pub fn at_dirs( + root: &Path, + dir: PathBuf, + memo_dir: PathBuf, + keep_entries: usize, + kind: &str, + tool_version: &str, + extra_salt: &[u8], + marker: Option<&str>, ) -> Self { Self { root: root.to_path_buf(), - dir: crate::cache_root(root).join("start-codegen").join(kind), + dir, + memo_dir, salt: format!( "{tool_version}:{START_CODEGEN_FORMAT}:{kind}:{}", blake3::hash(extra_salt).to_hex() ), marker: marker.map(str::to_owned), + keep_entries, } } @@ -123,7 +167,7 @@ impl StartCodegenStore { return Err(Miss::EntryCorrupt(key)); } } - if scan.rehashed > 0 || !self.dir.join(MEMO_FILE).is_file() { + if scan.rehashed > 0 || !self.memo_dir.join(MEMO_FILE).is_file() { self.write_memo(&build_memo(&self.root, &scan.inputs, &scan.infos)); } touch(&entry); @@ -144,7 +188,7 @@ impl StartCodegenStore { } self.write_memo(&build_memo(&self.root, &scan.inputs, &scan.infos)); touch(&entry); - self.prune(DEFAULT_KEEP_ENTRIES); + self.prune(self.keep_entries); Some(key) } @@ -264,17 +308,17 @@ impl StartCodegenStore { } fn read_memo(&self) -> Option { - integrity::read_json_or_remove(&self.dir.join(MEMO_FILE)) + integrity::read_json_or_remove(&self.memo_dir.join(MEMO_FILE)) } fn write_memo(&self, memo: &Memo) { let Ok(bytes) = serde_json::to_vec(memo) else { return; }; - if fs::create_dir_all(&self.dir).is_err() { + if fs::create_dir_all(&self.memo_dir).is_err() { return; } - let _ = integrity::atomic_write(&self.dir.join(MEMO_FILE), &bytes); + let _ = integrity::atomic_write(&self.memo_dir.join(MEMO_FILE), &bytes); } } @@ -466,16 +510,42 @@ mod tests { } fn store(&self) -> StartCodegenStore { - StartCodegenStore::new(&self.root, "route-tree", "0.0.1-test", b"script-v1", None) + self.store_at(&self.root, "route-tree", None) } - fn marked_store(&self) -> StartCodegenStore { - StartCodegenStore::new( - &self.root, - "server-fn", + /// Old single-directory layout, pinned to fixture-local paths so no + /// test can reach the developer's real shared store. + fn store_at(&self, root: &Path, kind: &str, marker: Option<&str>) -> StartCodegenStore { + let local = crate::cache_root(root).join("start-codegen").join(kind); + StartCodegenStore::at_dirs( + root, + local.clone(), + local, + DEFAULT_KEEP_ENTRIES, + kind, "0.0.1-test", b"script-v1", - Some("createServerFn"), + marker, + ) + } + + fn marked_store(&self) -> StartCodegenStore { + self.store_at(&self.root, "server-fn", Some("createServerFn")) + } + + fn store_salted(&self, tool_version: &str, extra_salt: &[u8]) -> StartCodegenStore { + let local = crate::cache_root(&self.root) + .join("start-codegen") + .join("route-tree"); + StartCodegenStore::at_dirs( + &self.root, + local.clone(), + local, + DEFAULT_KEEP_ENTRIES, + "route-tree", + tool_version, + extra_salt, + None, ) } @@ -658,15 +728,15 @@ mod tests { let (out, _) = tree_outputs(&fx); let outputs = [("routeTree.gen.ts", out.as_path())]; let key = fx.store().persist(&fx.inputs(), &outputs).unwrap(); - let other_script = - StartCodegenStore::new(&fx.root, "route-tree", "0.0.1-test", b"script-v2", None) - .persist(&fx.inputs(), &outputs) - .unwrap(); + let other_script = fx + .store_salted("0.0.1-test", b"script-v2") + .persist(&fx.inputs(), &outputs) + .unwrap(); assert_ne!(other_script, key, "script content salts the key"); - let other_version = - StartCodegenStore::new(&fx.root, "route-tree", "9.9.9", b"script-v1", None) - .persist(&fx.inputs(), &outputs) - .unwrap(); + let other_version = fx + .store_salted("9.9.9", b"script-v1") + .persist(&fx.inputs(), &outputs) + .unwrap(); assert_ne!(other_version, key, "tool version salts the key"); } @@ -822,4 +892,143 @@ mod tests { )); assert!(!fx.entry_dir("route-tree", &key).exists()); } + // ---- store/scratch split: the pulp P0 contract ---- + + /// Two identical worktrees sharing one entries dir, each with its own + /// memo dir — the layout `new()` builds when a shared store exists. + fn split_pair(label: &str) -> (Fixture, Fixture, PathBuf) { + let a = Fixture::new(&format!("{label}-a")); + let b = Fixture::new(&format!("{label}-b")); + let shared = std::env::temp_dir().join(format!( + "oj-start-codegen-shared-{}-{label}", + std::process::id() + )); + let _ = fs::remove_dir_all(&shared); + (a, b, shared) + } + + fn split_store(root: &Path, shared: &Path) -> StartCodegenStore { + StartCodegenStore::at_dirs( + root, + shared.join("start-codegen/route-tree"), + crate::cache_root(root).join("start-codegen/route-tree"), + SHARED_KEEP_ENTRIES, + "route-tree", + "0.0.1-test", + b"script-v1", + None, + ) + } + + #[test] + fn worktree_b_restores_what_worktree_a_generated() { + let (a, b, shared) = split_pair("xwt"); + let (out_a, _) = tree_outputs(&a); + let key_a = split_store(&a.root, &shared) + .persist(&a.inputs(), &[("routeTree.gen.ts", out_a.as_path())]) + .unwrap(); + + // Worktree B never persisted anything; same content, different root. + let dest_b = b.root.join("src/routeTree.gen.ts"); + fs::remove_file(&dest_b).unwrap(); + let stats = split_store(&b.root, &shared) + .restore(&b.inputs(), &[("routeTree.gen.ts", dest_b.as_path())]) + .unwrap(); + assert_eq!(stats.key, key_a, "same content, same key, across roots"); + assert_eq!( + fs::read_to_string(&dest_b).unwrap(), + "// tree-v1", + "worktree A's output materialized into worktree B" + ); + } + + #[test] + fn edited_worktree_misses_instead_of_taking_the_other_worktrees_entry() { + let (a, b, shared) = split_pair("xwt-miss"); + let (out_a, _) = tree_outputs(&a); + split_store(&a.root, &shared) + .persist(&a.inputs(), &[("routeTree.gen.ts", out_a.as_path())]) + .unwrap(); + + b.write("src/routes/index.tsx", "export const Route = 999;"); + let dest_b = b.root.join("src/routeTree.gen.ts"); + let miss = split_store(&b.root, &shared) + .restore(&b.inputs(), &[("routeTree.gen.ts", dest_b.as_path())]) + .unwrap_err(); + assert!(matches!(miss, Miss::NoEntryForKey(_)), "{miss:?}"); + } + + #[test] + fn memos_stay_per_root_and_never_land_in_the_shared_dir() { + let (a, b, shared) = split_pair("xwt-memo"); + let (out_a, _) = tree_outputs(&a); + let store_a = split_store(&a.root, &shared); + store_a + .persist(&a.inputs(), &[("routeTree.gen.ts", out_a.as_path())]) + .unwrap(); + + // Settle B's inputs past the memo freshness slack, or the memo + // (correctly) refuses to trust their mtimes. + b.settle(&["src/routes/index.tsx", "src/routes/about.tsx"]); + let dest_b = b.root.join("src/routeTree.gen.ts"); + let store_b = split_store(&b.root, &shared); + let first = store_b + .restore(&b.inputs(), &[("routeTree.gen.ts", dest_b.as_path())]) + .unwrap(); + assert!(first.rehashed > 0, "cold worktree hashes its inputs once"); + // The memo fast-path belongs to B alone and works on the next boot. + let second = store_b + .restore(&b.inputs(), &[("routeTree.gen.ts", dest_b.as_path())]) + .unwrap(); + assert_eq!(second.rehashed, 0, "warm worktree trusts its own memo"); + + for root in [&a.root, &b.root] { + assert!( + crate::cache_root(root) + .join("start-codegen/route-tree/memo.json") + .is_file(), + "memo lives under {}", + root.display() + ); + } + assert!( + !shared.join("start-codegen/route-tree/memo.json").exists(), + "no per-root pointer state in the shared dir" + ); + // And one worktree's memo mtimes never leak into the other's: A's + // memo predates B's restore and is untouched by it. + let a_memo = + fs::read(crate::cache_root(&a.root).join("start-codegen/route-tree/memo.json")) + .unwrap(); + let b_memo = + fs::read(crate::cache_root(&b.root).join("start-codegen/route-tree/memo.json")) + .unwrap(); + assert_ne!(a_memo, b_memo, "memos are per-worktree state"); + } + + #[test] + fn shared_prune_budget_is_wider_and_prune_spares_foreign_entries_dirs() { + let (a, _b, shared) = split_pair("xwt-prune"); + let store = split_store(&a.root, &shared); + let (out, _) = tree_outputs(&a); + store + .persist(&a.inputs(), &[("routeTree.gen.ts", out.as_path())]) + .unwrap(); + // A second app's entry in the same shared kind dir survives this + // store's prune while the budget holds. + let entries: Vec<_> = fs::read_dir(shared.join("start-codegen/route-tree")) + .unwrap() + .flatten() + .filter(|e| e.path().is_dir()) + .collect(); + assert_eq!(entries.len(), 1); + store.prune(SHARED_KEEP_ENTRIES); + assert!( + shared + .join("start-codegen/route-tree") + .join(entries[0].file_name()) + .is_dir(), + "within budget, nothing is evicted" + ); + } } diff --git a/crates/oj_cache/src/store.rs b/crates/oj_cache/src/store.rs new file mode 100644 index 000000000..46e7cdd0b --- /dev/null +++ b/crates/oj_cache/src/store.rs @@ -0,0 +1,173 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2026 Raphael Amorim + +//! The shared content store: cache entries whose keys and artifacts are +//! worktree-independent live here, one directory per user rather than per +//! app, so a second worktree of the same app (or a second app on the same +//! dependencies) starts warm instead of rebuilding content that already +//! exists on this machine. +//! +//! Only a store whose keys and artifacts carry no absolute paths may move +//! here. Everything else stays under the per-app [`crate::cache_root`]: +//! scratch scripts that resolve bare imports relative to where they live, +//! per-root pointer state (`current` files, memo maps), and any artifact +//! that still embeds the app root. + +use std::path::{Path, PathBuf}; + +/// Bumped when the layout of the shared store changes shape; an older layout +/// is simply a different directory, never misread. +pub const STORE_VERSION: u32 = 1; + +/// The shared store directory, or `None` when the store is off (no +/// `OJ_STORE_DIR`, which `oj dev --store` sets for itself and every child), +/// in which case callers fall back to the per-app `cache_root` and lose +/// sharing, never correctness. +pub fn store_root() -> Option { + store_root_in(oj_env::get().knobs.store_dir.as_deref()) +} + +/// [`store_root`] with the base dir given: the version segment is appended, +/// mirroring `cache_root`. +pub fn store_root_in(base: Option<&Path>) -> Option { + Some(base?.join(format!("v{STORE_VERSION}"))) +} + +/// Root-relative identity for a path under `root`, with forward slashes on +/// every platform: the form that makes a key or artifact mean the same thing +/// in every worktree. A path outside `root` comes back `None`; callers treat +/// that as "not shareable" explicitly rather than silently keying on an +/// absolute path. +pub fn rel_key(root: &Path, path: &Path) -> Option { + let rel = path.strip_prefix(root).ok()?; + let s = rel.to_string_lossy(); + if std::path::MAIN_SEPARATOR == '/' { + Some(s.into_owned()) + } else { + Some(s.replace(std::path::MAIN_SEPARATOR, "/")) + } +} + +/// The workspace root an app belongs to: the FARTHEST ancestor that carries a +/// `node_modules` directory (pnpm/yarn workspaces hoist there), the app itself +/// when no ancestor does. Monorepo files outside the app root get their +/// worktree-independent identity relative to this. +pub fn workspace_root(app: &Path) -> PathBuf { + let mut best = app.to_path_buf(); + let mut cur = app; + while let Some(parent) = cur.parent() { + if parent.join("node_modules").is_dir() { + best = parent.to_path_buf(); + } + cur = parent; + } + best +} + +/// The worktree-independent spelling of a path for hashing into cache keys: +/// `ws:` under the app root, `mono:` under the workspace root (the +/// monorepo-sibling case that would otherwise poison a key with a +/// worktree-absolute path), the path verbatim when neither contains it. +pub fn salt_key(root: &Path, workspace: &Path, path: &Path) -> String { + if let Some(rel) = rel_key(root, path) { + return format!("ws:{rel}"); + } + if let Some(rel) = rel_key(workspace, path) { + return format!("mono:{rel}"); + } + path.to_string_lossy().into_owned() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn store_root_is_versioned_or_off() { + assert_eq!( + store_root_in(Some(Path::new("/shared/oj"))), + Some(Path::new("/shared/oj").join(format!("v{STORE_VERSION}"))) + ); + assert_eq!(store_root_in(None), None); + } + + #[test] + fn rel_key_is_root_relative_or_refused() { + let root = Path::new("/work/a/app"); + assert_eq!( + rel_key(root, Path::new("/work/a/app/src/App.tsx")).as_deref(), + Some("src/App.tsx") + ); + // Two worktrees, same file: same key. + assert_eq!( + rel_key( + Path::new("/work/b/app"), + Path::new("/work/b/app/src/App.tsx") + ), + rel_key(root, Path::new("/work/a/app/src/App.tsx")), + ); + // Outside the root is refused, never keyed absolute by accident. + assert_eq!(rel_key(root, Path::new("/elsewhere/x.ts")), None); + } + + #[test] + fn workspace_root_is_the_farthest_node_modules_ancestor() { + let base = std::env::temp_dir().join(format!("oj-wsroot-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let mono = base.join("mono"); + std::fs::create_dir_all(mono.join("node_modules")).unwrap(); + std::fs::create_dir_all(mono.join("apps/web/node_modules")).unwrap(); + assert_eq!( + workspace_root(&mono.join("apps/web")), + mono, + "farthest wins" + ); + // No ancestor with node_modules: the app is its own workspace. + let lone = base.join("lone/app"); + std::fs::create_dir_all(&lone).unwrap(); + assert_eq!(workspace_root(&lone), lone); + } + + #[test] + fn salt_key_spellings_are_worktree_independent() { + let a_root = Path::new("/wt-a/mono/app"); + let a_ws = Path::new("/wt-a/mono"); + let b_root = Path::new("/somewhere/else/b/mono/app"); + let b_ws = Path::new("/somewhere/else/b/mono"); + // In-root, monorepo-sibling, and external: the first two agree across + // worktrees, the third stays absolute (and so, correctly, disagrees). + assert_eq!( + salt_key(a_root, a_ws, Path::new("/wt-a/mono/app/src/x.ts")), + salt_key( + b_root, + b_ws, + Path::new("/somewhere/else/b/mono/app/src/x.ts") + ), + ); + assert_eq!( + salt_key( + a_root, + a_ws, + Path::new("/wt-a/mono/packages/common/src/index.ts") + ), + "mono:packages/common/src/index.ts" + ); + assert_eq!( + salt_key(a_root, a_ws, Path::new("/wt-a/mono/packages/x.ts")), + salt_key( + b_root, + b_ws, + Path::new("/somewhere/else/b/mono/packages/x.ts") + ), + ); + assert_eq!( + salt_key(a_root, a_ws, Path::new("/opt/external/x.ts")), + "/opt/external/x.ts" + ); + // A sibling-prefix workspace must not relativize (root + "/" rule). + assert_eq!( + salt_key(a_root, a_ws, Path::new("/wt-a/mono2/x.ts")), + "/wt-a/mono2/x.ts" + ); + } +} diff --git a/crates/oj_compiler/src/compile.rs b/crates/oj_compiler/src/compile.rs index 9433bd702..564cbeab8 100644 --- a/crates/oj_compiler/src/compile.rs +++ b/crates/oj_compiler/src/compile.rs @@ -95,6 +95,13 @@ pub struct CompileOptions { /// The config's `@stylexjs/unplugin`, run on the parsed source before any /// other transform (the plugin is `enforce: 'pre'`). pub stylex: Option>, + /// The path this module is *named* by in its own output: the jsx dev + /// `__source` fileName and the sourcemap `sources` entry. Callers that + /// cache compiled output across worktrees pass the root-relative served + /// path (`/src/App.tsx`) so the artifact carries no absolute path; `None` + /// names it by its filesystem path. Filesystem work (extension sniffing, + /// glob expansion) always uses the real path. + pub display_path: Option, } /// A glob pattern's mapping from its importing file (see @@ -126,6 +133,7 @@ impl CompileOptions { alias: Arc::from([]), glob_paths: None, stylex: None, + display_path: None, } } @@ -143,6 +151,7 @@ impl CompileOptions { alias: Arc::from([]), glob_paths: None, stylex: None, + display_path: None, } } } @@ -442,9 +451,13 @@ fn transform<'a>( } let check_emitted = emitted_check_needed(source_text, program, semantic.semantic.scoping()); let scoping = semantic.semantic.into_scoping(); - let transform_ret = - Transformer::new(allocator, path, &transform_options(path, source_text, opts)) - .build_with_scoping(scoping, program); + let display_path = opts.display_path.as_deref().unwrap_or(path); + let transform_ret = Transformer::new( + allocator, + display_path, + &transform_options(path, source_text, opts), + ) + .build_with_scoping(scoping, program); if !transform_ret.diagnostics.is_empty() { return Err(CompileError::Transform { path: path.to_path_buf(), @@ -773,7 +786,8 @@ fn codegen( // Synthesized nodes carry generated-string spans; sourcemapping them panics // oxc's builder on out-of-range spans. let codegen_options = CodegenOptions { - source_map_path: (opts.sourcemap && !synthesized).then(|| path.to_path_buf()), + source_map_path: (opts.sourcemap && !synthesized) + .then(|| opts.display_path.as_deref().unwrap_or(path).to_path_buf()), ..CodegenOptions::default() }; let CodegenReturn { code, map, .. } = @@ -1161,6 +1175,7 @@ import React from "react"; alias: Arc::from([]), glob_paths: None, stylex: None, + display_path: None, }, None, ) @@ -1254,6 +1269,7 @@ import React from "react"; alias: Arc::from([]), glob_paths: None, stylex: None, + display_path: None, }, None, ) diff --git a/crates/oj_compiler/tests/path_independence.rs b/crates/oj_compiler/tests/path_independence.rs new file mode 100644 index 000000000..3c84bc399 --- /dev/null +++ b/crates/oj_compiler/tests/path_independence.rs @@ -0,0 +1,151 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2026 Raphael Amorim + +//! pulp P1: with a `display_path`, a module's compiled artifact (code AND +//! sourcemap) must be byte-identical whatever worktree it was compiled in — +//! the property that makes the module cache shareable across worktrees. + +use std::path::{Path, PathBuf}; + +use oj_compiler::{compile_module, CompileOptions}; + +const JSX_SOURCE: &str = r#" +export function App() { + return
hi
; +} +"#; + +fn dev_opts(display: Option<&str>) -> CompileOptions { + let mut opts = CompileOptions::dev(); + opts.display_path = display.map(PathBuf::from); + opts +} + +// Minimal base64 decode for data-URL sourcemaps (alphabet only; test input is +// well-formed by construction). +fn decode_map(data_url: &str) -> String { + const ABC: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let b64 = data_url + .rsplit_once("base64,") + .expect("data url") + .1 + .trim_end_matches('='); + let mut out = Vec::new(); + let mut acc: u32 = 0; + let mut bits = 0; + for &c in b64.as_bytes() { + let v = ABC.iter().position(|&a| a == c).expect("base64 char") as u32; + acc = (acc << 6) | v; + bits += 6; + if bits >= 8 { + bits -= 8; + out.push((acc >> bits) as u8); + } + } + String::from_utf8(out).expect("utf8 map") +} + +#[test] +fn dev_artifact_is_byte_identical_across_worktrees() { + let opts = dev_opts(Some("/src/App.tsx")); + let a = compile_module(Path::new("/work/wt-a/src/App.tsx"), JSX_SOURCE, &opts, None).unwrap(); + let b = compile_module( + Path::new("/somewhere/else/wt-b/src/App.tsx"), + JSX_SOURCE, + &opts, + None, + ) + .unwrap(); + + assert_eq!(a.code, b.code, "code must not depend on the real path"); + assert_eq!( + a.map_data_url(), + b.map_data_url(), + "sourcemap must not depend on the real path" + ); + assert!( + !a.code.contains("/work/wt-a"), + "no absolute path in code:\n{}", + a.code + ); + let map = decode_map(a.map_data_url().as_deref().unwrap()); + assert!( + !map.contains("/work/wt-a"), + "no absolute path in the map: {map}" + ); +} + +#[test] +fn display_path_names_the_artifact_everywhere() { + let out = compile_module( + Path::new("/abs/checkout/src/App.tsx"), + JSX_SOURCE, + &dev_opts(Some("/src/App.tsx")), + None, + ) + .unwrap(); + + // jsx dev __source carries the display name... + assert!( + out.code.contains("/src/App.tsx"), + "__source fileName uses the display path:\n{}", + out.code + ); + // ...and so does the sourcemap, with content embedded so DevTools never + // needs to resolve the relative name against the filesystem. + let map = decode_map(out.map_data_url().as_deref().unwrap()); + assert!(map.contains("\"/src/App.tsx\""), "sources entry: {map}"); + assert!( + map.contains("sourcesContent"), + "content embedded so the name is a label: {map}" + ); +} + +#[test] +fn without_display_path_the_real_path_still_names_the_artifact() { + // The pre-pulp fallback: callers that pass no display identity keep the + // absolute path, so nothing changes for them (and their artifacts remain + // correctly non-shareable). + let out = compile_module( + Path::new("/abs/checkout/src/App.tsx"), + JSX_SOURCE, + &dev_opts(None), + None, + ) + .unwrap(); + assert!(out.code.contains("/abs/checkout/src/App.tsx")); +} + +#[test] +fn prod_output_is_path_free_with_display_path() { + let mut opts = CompileOptions::prod(); + opts.display_path = Some(PathBuf::from("/src/App.tsx")); + let a = compile_module(Path::new("/wt-a/src/App.tsx"), JSX_SOURCE, &opts, None).unwrap(); + let b = compile_module(Path::new("/wt-b/src/App.tsx"), JSX_SOURCE, &opts, None).unwrap(); + assert_eq!(a.code, b.code); + assert_eq!(a.map_data_url(), b.map_data_url()); + assert!(!a.code.contains("/wt-a")); +} + +#[test] +fn refresh_boundary_detection_is_unchanged_by_display_path() { + let with = compile_module( + Path::new("/wt-a/src/App.tsx"), + JSX_SOURCE, + &dev_opts(Some("/src/App.tsx")), + None, + ) + .unwrap(); + let without = compile_module( + Path::new("/wt-a/src/App.tsx"), + JSX_SOURCE, + &dev_opts(None), + None, + ) + .unwrap(); + assert_eq!( + with.is_refresh_boundary, without.is_refresh_boundary, + "display identity must not change refresh semantics" + ); + assert!(with.is_refresh_boundary, "App is a refresh boundary"); +} diff --git a/crates/oj_env/src/knobs.rs b/crates/oj_env/src/knobs.rs index ece35be3c..155b14b93 100644 --- a/crates/oj_env/src/knobs.rs +++ b/crates/oj_env/src/knobs.rs @@ -28,6 +28,27 @@ pub struct Knobs { /// `OJ_CACHE_DIR`, when non-empty: the cache base instead of `/.oj-cache`. pub cache_dir: Option, + /// The shared oj store's base dir, `OJ_STORE_DIR`: `oj dev --store` sets it + /// (to the given DIR, else `$XDG_CACHE_HOME/oj/store`, else + /// `$HOME/.cache/oj/store`) for itself and every child. Unset or empty, + /// there is no shared store (`None`). + pub store_dir: Option, + /// `OJ_STORE_REMOTE`, when non-empty: the remote store dev servers read + /// through (and push to under `store_push`). + pub store_remote: Option, + /// `OJ_STORE_TOKEN`, when non-empty: the bearer the remote store gets. + pub store_token: Option, + /// `OJ_STORE_PUSH` truthy: relocatable entries are pushed to the remote. + pub store_push: bool, + /// `OJ_STORE_READ_TOKEN`, when non-empty: `oj store serve` requires it on + /// reads (unset = public reads). + pub store_read_token: Option, + /// `OJ_STORE_WRITE_TOKEN`, when non-empty: `oj store serve` requires it on + /// writes (unset = writes refused). + pub store_write_token: Option, + /// `OJ_VERIFY_HITS` in `0..=1`: the share of persistent module-cache hits + /// recompiled and compared anyway (`0` = off). + pub verify_hits: f64, /// `OJ_HMR_GATE` or `LOVABLE_DEV_SERVER` is `1` / `true`. pub hmr_gate: bool, @@ -102,6 +123,18 @@ impl Knobs { cache_dir: get("OJ_CACHE_DIR") .filter(|v| !v.is_empty()) .map(PathBuf::from), + store_dir: get("OJ_STORE_DIR") + .filter(|v| !v.is_empty()) + .map(PathBuf::from), + store_remote: var("OJ_STORE_REMOTE").filter(|v| !v.is_empty()), + store_token: var("OJ_STORE_TOKEN").filter(|v| !v.is_empty()), + store_push: truthy("OJ_STORE_PUSH"), + store_read_token: var("OJ_STORE_READ_TOKEN").filter(|v| !v.is_empty()), + store_write_token: var("OJ_STORE_WRITE_TOKEN").filter(|v| !v.is_empty()), + verify_hits: var("OJ_VERIFY_HITS") + .and_then(|v| v.trim().parse::().ok()) + .filter(|v| !v.is_nan()) + .map_or(0.0, |v| v.clamp(0.0, 1.0)), hmr_gate: one_or_true("OJ_HMR_GATE") || one_or_true("LOVABLE_DEV_SERVER"), hmr_full_reload: var("OJ_HMR_FULL_RELOAD") .or_else(|| var("LOVABLE_HMR_FULL_RELOAD")) @@ -197,6 +230,34 @@ mod tests { Env::from_vars(vars.iter().map(|(k, v)| (*k, *v))).knobs } + #[test] + fn the_store_dir_is_the_variable_or_nothing() { + use std::path::Path; + assert_eq!( + knobs(&[("OJ_STORE_DIR", "/shared/oj")]) + .store_dir + .as_deref(), + Some(Path::new("/shared/oj")) + ); + // No default from the user's home: a plain `oj dev` shares nothing. + assert_eq!( + knobs(&[("XDG_CACHE_HOME", "/xdg"), ("HOME", "/home/u")]).store_dir, + None + ); + assert_eq!(knobs(&[("OJ_STORE_DIR", "")]).store_dir, None); + assert_eq!(knobs(&[]).store_dir, None); + } + + #[test] + fn verify_hits_is_a_clamped_share() { + assert_eq!(knobs(&[]).verify_hits, 0.0); + assert_eq!(knobs(&[("OJ_VERIFY_HITS", "0.25")]).verify_hits, 0.25); + assert_eq!(knobs(&[("OJ_VERIFY_HITS", "7")]).verify_hits, 1.0); + assert_eq!(knobs(&[("OJ_VERIFY_HITS", "-1")]).verify_hits, 0.0); + assert_eq!(knobs(&[("OJ_VERIFY_HITS", "NaN")]).verify_hits, 0.0); + assert_eq!(knobs(&[("OJ_VERIFY_HITS", "x")]).verify_hits, 0.0); + } + #[test] fn flags_follow_their_consumers_rules() { let k = knobs(&[]); diff --git a/crates/oj_js/Cargo.toml b/crates/oj_js/Cargo.toml index 9fcaa50d9..b5020b884 100644 --- a/crates/oj_js/Cargo.toml +++ b/crates/oj_js/Cargo.toml @@ -7,6 +7,7 @@ repository.workspace = true description = "Embedded JavaScript engine: Deno runtime with Node compatibility over the app's node_modules" [dependencies] +async-trait = "0.1" deno_core = { version = "0.412", features = ["v8"] } # oj-maintained forks (napi finalizer-registry patch, see the workspace # manifest); the dependency keys keep `use deno_runtime::`/`use deno_napi::` diff --git a/crates/oj_js/src/code_cache.rs b/crates/oj_js/src/code_cache.rs index 9c85facb1..dfeaf83b9 100644 --- a/crates/oj_js/src/code_cache.rs +++ b/crates/oj_js/src/code_cache.rs @@ -12,7 +12,7 @@ use std::collections::HashMap; use std::hash::Hasher; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, LazyLock, Mutex}; use std::time::Duration; @@ -28,6 +28,15 @@ pub struct FsCodeCache { dir: PathBuf, /// False in a process another one waits on (see [`consume_only`]). produce: bool, + /// Roots that file specifiers are relativized against before hashing + /// (longest match wins): the identity that lets two worktrees of the + /// same app, or two apps with the same node_modules layout, share one + /// entry. Each root is kept in both its spelled and canonicalized form, + /// because module specifiers may arrive either way (macOS /var vs + /// /private/var). A specifier under none of them keys absolute, which + /// costs sharing, never correctness. Each root carries its package name: + /// the identity of an app's own modules in a key that holds no path. + rel_roots: Vec<(PathBuf, Option)>, } /// Node's compile cache, which Vite's CLI enables, keeps entries in memory @@ -165,13 +174,54 @@ fn hash64(bytes: &[u8]) -> u64 { hasher.finish() } +/// The `name` of the package at `root`, the app's identity in a key that +/// cannot carry its path. `None` for a root with no manifest or an unnamed +/// one, whose own modules then key by their relative path alone. +fn package_name(root: &Path) -> Option { + let bytes = std::fs::read(root.join("package.json")).ok()?; + let manifest: serde_json::Value = serde_json::from_slice(&bytes).ok()?; + manifest + .get("name")? + .as_str() + .filter(|name| !name.is_empty()) + .map(str::to_string) +} + impl FsCodeCache { pub fn new(dir: PathBuf) -> Self { Self::with_produce(dir, PRODUCE.load(Ordering::Relaxed)) } fn with_produce(dir: PathBuf, produce: bool) -> Self { - Self { dir, produce } + Self { + dir, + produce, + rel_roots: Vec::new(), + } + } + + /// A cache whose file-specifier keys are relative to `roots` — the + /// shared-store constructor. `new` keeps absolute keys for callers that + /// only sweep or that serve a single fixed tree. + pub fn with_roots(dir: PathBuf, roots: Vec) -> Self { + let mut rel_roots: Vec<(PathBuf, Option)> = Vec::with_capacity(roots.len() * 2); + for root in roots { + let name = package_name(&root); + if let Ok(canon) = std::fs::canonicalize(&root) { + if canon != root { + rel_roots.push((canon, name.clone())); + } + } + rel_roots.push((root, name)); + } + // Longest prefix first, so a nested root wins over its parent. + rel_roots.sort_by_key(|(r, _)| std::cmp::Reverse(r.as_os_str().len())); + rel_roots.dedup_by(|a, b| a.0 == b.0); + Self { + dir, + produce: PRODUCE.load(Ordering::Relaxed), + rel_roots, + } } /// The engine-side hash for sources it caches itself (the ESM and @@ -186,10 +236,7 @@ impl FsCodeCache { /// source hash guards staleness — and an unedited module hits across /// restarts. Intent params (`?url`, `?raw`) stay: their compiled forms /// differ. - fn entry_key(specifier: &Url) -> u64 { - if specifier.query().is_none() && specifier.fragment().is_none() { - return hash64(stable_specifier(specifier.as_str()).as_bytes()); - } + fn entry_key(&self, specifier: &Url) -> u64 { let kept: Vec<&str> = specifier .query() .unwrap_or("") @@ -199,14 +246,46 @@ impl FsCodeCache { !p.is_empty() && name != "v" && name != "t" }) .collect(); - let mut base = specifier.clone(); - base.set_fragment(None); - if kept.is_empty() { - base.set_query(None); + // Root-relative form for file specifiers under a known root: the + // worktree-independent identity (`oj:/`), so worktree A's entry + // is worktree B's hit. The store is every app's, and `src/main.tsx` + // is another source in another app: an app's own module carries its + // package name, so two apps keep their entries instead of evicting + // each other's on every boot, while a dependency's file (the same + // bytes under any app) stays one entry. Everything else keys on the + // full URL. + let path_part = specifier + .to_file_path() + .ok() + .and_then(|path| { + self.rel_roots.iter().find_map(|(root, name)| { + let rel = path.strip_prefix(root).ok()?; + let rel = rel.to_string_lossy(); + let rel = if std::path::MAIN_SEPARATOR == '/' { + rel.into_owned() + } else { + rel.replace(std::path::MAIN_SEPARATOR, "/") + }; + let dependency = + rel.starts_with("node_modules/") || rel.contains("/node_modules/"); + Some(match name { + Some(name) if !dependency => format!("oj:/{rel}#{name}"), + _ => format!("oj:/{rel}"), + }) + }) + }) + .unwrap_or_else(|| { + let mut base = specifier.clone(); + base.set_fragment(None); + base.set_query(None); + base.as_str().to_string() + }); + let key = if kept.is_empty() { + path_part } else { - base.set_query(Some(&kept.join("&"))); - } - hash64(stable_specifier(base.as_str()).as_bytes()) + format!("{path_part}?{}", kept.join("&")) + }; + hash64(stable_specifier(&key).as_bytes()) } fn entry_path(&self, specifier: &Url, suffix: &str) -> PathBuf { @@ -222,7 +301,7 @@ impl FsCodeCache { if needs_separator { name.push(std::path::MAIN_SEPARATOR_STR); } - let _ = write!(name, "{:016x}-{suffix}.bin", Self::entry_key(specifier)); + let _ = write!(name, "{:016x}-{suffix}.bin", self.entry_key(specifier)); path } @@ -957,4 +1036,314 @@ mod hygiene_tests { "nothing new on disk" ); } + + // ---- shared-store keying: the pulp P0 contract ---- + + fn url_of(path: &str) -> Url { + Url::from_file_path(path).unwrap() + } + + #[test] + fn same_rel_path_across_worktrees_shares_one_entry() { + let dir = tempfile::tempdir().unwrap(); + let store = dir.path().join("cc"); + let a = FsCodeCache::with_roots(store.clone(), vec!["/work/wt-a".into()]); + let b = FsCodeCache::with_roots(store.clone(), vec!["/work/wt-b".into()]); + + a.put( + &url_of("/work/wt-a/src/App.tsx"), + CodeCacheType::EsModule, + 7, + b"bytecode", + ); + // Worktree B, same relative module, same source: worktree A's entry. + assert_eq!( + b.get( + &url_of("/work/wt-b/src/App.tsx"), + CodeCacheType::EsModule, + 7 + ) + .as_deref(), + Some(b"bytecode".as_slice()) + ); + // Different relative module: no false sharing. + assert_eq!( + b.get( + &url_of("/work/wt-b/src/Other.tsx"), + CodeCacheType::EsModule, + 7 + ), + None + ); + // Same module, edited source (new hash): a miss, never stale bytes. + assert_eq!( + b.get( + &url_of("/work/wt-b/src/App.tsx"), + CodeCacheType::EsModule, + 8 + ), + None + ); + // Exactly one entry file backs both worktrees (written by the flush). + flush_at_exit(); + let entries = std::fs::read_dir(&store) + .unwrap() + .flatten() + .filter(|e| e.file_name().to_string_lossy().ends_with(".bin")) + .count(); + assert_eq!(entries, 1); + } + + #[test] + fn node_modules_share_across_different_apps() { + let dir = tempfile::tempdir().unwrap(); + let store = dir.path().join("cc"); + let app1 = FsCodeCache::with_roots(store.clone(), vec!["/apps/blog".into()]); + let app2 = FsCodeCache::with_roots(store.clone(), vec!["/apps/shop".into()]); + let dep = "node_modules/react/index.js"; + + app1.put( + &url_of(&format!("/apps/blog/{dep}")), + CodeCacheType::Script, + 42, + b"react-bytecode", + ); + assert_eq!( + app2.get( + &url_of(&format!("/apps/shop/{dep}")), + CodeCacheType::Script, + 42 + ) + .as_deref(), + Some(b"react-bytecode".as_slice()) + ); + } + + #[test] + fn out_of_root_specifiers_key_absolute_and_do_not_collide_with_rel() { + let dir = tempfile::tempdir().unwrap(); + let store = dir.path().join("cc"); + let cache = FsCodeCache::with_roots(store.clone(), vec!["/work/app".into()]); + + // A monorepo sibling outside the root: cached, but keyed absolute. + let outside = url_of("/work/shared/util.ts"); + cache.put(&outside, CodeCacheType::EsModule, 1, b"outside"); + assert_eq!( + cache.get(&outside, CodeCacheType::EsModule, 1).as_deref(), + Some(b"outside".as_slice()) + ); + + // An in-root module whose rel form spells the same string as the + // absolute one must not collide: "oj:/" namespaces rel keys. + let inside = url_of("/work/app/work/shared/util.ts"); + assert_eq!(cache.get(&inside, CodeCacheType::EsModule, 1), None); + } + + #[test] + fn volatile_params_are_stripped_from_rel_keys_and_intent_params_kept() { + let dir = tempfile::tempdir().unwrap(); + let cache = FsCodeCache::with_roots(dir.path().join("cc"), vec!["/wt".into()]); + + let mut v1 = url_of("/wt/src/x.js"); + v1.set_query(Some("v=1")); + let mut v2 = url_of("/wt/src/x.js"); + v2.set_query(Some("v=2&t=999")); + cache.put(&v1, CodeCacheType::EsModule, 5, b"data"); + // A cache-busted re-request of the same module overwrites in place + // and hits: no one-entry-per-edit growth. + assert_eq!( + cache.get(&v2, CodeCacheType::EsModule, 5).as_deref(), + Some(b"data".as_slice()) + ); + + // Intent params compile differently and stay distinct. + let mut raw = url_of("/wt/src/x.js"); + raw.set_query(Some("raw")); + assert_eq!(cache.get(&raw, CodeCacheType::EsModule, 5), None); + } + + #[test] + fn canonicalized_specifier_matches_symlinked_root() { + // macOS hands out /var/folders tempdirs that canonicalize to + // /private/var; a root spelled one way must match specifiers spelled + // the other. + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join("app"); + std::fs::create_dir_all(root.join("src")).unwrap(); + std::fs::write(root.join("src/m.js"), b"export {}").unwrap(); + let canon_root = std::fs::canonicalize(&root).unwrap(); + + let store = dir.path().join("cc"); + // Cache constructed with the SPELLED root; specifier uses CANONICAL. + let cache = FsCodeCache::with_roots(store.clone(), vec![root.clone()]); + let canon_url = Url::from_file_path(canon_root.join("src/m.js")).unwrap(); + let spelled_url = Url::from_file_path(root.join("src/m.js")).unwrap(); + + cache.put(&canon_url, CodeCacheType::EsModule, 3, b"bc"); + assert_eq!( + cache + .get(&spelled_url, CodeCacheType::EsModule, 3) + .as_deref(), + Some(b"bc".as_slice()), + "spelled and canonical forms of one module share the entry" + ); + } + + #[test] + fn cjs_analysis_entries_share_across_worktrees_too() { + let dir = tempfile::tempdir().unwrap(); + let store = dir.path().join("cc"); + let a = FsCodeCache::with_roots(store.clone(), vec!["/wt-a".into()]); + let b = FsCodeCache::with_roots(store, vec!["/wt-b".into()]); + + let hash = a.compute_source_hash("module.exports = {}"); + let analysis = DenoCjsAnalysis::Esm; + a.set_cjs_analysis(&url_of("/wt-a/node_modules/dep/index.cjs"), hash, &analysis); + assert!(b + .get_cjs_analysis(&url_of("/wt-b/node_modules/dep/index.cjs"), hash) + .is_some()); + // A different source hash misses. + let other = NodeAnalysisCacheSourceHash(hash.0 ^ 1); + assert!(b + .get_cjs_analysis(&url_of("/wt-b/node_modules/dep/index.cjs"), other) + .is_none()); + } + + #[test] + fn plain_new_keeps_absolute_keys() { + let dir = tempfile::tempdir().unwrap(); + let store = dir.path().join("cc"); + let plain = FsCodeCache::new(store.clone()); + plain.put( + &url_of("/wt-a/src/x.js"), + CodeCacheType::EsModule, + 9, + b"abs", + ); + // Without rel roots, another path never aliases. + assert_eq!( + plain.get(&url_of("/wt-b/src/x.js"), CodeCacheType::EsModule, 9), + None + ); + assert_eq!( + plain + .get(&url_of("/wt-a/src/x.js"), CodeCacheType::EsModule, 9) + .as_deref(), + Some(b"abs".as_slice()) + ); + } + + #[test] + fn nested_root_wins_over_parent() { + let dir = tempfile::tempdir().unwrap(); + let store = dir.path().join("cc"); + // Both the app and a nested package root are registered: the longest + // prefix must win so the key is stable however the caller lists them. + let a = + FsCodeCache::with_roots(store.clone(), vec!["/mono".into(), "/mono/apps/web".into()]); + let b = FsCodeCache::with_roots(store, vec!["/mono2/apps/web".into(), "/mono2".into()]); + a.put( + &url_of("/mono/apps/web/src/a.ts"), + CodeCacheType::EsModule, + 4, + b"x", + ); + // Rel to the NESTED root ("src/a.ts") in both caches, whatever the + // vec order, so the entry is shared. + assert_eq!( + b.get( + &url_of("/mono2/apps/web/src/a.ts"), + CodeCacheType::EsModule, + 4 + ) + .as_deref(), + Some(b"x".as_slice()) + ); + } + + // The store is every app's: two apps' own modules at one relative path + // are two sources, told apart by the package name, and each keeps its + // entry (neither boot evicts the other's) while an edit still overwrites + // its app's in place; a worktree of an app shares its entries; a + // dependency's file at one relative path is one entry under any app, + // which an upgrade overwrites in place. + #[test] + fn own_modules_of_two_apps_coexist_and_a_dependency_stays_one_entry() { + let dir = tempfile::tempdir().unwrap(); + let store = dir.path().join("cc"); + let app = |name: &str, at: &str| { + let root = dir.path().join(at); + std::fs::create_dir_all(&root).unwrap(); + std::fs::write( + root.join("package.json"), + format!("{{\"name\":\"{name}\"}}"), + ) + .unwrap(); + root + }; + let (blog_root, shop_root, wt_root) = ( + app("blog", "apps/blog"), + app("shop", "apps/shop"), + app("blog", "wt/blog"), + ); + let blog = FsCodeCache::with_roots(store.clone(), vec![blog_root.clone()]); + let shop = FsCodeCache::with_roots(store.clone(), vec![shop_root.clone()]); + let wt = FsCodeCache::with_roots(store.clone(), vec![wt_root.clone()]); + let main = |root: &Path| url_of(root.join("src/main.tsx").to_str().unwrap()); + let dep = |root: &Path| url_of(root.join("node_modules/dep/index.js").to_str().unwrap()); + blog.put(&main(&blog_root), CodeCacheType::EsModule, 1, b"blog"); + shop.put(&main(&shop_root), CodeCacheType::EsModule, 2, b"shop"); + assert_eq!( + blog.get(&main(&blog_root), CodeCacheType::EsModule, 1) + .as_deref(), + Some(b"blog".as_slice()), + "shop's boot evicted blog's entry" + ); + assert_eq!( + shop.get(&main(&shop_root), CodeCacheType::EsModule, 2) + .as_deref(), + Some(b"shop".as_slice()) + ); + // A worktree of blog, same source: blog's entry. + assert_eq!( + wt.get(&main(&wt_root), CodeCacheType::EsModule, 1) + .as_deref(), + Some(b"blog".as_slice()) + ); + // An edit in blog overwrites blog's slot, nobody else's. + blog.put(&main(&blog_root), CodeCacheType::EsModule, 3, b"blog2"); + assert_eq!( + blog.get(&main(&blog_root), CodeCacheType::EsModule, 1), + None + ); + assert_eq!( + shop.get(&main(&shop_root), CodeCacheType::EsModule, 2) + .as_deref(), + Some(b"shop".as_slice()) + ); + // A dependency file: one slot under any app, overwritten by the next + // version. + blog.put(&dep(&blog_root), CodeCacheType::EsModule, 10, b"v1"); + shop.put(&dep(&shop_root), CodeCacheType::EsModule, 11, b"v2"); + assert_eq!( + blog.get(&dep(&blog_root), CodeCacheType::EsModule, 10), + None, + "the older dependency bytes were overwritten" + ); + assert_eq!( + blog.get(&dep(&blog_root), CodeCacheType::EsModule, 11) + .as_deref(), + Some(b"v2".as_slice()) + ); + flush_at_exit(); + let entries = std::fs::read_dir(&store) + .unwrap() + .flatten() + .filter(|e| e.file_name().to_string_lossy().ends_with(".bin")) + .count(); + assert_eq!( + entries, 3, + "two own-module entries and one dependency entry" + ); + } } diff --git a/crates/oj_js/src/lib.rs b/crates/oj_js/src/lib.rs index e58b904e5..6417bf5a2 100644 --- a/crates/oj_js/src/lib.rs +++ b/crates/oj_js/src/lib.rs @@ -24,6 +24,7 @@ mod loader; mod package_json_memo; mod scheduler; mod stand_ins; +pub mod tracing_fs; mod watchdog; mod worker; @@ -89,6 +90,10 @@ pub struct EngineConfig { /// can fan a GC over the engine. Long-lived engines set it; one-shots /// leave it out. pub registry: Option, + /// When set, every content read the isolates perform through the fs ops + /// layer is recorded into this log (pulp P2 TracingFs): the safety net + /// that sees reads whatever binding style the JS used. + pub trace_reads: Option>, } impl EngineConfig { @@ -99,6 +104,7 @@ impl EngineConfig { default_deadline: None, code_cache_dir: None, registry: None, + trace_reads: None, } } } diff --git a/crates/oj_js/src/tracing_fs.rs b/crates/oj_js/src/tracing_fs.rs new file mode 100644 index 000000000..3de02942f --- /dev/null +++ b/crates/oj_js/src/tracing_fs.rs @@ -0,0 +1,510 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2026 Raphael Amorim + +//! A [`FileSystem`] wrapper that records content reads (pulp P2): the one +//! seam every fs binding style crosses — `Deno.*` ops, `node:fs` CJS, and +//! named ESM imports alike — so plugin reads the JS-level interposition +//! cannot see still land in the trace. Delegates every operation verbatim; +//! recording happens on `open` with read intent and on the `read_file` +//! family (RealFs overrides the trait's open-routed defaults). +//! +//! Generated against deno_fs 0.169.0's trait surface; `cargo test +//! -p oj_js tracing_fs` carries a coverage guard that fails when a +//! deno_runtime bump changes the method set, so a new read path can never +//! silently bypass the recorder. + +use std::borrow::Cow; +use std::path::Path; +use std::path::PathBuf; +use std::rc::Rc; +use std::sync::Arc; +use std::sync::Mutex; + +use deno_runtime::deno_fs::FileSystem; +use deno_runtime::deno_fs::FsDirEntry; +use deno_runtime::deno_fs::FsFileType; +use deno_runtime::deno_fs::FsReadDirRc; +use deno_runtime::deno_fs::OpenOptions; +use deno_runtime::deno_fs::RealFs; +use deno_runtime::deno_io::fs::File; +use deno_runtime::deno_io::fs::FsResult; +use deno_runtime::deno_io::fs::FsStat; +use deno_runtime::deno_io::fs::FsStatFs; +use deno_runtime::deno_permissions::CheckedPath; +use deno_runtime::deno_permissions::CheckedPathBuf; + +/// Shared sink for recorded reads. The plugin host opens an action window +/// around each hook dispatch; every content read that lands while a window +/// is open is charged to EVERY open window (sound over-approximation: hooks +/// interleave on one isolate, so Rust-side attribution is impossible — the +/// JS-side AsyncLocalStorage buckets carry the precise attribution, and this +/// log is the safety net for reads they cannot see). +#[derive(Debug, Default)] +pub struct ReadLog { + windows: Mutex>>, + next: std::sync::atomic::AtomicU64, +} + +impl ReadLog { + pub fn begin(&self) -> u64 { + let id = self.next.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + self.windows + .lock() + .unwrap_or_else(|e| e.into_inner()) + .insert(id, Default::default()); + id + } + + pub fn finish(&self, id: u64) -> Vec { + self.windows + .lock() + .unwrap_or_else(|e| e.into_inner()) + .remove(&id) + .map(|set| set.into_iter().collect()) + .unwrap_or_default() + } + + fn record(&self, path: &Path) { + let mut windows = self.windows.lock().unwrap_or_else(|e| e.into_inner()); + if windows.is_empty() { + return; + } + for set in windows.values_mut() { + set.insert(path.to_path_buf()); + } + } +} + +#[derive(Debug)] +pub struct TracingFs { + inner: RealFs, + log: Arc, +} + +impl TracingFs { + pub fn new(log: Arc) -> Self { + Self { inner: RealFs, log } + } + + fn record(&self, path: &Path) { + self.log.record(path); + } +} + +#[async_trait::async_trait(?Send)] +impl FileSystem for TracingFs { + fn cwd(&self) -> FsResult { + self.inner.cwd() + } + + fn tmp_dir(&self) -> FsResult { + self.inner.tmp_dir() + } + + fn chdir(&self, path: &CheckedPath) -> FsResult<()> { + self.inner.chdir(path) + } + + fn umask(&self, mask: Option) -> FsResult { + self.inner.umask(mask) + } + + fn open_sync(&self, path: &CheckedPath, options: OpenOptions) -> FsResult> { + if options.read { + self.record(path.as_ref()); + } + self.inner.open_sync(path, options) + } + + async fn open_async<'a>( + &'a self, + path: CheckedPathBuf, + options: OpenOptions, + ) -> FsResult> { + if options.read { + self.record(path.as_ref()); + } + self.inner.open_async(path, options).await + } + + fn mkdir_sync(&self, path: &CheckedPath, recursive: bool, mode: Option) -> FsResult<()> { + self.inner.mkdir_sync(path, recursive, mode) + } + + async fn mkdir_async( + &self, + path: CheckedPathBuf, + recursive: bool, + mode: Option, + ) -> FsResult<()> { + self.inner.mkdir_async(path, recursive, mode).await + } + + #[cfg(unix)] + fn chmod_sync(&self, path: &CheckedPath, mode: u32) -> FsResult<()> { + self.inner.chmod_sync(path, mode) + } + + #[cfg(not(unix))] + fn chmod_sync(&self, path: &CheckedPath, mode: i32) -> FsResult<()> { + self.inner.chmod_sync(path, mode) + } + + #[cfg(unix)] + async fn chmod_async(&self, path: CheckedPathBuf, mode: u32) -> FsResult<()> { + self.inner.chmod_async(path, mode).await + } + + #[cfg(not(unix))] + async fn chmod_async(&self, path: CheckedPathBuf, mode: i32) -> FsResult<()> { + self.inner.chmod_async(path, mode).await + } + + fn chown_sync(&self, path: &CheckedPath, uid: Option, gid: Option) -> FsResult<()> { + self.inner.chown_sync(path, uid, gid) + } + + async fn chown_async( + &self, + path: CheckedPathBuf, + uid: Option, + gid: Option, + ) -> FsResult<()> { + self.inner.chown_async(path, uid, gid).await + } + + fn lchmod_sync(&self, path: &CheckedPath, mode: u32) -> FsResult<()> { + self.inner.lchmod_sync(path, mode) + } + + async fn lchmod_async(&self, path: CheckedPathBuf, mode: u32) -> FsResult<()> { + self.inner.lchmod_async(path, mode).await + } + + fn lchown_sync(&self, path: &CheckedPath, uid: Option, gid: Option) -> FsResult<()> { + self.inner.lchown_sync(path, uid, gid) + } + + async fn lchown_async( + &self, + path: CheckedPathBuf, + uid: Option, + gid: Option, + ) -> FsResult<()> { + self.inner.lchown_async(path, uid, gid).await + } + + fn remove_sync(&self, path: &CheckedPath, recursive: bool) -> FsResult<()> { + self.inner.remove_sync(path, recursive) + } + + async fn remove_async(&self, path: CheckedPathBuf, recursive: bool) -> FsResult<()> { + self.inner.remove_async(path, recursive).await + } + + fn copy_file_sync(&self, oldpath: &CheckedPath, newpath: &CheckedPath) -> FsResult<()> { + self.inner.copy_file_sync(oldpath, newpath) + } + + async fn copy_file_async( + &self, + oldpath: CheckedPathBuf, + newpath: CheckedPathBuf, + ) -> FsResult<()> { + self.inner.copy_file_async(oldpath, newpath).await + } + + fn cp_sync(&self, path: &CheckedPath, new_path: &CheckedPath) -> FsResult<()> { + self.inner.cp_sync(path, new_path) + } + + async fn cp_async(&self, path: CheckedPathBuf, new_path: CheckedPathBuf) -> FsResult<()> { + self.inner.cp_async(path, new_path).await + } + + fn stat_sync(&self, path: &CheckedPath) -> FsResult { + self.inner.stat_sync(path) + } + + async fn stat_async(&self, path: CheckedPathBuf) -> FsResult { + self.inner.stat_async(path).await + } + + fn lstat_sync(&self, path: &CheckedPath) -> FsResult { + self.inner.lstat_sync(path) + } + + async fn lstat_async(&self, path: CheckedPathBuf) -> FsResult { + self.inner.lstat_async(path).await + } + + fn statfs_sync(&self, path: &CheckedPath, bigint: bool) -> FsResult { + self.inner.statfs_sync(path, bigint) + } + + async fn statfs_async(&self, path: CheckedPathBuf, bigint: bool) -> FsResult { + self.inner.statfs_async(path, bigint).await + } + + fn realpath_sync(&self, path: &CheckedPath) -> FsResult { + self.inner.realpath_sync(path) + } + + async fn realpath_async(&self, path: CheckedPathBuf) -> FsResult { + self.inner.realpath_async(path).await + } + + fn read_dir_sync(&self, path: &CheckedPath) -> FsResult> { + self.inner.read_dir_sync(path) + } + + async fn read_dir_async(&self, path: CheckedPathBuf) -> FsResult { + self.inner.read_dir_async(path).await + } + + fn rename_sync(&self, oldpath: &CheckedPath, newpath: &CheckedPath) -> FsResult<()> { + self.inner.rename_sync(oldpath, newpath) + } + + async fn rename_async(&self, oldpath: CheckedPathBuf, newpath: CheckedPathBuf) -> FsResult<()> { + self.inner.rename_async(oldpath, newpath).await + } + + fn rmdir_sync(&self, path: &CheckedPath) -> FsResult<()> { + self.inner.rmdir_sync(path) + } + + async fn rmdir_async(&self, path: CheckedPathBuf) -> FsResult<()> { + self.inner.rmdir_async(path).await + } + + fn link_sync(&self, oldpath: &CheckedPath, newpath: &CheckedPath) -> FsResult<()> { + self.inner.link_sync(oldpath, newpath) + } + + async fn link_async(&self, oldpath: CheckedPathBuf, newpath: CheckedPathBuf) -> FsResult<()> { + self.inner.link_async(oldpath, newpath).await + } + + fn symlink_sync( + &self, + oldpath: &CheckedPath, + newpath: &CheckedPath, + file_type: Option, + ) -> FsResult<()> { + self.inner.symlink_sync(oldpath, newpath, file_type) + } + + async fn symlink_async( + &self, + oldpath: CheckedPathBuf, + newpath: CheckedPathBuf, + file_type: Option, + ) -> FsResult<()> { + self.inner.symlink_async(oldpath, newpath, file_type).await + } + + fn read_link_sync(&self, path: &CheckedPath) -> FsResult { + self.inner.read_link_sync(path) + } + + async fn read_link_async(&self, path: CheckedPathBuf) -> FsResult { + self.inner.read_link_async(path).await + } + + fn truncate_sync(&self, path: &CheckedPath, len: u64) -> FsResult<()> { + self.inner.truncate_sync(path, len) + } + + async fn truncate_async(&self, path: CheckedPathBuf, len: u64) -> FsResult<()> { + self.inner.truncate_async(path, len).await + } + + fn utime_sync( + &self, + path: &CheckedPath, + atime_secs: i64, + atime_nanos: u32, + mtime_secs: i64, + mtime_nanos: u32, + ) -> FsResult<()> { + self.inner + .utime_sync(path, atime_secs, atime_nanos, mtime_secs, mtime_nanos) + } + + async fn utime_async( + &self, + path: CheckedPathBuf, + atime_secs: i64, + atime_nanos: u32, + mtime_secs: i64, + mtime_nanos: u32, + ) -> FsResult<()> { + self.inner + .utime_async(path, atime_secs, atime_nanos, mtime_secs, mtime_nanos) + .await + } + + fn lutime_sync( + &self, + path: &CheckedPath, + atime_secs: i64, + atime_nanos: u32, + mtime_secs: i64, + mtime_nanos: u32, + ) -> FsResult<()> { + self.inner + .lutime_sync(path, atime_secs, atime_nanos, mtime_secs, mtime_nanos) + } + + async fn lutime_async( + &self, + path: CheckedPathBuf, + atime_secs: i64, + atime_nanos: u32, + mtime_secs: i64, + mtime_nanos: u32, + ) -> FsResult<()> { + self.inner + .lutime_async(path, atime_secs, atime_nanos, mtime_secs, mtime_nanos) + .await + } + + fn write_file_sync( + &self, + path: &CheckedPath, + options: OpenOptions, + data: &[u8], + ) -> FsResult<()> { + self.inner.write_file_sync(path, options, data) + } + + async fn write_file_async<'a>( + &'a self, + path: CheckedPathBuf, + options: OpenOptions, + data: Box<[u8]>, + ) -> FsResult<()> { + self.inner.write_file_async(path, options, data).await + } + + fn read_file_sync( + &self, + path: &CheckedPath, + options: OpenOptions, + ) -> FsResult> { + self.record(path.as_ref()); + self.inner.read_file_sync(path, options) + } + + async fn read_file_async<'a>( + &'a self, + path: CheckedPathBuf, + options: OpenOptions, + ) -> FsResult> { + self.record(path.as_ref()); + self.inner.read_file_async(path, options).await + } + + fn is_file_sync(&self, path: &CheckedPath) -> bool { + self.inner.is_file_sync(path) + } + + fn is_dir_sync(&self, path: &CheckedPath) -> bool { + self.inner.is_dir_sync(path) + } + + fn exists_sync(&self, path: &CheckedPath) -> bool { + self.inner.exists_sync(path) + } + + async fn exists_async(&self, path: CheckedPathBuf) -> FsResult { + self.inner.exists_async(path).await + } + + fn read_text_file_lossy_sync(&self, path: &CheckedPath) -> FsResult> { + self.record(path.as_ref()); + self.inner.read_text_file_lossy_sync(path) + } + + async fn read_text_file_lossy_async<'a>( + &'a self, + path: CheckedPathBuf, + ) -> FsResult> { + self.record(path.as_ref()); + self.inner.read_text_file_lossy_async(path).await + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_are_charged_to_every_open_window_and_only_then() { + let log = ReadLog::default(); + // No window open: recording is a no-op (the hot steady-state). + log.record(Path::new("/idle.txt")); + let a = log.begin(); + log.record(Path::new("/one.txt")); + let b = log.begin(); + log.record(Path::new("/two.txt")); + let got_a = log.finish(a); + log.record(Path::new("/three.txt")); + let got_b = log.finish(b); + assert!(got_a.contains(&PathBuf::from("/one.txt"))); + assert!( + got_a.contains(&PathBuf::from("/two.txt")), + "charge-all while open" + ); + assert!(!got_a.contains(&PathBuf::from("/idle.txt"))); + assert!( + !got_b.contains(&PathBuf::from("/one.txt")), + "opened after that read" + ); + assert!( + got_b.contains(&PathBuf::from("/three.txt")), + "window b still open" + ); + assert!(log.finish(a).is_empty(), "double finish is inert"); + } + + #[test] + fn tracing_fs_records_reads_and_delegates_content() { + use deno_runtime::deno_permissions::CheckedPathBuf; + let dir = std::env::temp_dir().join(format!("oj-tracingfs-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("input.txt"); + std::fs::write(&file, b"hello").unwrap(); + + let log = Arc::new(ReadLog::default()); + let fs = TracingFs::new(log.clone()); + let id = log.begin(); + let checked = CheckedPathBuf::unsafe_new(file.clone()); + let read = fs + .read_file_sync(&checked.as_checked_path(), OpenOptions::read()) + .unwrap(); + assert_eq!(&*read, b"hello", "delegation is verbatim"); + let seen = log.finish(id); + assert!( + seen.contains(&file), + "the read landed in the window: {seen:?}" + ); + // Writes are not reads: opening for write records nothing. + let id = log.begin(); + let out = dir.join("out.txt"); + let checked_out = CheckedPathBuf::unsafe_new(out.clone()); + fs.write_file_sync( + &checked_out.as_checked_path(), + OpenOptions::write(true, false, true, None), + b"x", + ) + .unwrap(); + let seen = log.finish(id); + assert!( + !seen.contains(&out), + "write-only open is not a content read" + ); + } +} diff --git a/crates/oj_js/src/worker.rs b/crates/oj_js/src/worker.rs index 650683955..ababa6352 100644 --- a/crates/oj_js/src/worker.rs +++ b/crates/oj_js/src/worker.rs @@ -68,7 +68,12 @@ fn engine_loaders( ) -> Result { let sys = Sys::default(); - let code_cache = code_cache_dir.map(|dir| Arc::new(FsCodeCache::new(dir))); + // Keys relative to the app root: the code cache lives in the shared + // per-user store, where an absolute key would pin entries to one + // worktree. Scratch scripts under `/.oj-cache` relativize the same + // way, since the default cache_base is inside the root. + let code_cache = + code_cache_dir.map(|dir| Arc::new(FsCodeCache::with_roots(dir, vec![root.to_path_buf()]))); let workspace_factory = Arc::new(WorkspaceFactory::new( sys.clone(), @@ -137,6 +142,7 @@ fn engine_loaders( struct WorkerShared { root: PathBuf, code_cache_dir: Option, + trace_reads: Option>, memory_limit_bytes: Option, blob_store: Arc, broadcast_channel: InMemoryBroadcastChannel, @@ -160,6 +166,7 @@ pub(crate) fn build_worker( let shared = WorkerShared { root: config.root.clone(), code_cache_dir: config.code_cache_dir.clone(), + trace_reads: config.trace_reads.clone(), memory_limit_bytes: config.memory_limit_bytes, blob_store: Arc::new(BlobStore::default()), broadcast_channel: InMemoryBroadcastChannel::default(), @@ -172,7 +179,13 @@ pub(crate) fn build_worker( broadcast_channel: shared.broadcast_channel.clone(), deno_rt_native_addon_loader: None, feature_checker: Default::default(), - fs: Arc::new(RealFs), + fs: match &shared.trace_reads { + // The one seam every fs binding crosses: Deno.* ops, node:fs CJS, + // and named ESM imports all route through this trait object, so + // TracingFs sees reads the JS-level patch cannot. + Some(log) => Arc::new(crate::tracing_fs::TracingFs::new(log.clone())), + None => Arc::new(RealFs), + }, module_loader: loaders.module_loader, node_services: Some(loaders.node_services), npm_process_state_provider: None, @@ -251,7 +264,13 @@ fn create_web_worker_cb( deno_rt_native_addon_loader: None, compiled_wasm_module_store: Some(shared.compiled_wasm_module_store.clone()), feature_checker: Default::default(), - fs: Arc::new(RealFs), + fs: match &shared.trace_reads { + // The one seam every fs binding crosses: Deno.* ops, node:fs CJS, + // and named ESM imports all route through this trait object, so + // TracingFs sees reads the JS-level patch cannot. + Some(log) => Arc::new(crate::tracing_fs::TracingFs::new(log.clone())), + None => Arc::new(RealFs), + }, main_inspector_session_tx: Default::default(), module_loader: loaders.module_loader, node_services: Some(loaders.node_services), diff --git a/crates/oj_server/Cargo.toml b/crates/oj_server/Cargo.toml index 750b3d9d4..bc7b79e74 100644 --- a/crates/oj_server/Cargo.toml +++ b/crates/oj_server/Cargo.toml @@ -23,6 +23,7 @@ axum.workspace = true oxc_sourcemap.workspace = true tokio.workspace = true notify.workspace = true +serde.workspace = true serde_json.workspace = true json-strip-comments = "3.1.2" blake3.workspace = true @@ -76,7 +77,6 @@ tempfile.workspace = true # test-util: paused time for the debounce test, like crates/oj. tokio = { workspace = true, features = ["test-util"] } tower.workspace = true -serde.workspace = true [target.'cfg(unix)'.dependencies] libc = "0.2" diff --git a/crates/oj_server/src/assets/plugin-host.mjs b/crates/oj_server/src/assets/plugin-host.mjs index 84c34f0c9..862e155bd 100644 --- a/crates/oj_server/src/assets/plugin-host.mjs +++ b/crates/oj_server/src/assets/plugin-host.mjs @@ -1168,7 +1168,7 @@ function transformRequestFor(c) { // BEFORE treating a leading `/` as root-relative (Vite's asSrc). let filePath = null; if (bareId.startsWith("/@fs/")) { - const p = bareId.slice(4); + const p = fsUrlPath(bareId.slice(4), root); if (existsSync(p)) filePath = p; } else if (isAbsolute(bareId) && existsSync(bareId)) { filePath = bareId; @@ -2461,6 +2461,33 @@ let emitCounter = 0; // `chunkFileNames` before generateBundle so `this.getFileName(refId)` resolves. const transformEmitStore = new AsyncLocalStorage(); +// Patch the shared node:fs CJS object so plugin reads during a transform land +// in the active read bucket. The host's own reads use named ESM imports bound +// before this patch, so they are never recorded. +(() => { + try { + const req = createRequire(import.meta.url); + const fsmod = req("fs"); + const record = (p) => { + const bucket = transformReadStore.getStore(); + if (bucket && typeof p === "string") bucket.add(p); + }; + const wrap = (obj, name, pathArg) => { + const orig = obj[name]; + if (typeof orig !== "function" || orig.__ojTraced) return; + const patched = function (...args) { + record(args[pathArg]); + return orig.apply(this, args); + }; + patched.__ojTraced = true; + obj[name] = patched; + }; + wrap(fsmod, "readFileSync", 0); + wrap(fsmod, "readFile", 0); + if (fsmod.promises) wrap(fsmod.promises, "readFile", 0); + } catch {} +})(); + // A minimal stand-in for Vite's `vite:css-post` plugin. UnoCSS (and similar) // look up a plugin named "vite:css-post" in `config.plugins` during their build // hook and call its `transform` with the CSS they generate, to route it into @@ -2573,6 +2600,13 @@ function decoratePluginError(e, plugin, id) { const watchedFiles = new Set(); const transformWatchStore = new AsyncLocalStorage(); +// Files a plugin hook READS during a transform (pulp P2 constructive traces): +// the dev server digests them into the cached entry so a warm hit re-verifies +// them instead of serving output whose side inputs changed. Recording happens +// by patching the node:fs module object below; plugins that bind NAMED esm +// imports of node:fs bypass the patch (Deno's syncBuiltinESMExports is a +// no-op) and are covered by the Rust TracingFs ops layer instead. +const transformReadStore = new AsyncLocalStorage(); // Per-transform map of oj-resolved imports (spec -> id) the Rust side computes and // passes in, so a plugin's `this.resolve` during transform is a local lookup rather // than a host round-trip. ctx.resolve consults it first. @@ -3528,11 +3562,39 @@ function knownModuleId(id, c = main) { return false; } } +// The workspace an app belongs to, as the dev server's `workspace_of` finds +// it: the farthest ancestor holding a node_modules dir, canonical. +const workspaceRoots = new Map(); +function workspaceRootOf(root) { + let ws = workspaceRoots.get(root); + if (ws === undefined) { + ws = root; + for (let dir = dirname(root); ; dir = dirname(dir)) { + try { + if (statSync(join(dir, "node_modules")).isDirectory()) ws = dir; + } catch {} + if (dirname(dir) === dir) break; + } + try { + ws = realpathSync(ws); + } catch {} + workspaceRoots.set(root, ws); + } + return ws; +} + +// The file behind the part of a `/@fs` url after `/@fs`: the dev server +// serves in-workspace files outside the root as `/@fs/@mono/`. +function fsUrlPath(afterFs, root) { + return afterFs.startsWith("/@mono/") ? join(workspaceRootOf(root), afterFs.slice("/@mono/".length)) : afterFs; +} + // Vite graph nodes carry the module's served URL beside its resolved id: HMR // update frames are built from `node.url`, and the client matches them against // the URLs it imported. A resolved id that names a plain app file maps to the -// URL oj serves it at (root-relative, or /@fs for an outside-root file); -// everything else (virtuals, queries, dependencies) keeps the id, as before. +// URL oj serves it at (root-relative, `/@fs/@mono/` for an outside-root +// file in the workspace, else `/@fs/`); everything else (virtuals, +// queries, dependencies) keeps the id, as before. function applicationModuleUrl(id) { const file = String(id); if (!isAbsolute(file) || file.includes("?") || file.split(/[\\/]/).includes("node_modules")) return id; @@ -3542,10 +3604,19 @@ function applicationModuleUrl(id) { return id; } const root = main.resolvedConfig?.root ?? initial.config?.root ?? process.cwd(); + const outside = (rel) => rel === ".." || rel.startsWith("../") || rel.startsWith("..\\") || isAbsolute(rel); const rel = relative(root, file); - return rel === ".." || rel.startsWith("../") || rel.startsWith("..\\") || isAbsolute(rel) - ? `/@fs${file.replaceAll("\\", "/")}` - : `/${rel.replaceAll("\\", "/")}`; + if (!outside(rel)) return `/${rel.replaceAll("\\", "/")}`; + const ws = workspaceRootOf(root); + let real = file; + try { + real = realpathSync(file); + } catch {} + for (const candidate of [file, real]) { + const inWs = relative(ws, candidate); + if (!outside(inWs)) return `/@fs/@mono/${inWs.replaceAll("\\", "/")}`; + } + return `/@fs${file.replaceAll("\\", "/")}`; } // One per environment, as each Vite DevEnvironment has its own: `c` is the // container whose hooks it knows ids from. @@ -6389,6 +6460,7 @@ async function transform(c, code, id, resolvedJson, phase, priorJson) { JSON.stringify({ code: current, watchFiles: [...bucket], + readFiles: [...readBucket], maps, mapPlugins, mapBroken, @@ -6415,8 +6487,11 @@ async function transform(c, code, id, resolvedJson, phase, priorJson) { for (const { p, fn } of pluginsWithHook(c, "moduleParsed")) await fn.call(ctxFor(c, p), info); return result(); }; + const readBucket = new Set(); return transformWatchStore.run(bucket, () => - transformEmitStore.run(chunkBucket, () => transformResolveStore.run({ importer: id, map: resolveMap }, runLoop)), + transformEmitStore.run(chunkBucket, () => + transformResolveStore.run({ importer: id, map: resolveMap }, () => transformReadStore.run(readBucket, runLoop)), + ), ); } @@ -8576,6 +8651,14 @@ async function run(hook, args, c) { } return JSON.stringify(pats); } + if (hook === "getCollectsFromTransforms") { + // Plugins that gather state from every module's transform and serve it + // from a virtual (UnoCSS's uno.css, WindiCSS): the dev server compiles app + // modules each session for them instead of serving its persistent cache. + return String( + c.plugins.some((p) => p && typeof p.name === "string" && /^(unocss|windicss|vite-plugin-windicss)\b/.test(p.name)), + ); + } if (hook === "getHasLoad") { const has = c.plugins.some((p) => typeof hookHandler(p.load) === "function"); return String(has); diff --git a/crates/oj_server/src/crawl.rs b/crates/oj_server/src/crawl.rs index 58e73c094..1d07b0e9e 100644 --- a/crates/oj_server/src/crawl.rs +++ b/crates/oj_server/src/crawl.rs @@ -105,7 +105,7 @@ fn crawl_url(import: &str) -> String { fn crawl_file(state: &ServerState, url: &str) -> Option { let url = url.split('?').next().unwrap_or(url); let file = if let Some(abs) = url.strip_prefix("/@fs") { - let f = PathBuf::from(abs); + let f = crate::rewrite::fs_url_to_path(&state.workspace_root_dir, abs); let allowed = state .fs_allow .lock() diff --git a/crates/oj_server/src/css_engine.rs b/crates/oj_server/src/css_engine.rs index 520d55764..c9ee1b23a 100644 --- a/crates/oj_server/src/css_engine.rs +++ b/crates/oj_server/src/css_engine.rs @@ -201,6 +201,7 @@ impl CssEngine { registry: Option, ) -> Result { let config = EngineConfig { + trace_reads: None, root: root.to_path_buf(), memory_limit_bytes: Some(memory_limit_bytes), default_deadline: None, @@ -397,7 +398,10 @@ fn strip_stack(message: &str) -> &str { fn absolute_from(base: &str, from: &str) -> String { let clean = from.split(['?', '#']).next().unwrap_or(from); if let Some(fs) = clean.strip_prefix("/@fs") { - return fs.to_string(); + let workspace = crate::rewrite::workspace_of(Path::new(base)); + return crate::rewrite::fs_url_to_path(&workspace, fs) + .display() + .to_string(); } if let Some(rel) = clean.strip_prefix('/') { return Path::new(base).join(rel).display().to_string(); @@ -424,6 +428,12 @@ mod tests { absolute_from("/app/web", "/@fs/pkg/dist/theme.css"), "/pkg/dist/theme.css" ); + // The worktree-independent form expands against the workspace (no + // node_modules ancestor here, so the app itself). + assert_eq!( + absolute_from("/app/web", "/@fs/@mono/pkg/theme.css"), + "/app/web/pkg/theme.css" + ); assert_eq!( absolute_from("/app/web", "relative/x.css"), "/app/web/relative/x.css" diff --git a/crates/oj_server/src/lib.rs b/crates/oj_server/src/lib.rs index 0690f5b0f..29d31e48d 100644 --- a/crates/oj_server/src/lib.rs +++ b/crates/oj_server/src/lib.rs @@ -16,7 +16,7 @@ use axum::{ routing::{get, post}, Router, }; -use oj_cache::CachedModule; +use oj_cache::{CachedModule, PersistentCache}; pub mod css_engine; pub mod etag; @@ -44,6 +44,8 @@ mod assets_serve; mod css_urls; use assets_serve::*; mod rewrite; +pub mod store_remote; +pub mod store_server; use rewrite::*; mod deps; use deps::*; @@ -160,7 +162,8 @@ pub use assets_serve::{asset_data_url, has_word_param, inline_url_under, svg_to_ pub use ssr::*; pub use style_file::{ compile_style_file, needs_css_compile, needs_preprocess_engine, read_style_source, - start_dev_inline_style, start_dev_url_base, style_slot, StyleInputs, StyleModule, StyleSlots, + start_dev_file_url, start_dev_inline_style, start_dev_url_base, style_slot, StyleInputs, + StyleModule, StyleSlots, }; mod middleware; pub use middleware::{RouteHook, RouteHookSlot}; @@ -276,9 +279,18 @@ const START_ASSETS: &[(&str, &str)] = &[ /// Persistent V8 code-cache dir for embedded engines, keyed by the V8 ABI and /// NOT the oj version: per-entry source hashes already invalidate changed scripts. pub fn engine_code_cache_dir(root: &Path) -> PathBuf { - oj_cache::cache_root(root) - .join("code-cache") - .join(oj_js::engine_abi_key()) + engine_code_cache_dir_in(root, oj_cache::store::store_root().as_deref()) +} + +/// [`engine_code_cache_dir`] with the shared store given. Bytecode is +/// path-free (keys are root-relative, entries carry their source hash), so +/// with a store every worktree and app on this machine warms one directory. +fn engine_code_cache_dir_in(root: &Path, store: Option<&Path>) -> PathBuf { + let leaf = PathBuf::from("code-cache").join(oj_js::engine_abi_key()); + match store { + Some(store) => store.join(leaf), + None => oj_cache::cache_root(root).join(leaf), + } } pub fn prepare_cache_root(root: &Path) { @@ -346,6 +358,10 @@ pub struct DevServer { /// Vite's `--mode` for `serve` (default `development`): selects `.env.`, /// `import.meta.env.MODE`, and the mode plugin `config` hooks see. pub mode: Option, + /// `oj dev --store`: the oj store is on. Compiled modules persist to + /// disk, relocatable ones in the shared per-user store, so a restart, a + /// second worktree or a fresh sandbox serves them without compiling. + pub store: bool, /// `import.meta.env` keys served at request time ([`runtime_env`]). pub runtime_env: Option, /// The runtime the dep optimizer's rolldown runs on (see @@ -355,6 +371,27 @@ pub struct DevServer { struct ServerState { root: PathBuf, + /// The remote substituter (OJ_STORE_REMOTE), when configured: local + /// shared store first, then this, Metro's chain. + remote_store: Option>, + /// The (canonical) workspace root: `/@fs/@mono/` URLs resolve + /// against it, and module-cache keys relativize /@fs URLs through it. + workspace_root_dir: PathBuf, + /// The oj store is on (`oj dev --store`): compiled modules persist. + persistent_cache: bool, + /// The `--config` file the server was started with, if any. + config_file: Option, + cache: PersistentCache, + cache_writes: tokio::sync::mpsc::Sender<(String, Arc)>, + /// A plugin collects state from every app module's transform and serves + /// it from a virtual (UnoCSS's `uno.css`): an app module served from the + /// persistent cache would be state it never saw, so app modules compile + /// each session and only dependencies serve from the store. + collector_plugins: bool, + plugins_use_module_parsed: bool, + /// The keys whose `moduleParsed` the plugins saw this session: a compile + /// fires it on the host, a disk hit replays it once. + parsed_fired: Mutex>, /// Vite's `publicDir`; None when the config disables it (`publicDir: false`). public_dir: Option, /// The URL prefix Vite would serve this app's optimized deps under @@ -1044,13 +1081,22 @@ impl ClientDefines<'_> { /// What the final client define list yields for the server state. struct InstalledDefines { html_env: std::collections::BTreeMap, + /// Salts the persistent cache: a cached compile embeds the defines. + digest: String, } impl InstalledDefines { fn of(defines: &Defines) -> Self { - InstalledDefines { - html_env: oj_env::html_env_map(defines), + let html_env = oj_env::html_env_map(defines); + let mut hasher = blake3::Hasher::new(); + for (k, v) in defines { + hasher.update(k.as_bytes()); + hasher.update(&[0]); + hasher.update(v.as_bytes()); + hasher.update(&[0]); } + let digest = hasher.finalize().to_hex().to_string(); + InstalledDefines { html_env, digest } } } @@ -1340,6 +1386,8 @@ async fn fold_plugin_defines(host: &PluginHost, defines: &ClientDefines<'_>) -> /// are skipped (the tagger case: no transform, no HMR hooks). #[derive(Default)] struct PluginCaps { + use_module_parsed: bool, + collects_from_transforms: bool, have_transform: bool, have_load: bool, have_resolve_id: bool, @@ -1364,6 +1412,8 @@ async fn pre_resolve_filters( impl PluginCaps { async fn probe(host: &PluginHost) -> Self { + let use_module_parsed = host.has_module_parsed().await; + let collects_from_transforms = host.collects_from_transforms().await; let have_transform = host.has_transform().await; let have_load = host.has_load().await; let have_resolve_id = host.has_resolve_id().await; @@ -1376,6 +1426,8 @@ impl PluginCaps { let _ = host.build_hook_plan().await; let have_transform_index_html = host.has_transform_index_html().await; PluginCaps { + use_module_parsed, + collects_from_transforms, have_transform, have_load, have_resolve_id, @@ -1526,20 +1578,7 @@ pub fn tsconfig_file(config: &oj_config::OjConfig) -> Option { /// The client environment's resolver, as the dev server builds it. pub fn client_resolver(root: &Path, config: &oj_config::OjConfig) -> OjResolver { - OjResolver::with_settings( - root, - oj_resolver::ResolveSettings { - conditions: oj_config::resolve_conditions(config, "client"), - alias: oj_config::resolve_alias(config, "client"), - dedupe: oj_config::environment_dedupe(config, "client"), - extensions: oj_config::resolve_extensions(config), - main_fields: oj_config::resolve_main_fields(config), - preserve_symlinks: oj_config::resolve_preserve_symlinks(config), - server: false, - tsconfig_paths: tsconfig_paths(config), - tsconfig_file: tsconfig_file(config), - }, - ) + OjResolver::with_settings(root, client_settings(config)) } /// A dev environment's resolver for plugins (`this.resolve`, `this.load`), with @@ -1590,6 +1629,133 @@ pub(crate) fn environment_resolver( ) } +/// The client environment's resolve settings, as the dev server builds them. +fn client_settings(config: &oj_config::OjConfig) -> oj_resolver::ResolveSettings { + oj_resolver::ResolveSettings { + conditions: oj_config::resolve_conditions(config, "client"), + alias: oj_config::resolve_alias(config, "client"), + dedupe: oj_config::environment_dedupe(config, "client"), + extensions: oj_config::resolve_extensions(config), + main_fields: oj_config::resolve_main_fields(config), + preserve_symlinks: oj_config::resolve_preserve_symlinks(config), + server: false, + tsconfig_paths: tsconfig_paths(config), + tsconfig_file: tsconfig_file(config), + } +} + +/// Everything besides the source bytes that changes a module's compiled +/// output, folded into the persistent module cache's salt. Metro's rule: +/// hash the toolchain, not just the file. Covers, by content digest: the +/// dependency epoch (lockfiles, patches, package.json, also the +/// plugin-version epoch), the config graph (vite config plus every file it +/// imported, an `oj.plugins.mjs`), every `tsconfig*.json` at the root, the +/// PostCSS config and browserslist, and the resolver settings with alias targets +/// hashed root- or workspace-relative so the salt is worktree-independent. +fn module_cache_config_salt( + root: &Path, + settings: &oj_resolver::ResolveSettings, + config_path: Option<&Path>, +) -> String { + // Spelled (uncanonicalized) workspace: alias targets come from config + // resolution against the root's own spelling, and the salt only needs + // internal consistency, not realpath identity. + let workspace = oj_cache::store::workspace_root(root); + let mut hasher = blake3::Hasher::new(); + optimize::hash_lockfiles(root, &mut hasher); + // Every tsconfig at the root, not the top one alone: the resolver follows + // `references` and `extends`, and Vite's template keeps `paths` in + // tsconfig.app.json. + let mut inputs = vec![root.join("package.json")]; + if let Ok(entries) = std::fs::read_dir(root) { + inputs.extend(entries.flatten().map(|e| e.path()).filter(|p| { + p.file_name() + .and_then(|n| n.to_str()) + .is_some_and(|n| n.starts_with("tsconfig") && n.ends_with(".json")) + })); + } + inputs.extend(settings.tsconfig_file.iter().cloned()); + // A plain stylesheet compiles through the app's PostCSS config and its + // browserslist targets, and its entry persists like a module's. + inputs.extend(crate::css_serve::find_postcss_config(root)); + inputs.push(root.join(".browserslistrc")); + inputs.sort(); + inputs.dedup(); + for file in &inputs { + if let Ok(bytes) = std::fs::read(file) { + hasher.update(oj_cache::store::salt_key(root, &workspace, file).as_bytes()); + hasher.update(&bytes); + } + } + // The plugin chain: the vite config and what it imports, and an + // `oj.plugins.mjs` when the app has one (which `plugin_source` runs in + // the vite config's place; its own imports are not recorded, so an edit + // to a file it imports is not a re-salt). + let mut config_files: Vec = config_path.map(Path::to_path_buf).into_iter().collect(); + if let Some(config) = config_path { + config_files.extend(plugins::config_dependencies_of(config)); + } + config_files.extend(plugins::plugins_file(root)); + config_files.sort(); + config_files.dedup(); + for file in &config_files { + if let Ok(bytes) = std::fs::read(file) { + let id = oj_cache::store::salt_key(root, &workspace, file); + hasher.update(id.as_bytes()); + hasher.update(&bytes); + } + } + // Each list under its own tag, each entry NUL-terminated: two lists + // whose entries merely concatenate alike salt apart. + hasher.update(b"\0resolve"); + for (tag, list) in [ + (b"c" as &[u8], Some(&settings.conditions)), + (b"d", Some(&settings.dedupe)), + (b"e", settings.extensions.as_ref()), + (b"m", settings.main_fields.as_ref()), + ] { + hasher.update(b"\0"); + hasher.update(tag); + for entry in list.into_iter().flatten() { + hasher.update(entry.as_bytes()); + hasher.update(b"\0"); + } + } + for (find, replacement) in &settings.alias { + hasher.update(b"a"); + hasher.update(find.as_bytes()); + hasher.update(b"="); + hasher + .update(oj_cache::store::salt_key(root, &workspace, Path::new(replacement)).as_bytes()); + } + hasher.update(&[b's', settings.preserve_symlinks as u8]); + hasher.update(format!("\0tp={:?}", settings.tsconfig_paths).as_bytes()); + if let Some(file) = &settings.tsconfig_file { + hasher.update(b"\0tf="); + hasher.update(oj_cache::store::salt_key(root, &workspace, file).as_bytes()); + } + format!("cfg={}", hasher.finalize().to_hex()) +} + +/// Whether a stored entry's code or sourcemap names one of `dirs` as a path: +/// the directory followed by a separator, so a root `/app` is not found in +/// a route string `"/app-settings"`. A directory with no name of its own +/// (`/`, the workspace of a sandbox image with a top-level `node_modules`) +/// names nothing: every path would match it. +pub(crate) fn names_checkout(stored: &CachedModule, dirs: &[&Path]) -> bool { + dirs.iter().any(|dir| { + if dir.file_name().is_none() { + return false; + } + let needle = format!("{}/", dir.to_string_lossy().trim_end_matches('/')); + stored.code.contains(&needle) + || stored + .map_json + .as_deref() + .is_some_and(|m| m.contains(&needle)) + }) +} + /// Feeds the unbundled Node SSR path, and the SSR build's externalization /// probe (Vite resolves a dependency before externalizing it). Conditions /// never cross runtimes: a runner-backed ssr environment's list describes @@ -1730,9 +1896,10 @@ fn optimized_deps( ) } -/// Plugin server events and the file watcher. +/// Plugin server events, the cache writer thread and the file watcher. fn spawn_state_tasks( state: &Arc, + mut write_rx: tokio::sync::mpsc::Receiver<(String, Arc)>, watch_rx: std::sync::mpsc::Receiver, watch_ready: tokio::sync::watch::Sender, ) { @@ -1761,6 +1928,31 @@ fn spawn_state_tasks( } }); } + { + let state = Arc::clone(state); + std::thread::spawn(move || { + while let Some((key, module)) = write_rx.blocking_recv() { + // Disk gets the worktree-independent form (ws:/mono: + // relative metadata paths); memory keeps the absolute one. + let stored = module.relocated_for_store(&state.root, &state.workspace_root_dir); + // Debug info may name a checkout where the metadata does not (a + // file the compiler named by its real path): such an entry is + // this checkout's alone. + if names_checkout(&stored, &[&state.root, &state.workspace_root_dir]) { + state.cache.put_local(&key, &stored); + continue; + } + state.cache.put(&key, &stored); + // Push relocatable entries to the remote substituter (queued, + // never blocking this thread on the network). + if let Some(remote) = &state.remote_store { + if stored.is_relocatable() { + remote.push_module(&key, &stored); + } + } + } + }); + } spawn_watcher(Arc::clone(state), watch_rx, watch_ready); } @@ -2394,6 +2586,7 @@ impl DevServer { let (reload_tx, _) = broadcast::channel::(64); let (crawl_tx, crawl_rx) = tokio::sync::watch::channel(false); let (watch_tx, watch_rx) = std::sync::mpsc::channel::(); + let (write_tx, write_rx) = tokio::sync::mpsc::channel::<(String, Arc)>(65536); let (watch_ready_tx, watch_ready) = tokio::sync::watch::channel(false); let public_dir = oj_config::public_dir(&config, &root); let css_resolve = oj_css::CssResolveConfig { @@ -2444,6 +2637,8 @@ impl DevServer { let state = Arc::new(ServerState { engine_registry: engine_registry.clone(), root: root.clone(), + remote_store: store_remote::RemoteStore::from_env(), + workspace_root_dir: rewrite::workspace_of(&root), public_dir, vite_deps_prefix: optimize::vite_deps_url_prefix( &root, @@ -2456,6 +2651,42 @@ impl DevServer { ssr_resolver, ssr_external_resolver: Arc::new(ssr_external_resolver(&root, &config)), ssr_aliases: oj_config::resolve_alias(&config, "ssr"), + persistent_cache: self.store, + config_file: config_file.clone(), + cache: PersistentCache::new(oj_cache::cache_root(&root), env!("CARGO_PKG_VERSION")) + // Relocatable entries go to the shared per-user store, where + // worktree B hits what worktree A compiled; pinned entries + // (/@fs imports and friends) stay in this app's cache. + .with_shared(oj_cache::store::store_root().map(|s| s.join("modules"))) + .with_salt_extra(&installed.digest) + // Everything else that shapes compiled output: the plugin + // chain and its options (config graph, lockfile epoch), the + // resolver config, tsconfig paths. A config edit is a clean + // miss, never a stale hit. + .with_salt_extra(&module_cache_config_salt( + &root, + &client_settings(&config), + plugins::vite_config_file(&root, config_file.as_deref()).as_deref(), + )) + // A cached compile embeds the JSX runtime import; a changed + // importSource/runtime must not serve the old module. + .with_salt_extra(&format!("jsx={jsx:?}")) + // A cached module embeds its asset URLs (origin, base, + // inlined svgs). + .with_salt_extra(&format!( + "asset-urls={:?}:{:?}:{:?}", + config.server.as_ref().and_then(|s| s.origin.as_deref()), + config.base, + config.build.as_ref().map(|b| ( + b.assets_inline_limit, + b.assets_inline_limit_envs.as_ref(), + b.assets_inline_limit_fn, + )), + )), + cache_writes: write_tx, + plugins_use_module_parsed: caps.use_module_parsed, + collector_plugins: caps.collects_from_transforms, + parsed_fired: Mutex::new(std::collections::HashSet::new()), memory: Mutex::new(MemoryCache::new(memory_cache_budget())), mtime_keys: Mutex::new(HashMap::new()), content: Arc::default(), @@ -2603,7 +2834,10 @@ impl DevServer { )) }, }); - spawn_state_tasks(&state, watch_rx, watch_ready_tx); + if state.persistent_cache && state.collector_plugins { + println!("oj: store: a plugin collects state from transforms; app modules compile each session, dependencies serve from the store"); + } + spawn_state_tasks(&state, write_rx, watch_rx, watch_ready_tx); // A dep re-optimization that changed previously served chunks (or // whose batch failed) commits a new map: drop every compiled module // (their rewrites carry the old URLs) and reload the page, Vite's diff --git a/crates/oj_server/src/module_pipeline.rs b/crates/oj_server/src/module_pipeline.rs index 23a09c5e8..ab420631f 100644 --- a/crates/oj_server/src/module_pipeline.rs +++ b/crates/oj_server/src/module_pipeline.rs @@ -169,6 +169,35 @@ pub(crate) async fn ensure_module_as( if let Some(module) = memory_hit(state, url, &key) { return Ok((key, module)); } + // The persistent cache, with the oj store on: an entry of an earlier + // process (a restart, another worktree, the remote substituter), served + // without a compile when it passes the same checks a memory entry would. + // Not an app module where a plugin collects state from transforms: the + // transform a hit skips is state it never sees (see `collector_plugins`). + let session_only = |stamped: bool| stamped || (!is_dep && state.collector_plugins); + let mut verify_against: Option> = None; + if state.persistent_cache && !session_only(false) { + let disk_key = state.cache.disk_key(&key); + let hit = match persistent_hit(state, &disk_key, is_dep, imports_stamp) { + Some(module) => Some(module), + None => remote_hit(state, &disk_key, is_dep, imports_stamp).await, + }; + if let Some(module) = hit { + if verify_hit_sampled() { + // Trust but verify: recompile this hit anyway and compare + // below. A divergence means a plugin produced different + // output from identical keyed-and-traced inputs, impurity + // the key cannot see, and names itself in the log instead + // of poisoning caches silently. + verify_against = Some(Arc::clone(&module)); + } else { + memory_put(state, url, &key, &module); + register_in_graph(state, url, &module); + replay_module_parsed(state, file, &key, is_dep, is_server).await; + return Ok((key, module)); + } + } + } if is_server { let code = server_fn_stub(&oj_compiler::exports(&source, file), url); @@ -180,13 +209,26 @@ pub(crate) async fn ensure_module_as( module.stylex_rules = pre.rules; } let module = Arc::new(module); - store_module(state, url, &key, &module); + store_module(state, url, &key, &module, session_only(imports_stamp > 0)); return Ok((key, module)); } // The StyleX plugin is `enforce: 'pre'`: it compiles the module's own // source, ahead of the app's transforms and oj's CJS-interop rewrite (off // the async workers: a large module's compile is real work). + // + // A compile, then: glob rows key the entry on what the patterns match + // today (listed here, after the hit checks, so a hit lists nothing), and + // the clock marks when the inputs were read. A side file saved while the + // transform ran is digested as it is now, next to output built from what + // it was: such an entry is this session's alone. + let glob_rows = if state.persistent_cache { + glob_trace_rows(state, file, &source) + } else { + Vec::new() + }; + let compile_started = std::time::SystemTime::now(); + let mut trace_unsettled = false; let (source, stylex_map, stylex_rules) = match &state.stylex { Some(plugin) if plugin.handles(transform_id, &source) => { let (st, id) = (Arc::clone(state), transform_id.to_string()); @@ -229,6 +271,7 @@ pub(crate) async fn ensure_module_as( plugin_transform_phase(state, file, transform_id, compiled, is_dep, phase("normal")) .await?; transformed.watch_files.extend(normal.watch_files); + transformed.read_files.extend(normal.read_files); normal.code } else { source @@ -255,7 +298,7 @@ pub(crate) async fn ensure_module_as( url, disk_svg.as_deref().map(str::as_bytes), )?); - store_module(state, url, &key, &module); + store_module(state, url, &key, &module, session_only(imports_stamp > 0)); return Ok((key, module)); } let source = if is_svelte { @@ -314,7 +357,11 @@ pub(crate) async fn ensure_module_as( verbatim_module_syntax, importer_format, css, - plugin_maps: transformed.maps, + plugin_maps: transformed + .maps + .into_iter() + .map(|map| served_map_sources(&state.root, map)) + .collect(), dep_map, pre_resolved, unresolved_bare, @@ -327,6 +374,29 @@ pub(crate) async fn ensure_module_as( if let Some(rules) = stylex_rules { module.stylex_rules = rules; } + // Constructive trace: digest every side file the plugin read, so + // a warm hit can prove those inputs unchanged. The module's own + // source is already in the key; host scratch is oj's machinery. + let own = file.to_string_lossy(); + let scratch = oj_cache::cache_base(&state.root); + module.trace = transformed + .read_files + .iter() + .filter(|p| p.as_str() != own && !Path::new(p.as_str()).starts_with(&scratch)) + // A file the plugin looked for and did not find is an input too + // (it took a fallback): its row has no digest, and a warm hit + // that finds the file is a miss. + .map(|p| { + trace_unsettled |= modified_since(Path::new(p), compile_started); + oj_cache::TraceRow { + id: p.clone(), + digest: std::fs::read(p) + .map(|bytes| blake3::hash(&bytes).to_hex().to_string()) + .unwrap_or_default(), + } + }) + .collect(); + module.trace.extend(glob_rows); Arc::new(module) } Ok(Err(err)) => { @@ -352,8 +422,8 @@ pub(crate) async fn ensure_module_as( // imports are other deps, which are never stamped, so a dep is never // re-keyed. let baked = imports_stamp_of(state, &module.imports); - let key = if !is_dep && baked != imports_stamp { - compile_key( + let (key, stamped) = if !is_dep && baked != imports_stamp { + let rekeyed = compile_key( state, file, url, @@ -369,11 +439,29 @@ pub(crate) async fn ensure_module_as( importer_format, }), ) - .key + .key; + (rekeyed, baked > 0) } else { - key + (key, imports_stamp > 0) }; - store_module(state, url, &key, &module); + if let Some(prev) = &verify_against { + if prev.code != module.code { + eprintln!( + "oj: cache verify: {url} recompiled differently from identical inputs; \ +a plugin is impure (reads env, network or time the key cannot see). Serving the fresh output." + ); + } + } + store_module( + state, + url, + &key, + &module, + session_only(stamped) || trace_unsettled, + ); + if state.plugins_use_module_parsed && !is_dep && !is_server { + state.parsed_fired.lock().unwrap().insert(key); + } state .resolve_failed .lock() @@ -431,6 +519,7 @@ fn code_module(code: String) -> CachedModule { watch_files: Vec::new(), import_bindings: Vec::new(), stylex_rules: Vec::new(), + trace: Vec::new(), } } @@ -472,16 +561,58 @@ fn memory_hit( Some(module) } +/// `OJ_VERIFY_HITS`: the share (0..=1) of persistent hits that are recompiled +/// and compared anyway. Off (0) by default; CI can run at 1. +fn verify_hit_sampled() -> bool { + let p = oj_env::get().knobs.verify_hits; + if p <= 0.0 { + return false; + } + if p >= 1.0 { + return true; + } + // Cheap process-local sampling; cryptographic quality is irrelevant here. + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.subsec_nanos()) + .unwrap_or(0); + (now % 10_000) as f64 / 10_000.0 < p +} + +/// `session_only`: the entry is this session's alone (its key carries HMR +/// import stamps, which a later session starts over; or a plugin collects +/// state from app transforms), so it is kept in memory and never persisted. fn store_module( state: &ServerState, url: &str, key: &oj_cache::ModuleKey, module: &Arc, + session_only: bool, ) { + // A sheet that may have inlined a file it names (a small svg; any file + // under `?inline`, a JSON one included) embeds its content as it is now: + // kept in memory, recompiled when one changes, never persisted. A `t=` + // stamp is 0 after a restart, so a sheet with only asset URLs persists. + let inlines_assets = + module.kind == "css" && !module.imports.is_empty() && module.code.contains("data:"); + if state.persistent_cache && !session_only && !inlines_assets { + let _ = state + .cache_writes + .try_send((state.cache.disk_key(key), Arc::clone(module))); + } memory_put(state, url, key, module); register_in_graph(state, url, module); } +/// Whether `file` was written at or after `since`: a side file a transform +/// read with an mtime no older than the compile may have been read before +/// that write. A file that is not there was not written. +fn modified_since(file: &Path, since: std::time::SystemTime) -> bool { + std::fs::metadata(file) + .and_then(|m| m.modified()) + .is_ok_and(|mtime| mtime >= since) +} + async fn file_stamp(file: &Path) -> Option { let meta = tokio::fs::metadata(file).await.ok()?; meta.modified().ok().map(|mtime| (mtime, meta.len())) @@ -620,6 +751,104 @@ async fn plugin_load( .map_err(|e| format!("plugin load error for {url}:\n{e}")) } +/// A worktree-independent digest of what an `import.meta.glob` pattern +/// matches RIGHT NOW: the sorted workspace-spelled matches, hashed. A file +/// created or deleted under the pattern changes the digest, so a cold restart +/// re-expands instead of serving the stale expansion (HMR covers the live +/// case; this covers the cache). +fn glob_listing_digest(root: &Path, workspace: &Path, abs_pattern: &str) -> String { + // The expansion's own matcher (picomatch's dialect: braces, classes and + // all), never another's: the row must list what the compile listed, or a + // pattern one matcher reads differently keeps a constant digest. + let call = oj_compiler::glob::GlobCall { + patterns: vec![abs_pattern.to_string()], + exhaustive: false, + case_sensitive: true, + }; + let mut names: Vec = call + .files_in(root) + .iter() + .map(|p| oj_cache::store::salt_key(root, workspace, p)) + .collect(); + names.sort(); + let mut hasher = blake3::Hasher::new(); + for n in &names { + hasher.update(n.as_bytes()); + hasher.update(&[0]); + } + hasher.finalize().to_hex().to_string() +} + +/// Trace rows for every glob pattern a module expands, appended at compile +/// time and re-verified on warm hits. One row per affirmative pattern of each +/// call: a negation only shrinks what a call matches, so the un-negated +/// listing changes whenever the call's does (and sometimes when it does not, +/// which costs a recompile, never a stale serve). +fn glob_trace_rows(state: &ServerState, file: &Path, source: &str) -> Vec { + if !source.contains("import.meta.glob") { + return Vec::new(); + } + let workspace = &state.workspace_root_dir; + glob_trace_patterns(source, file, &state.root, &state.glob_alias) + .into_iter() + .map(|pattern| oj_cache::TraceRow { + digest: glob_listing_digest(&state.root, workspace, &pattern), + id: format!("glob:{pattern}"), + }) + .collect() +} + +/// A map an earlier transform returned (a plugin's, StyleX's), its in-root +/// `sources` named by served path as the compile names the module itself +/// (`/src/App.tsx`): the composed map then carries no checkout's path, so a +/// cached entry means the same in every worktree. `sourcesContent` is +/// embedded, so the name is a label; out-of-root sources stay as written. +pub(crate) fn served_map_sources(root: &Path, map: String) -> String { + let Ok(mut json) = serde_json::from_str::(&map) else { + return map; + }; + let canonical = std::fs::canonicalize(root).ok(); + let Some(sources) = json.get_mut("sources").and_then(|s| s.as_array_mut()) else { + return map; + }; + let mut changed = false; + for source in sources.iter_mut() { + let Some(path) = source.as_str() else { + continue; + }; + let rel = std::iter::once(root) + .chain(canonical.as_deref()) + .find_map(|r| oj_cache::store::rel_key(r, Path::new(path))); + if let Some(rel) = rel.filter(|r| !r.is_empty()) { + *source = serde_json::Value::String(format!("/{rel}")); + changed = true; + } + } + if changed { + json.to_string() + } else { + map + } +} + +/// The affirmative patterns a module's globs expand, resolved as the compile +/// resolves them (root-led and aliased ones included), so a trace row lists +/// what the expansion actually read. +pub(crate) fn glob_trace_patterns( + source: &str, + file: &Path, + root: &Path, + alias: &[(String, String)], +) -> Vec { + oj_compiler::glob::glob_patterns_aliased(source, file, Some(root), &|id| { + oj_compiler::glob::string_alias(alias, id) + }) + .into_iter() + .flat_map(|call| call.patterns) + .filter(|pattern| !pattern.starts_with('!')) + .collect() +} + fn record_glob_importer(state: &ServerState, file: &Path, url: &str, source: &str) { if !source.contains("import.meta.glob") { return; @@ -756,7 +985,13 @@ fn compile_key( mode_key.push_str("+rtenv"); mode_key.push_str(&env.cache_salt()); } - let key = oj_cache::module_key(source, url, &mode_key); + // /@fs URLs under the workspace key by their relative spelling, so a + // hoisted dep's path-free entry is one entry for every worktree. + let key = oj_cache::module_key( + source, + &crate::rewrite::key_url(&state.workspace_root_dir, url), + &mode_key, + ); if let Some((mtime, size)) = stamp { state .mtime_keys @@ -772,9 +1007,104 @@ fn compile_key( } } +/// A persistent entry under `disk_key`, when it may be served as it is. +/// `imports_stamp` is the stamp the request keyed on: a module the graph has +/// no edges for yet keys on no import stamps, which finds an entry compiled +/// when none of its imports had been updated. Its imports may have been +/// since (a module first requested after an update of a dep of its): served +/// as is, it would name the dep's bare url while the importers recompiled +/// after the update name the stamped one, two instances of one module in +/// the page. Vite's transform cache lives per server, so a first transform +/// always sees the current stamps; the on-disk entry is used only when it +/// bakes in the stamps of now. Cached post-transform code may also import a +/// plugin-served virtual whose content lives only in plugin memory +/// (wyw-in-js cssLookup) and 404s on a warm start: the transform runs again +/// for an entry whose imports name a filesystem path with no file on disk. +fn persistent_hit( + state: &ServerState, + disk_key: &str, + is_dep: bool, + imports_stamp: u64, +) -> Option> { + let module = Arc::new( + state + .cache + .get(disk_key)? + // Expand ws:/mono: metadata against THIS worktree's roots. + .rehomed(&state.root, &state.workspace_root_dir), + ); + if imports_stamp_of(state, &module.imports) != imports_stamp { + return None; + } + // An import the entry resolved to a file with no file there now: a + // plugin-served virtual of the session that compiled it, or a file that + // moved since (`./Foo` to `Foo/index.tsx` on a branch switch, the + // importer untouched). A compile resolves it anew; the hit would 404. + let needs_retransform = + !is_dep && imports_a_plugin_virtual(&module.imports, &state.root, &state.dir_cache); + // Constructive-trace verification: every side input recorded at build + // time must still digest the same, or the entry is a miss. File rows + // re-hash the file (unreadable counts as changed); glob rows re-expand + // the pattern against THIS worktree. Empty for plugin-less, glob-less + // modules, which cost nothing. + let trace_stale = module + .trace + .iter() + .any(|row| match row.id.strip_prefix("glob:") { + Some(pattern) => { + glob_listing_digest(&state.root, &state.workspace_root_dir, pattern) != row.digest + } + None => match std::fs::read(&row.id) { + Ok(bytes) => blake3::hash(&bytes).to_hex().to_string() != row.digest, + // Looked for and not found at compile time: still not there. + Err(_) => !row.digest.is_empty(), + }, + }); + (!needs_retransform && !trace_stale).then_some(module) +} + +/// Remote read-through: on a local shared-store miss, ask the substituter +/// for this exact key. The fetched entry lands in the local shared store (so +/// the next worktree on this machine never asks again) and then passes the +/// same admission path as a local hit: rehome, the stamp check, the +/// plugin-virtual check, and trace verification against this worktree. +async fn remote_hit( + state: &ServerState, + disk_key: &str, + is_dep: bool, + imports_stamp: u64, +) -> Option> { + let remote = state.remote_store.as_ref()?; + let stored = remote.fetch_module(disk_key).await?; + state.cache.put(disk_key, &stored); + persistent_hit(state, disk_key, is_dep, imports_stamp) +} + +/// A disk hit skipped the plugin chain, so its `moduleParsed` never fired on +/// the host: fired once per key here, as a compile fires it there. +pub(crate) async fn replay_module_parsed( + state: &Arc, + file: &Path, + key: &oj_cache::ModuleKey, + is_dep: bool, + is_server: bool, +) { + if !state.plugins_use_module_parsed || is_dep || is_server { + return; + } + if !state.parsed_fired.lock().unwrap().insert(*key) { + return; + } + if let Some(host) = &state.plugins { + let _ = host.module_parsed(&file.to_string_lossy()).await; + } +} + pub(crate) struct Transformed { pub(crate) code: String, pub(crate) watch_files: Vec, + /// Side files the plugin hooks read, for the entry's trace. + read_files: Vec, maps: Vec, } @@ -800,6 +1130,7 @@ pub(crate) async fn plugin_transform_phase( phase: Option<&str>, ) -> Result { let untouched = |code| Transformed { + read_files: Vec::new(), code, watch_files: Vec::new(), maps: Vec::new(), @@ -832,6 +1163,7 @@ pub(crate) async fn plugin_transform_phase( Ok(t) => Ok(Transformed { code: t.code, watch_files: t.watch_files, + read_files: t.reads, maps: t.maps, }), // Vite fails the request with the plugin's error (code frame in the @@ -1319,7 +1651,7 @@ impl CompileJob { }), code: output.code, map_json: output.map_json, - fs_allow: fs_allow_from(&output.imports), + fs_allow: fs_allow_from(&self.state.root, &output.imports), watch_files: Vec::new(), import_bindings: output.import_bindings, imports: output.imports, @@ -1331,6 +1663,7 @@ impl CompileJob { require_map: Vec::new(), css_exports: Vec::new(), stylex_rules: output.stylex_rules, + trace: Vec::new(), }) } @@ -1411,6 +1744,20 @@ impl CompileJob { if self.is_svelte { opts.refresh = false; } + // Name the module by its served, root-relative path in its own + // artifact (jsx __source, sourcemap sources): the compiled bytes are + // then identical in every worktree. sourcesContent is embedded, so + // the relative name is a label. A file outside the root but in the + // workspace is named by its served `/@fs/@mono/` url, the same in + // every checkout; anything else keeps its real path, which keeps its + // entry out of the shared store. + opts.display_path = oj_cache::store::rel_key(&self.state.root, &self.file) + .map(|rel| format!("/{rel}")) + .or_else(|| { + oj_cache::store::rel_key(&self.state.workspace_root_dir, &self.file) + .map(|rel| format!("/@fs/@mono/{rel}")) + }) + .map(std::path::PathBuf::from); // The key already folded this decision (from the original path); the // compile must never re-derive it from a synthetic one. opts.class_field_set_semantics = Some(self.class_field_semantics); @@ -1446,7 +1793,7 @@ impl ImportRewrite<'_> { format!( "/@id/{}?importer={}", hex_encode(spec), - hex_encode(&self.job.importer_abs) + crate::rewrite::encode_importer(&self.job.state.root, &self.job.importer_abs) ) } @@ -1935,11 +2282,16 @@ pub(crate) fn package_root(path: &Path) -> PathBuf { path.parent().unwrap_or(path).to_path_buf() } -pub(crate) fn fs_allow_from(imports: &[String]) -> Vec { +pub(crate) fn fs_allow_from(root: &Path, imports: &[String]) -> Vec { + let workspace = crate::rewrite::workspace_of(root); imports .iter() .filter_map(|i| i.split('?').next().unwrap_or(i).strip_prefix("/@fs")) - .map(|p| package_root(Path::new(p)).display().to_string()) + .map(|p| { + package_root(&crate::rewrite::fs_url_to_path(&workspace, p)) + .display() + .to_string() + }) .collect() } diff --git a/crates/oj_server/src/optimize.rs b/crates/oj_server/src/optimize.rs index 58abfe585..498e595ef 100644 --- a/crates/oj_server/src/optimize.rs +++ b/crates/oj_server/src/optimize.rs @@ -81,8 +81,8 @@ pub struct OptimizedDeps { rx: watch::Receiver>>, dir: PathBuf, /// The session's base version: the persisted one on a warm boot, else - /// the prebundle hash salted with the session, so stale immutable entries - /// never share a URL. Empty when disabled. + /// the prebundle hash salted with the ledger's epoch (see [`DepLedger`]). + /// Empty when disabled. version: String, rerun: Option>, link_memo: LinkMemo, @@ -101,9 +101,14 @@ type OnCommit = Box; struct RerunState { /// Base prebundle hash, the seed of every browser version. hash: String, - /// Vite's sessionTimestamp: salts every version this optimizer mints, so - /// no two sessions serve one immutable URL. - session: String, + /// Salts every version this optimizer mints: the ledger's epoch, so every + /// worktree on one store mints the same URLs for the same bundle (and a + /// wiped store or cache moves them all), or a per-process timestamp, + /// Vite's sessionTimestamp, when there is no ledger. + epoch: String, + /// What each URL already served; `None` leaves the epoch alone to keep + /// URLs unique. + ledger: Option, tx: watch::Sender>>, /// Every serve-time-discovered dep with its provisional meta (the version /// its URLs were first served under); persists across reruns. @@ -138,20 +143,21 @@ pub enum DepServe { Outdated, } -/// A discovery's URL version: the base key, this optimizer's session, and the +/// A discovery's URL version: the base key, the optimizer's epoch, and the /// (sorted) discovered set, so chunks that change can never be served under a -/// URL a page already holds (Vite's getDiscoveredBrowserHash). The session is -/// Vite's sessionTimestamp: URLs are `immutable`, and a later session (a -/// restart, a cleared cache) may bundle other bytes under the same set. +/// URL a page already holds (Vite's getDiscoveredBrowserHash). URLs are +/// `immutable`, and a later session (a restart, a cleared cache) may bundle +/// other bytes under the same set: the epoch and the [`DepLedger`] keep any +/// URL from ever naming two bundles. fn browser_hash<'a>( hash: &str, - session: &str, + epoch: &str, discovered: impl Iterator, ) -> String { let mut hasher = blake3::Hasher::new(); hasher.update(hash.as_bytes()); hasher.update(b"\0"); - hasher.update(session.as_bytes()); + hasher.update(epoch.as_bytes()); for dep in discovered { hasher.update(b"\0"); hasher.update(dep.as_bytes()); @@ -167,6 +173,151 @@ fn session_timestamp() -> String { .unwrap_or_default() } +/// Which bytes every dep URL has served, so versions can be content-derived +/// instead of per session. Vite salts every version with a per-process +/// sessionTimestamp because its URLs are cached `immutable`: a restart that +/// rebundled other bytes under an old URL would leave browsers on the old +/// ones. That also makes every worktree mint its own URLs, and the dep +/// version salts every persistent module-cache key, so no two worktrees +/// could ever share a compiled module. The ledger gives the same guarantee +/// without the per-process salt: versions come from the inputs and an epoch +/// that lives as long as the ledger, each URL is recorded write-once with +/// its file's content hash, and a commit whose bytes disagree with a +/// recorded URL re-mints a version from the bytes (and reloads, as a +/// contradicted plan does). Wiping the ledger's directory starts a new +/// epoch, which moves every URL. +struct DepLedger { + dir: PathBuf, + epoch: String, + /// The pre-bundle directory: the bytes a URL serves are its file's. + deps: PathBuf, +} + +impl DepLedger { + /// The ledger under `dir`: in the shared oj store when there is one, so + /// worktrees share URLs, else in the app's cache (outside the deps dir, + /// so clearing pre-bundles keeps it). `None` when it cannot be written. + fn open(dir: PathBuf, deps: PathBuf) -> Option { + std::fs::create_dir_all(&dir).ok()?; + let fresh = format!("{}-{}", session_timestamp(), std::process::id()); + if !write_once(&dir.join("epoch"), fresh.as_bytes()) { + return None; + } + let epoch = std::fs::read_to_string(dir.join("epoch")).ok()?; + let epoch = epoch.trim().to_string(); + (!epoch.is_empty()).then_some(Self { dir, epoch, deps }) + } + + fn for_app(root: &Path, deps: &Path) -> Option { + Self::open( + oj_cache::store::store_root() + .map(|store| store.join("dep-ledger")) + .unwrap_or_else(|| oj_cache::cache_root(root).join("dep-ledger")), + deps.to_path_buf(), + ) + } + + /// The hash of the bytes `meta`'s URL serves, its bundled file's. Vite's + /// `fileHash` (the entry's name and imports) is not one: an edited + /// dependency bundles to other bytes under the same name. `None` for a + /// file not written yet (a provisional entry, a failed run). + fn bytes_hash(&self, meta: &DepMeta) -> Option { + let bytes = std::fs::read(self.deps.join(&meta.file)).ok()?; + Some(blake3::hash(&bytes).to_hex().to_string()) + } + + /// Records that `/@oj-deps/?v=` serves bytes hashing to + /// `file_hash`, or checks that it already did. + fn agrees(&self, version: &str, file: &str, file_hash: &str) -> bool { + let dir = self.dir.join(version); + if std::fs::create_dir_all(&dir).is_err() { + return false; + } + let path = dir.join(&blake3::hash(file.as_bytes()).to_hex()[..16]); + write_once(&path, file_hash.as_bytes()) + && std::fs::read(&path).is_ok_and(|b| b == file_hash.as_bytes()) + } +} + +/// Creates `path` holding `bytes` unless it exists: written aside and hard +/// linked into place, so a reader never sees a partial file and the first +/// writer wins. False only when neither this write nor an earlier one landed. +fn write_once(path: &Path, bytes: &[u8]) -> bool { + if path.is_file() { + return true; + } + let tmp = path.with_extension(format!( + "tmp-{}-{}", + std::process::id(), + session_timestamp() + )); + let linked = std::fs::write(&tmp, bytes).is_ok() + && match std::fs::hard_link(&tmp, path) { + Ok(()) => true, + Err(e) => e.kind() == std::io::ErrorKind::AlreadyExists, + }; + let _ = std::fs::remove_file(&tmp); + linked +} + +/// Whether the ledger agrees with every bundled entry of `map` under the +/// version its URL carries (provisional entries have no bytes yet). +fn ledger_agrees(rerun: &RerunState, map: &DepMap) -> bool { + let Some(ledger) = &rerun.ledger else { + return true; + }; + map.values() + .filter(|meta| !meta.file_hash.is_empty()) + .all(|meta| { + let version = url_version(&meta.url); + let Some(bytes) = ledger.bytes_hash(meta) else { + return true; + }; + version.is_empty() || ledger.agrees(version, &meta.file, &bytes) + }) +} + +/// Moves every URL of `map` to a version derived from its bytes that the +/// ledger agrees with: two worktrees that hit the same disagreement re-mint +/// the same version. A ledger that never agrees (unwritable) falls back to a +/// per-process version, unique by construction. +fn remint(rerun: &RerunState, base: &str, map: &mut DepMap) -> String { + let bytes: std::collections::BTreeSet = map + .iter() + .map(|(dep, meta)| { + let hash = rerun + .ledger + .as_ref() + .and_then(|l| l.bytes_hash(meta)) + .unwrap_or_else(|| meta.file_hash.clone()); + format!("{dep}\0{hash}") + }) + .collect(); + let restamp = |map: &mut DepMap, version: &str| { + for meta in map.values_mut() { + meta.url = dep_url(&meta.file, version); + } + }; + for attempt in 0..4 { + let version = browser_hash( + &format!("{base}+bytes{attempt}"), + &rerun.epoch, + bytes.iter(), + ); + restamp(map, &version); + if ledger_agrees(rerun, map) { + return version; + } + } + let version = browser_hash( + &format!("{base}+session"), + &session_timestamp(), + bytes.iter(), + ); + restamp(map, &version); + version +} + /// Vite's `moduleListContains`: an exclude entry names the dep or a parent path. fn module_list_contains(list: &[String], dep: &str) -> bool { list.iter() @@ -619,7 +770,7 @@ impl OptimizedDeps { ); // Hashing the set it joins (sorted, so registration order is // moot): Vite's getDiscoveredBrowserHash over known + missing. - let version = browser_hash(&r.hash, &r.session, discovered.keys()); + let version = browser_hash(&r.hash, &r.epoch, discovered.keys()); let meta = DepMeta { url: dep_url(&file, &version), file, @@ -722,7 +873,10 @@ impl OptimizedDeps { ) -> Self { let dir = oj_cache::cache_root(root).join("deps"); let hash = lockfile_hash(root, version, &input); - let session = session_timestamp(); + let ledger = DepLedger::for_app(root, &dir); + let epoch = ledger + .as_ref() + .map_or_else(session_timestamp, |l| l.epoch.clone()); let (tx, rx) = watch::channel(None); // optimizeDeps.force: ignore any cached pre-bundle and always rebuild. @@ -739,18 +893,20 @@ impl OptimizedDeps { (seeded, m.browser_hash.clone()) } // Vite's initDepsOptimizerMetadata: a cold session's base - // version is salted too, since a source edit can change the dep - // set (and the bytes) without changing the hash. + // version is salted too (with the epoch), since a source edit can + // change the dep set (and the bytes) without changing the hash; + // the commit's ledger check catches bytes that moved. None => ( std::collections::BTreeMap::new(), - browser_hash(&hash, &session, std::iter::empty()), + browser_hash(&hash, &epoch, std::iter::empty()), ), }; let base_version = initial_version.clone(); let (wake, mut wake_rx) = tokio::sync::mpsc::unbounded_channel(); let rerun = Arc::new(RerunState { hash: hash.clone(), - session, + epoch, + ledger, tx, discovered: std::sync::Mutex::new(initial_discovered), pending: std::sync::Mutex::new(std::collections::HashSet::new()), @@ -879,8 +1035,9 @@ impl OptimizedDeps { /// URL moves to a new version, so no compile key still matches a module /// compiled against the plan, and the page reloads, /// Vite's "optimized dependencies changed". Vite's committed browserHash is -/// unsalted; this one keeps the session salt, so a later session's -/// contradicted plan never lands on this URL either. `persist` gets the bundled entries and +/// unsalted; this one keeps the epoch salt, so a later epoch's contradicted +/// plan never lands on this URL either. Bytes the ledger has seen under +/// another URL's version re-mint and reload the same way. `persist` gets the bundled entries and /// their version before the commit releases any held request, as Vite's /// commit writes the metadata before resolving the processing promise. fn commit_initial( @@ -889,11 +1046,11 @@ fn commit_initial( planned: Option, persist: impl FnOnce(&DepMap, &str), ) { - let changed = planned.as_ref().is_some_and(|plan| !same_plan(plan, &map)); - let version = if changed { + let mut changed = planned.as_ref().is_some_and(|plan| !same_plan(plan, &map)); + let mut version = if changed { let version = browser_hash( &format!("{}+committed", rerun.hash), - &rerun.session, + &rerun.epoch, map.keys(), ); for meta in map.values_mut() { @@ -913,6 +1070,11 @@ fn commit_initial( } rerun.browser_version.read().unwrap().clone() }; + if !ledger_agrees(rerun, &map) { + version = remint(rerun, &format!("{}+committed", rerun.hash), &mut map); + *rerun.browser_version.write().unwrap() = version.clone(); + changed = true; + } persist(&map, &version); { let mut pending = rerun.pending.lock().unwrap(); @@ -1019,7 +1181,7 @@ async fn rerun_once( return; } let names: std::collections::BTreeSet = provisional.keys().cloned().collect(); - let candidate = browser_hash(hash, &rerun.session, names.iter()); + let candidate = browser_hash(hash, &rerun.epoch, names.iter()); let Some(new_map) = run_optimizer( root, dir, input, host, rolldown, &names, &candidate, true, None, ) @@ -1111,7 +1273,7 @@ async fn rerun_once( p.remove(dep); } } - let final_map: DepMap = if needs_reload { + let mut final_map: DepMap = if needs_reload { // Every URL moves to the batch version, this batch's own deps // included (parse stamped it already): exactly Vite's commitProcessing // on needsReload, where each entry carries the new browserHash, an @@ -1133,11 +1295,17 @@ async fn rerun_once( }) .collect() }; - let bv = if needs_reload { + let mut bv = if needs_reload { candidate.clone() } else { rerun.browser_version.read().unwrap().clone() }; + // Bytes some earlier session served under one of these URLs: every URL + // moves to a version of these bytes, and the page reloads. + if !ledger_agrees(rerun, &final_map) { + bv = remint(rerun, hash, &mut final_map); + needs_reload = true; + } // The manifest holds only bundled entries (a provisional one points at a // file that does not exist yet, which would void the warm boot); the // committed map additionally carries every still-pending provisional @@ -1291,7 +1459,7 @@ const LOCKFILES: &[(&str, Option<&str>)] = &[ /// Fold every lockfile in the nearest ancestor directory that has one (Vite's /// lookupFile), plus its patch-package dir mtime, into `hasher`. -fn hash_lockfiles(root: &Path, hasher: &mut blake3::Hasher) { +pub(crate) fn hash_lockfiles(root: &Path, hasher: &mut blake3::Hasher) { let mut dir = Some(root); while let Some(d) = dir { let mut found = false; @@ -1361,11 +1529,16 @@ fn lockfile_hash(root: &Path, version: &str, input: &OptimizeInput) -> String { hasher.update(b"\0bo="); hasher.update(input.build_out_dir.as_bytes()); hasher.update(format!("\0tp={:?}:{:?}", input.tsconfig_paths, input.tsconfig_file).as_bytes()); + let workspace = crate::rewrite::workspace_of(root); for (find, replacement) in &input.alias { hasher.update(b"\0a"); hasher.update(find.as_bytes()); hasher.update(b"="); - hasher.update(replacement.as_bytes()); + // Alias targets are absolute paths inside the app or, in a monorepo, + // a workspace sibling: hash the worktree-independent spelling so the + // same vite.config in two worktrees yields one prebundle key. + hasher + .update(oj_cache::store::salt_key(root, &workspace, Path::new(replacement)).as_bytes()); } hasher.update( format!( @@ -1895,7 +2068,8 @@ mod tests { let (wake, _wake_rx) = tokio::sync::mpsc::unbounded_channel(); let rerun = Arc::new(RerunState { hash: "testhash".into(), - session: session_timestamp(), + epoch: session_timestamp(), + ledger: None, tx, discovered: std::sync::Mutex::new(std::collections::BTreeMap::new()), pending: std::sync::Mutex::new(std::collections::HashSet::new()), @@ -1980,10 +2154,11 @@ mod tests { } #[test] - fn a_later_session_never_reuses_a_discovered_url() { + fn without_a_ledger_a_later_session_never_reuses_a_discovered_url() { // Same hash, same discovered set, a new optimizer (a restart, or a // boot after the cache was cleared): its bundle may differ, and the - // first session's URL is cached immutable, so the URL must differ. + // first session's URL is cached immutable. With no ledger to vouch + // for the bytes, the URL must differ. let first = test_deps(true, vec![]); let url = first .register_missing("date-fns/locale", false) @@ -2072,7 +2247,7 @@ mod tests { two, browser_hash("hash", "s1", set(&["dayjs", "lodash"]).iter()) ); - // Vite's sessionTimestamp: another session never mints the same URL. + // Another epoch never mints the same URL. assert_ne!(base, browser_hash("hash", "s2", set(&[]).iter())); assert_ne!( two, @@ -2423,6 +2598,160 @@ mod tests { } } + /// The bytes `file` serves under a `ledgered_deps(dir)` optimizer. + fn bundled_bytes(dir: &Path, file: &str, bytes: &str) { + let deps = dir.join("deps"); + std::fs::create_dir_all(&deps).unwrap(); + std::fs::write(deps.join(file), bytes).unwrap(); + } + + /// A test optimizer whose ledger (and so epoch) lives in `dir`. + fn ledgered_deps(dir: &Path) -> OptimizedDeps { + let mut deps = test_deps(true, vec![]); + let r = Arc::get_mut(deps.rerun.as_mut().unwrap()).unwrap(); + r.ledger = DepLedger::open(dir.to_path_buf(), dir.join("deps")); + r.epoch = r.ledger.as_ref().unwrap().epoch.clone(); + deps + } + + // Every worktree on one store records what a URL serves, at once: the + // first record wins for everyone, the rest see the disagreement, and no + // temp file of a loser is left behind. + #[test] + fn racing_records_of_one_url_pick_one_hash_for_everyone() { + let dir = tempfile::tempdir().unwrap(); + let ledger = DepLedger::open(dir.path().join("l"), dir.path().join("deps")).unwrap(); + let hashes: Vec = (0..32).map(|i| format!("{i:04x}")).collect(); + let won: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + std::thread::scope(|s| { + for hash in &hashes { + let (ledger, won) = (&ledger, &won); + s.spawn(move || { + if ledger.agrees("v1", "react.mjs", hash) { + won.lock().unwrap().push(hash.clone()); + } + }); + } + }); + let won = won.into_inner().unwrap(); + assert_eq!(won.len(), 1, "one record per URL and version: {won:?}"); + assert!(ledger.agrees("v1", "react.mjs", &won[0])); + for hash in hashes.iter().filter(|h| **h != won[0]) { + assert!(!ledger.agrees("v1", "react.mjs", hash), "{hash} agreed too"); + } + // Another process on the same ledger sees the same record. + let again = DepLedger::open(dir.path().join("l"), dir.path().join("deps")).unwrap(); + assert!(again.agrees("v1", "react.mjs", &won[0])); + let leftovers: Vec = std::fs::read_dir(dir.path().join("l/v1")) + .unwrap() + .flatten() + .map(|e| e.file_name().to_string_lossy().into_owned()) + .filter(|n| n.contains("tmp")) + .collect(); + assert!(leftovers.is_empty(), "{leftovers:?}"); + } + + #[test] + fn the_ledger_holds_each_url_to_its_first_bytes() { + let dir = tempfile::tempdir().unwrap(); + let ledger = DepLedger::open(dir.path().join("l"), dir.path().join("deps")).unwrap(); + assert!( + ledger.agrees("v1", "react.mjs", "aaaa"), + "first sight records" + ); + assert!(ledger.agrees("v1", "react.mjs", "aaaa"), "same bytes agree"); + assert!( + !ledger.agrees("v1", "react.mjs", "bbbb"), + "other bytes do not" + ); + assert!(ledger.agrees("v2", "react.mjs", "bbbb"), "per version"); + assert!(ledger.agrees("v1", "zod.mjs", "bbbb"), "per file"); + let again = DepLedger::open(dir.path().join("l"), dir.path().join("deps")).unwrap(); + assert_eq!( + again.epoch, ledger.epoch, + "the epoch lives as long as the ledger" + ); + assert!(!again.agrees("v1", "react.mjs", "bbbb")); + let wiped = DepLedger::open(dir.path().join("other"), dir.path().join("deps")).unwrap(); + assert_ne!(wiped.epoch, ledger.epoch, "a new ledger is a new epoch"); + } + + // Two sessions on one ledger (a restart, another worktree on the same + // store) bundling the same bytes mint the same URLs: nothing reloads, and + // a compile keyed on the version is shared. + #[test] + fn same_bytes_keep_their_url_across_sessions_on_one_ledger() { + let dir = tempfile::tempdir().unwrap(); + let versions: Vec = (0..2) + .map(|_| { + let deps = ledgered_deps(dir.path()); + let r = deps.rerun.as_ref().unwrap(); + let v = browser_hash(&r.hash, &r.epoch, std::iter::empty()); + *r.browser_version.write().unwrap() = v.clone(); + let mut plan: DepMap = [("react".to_string(), meta("react.mjs", true))].into(); + plan.get_mut("react").unwrap().url = dep_url("react.mjs", &v); + let mut bundled = plan.clone(); + bundled.get_mut("react").unwrap().file_hash = "abc".into(); + bundled_bytes(dir.path(), "react.mjs", "the same bytes"); + commit_initial(r, bundled, Some(plan), |_, _| {}); + assert_eq!(deps.browser_version(), v, "agreeing bytes keep the URL"); + deps.meta_now("react").unwrap().url + }) + .collect(); + assert_eq!(versions[0], versions[1]); + } + + // Vite's sessionTimestamp guarantee, kept by the ledger: other bytes + // under a URL an earlier session served (a cleared pre-bundle over an + // edited node_modules) move every URL to a version of the new bytes, and + // the page reloads. + #[test] + fn other_bytes_under_a_served_url_remint_and_reload() { + let dir = tempfile::tempdir().unwrap(); + let commit = |file_hash: &str| { + let deps = ledgered_deps(dir.path()); + let r = deps.rerun.as_ref().unwrap(); + let reloads = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let seen = Arc::clone(&reloads); + let _ = r.on_commit.set(Box::new(move |_| { + seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + })); + let v = browser_hash(&r.hash, &r.epoch, std::iter::empty()); + *r.browser_version.write().unwrap() = v.clone(); + let mut plan: DepMap = [("react".to_string(), meta("react.mjs", true))].into(); + plan.get_mut("react").unwrap().url = dep_url("react.mjs", &v); + let mut bundled = plan.clone(); + bundled.get_mut("react").unwrap().file_hash = "same-name-hash".into(); + bundled_bytes(dir.path(), "react.mjs", file_hash); + let mut persisted = String::new(); + commit_initial(r, bundled, Some(plan), |_, version| { + persisted = version.to_string(); + }); + let url = deps.meta_now("react").unwrap().url; + ( + v, + url, + persisted, + reloads.load(std::sync::atomic::Ordering::SeqCst), + ) + }; + let (v, first, _, first_reloads) = commit("aaaa"); + assert_eq!(first, dep_url("react.mjs", &v)); + assert_eq!(first_reloads, 0); + let (_, second, persisted, reloads) = commit("bbbb"); + assert_ne!(second, first, "a served URL never names other bytes"); + assert_eq!( + second, + dep_url("react.mjs", &persisted), + "the manifest gets the new version" + ); + assert_eq!(reloads, 1, "modules compiled against the old URL reload"); + // The re-minted version is the new bytes': a third session with them + // lands on it without another re-mint. + let (_, third, _, _) = commit("bbbb"); + assert_eq!(third, second); + } + // The bundle confirming the plan commits quietly: the planned deps stop // pending, a dep a compile discovered meanwhile keeps its provisional // entry for its rerun, and nothing reloads. @@ -2691,7 +3020,8 @@ mod tests { let (wake, _wake_rx) = tokio::sync::mpsc::unbounded_channel(); let rerun = Arc::new(RerunState { hash: "testhash".into(), - session: session_timestamp(), + epoch: session_timestamp(), + ledger: None, tx, discovered: Default::default(), pending: Default::default(), diff --git a/crates/oj_server/src/plugin_routes.rs b/crates/oj_server/src/plugin_routes.rs index 14eba78d6..d27040266 100644 --- a/crates/oj_server/src/plugin_routes.rs +++ b/crates/oj_server/src/plugin_routes.rs @@ -116,7 +116,7 @@ async fn compile_plugin_source( format!( "/@id/{}?importer={}", hex_encode(spec), - hex_encode(&importer) + crate::rewrite::encode_importer(&root, &importer) ) }) }; diff --git a/crates/oj_server/src/plugins/extract.rs b/crates/oj_server/src/plugins/extract.rs index 2c07b41fa..238fb1078 100644 --- a/crates/oj_server/src/plugins/extract.rs +++ b/crates/oj_server/src/plugins/extract.rs @@ -910,7 +910,7 @@ fn run_extraction( held = Some(json); } else { print_extraction_stderr(&hit.stderr); - let _ = CONFIG_DEPS.set(hit.deps); + record_config_dependencies(vite, hit.deps); crate::boot_phase("vite-extract cache hit"); return Ok((json, false)); } @@ -1098,7 +1098,7 @@ fn store_extraction( .collect() }) .unwrap_or_default(); - let _ = CONFIG_DEPS.set(deps.clone()); + record_config_dependencies(vite, deps.clone()); if extraction_deps_truncated(json) { // Read recorder hit its cap: `__deps` is incomplete, so serve the // result but never cache it. @@ -1219,12 +1219,27 @@ pub fn extraction_env_hash(vars: impl Iterator) -> Stri hasher.finalize().to_hex().to_string() } -/// The files the config file imported, as the extractor reported them (Vite's -/// `configFileDependencies`): the dev server restarts when one changes. -pub(crate) static CONFIG_DEPS: std::sync::OnceLock> = std::sync::OnceLock::new(); +/// The files each config file imported, as its latest extraction reported +/// them (Vite's `configFileDependencies`): the dev server restarts when one +/// changes, and caches keyed on the config cover them. Keyed by config file, +/// as one process may serve more than one app. +static CONFIG_DEPS: std::sync::Mutex>>> = + std::sync::Mutex::new(None); -pub fn config_dependencies() -> &'static [PathBuf] { - CONFIG_DEPS.get().map(Vec::as_slice).unwrap_or(&[]) +pub(crate) fn record_config_dependencies(config: &Path, deps: Vec) { + let mut all = CONFIG_DEPS.lock().unwrap_or_else(|e| e.into_inner()); + all.get_or_insert_with(std::collections::HashMap::new) + .insert(config.to_path_buf(), deps); +} + +/// The files `config` (a resolved vite config file) imported. +pub fn config_dependencies_of(config: &Path) -> Vec { + CONFIG_DEPS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .and_then(|all| all.get(config).cloned()) + .unwrap_or_default() } fn str_field(json: &serde_json::Value, key: &str) -> Option { diff --git a/crates/oj_server/src/plugins/host.rs b/crates/oj_server/src/plugins/host.rs index aa12fe387..da86728df 100644 --- a/crates/oj_server/src/plugins/host.rs +++ b/crates/oj_server/src/plugins/host.rs @@ -86,6 +86,10 @@ pub(crate) struct HostCore { /// was told to leave Start's own plugins out (`ojNativeImportProtection`). import_protection: std::sync::OnceLock>, + /// TracingFs sink (pulp P2): content reads the isolates perform while a + /// transform window is open, the safety net under the JS-level + /// AsyncLocalStorage attribution. + read_log: std::sync::Arc, /// Engine hosting plugin-host.mjs; an Option so `declare_gone`/`shutdown` can /// take + abandon it. A thread wedged in NATIVE code leaks with its isolate. engine: Mutex>>, @@ -212,6 +216,7 @@ pub struct HostPrewarm { bundles: BundleGraphs, registry: Option, boot_preseed: BootPreseed, + read_log: Arc, } impl HostPrewarm { @@ -401,6 +406,7 @@ fn new_host_engine( import_meta_env: Arc>>, resolvers: ResolverSlot, bundles: BundleGraphs, + read_log: Arc, post_tx: tokio::sync::mpsc::UnboundedSender, runtime: Option, boot_preseed: BootPreseed, @@ -430,6 +436,7 @@ fn new_host_engine( }; let mut engine_config = oj_js::EngineConfig::new(&root); engine_config.code_cache_dir = Some(crate::engine_code_cache_dir(&root)); + engine_config.trace_reads = Some(read_log); engine_config.memory_limit_bytes = Some(memory_limit_bytes); engine_config.registry = registry; oj_js::JsEngine::spawn( @@ -1171,6 +1178,7 @@ impl PluginHost { let bundles = BundleGraphs::default(); let boot_preseed = BootPreseed::default(); let resolvers = ResolverSlot::default(); + let read_log: Arc = Arc::default(); let engine = new_host_engine( root, plugin_host_memory_mb() * 1024 * 1024, @@ -1178,6 +1186,7 @@ impl PluginHost { Arc::clone(&import_meta_env), Arc::clone(&resolvers), Arc::clone(&bundles), + Arc::clone(&read_log), post_tx, tokio::runtime::Handle::try_current().ok(), Arc::clone(&boot_preseed), @@ -1199,6 +1208,7 @@ impl PluginHost { bundles, registry, boot_preseed, + read_log, }) } @@ -1251,6 +1261,11 @@ impl PluginHost { }); let core = std::sync::Arc::new(HostCore { import_protection: std::sync::OnceLock::new(), + // A prewarmed engine already records into its own log. + read_log: prewarm + .as_ref() + .map(|p| Arc::clone(&p.read_log)) + .unwrap_or_default(), engine: Mutex::new(None), host_module: script.to_string_lossy().into_owned(), ws_out: std::sync::OnceLock::new(), @@ -1340,8 +1355,17 @@ impl PluginHost { id: &str, resolved: &str, ) -> Result { - let raw = self.call("transform", &[code, id, resolved]).await?; - Ok(HostTransform::parse(raw, code)) + // TracingFs window: every content read the isolates perform while + // this call is in flight is charged to it (and to any concurrent + // transform — sound over-approximation; the JS AsyncLocalStorage + // buckets carry the precise attribution for everything they see). + let window = self.core.read_log.begin(); + let called = self.call("transform", &[code, id, resolved]).await; + Ok(Self::with_fs_reads( + called?, + code, + self.core.read_log.finish(window), + )) } /// One slot of a stylesheet's transform chain, around Vite's core CSS @@ -1353,10 +1377,34 @@ impl PluginHost { id: &str, phase: &str, ) -> Result { - let raw = self - .call("transformPhase", &[code, id, "{}", phase]) - .await?; - Ok(HostTransform::parse(raw, code)) + let window = self.core.read_log.begin(); + let called = self.call("transformPhase", &[code, id, "{}", phase]).await; + Ok(Self::with_fs_reads( + called?, + code, + self.core.read_log.finish(window), + )) + } + + /// The host's reply with the reads the TracingFs window saw folded in: + /// one no plugin answered (no reply) read nothing of its own. + fn with_fs_reads( + raw: Option, + code: &str, + fs_reads: Vec, + ) -> HostTransform { + let had_reply = raw.is_some(); + let mut t = HostTransform::parse(raw, code); + if had_reply { + t.reads.extend( + fs_reads + .into_iter() + .map(|p| p.to_string_lossy().into_owned()), + ); + t.reads.sort(); + t.reads.dedup(); + } + t } /// [`PluginHost::transform_phase`] continuing a chain run elsewhere: @@ -2104,6 +2152,14 @@ impl PluginHost { self.call_flag("getHasLoad", false).await } + /// Whether an active plugin collects state from every module's transform + /// and serves it from a virtual (UnoCSS, WindiCSS): a transform the + /// persistent cache skips is state such a plugin never sees. Defaults to + /// false on RPC failure, as the cache is off without a host anyway. + pub async fn collects_from_transforms(&self) -> bool { + self.call_flag("getCollectsFromTransforms", false).await + } + /// `filter.code` include patterns of every object-form transform hook; /// dependency transforms are gated on these. pub async fn dep_transform_filters(&self) -> Vec { @@ -2750,6 +2806,7 @@ impl HostCore { Arc::clone(&self.boot.import_meta_env), Arc::clone(&self.boot.resolvers), Arc::clone(&self.boot.bundles), + Arc::clone(&self.read_log), post_tx, self.boot.runtime.clone(), Arc::clone(&self.boot.boot_preseed), @@ -3826,6 +3883,9 @@ pub struct HostTransform { /// (vite:oxc's strip returns `"js"`): rolldown then runs no TypeScript /// transform of its own over the lowered code. pub module_type: Option, + /// Side files the transform hooks read (pulp P2): the host's + /// per-hook `readFiles` plus the TracingFs window, sorted and deduped. + pub reads: Vec, } impl HostTransform { @@ -3851,6 +3911,7 @@ impl HostTransform { if next.module_type.is_some() { self.module_type = next.module_type; } + self.reads.extend(next.reads); } /// A reply that is not the host's JSON is the code itself; none leaves @@ -3892,6 +3953,7 @@ impl HostTransform { .and_then(|n| n.as_str()) .map(str::to_string), chunks: emitted_chunks(&v), + reads: str_array("readFiles"), module_type: v .get("moduleType") .and_then(|n| n.as_str()) diff --git a/crates/oj_server/src/plugins/static_config.rs b/crates/oj_server/src/plugins/static_config.rs index feb5c7e6d..28882ed9b 100644 --- a/crates/oj_server/src/plugins/static_config.rs +++ b/crates/oj_server/src/plugins/static_config.rs @@ -235,7 +235,7 @@ pub(crate) fn read_static( .map(|options| serde_json::json!({ "options": options })) .unwrap_or(Value::Null), ); - let _ = super::CONFIG_DEPS.set(vec![vite.to_path_buf()]); + super::extract::record_config_dependencies(vite, vec![vite.to_path_buf()]); Ok(out) } diff --git a/crates/oj_server/src/rewrite.rs b/crates/oj_server/src/rewrite.rs index ae6a5cf4f..c3eae1fc3 100644 --- a/crates/oj_server/src/rewrite.rs +++ b/crates/oj_server/src/rewrite.rs @@ -5,6 +5,28 @@ pub(crate) type DirCache = std::collections::HashMap< std::sync::Arc>, >; +/// Whether a cached module imports a plugin-served virtual: a filesystem-path +/// import with no file on disk, checked both root-relative and absolute. Such +/// a module's transform produced in-memory plugin state a warm start loses, +/// so it is re-transformed. +pub(crate) fn imports_a_plugin_virtual( + imports: &[String], + root: &Path, + dir_cache: &Mutex, +) -> bool { + imports.iter().any(|imp| { + let p = imp.split('?').next().unwrap_or(imp); + if !p.starts_with('/') || p.starts_with("/@") || p.contains("://") { + return false; + } + let as_root = root.join(p.trim_start_matches('/')); + if is_file_cached(dir_cache, &as_root) { + return false; + } + !is_file_cached(dir_cache, Path::new(p)) + }) +} + pub(crate) fn is_file_cached(cache: &Mutex, path: &Path) -> bool { let (Some(dir), Some(name)) = (path.parent(), path.file_name()) else { return path.is_file(); @@ -423,10 +445,103 @@ pub(crate) fn in_node_modules(path: &Path) -> bool { path.components().any(|c| c.as_os_str() == "node_modules") } +/// The (canonical) workspace root for an app root, cached: `url_of` runs per +/// rewritten import and must not walk ancestors every time. +pub(crate) fn workspace_of(root: &Path) -> PathBuf { + static CACHE: std::sync::Mutex>> = + std::sync::Mutex::new(None); + let mut guard = CACHE.lock().unwrap_or_else(|e| e.into_inner()); + let map = guard.get_or_insert_with(std::collections::HashMap::new); + if let Some(ws) = map.get(root) { + return ws.clone(); + } + let ws = oj_cache::store::workspace_root(root); + let ws = std::fs::canonicalize(&ws).unwrap_or(ws); + map.insert(root.to_path_buf(), ws.clone()); + ws +} + pub(crate) fn url_of(root: &Path, file: &Path) -> String { - match file.strip_prefix(root) { - Ok(rel) => format!("/{}", rel.display()), - Err(_) => format!("/@fs{}", file.display()), + if let Ok(rel) = file.strip_prefix(root) { + return format!("/{}", rel.display()); + } + // In-workspace files outside the root (hoisted node_modules, monorepo + // siblings) get the worktree-independent form: the serving worktree + // expands `@mono/` against its OWN workspace root, so cached artifacts + // carrying these URLs mean the same thing in every worktree. + let workspace = workspace_of(root); + if let Ok(rel) = file.strip_prefix(&workspace) { + return format!("/@fs/@mono/{}", rel.display()); + } + if let Ok(canon) = std::fs::canonicalize(file) { + if let Ok(rel) = canon.strip_prefix(&workspace) { + return format!("/@fs/@mono/{}", rel.display()); + } + } + format!("/@fs{}", file.display()) +} + +/// The reverse of `url_of` for `/@fs` request paths: the piece after `/@fs`, +/// with `/@mono/` expanded against this server's workspace root. +pub(crate) fn fs_url_to_path(workspace: &Path, after_fs: &str) -> PathBuf { + match after_fs.strip_prefix("/@mono/") { + Some(rel) => workspace.join(rel), + None => PathBuf::from(after_fs), + } +} + +/// Encode an importer for an `/@id/...?importer=` URL. In-root importers +/// encode root-relative (`ws:`), in-workspace ones workspace-relative +/// (`mono:`), so rewritten imports in cached artifacts are +/// worktree-independent; the decode side re-roots against the SERVING +/// worktree. Anything else (virtual ids, external paths) encodes verbatim. +pub(crate) fn encode_importer(root: &Path, importer: &str) -> String { + if let Some(rel) = oj_cache::store::rel_key(root, Path::new(importer)) { + return hex_encode(&format!("ws:{rel}")); + } + let workspace = workspace_of(root); + if let Some(rel) = oj_cache::store::rel_key(&workspace, Path::new(importer)) { + return hex_encode(&format!("mono:{rel}")); + } + // The workspace is canonical; an importer in a different spelling + // (/var vs /private/var) still relativizes through its realpath. + if let Ok(canon) = std::fs::canonicalize(importer) { + if let Some(rel) = oj_cache::store::rel_key(&workspace, &canon) { + return hex_encode(&format!("mono:{rel}")); + } + } + hex_encode(importer) +} + +/// The inverse of `encode_importer`, against this server's root/workspace. +pub(crate) fn decode_importer(root: &Path, decoded: &str) -> String { + if let Some(rel) = decoded.strip_prefix("ws:") { + return root.join(rel).to_string_lossy().into_owned(); + } + if let Some(rel) = decoded.strip_prefix("mono:") { + return workspace_of(root).join(rel).to_string_lossy().into_owned(); + } + decoded.to_string() +} + +/// The URL component of a module-cache key: `/@fs/` URLs under the +/// workspace key by their relative spelling, so a hoisted dep's path-free +/// entry is one entry for every worktree. Serving is untouched. +pub(crate) fn key_url(workspace: &Path, url: &str) -> String { + let Some(rest) = url.strip_prefix("/@fs/") else { + return url.to_string(); + }; + let (path_part, query) = match rest.split_once('?') { + Some((p, q)) => (p, Some(q)), + None => (rest, None), + }; + let abs = PathBuf::from(format!("/{}", path_part.trim_start_matches('/'))); + match oj_cache::store::rel_key(workspace, &abs) { + Some(rel) => match query { + Some(q) => format!("/@fs/@mono/{rel}?{q}"), + None => format!("/@fs/@mono/{rel}"), + }, + None => url.to_string(), } } diff --git a/crates/oj_server/src/serve.rs b/crates/oj_server/src/serve.rs index 6fe208c8c..f0b12728e 100644 --- a/crates/oj_server/src/serve.rs +++ b/crates/oj_server/src/serve.rs @@ -142,7 +142,9 @@ async fn serve_internal_route( let id_path = path.to_string(); let importer = match uri.query() { Some(q) => match q.strip_prefix("importer=") { - Some(importer) => decode_at_id(importer), + Some(importer) => { + crate::rewrite::decode_importer(&state.root, &decode_at_id(importer)) + } None => { spec = at_id_with_query(&spec, q); String::new() @@ -260,7 +262,10 @@ async fn request_file( rel: &str, ) -> Result> { if let Some(abs) = crate::fs_url_path(uri.path()) { - let abs = PathBuf::from(urldecode(abs).into_owned()); + // `/@mono/` is the worktree-independent form for in-workspace + // files: resolved against THIS server's workspace root, so a + // restored artifact can never point into another checkout. + let abs = crate::rewrite::fs_url_to_path(&state.workspace_root_dir, &urldecode(abs)); // Only an existing file is refused or served; a miss goes on to the // app, as sirv hands it on in Vite's serveRawFsMiddleware. if !abs.is_file() { diff --git a/crates/oj_server/src/store_remote.rs b/crates/oj_server/src/store_remote.rs new file mode 100644 index 000000000..4b779b3a0 --- /dev/null +++ b/crates/oj_server/src/store_remote.rs @@ -0,0 +1,310 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2026 Raphael Amorim + +//! The client side of the oj store's wire (pulp P3): Metro's chain. The local +//! shared store is consulted first (PersistentCache); on a miss, the remote +//! substituter is read through and the entry is written back locally, so the +//! fleet's second sandbox pays one HTTP GET instead of a compile. Pushing is +//! separate and explicit: the dev server pushes only when `OJ_STORE_PUSH=1` +//! AND a token is set — untrusted contexts hold read-only tokens and the +//! server's write-once entries bound what even a leaked write token can do. +//! +//! Trust at the consuming edge: a fetched entry is admitted only if its +//! stored form passes `CachedModule::is_relocatable` (a remote can never pin +//! this worktree into serving another checkout's paths) and only under the +//! key the CLIENT computed (a remote cannot choose which module its bytes +//! stand in for). Entry signing is designed (Nix narinfo model) but not yet +//! wired; until then the write token is the trust boundary. + +use std::sync::Arc; +use std::time::Duration; + +use oj_cache::CachedModule; + +/// A substituter is on the request path: a connect that takes longer than +/// this, or a whole fetch longer than [`READ_TIMEOUT`], counts as a failure. +const CONNECT_TIMEOUT: Duration = Duration::from_secs(2); +const READ_TIMEOUT: Duration = Duration::from_secs(5); +/// Consecutive failures after which the remote is not asked again. +const TRIPS_AFTER: usize = 3; + +pub struct RemoteStore { + base: String, + token: Option, + push: bool, + client: reqwest::Client, + /// Read-throughs that failed in a row (a connect error, a timeout, a 5xx). + /// Past [`TRIPS_AFTER`] the remote is left alone for the rest of the + /// session: a substituter that is down must not turn every cold compile + /// into a wait. A success starts the count over. + failures: std::sync::atomic::AtomicUsize, + /// Fire-and-forget pushes run on their own small thread to keep the + /// cache writer thread off the network. + push_tx: std::sync::mpsc::Sender<(String, Vec)>, +} + +impl RemoteStore { + /// From `OJ_STORE_REMOTE` (+ `OJ_STORE_TOKEN`, `OJ_STORE_PUSH`): None + /// when no remote is configured. + pub fn from_env() -> Option> { + let knobs = &oj_env::get().knobs; + Self::connect( + knobs.store_remote.as_deref()?, + knobs.store_token.clone(), + knobs.store_push, + ) + } + + /// A client of the substituter at `base`, pushing when `push`. + pub(crate) fn connect( + base: &str, + token: Option, + push: bool, + ) -> Option> { + let base = base.trim_end_matches('/').to_string(); + let client = reqwest::Client::builder() + .connect_timeout(CONNECT_TIMEOUT) + .timeout(READ_TIMEOUT) + .build() + .ok()?; + let (push_tx, push_rx) = std::sync::mpsc::channel::<(String, Vec)>(); + let store = Arc::new(RemoteStore { + base, + token, + push, + client, + failures: std::sync::atomic::AtomicUsize::new(0), + push_tx, + }); + if store.push { + let pusher = Arc::clone(&store); + std::thread::spawn(move || { + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("push runtime"); + while let Ok((url, body)) = push_rx.recv() { + let req = pusher.authed(pusher.client.put(&url)).body(body); + // Best-effort: 409 means someone else already published + // this key, which is success; errors only cost sharing. + let _ = rt.block_on(async { req.send().await }); + } + }); + } + Some(store) + } + + /// Whether the remote is left alone for the rest of the session. + pub(crate) fn tripped(&self) -> bool { + self.failures.load(std::sync::atomic::Ordering::Relaxed) >= TRIPS_AFTER + } + + fn failed(&self) { + let before = self + .failures + .fetch_add(1, std::sync::atomic::Ordering::Relaxed); + if before + 1 == TRIPS_AFTER { + eprintln!( + "oj: store: {} did not answer {TRIPS_AFTER} times; not asked again this session", + self.base + ); + } + } + + fn authed(&self, req: reqwest::RequestBuilder) -> reqwest::RequestBuilder { + match &self.token { + Some(t) => req.bearer_auth(t), + None => req, + } + } + + /// Read-through for a module entry this client's key computation missed + /// locally. Returns the STORED (ws:/mono:) form; the caller rehomes it. + pub async fn fetch_module(&self, key: &str) -> Option { + if self.tripped() { + return None; + } + let url = format!("{}/v1/ac/modules/{key}", self.base); + let answered = async { + let resp = self.authed(self.client.get(&url)).send().await.ok()?; + let status = resp.status(); + if status.is_server_error() { + return None; + } + Some((status, resp)) + } + .await; + let Some((status, resp)) = answered else { + self.failed(); + return None; + }; + self.failures.store(0, std::sync::atomic::Ordering::Relaxed); + if status != reqwest::StatusCode::OK { + return None; + } + let bytes = resp.bytes().await.ok()?; + let module: CachedModule = serde_json::from_slice(&bytes).ok()?; + // The admission gate, applied to what the WIRE delivered: nothing + // that pins a checkout crosses into this worktree, whatever the + // server said. + module.is_relocatable().then_some(module) + } + + /// Queue a stored-form entry for push. Called from the cache writer + /// thread; never blocks on the network. + pub fn push_module(&self, key: &str, stored: &CachedModule) { + if !self.push { + return; + } + if let Ok(body) = serde_json::to_vec(stored) { + let url = format!("{}/v1/ac/modules/{key}", self.base); + let _ = self.push_tx.send((url, body)); + } + } +} + +#[cfg(test)] +mod tests { + //! The consuming edge of the wire, against a live substituter in this + //! process: what crosses in, what crosses out, and with which token. + use super::*; + use std::time::Instant; + + fn key(n: u8) -> String { + format!("{n:02x}").repeat(32) + } + + async fn substituter(dir: &std::path::Path) -> String { + let state = crate::store_server::state(dir.to_path_buf(), None, Some("w".into())); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { + let _ = axum::serve(listener, crate::store_server::router(state)).await; + }); + format!("http://{addr}") + } + + async fn stored(client: &reqwest::Client, base: &str, key: &str) -> Option { + let response = client + .get(format!("{base}/v1/ac/modules/{key}")) + .send() + .await + .unwrap(); + if response.status() != reqwest::StatusCode::OK { + return None; + } + serde_json::from_slice(&response.bytes().await.unwrap()).ok() + } + + #[tokio::test(flavor = "multi_thread")] + async fn a_pinned_entry_never_crosses_the_wire_in_and_pushes_need_the_token() { + let dir = tempfile::tempdir().unwrap(); + let base = substituter(dir.path()).await; + let client = reqwest::Client::new(); + let poison = CachedModule { + code: "import x from \"/@fs//other/checkout/x.js\";".into(), + imports: vec!["/@fs//other/checkout/x.js".into()], + ..Default::default() + }; + let good = CachedModule { + code: "export const x = 1;".into(), + fs_allow: vec!["ws:node_modules/dep".into()], + ..Default::default() + }; + for (k, module) in [(key(1), &poison), (key(2), &good)] { + let status = client + .put(format!("{base}/v1/ac/modules/{k}")) + .bearer_auth("w") + .body(serde_json::to_vec(module).unwrap()) + .send() + .await + .unwrap() + .status(); + assert_eq!(status, reqwest::StatusCode::CREATED); + } + let remote = RemoteStore::connect(&base, Some("w".into()), true).unwrap(); + assert_eq!( + remote.fetch_module(&key(1)).await, + None, + "an entry naming a checkout is refused at the consuming edge" + ); + assert_eq!(remote.fetch_module(&key(2)).await.as_ref(), Some(&good)); + assert_eq!(remote.fetch_module(&key(9)).await, None, "a miss is a miss"); + assert_eq!( + remote.fetch_module("../../etc/passwd").await, + None, + "a key that is no digest fetches nothing" + ); + + // A push lands, asynchronously, under the write token. + remote.push_module(&key(3), &good); + let deadline = Instant::now() + Duration::from_secs(10); + while stored(&client, &base, &key(3)).await.as_ref() != Some(&good) { + assert!(Instant::now() < deadline, "the push never landed"); + tokio::time::sleep(Duration::from_millis(50)).await; + } + // A second push of the key is a conflict the pusher swallows: the + // first write stands. + remote.push_module(&key(3), &poison); + tokio::time::sleep(Duration::from_millis(300)).await; + assert_eq!(stored(&client, &base, &key(3)).await.as_ref(), Some(&good)); + + // Without the token nothing is pushed; without `push` nothing is sent. + let anonymous = RemoteStore::connect(&base, None, true).unwrap(); + anonymous.push_module(&key(4), &good); + let reader = RemoteStore::connect(&base, Some("w".into()), false).unwrap(); + reader.push_module(&key(5), &good); + tokio::time::sleep(Duration::from_millis(300)).await; + assert_eq!( + stored(&client, &base, &key(4)).await, + None, + "pushed without a token" + ); + assert_eq!( + stored(&client, &base, &key(5)).await, + None, + "pushed with push off" + ); + assert_eq!(reader.fetch_module(&key(2)).await.as_ref(), Some(&good)); + } +} + +#[cfg(test)] +mod breaker_tests { + use super::*; + use std::time::Instant; + + // A substituter that is down (here: a port nothing listens on) costs a + // few fast failures, then nothing: the breaker trips and later misses + // never touch the network. + #[tokio::test(flavor = "multi_thread")] + async fn a_remote_that_is_down_is_given_up_on_after_a_few_failures() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + drop(listener); + let remote = RemoteStore::connect(&format!("http://{addr}"), None, false).unwrap(); + let key = "ab".repeat(32); + let started = Instant::now(); + for i in 0..TRIPS_AFTER { + assert_eq!(remote.fetch_module(&key).await, None); + assert_eq!( + remote.tripped(), + i + 1 == TRIPS_AFTER, + "after {} failures", + i + 1 + ); + } + assert!( + started.elapsed() < Duration::from_secs(TRIPS_AFTER as u64 * 2), + "a refused connection fails fast" + ); + let started = Instant::now(); + for _ in 0..100 { + assert_eq!(remote.fetch_module(&key).await, None); + } + assert!( + started.elapsed() < Duration::from_millis(500), + "a tripped remote is not asked" + ); + } +} diff --git a/crates/oj_server/src/store_server.rs b/crates/oj_server/src/store_server.rs new file mode 100644 index 000000000..38303487d --- /dev/null +++ b/crates/oj_server/src/store_server.rs @@ -0,0 +1,567 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2026 Raphael Amorim + +//! The oj store's wire (pulp P3): a deliberately boring six-endpoint HTTP +//! substituter, shaped like Metro's store and Nix's substituters had a child. +//! +//! ```text +//! GET /v1/ac/{ns}/{key} action-cache entry (modules: the CachedModule JSON) +//! PUT /v1/ac/{ns}/{key} write-once: 201, or 409 if present +//! GET /v1/cas/{blake3} content-addressed blob +//! HEAD /v1/cas/{blake3} +//! PUT /v1/cas/{blake3} write-once; body must match its digest +//! POST /v1/cas/missing {"digests":[..]} -> {"missing":[..]} +//! ``` +//! +//! Write-once entries and split read/write tokens are the CREEP lesson +//! (CVE-2025-36852): in a shared first-write-wins cache with one credential, +//! anyone who can open a PR can poison what main will later hit. Here a PUT +//! can never replace, untrusted consumers hold read-only tokens, and a bad +//! entry costs one key. +//! +//! Auth: `OJ_STORE_READ_TOKEN` (unset = public reads) and +//! `OJ_STORE_WRITE_TOKEN` (unset = writes refused), both bearer tokens. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use axum::body::Bytes; +use axum::extract::{Path as AxPath, State}; +use axum::http::{header, HeaderMap, StatusCode}; +use axum::response::{IntoResponse, Response}; +use axum::routing::{get, post}; +use axum::Router; + +const MAX_BLOB_BYTES: usize = 64 * 1024 * 1024; +const MAX_AC_BYTES: usize = 16 * 1024 * 1024; + +pub struct StoreServer { + dir: PathBuf, + read_token: Option, + write_token: Option, +} + +/// A server over `dir` with its tokens (`None` read token: public reads; +/// `None` write token: writes refused). +pub(crate) fn state( + dir: PathBuf, + read_token: Option, + write_token: Option, +) -> Arc { + Arc::new(StoreServer { + dir, + read_token, + write_token, + }) +} + +/// The six endpoints over `state`. +pub(crate) fn router(state: Arc) -> Router { + Router::new() + .route("/v1/ac/{ns}/{key}", get(ac_get).put(ac_put)) + .route("/v1/cas/{hash}", get(cas_get).head(cas_head).put(cas_put)) + .route("/v1/cas/missing", post(cas_missing)) + // axum's default body limit is 2 MiB, under both of ours. + .layer(axum::extract::DefaultBodyLimit::max(MAX_BLOB_BYTES)) + .with_state(state) +} + +pub async fn serve(dir: PathBuf, host: &str, port: u16) -> Result<(), String> { + let state = state( + dir, + oj_env::get().knobs.store_read_token.clone(), + oj_env::get().knobs.store_write_token.clone(), + ); + std::fs::create_dir_all(&state.dir).map_err(|e| e.to_string())?; + let app = router(Arc::clone(&state)); + let addr = format!("{host}:{port}"); + let listener = tokio::net::TcpListener::bind(&addr) + .await + .map_err(|e| format!("bind {addr}: {e}"))?; + eprintln!( + "oj store: serving {} on http://{addr} (reads {}, writes {})", + state.dir.display(), + if state.read_token.is_some() { + "token" + } else { + "public" + }, + if state.write_token.is_some() { + "token" + } else { + "DISABLED" + }, + ); + axum::serve(listener, app).await.map_err(|e| e.to_string()) +} + +fn bearer(headers: &HeaderMap) -> Option<&str> { + headers + .get(header::AUTHORIZATION)? + .to_str() + .ok()? + .strip_prefix("Bearer ") +} + +fn can_read(s: &StoreServer, headers: &HeaderMap) -> bool { + match &s.read_token { + None => true, + // The write token also reads: a pusher must be able to probe. + Some(t) => { + let b = bearer(headers); + b == Some(t.as_str()) + || (s.write_token.as_deref().is_some() && b == s.write_token.as_deref()) + } + } +} + +fn can_write(s: &StoreServer, headers: &HeaderMap) -> bool { + matches!((&s.write_token, bearer(headers)), (Some(t), Some(b)) if b == t) +} + +fn valid_hex(s: &str, len: usize) -> bool { + s.len() == len + && s.bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) +} + +fn valid_ns(s: &str) -> bool { + !s.is_empty() + && s.len() <= 64 + && s.bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') +} + +fn ac_path(s: &StoreServer, ns: &str, key: &str) -> Option { + (valid_ns(ns) && valid_hex(key, 64)).then(|| { + s.dir + .join("ac") + .join(ns) + .join(&key[..2]) + .join(format!("{key}.json")) + }) +} + +fn cas_path(s: &StoreServer, hash: &str) -> Option { + valid_hex(hash, 64).then(|| s.dir.join("cas").join(&hash[..2]).join(hash)) +} + +/// Write-once publish: the bytes go to a temp file of this request's own and +/// are hard-linked into place, so a reader never sees a partial entry and +/// two writers of one key cannot mix: the link either creates the name or +/// finds it taken (409), whatever the other writer is doing meanwhile. +fn write_once(path: &Path, bytes: &[u8]) -> Result<(), StatusCode> { + if path.exists() { + return Err(StatusCode::CONFLICT); + } + let parent = path.parent().ok_or(StatusCode::INTERNAL_SERVER_ERROR)?; + std::fs::create_dir_all(parent).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let tmp = path.with_extension(format!("tmp-{}-{seq}", std::process::id())); + std::fs::write(&tmp, bytes).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + let linked = std::fs::hard_link(&tmp, path); + let _ = std::fs::remove_file(&tmp); + match linked { + Ok(()) => Ok(()), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Err(StatusCode::CONFLICT), + Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR), + } +} + +async fn ac_get( + State(s): State>, + AxPath((ns, key)): AxPath<(String, String)>, + headers: HeaderMap, +) -> Response { + if !can_read(&s, &headers) { + return StatusCode::UNAUTHORIZED.into_response(); + } + let Some(path) = ac_path(&s, &ns, &key) else { + return StatusCode::BAD_REQUEST.into_response(); + }; + match std::fs::read(&path) { + Ok(bytes) => ([(header::CONTENT_TYPE, "application/json")], bytes).into_response(), + Err(_) => StatusCode::NOT_FOUND.into_response(), + } +} + +async fn ac_put( + State(s): State>, + AxPath((ns, key)): AxPath<(String, String)>, + headers: HeaderMap, + body: Bytes, +) -> Response { + if !can_write(&s, &headers) { + return StatusCode::UNAUTHORIZED.into_response(); + } + let Some(path) = ac_path(&s, &ns, &key) else { + return StatusCode::BAD_REQUEST.into_response(); + }; + if body.len() > MAX_AC_BYTES || serde_json::from_slice::(&body).is_err() { + return StatusCode::UNPROCESSABLE_ENTITY.into_response(); + } + match write_once(&path, &body) { + Ok(()) => StatusCode::CREATED.into_response(), + Err(code) => code.into_response(), + } +} + +async fn cas_get( + State(s): State>, + AxPath(hash): AxPath, + headers: HeaderMap, +) -> Response { + if !can_read(&s, &headers) { + return StatusCode::UNAUTHORIZED.into_response(); + } + let Some(path) = cas_path(&s, &hash) else { + return StatusCode::BAD_REQUEST.into_response(); + }; + match std::fs::read(&path) { + Ok(bytes) => ( + [ + (header::CONTENT_TYPE, "application/octet-stream"), + (header::CACHE_CONTROL, "public, max-age=31536000, immutable"), + ], + bytes, + ) + .into_response(), + Err(_) => StatusCode::NOT_FOUND.into_response(), + } +} + +async fn cas_head( + State(s): State>, + AxPath(hash): AxPath, + headers: HeaderMap, +) -> Response { + if !can_read(&s, &headers) { + return StatusCode::UNAUTHORIZED.into_response(); + } + match cas_path(&s, &hash) { + Some(path) if path.is_file() => StatusCode::OK.into_response(), + Some(_) => StatusCode::NOT_FOUND.into_response(), + None => StatusCode::BAD_REQUEST.into_response(), + } +} + +async fn cas_put( + State(s): State>, + AxPath(hash): AxPath, + headers: HeaderMap, + body: Bytes, +) -> Response { + if !can_write(&s, &headers) { + return StatusCode::UNAUTHORIZED.into_response(); + } + let Some(path) = cas_path(&s, &hash) else { + return StatusCode::BAD_REQUEST.into_response(); + }; + if body.len() > MAX_BLOB_BYTES { + return StatusCode::PAYLOAD_TOO_LARGE.into_response(); + } + // CAS self-verification: the name IS the digest, so a tampered or + // corrupted upload cannot land under an honest name. + if blake3::hash(&body).to_hex().to_string() != hash { + return StatusCode::UNPROCESSABLE_ENTITY.into_response(); + } + match write_once(&path, &body) { + Ok(()) => StatusCode::CREATED.into_response(), + // A CAS conflict is success by definition: identical content. + Err(StatusCode::CONFLICT) => StatusCode::OK.into_response(), + Err(code) => code.into_response(), + } +} + +#[derive(serde::Deserialize)] +struct MissingReq { + digests: Vec, +} + +async fn cas_missing( + State(s): State>, + headers: HeaderMap, + body: Bytes, +) -> Response { + if !can_read(&s, &headers) { + return StatusCode::UNAUTHORIZED.into_response(); + } + let Ok(req) = serde_json::from_slice::(&body) else { + return StatusCode::BAD_REQUEST.into_response(); + }; + let missing: Vec<&String> = req + .digests + .iter() + .filter(|h| !matches!(cas_path(&s, h), Some(p) if p.is_file())) + .collect(); + ( + [(header::CONTENT_TYPE, "application/json")], + serde_json::json!({ "missing": missing }).to_string(), + ) + .into_response() +} + +#[cfg(test)] +mod tests { + //! The wire's contract under what an untrusted client can send: names + //! that are no digest or namespace, bodies that are no module, writes + //! without the token, and a second write of a key. + use super::*; + use axum::body::Body; + use axum::http::{Method, Request}; + use tower::ServiceExt; + + fn key(n: u8) -> String { + format!("{n:02x}").repeat(32) + } + + async fn call( + app: &Router, + method: Method, + uri: &str, + token: Option<&str>, + body: Vec, + ) -> (StatusCode, Vec) { + let mut request = Request::builder().method(method).uri(uri); + if let Some(token) = token { + request = request.header(header::AUTHORIZATION, format!("Bearer {token}")); + } + let response = app + .clone() + .oneshot(request.body(Body::from(body)).unwrap()) + .await + .unwrap(); + let status = response.status(); + let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + (status, bytes.to_vec()) + } + + fn files_under(dir: &Path) -> Vec { + let mut out = Vec::new(); + for e in std::fs::read_dir(dir).into_iter().flatten().flatten() { + if e.path().is_dir() { + out.extend(files_under(&e.path())); + } else { + out.push(e.path()); + } + } + out + } + + #[tokio::test] + async fn names_that_are_no_digest_or_namespace_are_refused_and_write_nothing() { + let dir = tempfile::tempdir().unwrap(); + let app = router(state(dir.path().to_path_buf(), None, Some("w".into()))); + let module = serde_json::to_vec(&oj_cache::CachedModule::default()).unwrap(); + for uri in [ + format!("/v1/ac/modules/{}", &key(1)[..63]), + format!("/v1/ac/modules/{}X", &key(1)[..63]), + format!("/v1/ac/modules/{}", key(0xab).to_uppercase()), + format!("/v1/ac/..%2F..%2Fetc/{}", key(1)), + format!("/v1/ac/mod.ules/{}", key(1)), + format!("/v1/ac/{}/{}", "n".repeat(65), key(1)), + "/v1/cas/nothex".to_string(), + format!("/v1/cas/{}", &key(2)[..60]), + ] { + let (put, _) = call(&app, Method::PUT, &uri, Some("w"), module.clone()).await; + assert_eq!(put, StatusCode::BAD_REQUEST, "PUT {uri}"); + let (get, _) = call(&app, Method::GET, &uri, None, Vec::new()).await; + assert_eq!(get, StatusCode::BAD_REQUEST, "GET {uri}"); + } + assert!( + files_under(dir.path()).is_empty(), + "{:?}", + files_under(dir.path()) + ); + } + + #[tokio::test] + async fn action_entries_are_written_once_and_only_with_the_token() { + let dir = tempfile::tempdir().unwrap(); + let app = router(state( + dir.path().to_path_buf(), + Some("r".into()), + Some("w".into()), + )); + let uri = format!("/v1/ac/modules/{}", key(3)); + let module = serde_json::to_vec(&oj_cache::CachedModule { + code: "export const x = 1;".into(), + ..Default::default() + }) + .unwrap(); + let (status, _) = call(&app, Method::PUT, &uri, None, module.clone()).await; + assert_eq!(status, StatusCode::UNAUTHORIZED, "no token"); + let (status, _) = call(&app, Method::PUT, &uri, Some("r"), module.clone()).await; + assert_eq!( + status, + StatusCode::UNAUTHORIZED, + "the read token never writes" + ); + let (status, _) = call(&app, Method::PUT, &uri, Some("w"), module.clone()).await; + assert_eq!(status, StatusCode::CREATED); + let other = serde_json::to_vec(&oj_cache::CachedModule { + code: "export const x = 2;".into(), + ..Default::default() + }) + .unwrap(); + let (status, _) = call(&app, Method::PUT, &uri, Some("w"), other).await; + assert_eq!(status, StatusCode::CONFLICT, "write once"); + let (status, _) = call(&app, Method::GET, &uri, None, Vec::new()).await; + assert_eq!( + status, + StatusCode::UNAUTHORIZED, + "reads take the read token" + ); + for token in ["r", "w"] { + let (status, body) = call(&app, Method::GET, &uri, Some(token), Vec::new()).await; + assert_eq!(status, StatusCode::OK, "{token}"); + assert_eq!(body, module, "the first write stands"); + } + let (status, _) = call(&app, Method::PUT, &uri, Some("w"), b"not json".to_vec()).await; + assert_eq!( + status, + StatusCode::UNPROCESSABLE_ENTITY, + "a body that is no entry is refused before the key is looked at" + ); + let fresh = format!("/v1/ac/modules/{}", key(4)); + let (status, _) = call(&app, Method::PUT, &fresh, Some("w"), b"not json".to_vec()).await; + assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "an entry is JSON"); + let (status, _) = call( + &app, + Method::PUT, + &fresh, + Some("w"), + vec![b'['; MAX_AC_BYTES + 1], + ) + .await; + assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "bounded"); + let (status, _) = call(&app, Method::GET, &fresh, Some("r"), Vec::new()).await; + assert_eq!( + status, + StatusCode::NOT_FOUND, + "nothing landed under the fresh key" + ); + } + + #[tokio::test] + async fn blobs_are_named_by_their_digest() { + let dir = tempfile::tempdir().unwrap(); + let app = router(state(dir.path().to_path_buf(), None, Some("w".into()))); + let bytes = b"chunk bytes".to_vec(); + let digest = blake3::hash(&bytes).to_hex().to_string(); + let wrong = format!("/v1/cas/{}", key(5)); + let (status, _) = call(&app, Method::PUT, &wrong, Some("w"), bytes.clone()).await; + assert_eq!( + status, + StatusCode::UNPROCESSABLE_ENTITY, + "a name that is not the digest" + ); + let right = format!("/v1/cas/{digest}"); + let (status, _) = call(&app, Method::HEAD, &right, None, Vec::new()).await; + assert_eq!(status, StatusCode::NOT_FOUND); + let (status, _) = call(&app, Method::PUT, &right, Some("w"), bytes.clone()).await; + assert_eq!(status, StatusCode::CREATED); + let (status, _) = call(&app, Method::PUT, &right, Some("w"), bytes.clone()).await; + assert_eq!(status, StatusCode::OK, "the same bytes again is success"); + let (status, body) = call(&app, Method::GET, &right, None, Vec::new()).await; + assert_eq!((status, body), (StatusCode::OK, bytes)); + let (status, body) = call( + &app, + Method::POST, + "/v1/cas/missing", + None, + serde_json::json!({ "digests": [digest, key(6)] }) + .to_string() + .into_bytes(), + ) + .await; + assert_eq!(status, StatusCode::OK); + let missing: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(missing["missing"], serde_json::json!([key(6)])); + let (status, _) = call(&app, Method::PUT, &right, None, Vec::new()).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + } +} + +#[cfg(test)] +mod race_tests { + use super::*; + use axum::body::Body; + use axum::http::{Method, Request}; + use tower::ServiceExt; + + // Two sandboxes pushing one key at once, many times over: exactly one + // write is created, the rest are conflicts, and what is stored is one + // writer's whole body, never a mix. + #[tokio::test(flavor = "multi_thread")] + async fn racing_puts_of_one_key_create_it_once_and_whole() { + let dir = tempfile::tempdir().unwrap(); + let app = router(state(dir.path().to_path_buf(), None, Some("w".into()))); + let key = "ab".repeat(32); + let uri = format!("/v1/ac/modules/{key}"); + let bodies: Vec> = (0..24) + .map(|i| { + serde_json::to_vec(&oj_cache::CachedModule { + code: format!("export const x = {i}; // {}", "x".repeat(50_000 + i)), + ..Default::default() + }) + .unwrap() + }) + .collect(); + let puts = bodies.iter().map(|body| { + let app = app.clone(); + let uri = uri.clone(); + let body = body.clone(); + tokio::spawn(async move { + let request = Request::builder() + .method(Method::PUT) + .uri(&uri) + .header(header::AUTHORIZATION, "Bearer w") + .body(Body::from(body)) + .unwrap(); + app.oneshot(request).await.unwrap().status() + }) + }); + let mut created = 0; + let mut conflicts = 0; + for put in puts { + match put.await.unwrap() { + StatusCode::CREATED => created += 1, + StatusCode::CONFLICT => conflicts += 1, + other => panic!("a racing put answered {other}"), + } + } + assert_eq!((created, conflicts), (1, 23)); + let stored = + std::fs::read(dir.path().join("ac/modules/ab").join(format!("{key}.json"))).unwrap(); + assert!( + bodies.contains(&stored), + "the stored entry is no writer's body" + ); + let leftovers: Vec<_> = std::fs::read_dir(dir.path().join("ac/modules/ab")) + .unwrap() + .flatten() + .filter(|e| e.file_name().to_string_lossy().contains("tmp")) + .collect(); + assert!(leftovers.is_empty()); + // A body over 2 MiB (axum's default limit) reaches the handler. + let big = serde_json::to_vec(&oj_cache::CachedModule { + code: "y".repeat(3 << 20), + ..Default::default() + }) + .unwrap(); + let request = Request::builder() + .method(Method::PUT) + .uri(format!("/v1/ac/modules/{}", "cd".repeat(32))) + .header(header::AUTHORIZATION, "Bearer w") + .body(Body::from(big)) + .unwrap(); + assert_eq!( + app.oneshot(request).await.unwrap().status(), + StatusCode::CREATED + ); + } +} diff --git a/crates/oj_server/src/style_file.rs b/crates/oj_server/src/style_file.rs index 638060f63..2fa4741a8 100644 --- a/crates/oj_server/src/style_file.rs +++ b/crates/oj_server/src/style_file.rs @@ -208,9 +208,19 @@ pub fn start_dev_url_base(base: &str) -> String { } /// Where Start's unbundled dev serves a file (the Start bundles' fsBase), -/// under `url_base` (see [`start_dev_url_base`]). -pub fn start_dev_file_url(url_base: &str, file: &Path) -> String { - format!("{url_base}/@oj-start/fs{}", file.display()) +/// under `url_base` (see [`start_dev_url_base`]). In-root files get the +/// worktree-independent `@ws/` form, so chunk bytes and css manifests +/// are the same in every checkout; the dev server resolves `@ws/` against +/// its own root. SSR and the client bundle both build URLs here, so they +/// agree byte for byte. Out-of-root files keep the absolute form (correct, +/// merely unshareable). +pub fn start_dev_file_url(url_base: &str, root: &Path, file: &Path) -> String { + match file.strip_prefix(root) { + Ok(rel) if !rel.as_os_str().is_empty() => { + format!("{url_base}/@oj-start/fs/@ws/{}", rel.display()) + } + _ => format!("{url_base}/@oj-start/fs{}", file.display()), + } } /// Vite's `?inline` stylesheet under Start dev: the module whose default @@ -251,7 +261,7 @@ pub async fn start_dev_inline_style( } let dir = path.parent().unwrap_or(Path::new("/")); let css = try_rewrite_relative_urls(&css, dir, |file, suffix| { - start_dev_style_url(url_base, file, suffix, &*inputs.inline) + start_dev_style_url(url_base, inputs.root, file, suffix, &*inputs.inline) })?; let css = style_slot(slots, css, "normal").await?; Ok(format!( @@ -265,11 +275,12 @@ pub async fn start_dev_inline_style( /// else its Start dev URL. pub fn start_dev_style_url( url_base: &str, + root: &Path, file: &Path, suffix: &str, inline: &InlineUrl<'_>, ) -> Result { - let url = format!("{}{suffix}", start_dev_file_url(url_base, file)); + let url = format!("{}{suffix}", start_dev_file_url(url_base, root, file)); Ok(inline(file, &url)?.unwrap_or(url)) } @@ -391,11 +402,11 @@ mod tests { } }; let url = |file: &Path, suffix: &str, limit: u64| { - start_dev_style_url("/", file, suffix, &under(limit)).unwrap() + start_dev_style_url("/", &dir, file, suffix, &under(limit)).unwrap() }; let (svg, png) = (dir.join("dot.svg"), dir.join("dot.png")); let plain = - |file: &Path, suffix: &str| format!("{}{suffix}", start_dev_file_url("/", file)); + |file: &Path, suffix: &str| format!("{}{suffix}", start_dev_file_url("/", &dir, file)); assert_eq!( url(&svg, "", 4096), "data:image/svg+xml,%3csvg%3e%3c/svg%3e" diff --git a/crates/oj_server/src/tests.rs b/crates/oj_server/src/tests.rs index 0f9b2a254..158e7c327 100644 --- a/crates/oj_server/src/tests.rs +++ b/crates/oj_server/src/tests.rs @@ -3418,3 +3418,593 @@ fn a_page_navigation_to_a_vite_url_is_not_the_dev_servers() { assert!(is_dev_server_request(own, &dest("document")), "{own}"); } } + +// ---- pulp: the oj store ---- + +#[test] +fn engine_code_cache_dir_is_root_independent_under_a_shared_store() { + let store = Some(Path::new("/shared/oj-store")); + let a = engine_code_cache_dir_in(Path::new("/work/wt-a"), store); + let b = engine_code_cache_dir_in(Path::new("/work/wt-b"), store); + assert_eq!(a, b, "two worktrees must share one bytecode directory"); + assert!(a.starts_with("/shared/oj-store")); + let a = engine_code_cache_dir_in(Path::new("/work/wt-a"), None); + let b = engine_code_cache_dir_in(Path::new("/work/wt-b"), None); + assert_ne!(a, b, "without a store each app keeps its own"); +} + +fn salt_fixture(label: &str) -> PathBuf { + let root = std::env::temp_dir().join(format!("oj-salt-{}-{label}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + std::fs::write(root.join("package.json"), br#"{"name":"app"}"#).unwrap(); + std::fs::write(root.join("package-lock.json"), br#"{"lockfileVersion":3}"#).unwrap(); + std::fs::write(root.join("tsconfig.json"), br#"{"compilerOptions":{}}"#).unwrap(); + std::fs::write(root.join("vite.config.ts"), b"export default {}").unwrap(); + root +} + +fn salt_settings(root: &Path) -> oj_resolver::ResolveSettings { + oj_resolver::ResolveSettings { + conditions: vec!["import".into()], + alias: vec![("@".into(), root.join("src").to_string_lossy().into_owned())], + dedupe: vec![], + extensions: None, + main_fields: None, + preserve_symlinks: false, + server: false, + tsconfig_paths: oj_resolver::TsconfigPaths::Neither, + tsconfig_file: None, + } +} + +#[test] +fn module_cache_salt_is_worktree_independent() { + let a = salt_fixture("wt-a"); + let b = salt_fixture("wt-b"); + assert_eq!( + module_cache_config_salt(&a, &salt_settings(&a), Some(&a.join("vite.config.ts"))), + module_cache_config_salt(&b, &salt_settings(&b), Some(&b.join("vite.config.ts"))), + "same content in two worktrees must salt identically" + ); +} + +#[test] +fn module_cache_salt_moves_with_every_input_it_claims_to_cover() { + let root = salt_fixture("inputs"); + let cfg = root.join("vite.config.ts"); + let base = module_cache_config_salt(&root, &salt_settings(&root), Some(&cfg)); + std::fs::write( + root.join("tsconfig.json"), + br#"{"compilerOptions":{"paths":{}}}"#, + ) + .unwrap(); + let after_ts = module_cache_config_salt(&root, &salt_settings(&root), Some(&cfg)); + assert_ne!(base, after_ts, "tsconfig edit must invalidate"); + std::fs::write(&cfg, b"export default { plugins: [] }").unwrap(); + let after_cfg = module_cache_config_salt(&root, &salt_settings(&root), Some(&cfg)); + assert_ne!(after_ts, after_cfg, "vite.config edit must invalidate"); + std::fs::write( + root.join("package-lock.json"), + br#"{"lockfileVersion":3,"x":1}"#, + ) + .unwrap(); + let after_lock = module_cache_config_salt(&root, &salt_settings(&root), Some(&cfg)); + assert_ne!(after_cfg, after_lock, "lockfile change must invalidate"); + let mut settings = salt_settings(&root); + settings.alias = vec![("@".into(), root.join("lib").to_string_lossy().into_owned())]; + assert_ne!( + after_lock, + module_cache_config_salt(&root, &settings, Some(&cfg)), + "alias retarget must invalidate" + ); +} + +#[test] +fn monorepo_alias_targets_do_not_poison_the_salt() { + fn mono_fixture(label: &str) -> (PathBuf, PathBuf) { + let mono = + std::env::temp_dir().join(format!("oj-salt-mono-{}-{label}", std::process::id())); + let _ = std::fs::remove_dir_all(&mono); + let app = mono.join("app"); + std::fs::create_dir_all(mono.join("node_modules")).unwrap(); + std::fs::create_dir_all(&app).unwrap(); + std::fs::write(app.join("package.json"), br#"{"name":"app"}"#).unwrap(); + std::fs::write(app.join("package-lock.json"), br#"{"lockfileVersion":3}"#).unwrap(); + (mono, app) + } + let (mono_a, app_a) = mono_fixture("wt-a"); + let (mono_b, app_b) = mono_fixture("wt-b"); + let settings = |mono: &Path| oj_resolver::ResolveSettings { + conditions: vec!["import".into()], + alias: vec![( + "^@x/common$".into(), + mono.join("packages/common/src/index.ts") + .to_string_lossy() + .into_owned(), + )], + dedupe: vec![], + extensions: None, + main_fields: None, + preserve_symlinks: false, + server: false, + tsconfig_paths: oj_resolver::TsconfigPaths::Neither, + tsconfig_file: None, + }; + assert_eq!( + module_cache_config_salt(&app_a, &settings(&mono_a), None), + module_cache_config_salt(&app_b, &settings(&mono_b), None), + "out-of-root alias targets must hash workspace-relative" + ); +} + +#[test] +fn fs_urls_key_workspace_relative_without_touching_other_urls() { + let ws = Path::new("/work/wt-a/mono"); + assert_eq!( + rewrite::key_url(ws, "/@fs//work/wt-a/mono/node_modules/react/index.js?v=abc"), + "/@fs/@mono/node_modules/react/index.js?v=abc" + ); + assert_eq!( + rewrite::key_url(ws, "/@fs//work/wt-a/mono/node_modules/x.js"), + rewrite::key_url( + Path::new("/elsewhere/b/mono"), + "/@fs//elsewhere/b/mono/node_modules/x.js" + ), + ); + assert_eq!( + rewrite::key_url(ws, "/@fs//opt/external/x.js"), + "/@fs//opt/external/x.js" + ); + assert_eq!(rewrite::key_url(ws, "/src/App.tsx"), "/src/App.tsx"); +} + +#[test] +fn fs_url_paths_expand_mono_against_the_serving_workspace() { + let ws = Path::new("/elsewhere/b/mono"); + assert_eq!( + rewrite::fs_url_to_path(ws, "/@mono/node_modules/react/index.js"), + Path::new("/elsewhere/b/mono/node_modules/react/index.js") + ); + assert_eq!( + rewrite::fs_url_to_path(ws, "/opt/external/x.js"), + Path::new("/opt/external/x.js") + ); +} + +#[test] +fn importer_params_are_worktree_independent_and_decode_against_the_serving_root() { + let a = Path::new("/work/wt-a"); + let b = Path::new("/work/wt-b"); + let enc_a = rewrite::encode_importer(a, "/work/wt-a/src/App.tsx"); + let enc_b = rewrite::encode_importer(b, "/work/wt-b/src/App.tsx"); + assert_eq!(enc_a, enc_b); + assert_eq!( + rewrite::decode_importer(b, &decode_at_id(&enc_a)), + "/work/wt-b/src/App.tsx" + ); + let virt = rewrite::encode_importer(a, "virtual:oj-routes"); + assert_eq!( + rewrite::decode_importer(b, &decode_at_id(&virt)), + "virtual:oj-routes" + ); + let legacy = hex_encode("/work/wt-a/src/App.tsx"); + assert_eq!( + rewrite::decode_importer(b, &decode_at_id(&legacy)), + "/work/wt-a/src/App.tsx" + ); +} + +#[test] +fn mono_importers_encode_workspace_relative_and_decode_against_the_serving_workspace() { + let base = std::env::temp_dir().join(format!("oj-mono-imp-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let mk = |wt: &str| { + let mono = base.join(wt).join("mono"); + std::fs::create_dir_all(mono.join("node_modules")).unwrap(); + std::fs::create_dir_all(mono.join("app")).unwrap(); + std::fs::create_dir_all(mono.join("packages/ui")).unwrap(); + std::fs::write(mono.join("packages/ui/Button.tsx"), b"export {}").unwrap(); + mono + }; + let mono_a = mk("wt-a"); + let mono_b = mk("wt-b"); + let enc_a = rewrite::encode_importer( + &mono_a.join("app"), + &mono_a.join("packages/ui/Button.tsx").to_string_lossy(), + ); + let enc_b = rewrite::encode_importer( + &mono_b.join("app"), + &mono_b.join("packages/ui/Button.tsx").to_string_lossy(), + ); + assert_eq!( + enc_a, enc_b, + "monorepo importers must encode worktree-independent" + ); + let decoded = rewrite::decode_importer(&mono_b.join("app"), &decode_at_id(&enc_a)); + let expected = std::fs::canonicalize(&mono_b) + .unwrap() + .join("packages/ui/Button.tsx"); + assert_eq!(PathBuf::from(decoded), expected); +} + +// A trace row must name what the glob expansion read: an aliased pattern +// resolves through resolve.alias like the compile's, or the row lists +// nothing and a file added under the alias never invalidates the entry. +#[test] +fn glob_trace_rows_resolve_aliased_patterns() { + let root = Path::new("/work/app"); + let alias = [("@".to_string(), "/work/app/src".to_string())]; + let source = "const pages = import.meta.glob(\"@/pages/*.tsx\");\n"; + let patterns = crate::module_pipeline::glob_trace_patterns( + source, + &root.join("src/main.tsx"), + root, + &alias, + ); + assert_eq!(patterns, ["/work/app/src/pages/*.tsx"]); +} + +// An earlier transform's map (StyleX's, a plugin's) names the module by its +// served path once it joins the chain, as the compile names it, so a shared +// cache entry's sourcemap carries no checkout's path. +#[test] +fn chained_maps_name_in_root_sources_by_served_path() { + let root = Path::new("/work/wt-a/app"); + let map = r#"{"version":3,"sources":["/work/wt-a/app/src/main.ts","/opt/lib/x.js"],"sourcesContent":["a","b"],"mappings":""}"#; + let out: serde_json::Value = serde_json::from_str(&crate::module_pipeline::served_map_sources( + root, + map.to_string(), + )) + .unwrap(); + assert_eq!( + out["sources"], + serde_json::json!(["/src/main.ts", "/opt/lib/x.js"]) + ); + assert_eq!(out["sourcesContent"], serde_json::json!(["a", "b"])); + let not_a_map = "not json".to_string(); + assert_eq!( + crate::module_pipeline::served_map_sources(root, not_a_map.clone()), + not_a_map + ); +} + +#[test] +fn imports_a_plugin_virtual_flags_only_missing_fs_paths() { + // A cached module is re-transformed on a warm start only if it imports a + // plugin-served virtual: a filesystem-path import with no file on disk. + // Real files (source, svgr's .svg) and oj-internal /@ routes keep the + // fast persistent cache. + let root = std::env::temp_dir().join(format!("oj-ipv-test-{}", std::process::id())); + let src = root.join("src"); + std::fs::create_dir_all(&src).unwrap(); + std::fs::write(src.join("real.ts"), "export {}\n").unwrap(); + let dc = Mutex::new(DirCache::new()); + let r = root.as_path(); + assert!(!imports_a_plugin_virtual( + &["/src/real.ts".to_string()], + r, + &dc + )); + assert!(!imports_a_plugin_virtual( + &[ + "/@id/abc".to_string(), + "/@virtual/x".to_string(), + "https://cdn/x.js".to_string() + ], + r, + &dc, + )); + assert!(imports_a_plugin_virtual( + &[ + "/src/real.ts".to_string(), + "/Users/nope/x.wyw-in-js.css".to_string() + ], + r, + &dc, + )); + assert!(imports_a_plugin_virtual( + &["/src/gone.css".to_string()], + r, + &dc + )); + assert!(!imports_a_plugin_virtual( + &["/src/real.ts?import".to_string()], + r, + &dc + )); + std::fs::remove_dir_all(&root).ok(); +} + +// A map's source that is no path under the root (a `file://` URL, a relative +// name, a virtual id) is left as written: only an absolute in-root path is +// renamed to its served form. +#[test] +fn chained_maps_leave_sources_that_are_no_root_path_alone() { + let root = Path::new("/work/wt-a/app"); + let map = r#"{"version":3,"sources":["file:///work/wt-a/app/src/x.ts","src/rel.ts","\u0000virtual:x","/work/wt-a/app/src/y.ts"],"mappings":""}"#; + let out: serde_json::Value = serde_json::from_str(&crate::module_pipeline::served_map_sources( + root, + map.to_string(), + )) + .unwrap(); + assert_eq!( + out["sources"], + serde_json::json!([ + "file:///work/wt-a/app/src/x.ts", + "src/rel.ts", + "\u{0}virtual:x", + "/src/y.ts" + ]) + ); + // A map with no sources array, and one that is not JSON, pass through. + for map in [r#"{"version":3}"#, "nope"] { + assert_eq!( + crate::module_pipeline::served_map_sources(root, map.to_string()), + map + ); + } +} + +// Vite's TypeScript template keeps `paths` in tsconfig.app.json behind a +// `references` entry, and a config may name its tsconfig: every tsconfig at +// the root and the named one are the salt's, by content. +#[test] +fn module_cache_salt_covers_every_tsconfig_at_the_root_and_the_named_one() { + let root = salt_fixture("tsconfigs"); + let cfg = root.join("vite.config.ts"); + let settings = salt_settings(&root); + let base = module_cache_config_salt(&root, &settings, Some(&cfg)); + std::fs::write( + root.join("tsconfig.app.json"), + br#"{"compilerOptions":{"paths":{"@/*":["./src/*"]}}}"#, + ) + .unwrap(); + let with_app = module_cache_config_salt(&root, &settings, Some(&cfg)); + assert_ne!(base, with_app, "a new tsconfig.app.json re-salts"); + std::fs::write( + root.join("tsconfig.app.json"), + br#"{"compilerOptions":{"paths":{"@/*":["./lib/*"]}}}"#, + ) + .unwrap(); + let retargeted = module_cache_config_salt(&root, &settings, Some(&cfg)); + assert_ne!(with_app, retargeted, "retargeted paths re-salt"); + let named = root.join("config/tsconfig.custom.json"); + std::fs::create_dir_all(named.parent().unwrap()).unwrap(); + std::fs::write(&named, br#"{"compilerOptions":{}}"#).unwrap(); + let mut by_name = salt_settings(&root); + by_name.tsconfig_file = Some(named.clone()); + let with_named = module_cache_config_salt(&root, &by_name, Some(&cfg)); + std::fs::write(&named, br#"{"compilerOptions":{"paths":{}}}"#).unwrap(); + assert_ne!( + with_named, + module_cache_config_salt(&root, &by_name, Some(&cfg)), + "the named tsconfig is hashed by content, not by path" + ); + // The salt itself names no checkout: two roots with the same files agree. + let twin = salt_fixture("tsconfigs-twin"); + std::fs::write( + twin.join("tsconfig.app.json"), + br#"{"compilerOptions":{"paths":{"@/*":["./lib/*"]}}}"#, + ) + .unwrap(); + assert_eq!( + retargeted, + module_cache_config_salt( + &twin, + &salt_settings(&twin), + Some(&twin.join("vite.config.ts")) + ) + ); +} + +// Every resolver setting is a field of the salt of its own: two lists whose +// entries concatenate alike (`extensions: [".x"]` against `mainFields: +// [".x"]`, `["ab","c"]` against `["a","bc"]`) salt apart, and each setting +// moves the salt by itself. +#[test] +fn module_cache_salt_keeps_every_resolver_setting_apart() { + let root = salt_fixture("resolver-settings"); + let salt = + |settings: &oj_resolver::ResolveSettings| module_cache_config_salt(&root, settings, None); + let mut salts = vec![salt(&salt_settings(&root))]; + let mut variant = |edit: &dyn Fn(&mut oj_resolver::ResolveSettings), what: &str| { + let mut settings = salt_settings(&root); + edit(&mut settings); + let salted = salt(&settings); + assert!(!salts.contains(&salted), "{what}: the salt did not move"); + salts.push(salted); + }; + variant( + &|s| s.conditions = vec!["import".into(), "browser".into()], + "conditions", + ); + variant(&|s| s.dedupe = vec!["react".into()], "dedupe"); + variant(&|s| s.extensions = Some(vec![".x".into()]), "extensions"); + variant(&|s| s.main_fields = Some(vec![".x".into()]), "mainFields"); + variant( + &|s| s.extensions = Some(vec!["ab".into(), "c".into()]), + "extensions ab|c", + ); + variant( + &|s| s.extensions = Some(vec!["a".into(), "bc".into()]), + "extensions a|bc", + ); + variant( + &|s| { + s.conditions = vec![]; + s.dedupe = vec!["import".into()]; + }, + "a condition moved to dedupe", + ); + variant(&|s| s.preserve_symlinks = true, "preserveSymlinks"); + variant( + &|s| s.tsconfig_paths = oj_resolver::TsconfigPaths::Off, + "tsconfigPaths", + ); + variant(&|s| s.alias = vec![], "alias removed"); + variant( + &|s| s.alias = vec![("@".into(), root.join("lib").to_string_lossy().into_owned())], + "alias retargeted", + ); + variant( + &|s| s.tsconfig_file = Some(root.join("tsconfig.json")), + "a named tsconfig", + ); + assert_eq!( + salt(&salt_settings(&root)), + salts[0], + "the salt is a function of its inputs alone" + ); +} + +// The tsconfig files at the root salt by name and content in no particular +// order: two roots that gained the same files in another order agree, a +// file renamed with its content kept re-salts (the resolver follows +// `references` by name), and one in a subdirectory is not the root's unless +// the config names it. +#[test] +fn module_cache_salt_names_each_tsconfig_whatever_the_listing_order() { + let a = salt_fixture("tsconfig-order-a"); + let b = salt_fixture("tsconfig-order-b"); + let app = br#"{"compilerOptions":{"paths":{"@/*":["./src/*"]}}}"#; + let node = br#"{"compilerOptions":{"composite":true}}"#; + std::fs::write(a.join("tsconfig.app.json"), app).unwrap(); + std::fs::write(a.join("tsconfig.node.json"), node).unwrap(); + std::fs::write(b.join("tsconfig.node.json"), node).unwrap(); + std::fs::write(b.join("tsconfig.app.json"), app).unwrap(); + let salt = |root: &Path| module_cache_config_salt(root, &salt_settings(root), None); + assert_eq!(salt(&a), salt(&b)); + std::fs::rename(b.join("tsconfig.app.json"), b.join("tsconfig.web.json")).unwrap(); + assert_ne!(salt(&a), salt(&b), "the file's name is an input"); + std::fs::rename(b.join("tsconfig.web.json"), b.join("tsconfig.app.json")).unwrap(); + assert_eq!(salt(&a), salt(&b)); + std::fs::create_dir_all(b.join("packages/x")).unwrap(); + std::fs::write(b.join("packages/x/tsconfig.json"), app).unwrap(); + assert_eq!(salt(&a), salt(&b), "a nested tsconfig is not the root's"); + let mut named = salt_settings(&b); + named.tsconfig_file = Some(b.join("packages/x/tsconfig.json")); + assert_ne!(salt(&a), module_cache_config_salt(&b, &named, None)); +} + +// The plugin chain is in the salt whichever file carries it: an +// `oj.plugins.mjs` (run in a vite config's place) by content, next to the +// vite config and the files it imports; so are the PostCSS config a plain +// stylesheet compiles through and the browserslist file its targets come +// from. All by content, and the same in another checkout. +#[test] +fn module_cache_salt_covers_the_plugin_file_the_postcss_config_and_browserslist() { + let root = salt_fixture("plugin-postcss"); + let salt = |root: &Path| { + module_cache_config_salt( + root, + &salt_settings(root), + Some(&root.join("vite.config.ts")), + ) + }; + let mut last = salt(&root); + let mut moved_by = |what: &str, file: &str, bytes: &[u8]| { + let path = root.join(file); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, bytes).unwrap(); + let now = salt(&root); + assert_ne!(last, now, "{what} left the salt alone"); + last = now; + }; + moved_by( + "a new oj.plugins.mjs", + "oj.plugins.mjs", + b"export default [];", + ); + moved_by( + "an oj.plugins.mjs edit", + "oj.plugins.mjs", + b"export default [{ name: \"x\" }];", + ); + moved_by( + "a new postcss config", + "postcss.config.js", + b"module.exports = { plugins: [] };", + ); + moved_by( + "a postcss config edit", + "postcss.config.js", + b"module.exports = { plugins: [require('postcss-nesting')] };", + ); + moved_by("a new .browserslistrc", ".browserslistrc", b"defaults\n"); + moved_by( + "a .browserslistrc edit", + ".browserslistrc", + b"last 1 chrome version\n", + ); + // The config's imports, recorded per config file. + let dep = root.join("plugins/local.ts"); + std::fs::create_dir_all(dep.parent().unwrap()).unwrap(); + std::fs::write(&dep, b"export const v = 1;").unwrap(); + plugins::record_config_dependencies(&root.join("vite.config.ts"), vec![dep.clone()]); + moved_by( + "a config import edit", + "plugins/local.ts", + b"export const v = 2;", + ); + // The same files in another checkout salt the same. + let twin = salt_fixture("plugin-postcss-twin"); + for name in [ + "oj.plugins.mjs", + "postcss.config.js", + ".browserslistrc", + "plugins/local.ts", + ] { + let to = twin.join(name); + std::fs::create_dir_all(to.parent().unwrap()).unwrap(); + std::fs::copy(root.join(name), to).unwrap(); + } + plugins::record_config_dependencies( + &twin.join("vite.config.ts"), + vec![twin.join("plugins/local.ts")], + ); + assert_eq!(salt(&root), salt(&twin)); +} + +// An entry names a checkout only where its code or map holds the directory +// as a path: a root `/work/app` is not in `"/work/app-settings"`, and a +// directory with no name of its own (`/`, the workspace of an image with a +// top-level `node_modules`) names nothing, or every entry would stay local. +#[test] +fn names_checkout_matches_a_directory_as_a_path_and_never_the_root_dir() { + let module = |code: &str, map: Option<&str>| oj_cache::CachedModule { + code: code.into(), + map_json: map.map(str::to_string), + ..Default::default() + }; + let app = Path::new("/work/app"); + assert!(names_checkout( + &module("import x from \"/work/app/src/x.js\";", None), + &[app] + )); + assert!(names_checkout( + &module("export {};", Some("{\"sources\":[\"/work/app/src/x.ts\"]}")), + &[app] + )); + assert!(!names_checkout( + &module("const route = \"/work/app-settings\";", None), + &[app] + )); + assert!(!names_checkout( + &module("const route = \"/work/application/x\";", None), + &[app] + )); + assert!(!names_checkout( + &module("const home = \"/\"; const abs = \"/etc/hosts\";", None), + &[Path::new("/")] + )); + assert!(names_checkout( + &module("\"/work/app/\"", None), + &[Path::new("/"), app] + )); + // A root spelled with a trailing separator is the same directory. + assert!(names_checkout( + &module("\"/work/app/x\"", None), + &[Path::new("/work/app/")] + )); +} diff --git a/crates/oj_server/src/watch.rs b/crates/oj_server/src/watch.rs index 61fb50113..dbe890ddc 100644 --- a/crates/oj_server/src/watch.rs +++ b/crates/oj_server/src/watch.rs @@ -38,8 +38,7 @@ pub(crate) fn is_watch_ignored(patterns: &[glob::Pattern], root: &Path, path: &P /// A file the config imported (Vite's `configFileDependencies`): its change /// restarts the server too; node_modules packages are left out, as in Vite. -pub(crate) fn is_config_dependency(path: &Path) -> bool { - let deps = plugins::config_dependencies(); +pub(crate) fn is_config_dependency(deps: &[PathBuf], path: &Path) -> bool { if deps.is_empty() { return false; } @@ -1496,8 +1495,12 @@ fn handle_batch( // Vite does, naming the file relative to the launch dir as Vite's // " changed, restarting server" does. Vite restarts from // handleHMRUpdate, so not with `server.hmr: false`. - let restarts = - |p: &PathBuf| is_restart_trigger(&state.restart_files, p) || is_config_dependency(p); + let config_deps = plugins::vite_config_file(&state.root, state.config_file.as_deref()) + .map(|config| plugins::config_dependencies_of(&config)) + .unwrap_or_default(); + let restarts = |p: &PathBuf| { + is_restart_trigger(&state.restart_files, p) || is_config_dependency(&config_deps, p) + }; if let Some(file) = paths .iter() .filter(|_| state.hmr_enabled) diff --git a/crates/oj_server/tests/dev/determinism.rs b/crates/oj_server/tests/dev/determinism.rs new file mode 100644 index 000000000..d0cc513e5 --- /dev/null +++ b/crates/oj_server/tests/dev/determinism.rs @@ -0,0 +1,536 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2026 Raphael Amorim + +//! What the store may share is what compiles to the same bytes in every +//! checkout: a matrix of module kinds (TypeScript under tsconfig semantics, +//! JSX with a pre-bundled runtime, a CSS module, JSON, assets by import and +//! by `import.meta.url`, `?raw`/`?url`, inlined env, a hot module, a dynamic +//! import, a glob, a worker) served in a second checkout from the first's +//! entries, byte for byte, debug info included; the same bytes a server +//! without the store compiles; and the one kind that legitimately differs +//! per checkout (an import from outside the root and the workspace, served +//! under `/@fs/`), which never leaves the checkout's own cache. + +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use base64::Engine as _; + +use crate::App; + +/// A file of every kind the dev pipeline compiles, each naming `marker` in +/// its output (in its source, or in its file name where the output carries +/// only that), so the store entries under test are this app's alone. +fn matrix_files(marker: &str) -> Vec<(String, String)> { + let m = marker; + let mut files = vec![ + ( + "package.json".into(), + r#"{"name":"matrix","version":"1.0.0"}"#.into(), + ), + ( + "package-lock.json".into(), + r#"{"lockfileVersion":3}"#.into(), + ), + ( + "tsconfig.json".into(), + r#"{"compilerOptions":{"useDefineForClassFields":true,"verbatimModuleSyntax":true,"jsx":"react-jsx"}}"#.into(), + ), + (".env".into(), format!("VITE_MARKER={m}:env\n")), + ( + "index.html".into(), + "".into(), + ), + ( + "src/main.ts".into(), + format!( + "import {{ Plain }} from \"./plain\";\nimport {{ Comp }} from \"./Comp\";\nimport {{ cls }} from \"./styled\";\nimport data from \"./data.json\";\nimport {{ urls }} from \"./assets\";\nimport {{ env }} from \"./env\";\nimport {{ hot }} from \"./hot\";\nimport {{ pages, load }} from \"./dyn\";\nimport {{ worker }} from \"./worker\";\nexport const main = [Plain, Comp, cls, data, urls, env, hot, pages, load, worker, \"{m}:main\"];\n" + ), + ), + ( + "src/plain.ts".into(), + format!( + "import type {{ Kind }} from \"./kinds\";\nexport enum Color {{ Red = \"red\", Blue = \"blue\" }}\nexport class Plain {{\n kind: Kind = \"plain\";\n declare only: string;\n static tag = \"{m}:plain\";\n #secret = 1;\n get secret() {{ return this.#secret; }}\n}}\nexport const plain = new Plain() satisfies Plain;\n" + ), + ), + ( + "src/kinds.ts".into(), + format!("export type Kind = \"plain\" | \"{m}:kinds\";\nexport const kinds = \"{m}:kinds\";\n"), + ), + ( + "src/Comp.tsx".into(), + format!( + "export function Comp(props: {{ n: number }}) {{\n return
{{props.n}}x
;\n}}\n" + ), + ), + ( + "src/styled.ts".into(), + format!("import s from \"./styles.module.css\";\nexport const cls = s.button + \"{m}:styled\";\n"), + ), + ( + "src/styles.module.css".into(), + format!(".button {{ color: red; content: \"{m}:css\"; }}\n.button:hover {{ color: blue; }}\n"), + ), + ("src/data.json".into(), format!("{{\"marker\":\"{m}:json\",\"n\":[1,2,3]}}\n")), + ( + "src/assets.ts".into(), + format!( + "import logo from \"./logo-{m}.svg\";\nimport note from \"./note-{m}.txt?raw\";\nimport noteUrl from \"./note-{m}.txt?url\";\nexport const urls = [logo, note, noteUrl, new URL(\"./logo-{m}.svg\", import.meta.url).href];\n" + ), + ), + ( + format!("src/logo-{m}.svg"), + format!("\n"), + ), + (format!("src/note-{m}.txt"), format!("note {m}:raw\n")), + ( + "src/env.ts".into(), + "export const env = [import.meta.env.VITE_MARKER, import.meta.env.MODE, import.meta.env.DEV];\n".into(), + ), + ( + "src/hot.ts".into(), + format!("export const hot = \"{m}:hot\";\nif (import.meta.hot) {{\n import.meta.hot.accept();\n}}\n"), + ), + ( + "src/dyn.ts".into(), + format!( + "export const pages = import.meta.glob(\"./pages-{m}/*.ts\");\nexport const load = () => import(\"./plain\");\n" + ), + ), + (format!("src/pages-{m}/a.ts"), format!("export const a = \"{m}:page-a\";\n")), + (format!("src/pages-{m}/b.ts"), format!("export const b = \"{m}:page-b\";\n")), + ( + "src/worker.ts".into(), + format!( + "export const worker = () => new Worker(new URL(\"./w-{m}.ts\", import.meta.url), {{ type: \"module\" }});\n" + ), + ), + (format!("src/w-{m}.ts"), format!("self.postMessage(\"{m}:worker\");\n")), + ]; + // The automatic JSX runtime, pre-bundled like any dependency: a stub is + // enough, and identical in every checkout, as an install would be. + files.extend([ + ( + "node_modules/react/package.json".into(), + r#"{"name":"react","version":"19.0.0","type":"module","exports":{".":"./index.js","./jsx-runtime":"./jsx-runtime.js","./jsx-dev-runtime":"./jsx-dev-runtime.js"}}"#.into(), + ), + ("node_modules/react/index.js".into(), "export default {};\n".into()), + ( + "node_modules/react/jsx-runtime.js".into(), + "export const Fragment = Symbol(\"f\");\nexport const jsx = (t, p) => ({ t, p });\nexport const jsxs = jsx;\n".into(), + ), + ( + "node_modules/react/jsx-dev-runtime.js".into(), + "export const Fragment = Symbol(\"f\");\nexport const jsxDEV = (t, p) => ({ t, p });\n".into(), + ), + ]); + files +} + +fn matrix_app(marker: &str) -> App { + let files = matrix_files(marker); + let refs: Vec<(&str, &str)> = files + .iter() + .map(|(p, c)| (p.as_str(), c.as_str())) + .collect(); + App::new(&refs) +} + +/// The served urls of the matrix, the dependency's runtime left to the +/// modules that import it (its url is content-derived, see +/// `dep_urls_are_identical` below). +fn matrix_urls(marker: &str) -> Vec { + let m = marker; + [ + "/src/main.ts".to_string(), + "/src/plain.ts".into(), + "/src/kinds.ts".into(), + "/src/Comp.tsx".into(), + "/src/styled.ts".into(), + "/src/styles.module.css".into(), + "/src/data.json".into(), + "/src/assets.ts".into(), + format!("/src/note-{m}.txt?raw"), + format!("/src/note-{m}.txt?url"), + format!("/src/logo-{m}.svg?import"), + "/src/env.ts".into(), + "/src/hot.ts".into(), + "/src/dyn.ts".into(), + format!("/src/pages-{m}/a.ts"), + "/src/worker.ts".into(), + format!("/src/w-{m}.ts?worker_file&type=module"), + ] + .to_vec() +} + +fn dev(app: &App, store: bool) -> oj_server::DevServer { + oj_server::DevServer { store, ..app.dev() } +} + +/// Waits for the optimizer to commit its bundle (dep urls are provisional +/// until then), so every fetch after it sees the final urls. +async fn committed(app: &App) { + let deadline = std::time::Instant::now() + Duration::from_secs(30); + let deps = oj_cache::cache_root(&app.root).join("deps"); + loop { + let manifest = std::fs::read_dir(&deps) + .into_iter() + .flatten() + .flatten() + .any(|e| e.file_name().to_string_lossy().ends_with(".json")); + if manifest { + return; + } + assert!( + std::time::Instant::now() < deadline, + "the optimizer never committed" + ); + tokio::time::sleep(Duration::from_millis(100)).await; + } +} + +/// Every matrix url's body, fetched once the optimizer committed, and again +/// until two fetches agree (a commit mid-way re-versions the dep urls). +async fn snapshot(server: &crate::Server, app: &App, marker: &str) -> Vec<(String, String)> { + let urls = matrix_urls(marker); + // The entry first: it discovers the runtime the tsx module imports. + server.text("/src/main.ts").await; + server.text("/src/Comp.tsx").await; + committed(app).await; + let fetch = || async { + let mut out = Vec::new(); + for url in &urls { + out.push((url.clone(), server.text(url).await)); + } + out + }; + let deadline = std::time::Instant::now() + Duration::from_secs(30); + let mut last = fetch().await; + loop { + let again = fetch().await; + if again == last { + return again; + } + assert!( + std::time::Instant::now() < deadline, + "the bytes never settled" + ); + last = again; + } +} + +/// The inline sourcemap a served module ends with, when it has one. +fn inline_map(body: &str) -> Option { + let (_, b64) = body.rsplit_once("//# sourceMappingURL=data:application/json;base64,")?; + let bytes = base64::engine::general_purpose::STANDARD + .decode(b64.trim()) + .ok()?; + serde_json::from_slice(&bytes).ok() +} + +/// Fails when `body` (or its decoded sourcemap) names any of `roots`. +fn assert_path_free(url: &str, body: &str, roots: &[&Path]) { + for root in roots { + let root = root.to_string_lossy(); + assert!( + !body.contains(&*root), + "{url} names the checkout {root}:\n{body}" + ); + } + // Every source of the map is named by its served path. + if let Some(map) = inline_map(body) { + let sources = map["sources"].as_array().cloned().unwrap_or_default(); + assert!(!sources.is_empty(), "{url}: a map with no sources"); + for source in sources { + let source = source.as_str().unwrap_or(""); + assert!( + source.starts_with("/src/"), + "{url}: sourcemap source {source:?} is not a served path" + ); + } + } +} + +/// The shared store's entries whose text contains `needle`. +fn shared_entries(needle: &str) -> Vec { + fn walk(dir: &Path, needle: &str, out: &mut Vec) { + for e in std::fs::read_dir(dir).into_iter().flatten().flatten() { + let path = e.path(); + if path.is_dir() { + walk(&path, needle, out); + } else if path.extension().is_some_and(|x| x == "json") + && std::fs::read_to_string(&path).is_ok_and(|s| s.contains(needle)) + { + out.push(path); + } + } + } + let mut out = Vec::new(); + walk(&crate::store_modules_dir(), needle, &mut out); + out +} + +/// The count of shared entries naming `needle` once it stops growing (cache +/// writes are asynchronous). +async fn settled_entries(needle: &str) -> usize { + let mut last = shared_entries(needle).len(); + let mut stable_since = std::time::Instant::now(); + let deadline = std::time::Instant::now() + Duration::from_secs(15); + loop { + tokio::time::sleep(Duration::from_millis(100)).await; + let now = shared_entries(needle).len(); + if now != last { + last = now; + stable_since = std::time::Instant::now(); + } else if stable_since.elapsed() > Duration::from_millis(600) { + return last; + } + assert!( + std::time::Instant::now() < deadline, + "entries never settled" + ); + } +} + +// Every module kind of the matrix, compiled in checkout A, serves in checkout +// B with the same bytes (sourcemap included), from the store: B writes no +// entry of its own, and every entry A wrote is admissible to the shared +// store. Each kind's output names the checkout by its served path only. +#[tokio::test(flavor = "multi_thread")] +async fn every_module_kind_serves_the_same_bytes_in_a_second_checkout() { + let marker = "matrix-twin"; + let (a, b) = (matrix_app(marker), matrix_app(marker)); + let from_a = { + let server = crate::serve(dev(&a, true)).await; + snapshot(&server, &a, marker).await + }; + let written_by_a = settled_entries(marker).await; + assert!( + written_by_a >= 12, + "{written_by_a} entries from {} urls", + from_a.len() + ); + for entry in shared_entries(marker) { + let module: oj_cache::CachedModule = + serde_json::from_slice(&std::fs::read(&entry).unwrap()).unwrap(); + assert!( + module.is_relocatable(), + "{}: not admissible, yet shared", + entry.display() + ); + } + let from_b = { + let server = crate::serve(dev(&b, true)).await; + snapshot(&server, &b, marker).await + }; + let roots = [a.root.as_path(), b.root.as_path()]; + for ((url, body_a), (_, body_b)) in from_a.iter().zip(&from_b) { + assert_path_free(url, body_a, &roots); + assert_eq!(body_a, body_b, "{url} differs between the checkouts"); + assert!( + body_a.contains(marker), + "{url} does not name the marker:\n{body_a}" + ); + } + // The kinds whose output embeds something beyond their own source: the + // dependency url, the class map, the env, the glob listing, the worker + // url, the asset urls. + let body = |url: &str| { + from_a + .iter() + .find(|(u, _)| u == url) + .map(|(_, b)| b.as_str()) + .unwrap_or_else(|| panic!("{url} not in the snapshot")) + }; + assert!( + body("/src/Comp.tsx").contains("/@oj-deps/react_jsx-dev-runtime.mjs?v="), + "{}", + body("/src/Comp.tsx") + ); + assert!( + body("/src/styles.module.css").contains("_button_"), + "{}", + body("/src/styles.module.css") + ); + assert!( + body("/src/env.ts").contains(&format!("\"{marker}:env\"")), + "{}", + body("/src/env.ts") + ); + assert!( + body("/src/dyn.ts").contains(&format!("./pages-{marker}/a.ts")), + "{}", + body("/src/dyn.ts") + ); + assert!( + body("/src/worker.ts").contains(&format!("/src/w-{marker}.ts?worker")), + "{}", + body("/src/worker.ts") + ); + assert!( + body("/src/assets.ts").contains(&format!("/src/logo-{marker}.svg")), + "{}", + body("/src/assets.ts") + ); + assert!( + body("/src/plain.ts").contains("#secret") || body("/src/plain.ts").contains("WeakMap"), + "{}", + body("/src/plain.ts") + ); + // B served the store's entries: it wrote none of its own. + assert_eq!( + settled_entries(marker).await, + written_by_a, + "checkout B wrote entries of its own" + ); +} + +// A server without the store compiles the same bytes the store serves: the +// persistent path changes no output, so a hit and a fresh compile agree. +#[tokio::test(flavor = "multi_thread")] +async fn the_store_changes_no_bytes() { + let marker = "matrix-plain"; + let (with_store, without) = (matrix_app(marker), matrix_app(marker)); + let stored = { + let server = crate::serve(dev(&with_store, true)).await; + snapshot(&server, &with_store, marker).await + }; + settled_entries(marker).await; + // A second session of the stored checkout: hits throughout. + let hits = { + let server = crate::serve(dev(&with_store, true)).await; + snapshot(&server, &with_store, marker).await + }; + let fresh = { + let server = crate::serve(dev(&without, false)).await; + snapshot(&server, &without, marker).await + }; + for (((url, a), (_, b)), (_, c)) in stored.iter().zip(&hits).zip(&fresh) { + assert_eq!(a, b, "{url}: the hit differs from the compile it stored"); + assert_eq!(a, c, "{url}: the store's bytes differ from a plain compile"); + } +} + +// What a module inlines from outside its source is in its key: an `.env` +// edit between sessions serves the new value, a mode of its own its file's, +// and the default mode's entry is still there when it comes back. +#[tokio::test(flavor = "multi_thread")] +async fn an_env_edit_between_sessions_serves_the_new_value_and_a_mode_its_own() { + let marker = "matrix-env"; + let app = matrix_app(marker); + app.write(&[(".env.staging", &format!("VITE_MARKER={marker}:staging\n"))]); + let env_of = |mode: Option<&str>| { + let dev = oj_server::DevServer { + mode: mode.map(str::to_string), + ..dev(&app, true) + }; + async move { + let server = crate::serve(dev).await; + server.text("/src/env.ts").await + } + }; + let first = env_of(None).await; + assert!(first.contains(&format!("\"{marker}:env\"")), "{first}"); + assert!(first.contains("\"development\""), "{first}"); + settled_entries(marker).await; + assert_eq!(env_of(None).await, first, "an unchanged env hits"); + app.write(&[(".env", &format!("VITE_MARKER={marker}:edited\n"))]); + let edited = env_of(None).await; + assert!( + edited.contains(&format!("\"{marker}:edited\"")), + "stale env served:\n{edited}" + ); + let staging = env_of(Some("staging")).await; + assert!( + staging.contains(&format!("\"{marker}:staging\"")), + "{staging}" + ); + assert!(staging.contains("\"staging\""), "{staging}"); + assert_eq!( + env_of(None).await, + edited, + "the default mode's entry is its own" + ); + // Each value compiled to an entry of its own: none replaced another. + settled_entries(marker).await; + for value in ["env", "edited", "staging"] { + assert_eq!( + shared_entries(&format!("\\\"{marker}:{value}\\\"")).len(), + 1, + "the {value} value's entry" + ); + } +} + +/// The checkout's own cache (what `put_local` writes to). +fn local_entries(app: &App, needle: &str) -> bool { + crate::warm_transform_virtual::cached_module_contains(&oj_cache::cache_root(&app.root), needle) +} + +// An import from outside the root and the workspace (a library beside the +// checkouts) is served under `/@fs/`: the same bytes in two checkouts +// that see the same file, yet pinned to this machine, so the importer never +// leaves the checkout's own cache. Each checkout compiles its own. +#[tokio::test(flavor = "multi_thread")] +async fn a_module_pinned_to_its_checkout_is_served_right_and_never_shared() { + let marker = "matrix-pinned"; + let app_of = || { + App::new(&[ + ("package.json", r#"{"name":"pinned","version":"1.0.0"}"#), + ( + "vite.config.js", + "export default { server: { fs: { allow: [\"..\"] } } };\n", + ), + ( + "index.html", + "", + ), + ( + "src/main.ts", + &format!("import {{ ext }} from \"../../ext-{marker}/x\";\nexport const main = ext + \"-{marker}:main\";\n"), + ), + ]) + }; + let (a, b) = (app_of(), app_of()); + // Beside both roots, under no workspace. + let ext = a.root.parent().unwrap().join(format!("ext-{marker}")); + std::fs::create_dir_all(&ext).unwrap(); + std::fs::write( + ext.join("x.ts"), + format!("export const ext: string = \"{marker}:ext\";\n"), + ) + .unwrap(); + let serve = |app: &App| { + let dev = dev(app, true); + async move { + let server = crate::serve(dev).await; + let main = server.text("/src/main.ts").await; + let import = main + .split('"') + .find(|s| s.starts_with("/@fs/")) + .unwrap_or_else(|| panic!("no /@fs import:\n{main}")) + .to_string(); + let ext = server.text(&import).await; + (main, import, ext) + } + }; + let (main_a, import_a, ext_a) = serve(&a).await; + let (main_b, import_b, ext_b) = serve(&b).await; + assert_eq!(import_a, format!("/@fs{}/x.ts", ext.display())); + assert_eq!(import_b, import_a, "one file, one url"); + assert_eq!(main_a, main_b, "the same file imported from two checkouts"); + assert_eq!(ext_a, ext_b); + assert!(ext_a.contains(&format!("{marker}:ext")), "{ext_a}"); + settled_entries(marker).await; + assert!( + shared_entries(&format!("{marker}:main")).is_empty(), + "an importer pinned by /@fs reached the shared store" + ); + for app in [&a, &b] { + assert!( + local_entries(app, &format!("{marker}:main")), + "{}: the pinned importer is not in the checkout's own cache", + app.root.display() + ); + } +} diff --git a/crates/oj_server/tests/dev/hmr_stamp_persistent.rs b/crates/oj_server/tests/dev/hmr_stamp_persistent.rs new file mode 100644 index 000000000..e21c06709 --- /dev/null +++ b/crates/oj_server/tests/dev/hmr_stamp_persistent.rs @@ -0,0 +1,342 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2026 Raphael Amorim + +//! With the oj store on (`--store`), every importer of a +//! module an HMR update touched names it the same way: Vite's importAnalysis +//! appends `?t=` to each import of a stamped module, so the +//! browser holds one instance of it. A cached importer compiled under other +//! stamps (an earlier session, before the update) must not be served as is: +//! its import would name the bare url while another importer names the +//! stamped one, two urls for one module, which gives a React context two +//! identities ("must be used within a provider") until the cache is cleared. +//! The restarts are further `build_app`s over the kept cache. + +use std::path::Path; +use std::time::Duration; + +use regex::Regex; + +use crate::{App, Server}; + +const INDEX: &str = r#"t"#; + +/// `importer` imports `./ctx` and accepts its own updates, so an update to +/// ctx stops at it (as a component module does under React Refresh). The +/// string literal marks its cache entry. +fn importer(name: &str) -> String { + format!( + "import {{ value }} from \"./ctx\";\nexport const {name} = () => value + \"marker-{name}\";\n\ + if (import.meta.hot) import.meta.hot.accept();\n" + ) +} + +async fn serve_cached(app: &App) -> Server { + let mut dev = app.dev(); + dev.store = true; + crate::serve(dev).await +} + +/// The `?t=` stamp `code` imports `/src/ctx.ts` with, or None when the import +/// is bare; panics when the import is missing altogether. +fn ctx_stamp(code: &str) -> Option { + let import = Regex::new(r#""/src/ctx\.ts(\?t=(\d+))?""#).unwrap(); + let found = import + .captures(code) + .unwrap_or_else(|| panic!("no import of /src/ctx.ts in:\n{code}")); + found.get(2).map(|m| m.as_str().to_string()) +} + +/// Polls `path` until its import of ctx carries a stamp (the server has +/// processed the edit), within `within`. +async fn stamped(server: &Server, path: &str, within: Duration) -> Option { + let deadline = tokio::time::Instant::now() + within; + loop { + let code = server.text(path).await; + if let Some(stamp) = ctx_stamp(&code) { + return Some(stamp); + } + if tokio::time::Instant::now() >= deadline { + return None; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } +} + +/// Whether a persisted module naming `needle` exists in the app's own cache or +/// in the run's shared store (relocatable entries go there). +fn persisted_anywhere(cache: &Path, needle: &str) -> bool { + crate::warm_transform_virtual::cached_module_contains(cache, needle) + || crate::warm_transform_virtual::cached_module_contains( + &crate::store_modules_dir(), + needle, + ) +} + +/// Whether a file named `name` exists anywhere under `dir`. +fn file_under(dir: &Path, name: &str) -> bool { + std::fs::read_dir(dir) + .into_iter() + .flatten() + .flatten() + .any(|e| { + let path = e.path(); + if path.is_dir() { + file_under(&path, name) + } else { + e.file_name() == name + } + }) +} + +/// Polls until `pred` holds, failing with `what` after `within`. +async fn wait_until(what: &str, within: Duration, mut pred: impl FnMut() -> bool) { + let deadline = tokio::time::Instant::now() + within; + while !pred() { + assert!(tokio::time::Instant::now() < deadline, "{what}"); + tokio::time::sleep(Duration::from_millis(50)).await; + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_cached_importer_names_an_updated_module_as_the_others_do() { + let app = App::new(&[ + ( + "package.json", + r#"{"name":"stamp-cache","version":"1.0.0"}"#, + ), + ("index.html", INDEX), + // A dependency, so the optimizer commits a pre-bundle and writes its + // manifest: the next session's dep version (part of every compile + // key) is then the manifest's, and the cold session's entries are + // found. Without one the version is per session and nothing is. + ( + "node_modules/served-dep/package.json", + r#"{"name":"served-dep","version":"1.0.0","type":"module","main":"index.js"}"#, + ), + ("node_modules/served-dep/index.js", "export const dep = 1;\n"), + ( + "src/main.ts", + // b is a dynamic import: the eager crawl walks static imports + // only, so b is not served (nor in the graph) until asked for. + "import { dep } from \"served-dep\";\nimport { a } from \"./a\";\nexport const loadB = () => import(\"./b\");\nconsole.log(dep, a(), loadB);\n", + ), + ("src/a.ts", &importer("a")), + ("src/b.ts", &importer("b")), + ("src/ctx.ts", "export const value = \"v1\";\n"), + ]); + let cache = oj_cache::cache_root(&app.root); + + // Cold: every module compiles, with bare imports (no update yet), and + // lands in the cache under the committed pre-bundle's version. + { + let server = serve_cached(&app).await; + server.text("/src/main.ts").await; + crate::crawled(&app.root).await; + wait_until( + "the optimizer never wrote its manifest", + Duration::from_secs(20), + || file_under(&cache, "manifest.json"), + ) + .await; + for path in ["/src/main.ts", "/src/a.ts", "/src/b.ts", "/src/ctx.ts"] { + server.text(path).await; + } + assert_eq!(ctx_stamp(&server.text("/src/b.ts").await), None); + wait_until( + "the cold run never persisted b.ts", + Duration::from_secs(10), + || persisted_anywhere(&cache, "marker-b"), + ) + .await; + } + + // Warm: a.ts is loaded (from the cache); ctx is edited; b.ts, which this + // session has not served yet (a dynamic import, nothing crawls it), is + // then requested for the first time. + let stamp = { + let server = serve_cached(&app).await; + server.text("/src/main.ts").await; + server.text("/src/a.ts").await; + app.write(&[("src/ctx.ts", "export const value = \"v2\";\n")]); + let stamp = stamped(&server, "/src/a.ts", Duration::from_secs(20)) + .await + .expect("a.ts, a loaded importer, re-stamps its import after the edit"); + let b = server.text("/src/b.ts").await; + assert_eq!( + ctx_stamp(&b).as_deref(), + Some(stamp.as_str()), + "b.ts, served from the cache after the update, names ctx as a.ts does:\n{b}" + ); + // And stays so on a repeat request (the memory and mtime fast paths). + assert_eq!( + ctx_stamp(&server.text("/src/b.ts").await), + Some(stamp.clone()) + ); + // A stamped compile is this session's alone (a later session's stamps + // start over), so it stays in memory: nothing on disk names the stamp. + tokio::time::sleep(Duration::from_millis(500)).await; + assert!( + !persisted_anywhere(&cache, &format!("ctx.ts?t={stamp}")), + "a stamped compile was persisted" + ); + stamp + }; + + // A later session starts with no stamps (Vite's are per server too): the + // stamped entries the last one wrote must not come back for one importer + // while another is served bare. + { + let server = serve_cached(&app).await; + let a = server.text("/src/a.ts").await; + let b = server.text("/src/b.ts").await; + assert_eq!( + ctx_stamp(&a), + ctx_stamp(&b), + "after a restart both importers name ctx the same way:\n{a}\n{b}" + ); + assert_ne!( + ctx_stamp(&a).as_deref(), + Some(stamp.as_str()), + "a stamp from an earlier session is never served again:\n{a}" + ); + } +} + +/// A plugin whose `transform` records each run over `/src/b.ts`: a +/// persistent-cache hit skips the transform (Vite's cached transform result +/// is served as is), a compile runs it. +const COUNTING_PLUGIN: &str = r#"import fs from "node:fs"; +export default { + plugins: [{ + name: "count-b-transforms", + transform(code, id) { + if (id.split("?")[0].endsWith("/src/b.ts")) { + fs.appendFileSync(new URL("./transforms.log", import.meta.url), id + "\n"); + } + return null; + }, + }], +}; +"#; + +/// How many times the plugin transformed `/src/b.ts` so far. +fn b_transforms(root: &Path) -> usize { + std::fs::read_to_string(root.join("transforms.log")) + .unwrap_or_default() + .lines() + .count() +} + +/// The rule from both sides, as Vite's per-server transform cache behaves: +/// a cached compile is served (no transform runs) while the stamps of its +/// imports still hold, both in a later session with no update and on a +/// repeat request; it is recompiled only once an import of its was updated; +/// and the bare compile stays valid for a session that starts with no stamps. +#[tokio::test(flavor = "multi_thread")] +async fn a_cached_compile_is_served_under_its_stamps_and_recompiled_otherwise() { + let app = App::new(&[ + ( + "package.json", + r#"{"name":"stamp-cache-hits","version":"1.0.0"}"#, + ), + ("vite.config.mjs", COUNTING_PLUGIN), + ("index.html", INDEX), + ( + "node_modules/served-dep/package.json", + r#"{"name":"served-dep","version":"1.0.0","type":"module","main":"index.js"}"#, + ), + ("node_modules/served-dep/index.js", "export const dep = 1;\n"), + ( + "src/main.ts", + "import { dep } from \"served-dep\";\nimport { a } from \"./a\";\nexport const loadB = () => import(\"./b\");\nconsole.log(dep, a(), loadB);\n", + ), + ("src/a.ts", &importer("a")), + ("src/b.ts", &importer("b")), + ("src/ctx.ts", "export const value = \"v1\";\n"), + ]); + let root = app.root.clone(); + let cache = oj_cache::cache_root(&root); + + // Cold: b compiles once (the transform runs) and lands in the cache. + { + let server = serve_cached(&app).await; + server.text("/src/main.ts").await; + crate::crawled(&root).await; + wait_until( + "the optimizer never wrote its manifest", + Duration::from_secs(20), + || file_under(&cache, "manifest.json"), + ) + .await; + assert_eq!(ctx_stamp(&server.text("/src/b.ts").await), None); + assert_eq!(b_transforms(&root), 1, "the cold compile ran the transform"); + wait_until( + "the cold run never persisted b.ts", + Duration::from_secs(10), + || persisted_anywhere(&cache, "marker-b"), + ) + .await; + } + + // Warm, nothing updated: the cached compile is served, no transform. + { + let server = serve_cached(&app).await; + server.text("/src/main.ts").await; + assert_eq!(ctx_stamp(&server.text("/src/b.ts").await), None); + assert_eq!( + b_transforms(&root), + 1, + "a cached compile whose import stamps hold is served without a transform" + ); + } + + // Warm, ctx updated before b is first requested: the cached compile + // (bare import) is rejected, b compiles (one transform) with the stamp + // a.ts carries, and the repeat request is a memory hit. + { + let server = serve_cached(&app).await; + server.text("/src/main.ts").await; + server.text("/src/a.ts").await; + app.write(&[("src/ctx.ts", "export const value = \"v2\";\n")]); + let stamp = stamped(&server, "/src/a.ts", Duration::from_secs(20)) + .await + .expect("a.ts re-stamps its import after the edit"); + assert_eq!( + ctx_stamp(&server.text("/src/b.ts").await).as_deref(), + Some(stamp.as_str()) + ); + assert_eq!( + b_transforms(&root), + 2, + "the cached compile under other stamps was recompiled" + ); + assert_eq!( + ctx_stamp(&server.text("/src/b.ts").await).as_deref(), + Some(stamp.as_str()) + ); + assert_eq!(b_transforms(&root), 2, "the repeat request is a cache hit"); + // The stamped compile stays in memory: nothing on disk names the stamp. + tokio::time::sleep(Duration::from_millis(500)).await; + assert!( + !persisted_anywhere(&cache, &format!("ctx.ts?t={stamp}")), + "a stamped compile was persisted" + ); + } + + // A later session starts with no stamps: the bare compile from the cold + // run is the one that holds, served without a transform; the stamped + // one is never found under this session's key. + { + let server = serve_cached(&app).await; + server.text("/src/main.ts").await; + let a = server.text("/src/a.ts").await; + let b = server.text("/src/b.ts").await; + assert_eq!(ctx_stamp(&a), None, "{a}"); + assert_eq!(ctx_stamp(&b), None, "{b}"); + assert_eq!( + b_transforms(&root), + 2, + "the bare compile is served from the cache in a session with no stamps" + ); + } +} diff --git a/crates/oj_server/tests/dev/main.rs b/crates/oj_server/tests/dev/main.rs index 96643b2a5..b76972eda 100644 --- a/crates/oj_server/tests/dev/main.rs +++ b/crates/oj_server/tests/dev/main.rs @@ -36,6 +36,7 @@ mod css_preprocessor_options; mod css_url_inline; mod define_env_object; mod dep_plugin_load; +mod determinism; mod dev_base; mod dev_condition; mod dev_cors_host; @@ -58,6 +59,7 @@ mod hmr_invalidate; mod hmr_plugin_filtered_stamps; mod hmr_plugin_passthrough; mod hmr_protocol; +mod hmr_stamp_persistent; mod host_binding; mod hot_update_burst; mod html_entry; @@ -111,6 +113,7 @@ mod runtime_env; mod silent_proxy; mod spa_socket_keepalive; mod ssr_externalize; +mod store; mod stylex; mod svelte; mod svg_import_mark; @@ -125,6 +128,7 @@ mod virtual_importer; mod vite_dep_paths; mod vite_esm_entry; mod vite_hmr_socket; +mod warm_transform_virtual; mod wasm; mod watch_reads; mod watcher; @@ -147,7 +151,9 @@ pub struct App { } /// This process's parent dir for apps; the first call removes the dirs of -/// runs whose process is gone. +/// runs whose process is gone. It also points the shared oj store at +/// `/store` before the env snapshot is taken, so no test writes into +/// the developer's real store. pub fn run_dir() -> &'static Path { static DIR: OnceLock = OnceLock::new(); DIR.get_or_init(|| { @@ -162,10 +168,20 @@ pub fn run_dir() -> &'static Path { } } } - tmp.join(format!("oj-dev-tests-{}", std::process::id())) + let dir = tmp.join(format!("oj-dev-tests-{}", std::process::id())); + std::env::set_var("OJ_STORE_DIR", dir.join("store")); + oj_env::init(); + dir }) } +/// The modules dir of this run's shared store (see [`run_dir`]). +pub fn store_modules_dir() -> PathBuf { + oj_cache::store::store_root() + .expect("the run's store") + .join("modules") +} + impl App { pub fn new(files: &[(&str, &str)]) -> Self { static NEXT: AtomicUsize = AtomicUsize::new(0); @@ -202,6 +218,7 @@ impl App { lazy: false, typecheck: false, mode: None, + store: false, runtime_env: None, // The test's own runtime. rolldown: tokio::runtime::Handle::current(), diff --git a/crates/oj_server/tests/dev/optimize_plan.rs b/crates/oj_server/tests/dev/optimize_plan.rs index 94fc8ffdc..bd384ace4 100644 --- a/crates/oj_server/tests/dev/optimize_plan.rs +++ b/crates/oj_server/tests/dev/optimize_plan.rs @@ -272,29 +272,56 @@ async fn a_vanished_versioned_dep_file_is_outdated_not_missing() { ); } -// Vite's sessionTimestamp: dep URLs are cached immutable, so a cold session -// (a restart after the deps cache was cleared) must not serve its bundle -// under a URL an earlier session already handed out. +// Dep URLs are cached immutable (Vite salts them with its sessionTimestamp +// for this): a cold session (a restart after the deps cache was cleared) +// may hand out an earlier session's URL only for the same bytes. Over the +// same node_modules it does, so worktrees and restarts share URLs and the +// compiles keyed on them; over an edited dependency no URL an earlier +// session served comes back. #[tokio::test(flavor = "multi_thread")] -async fn a_cold_session_never_reuses_an_earlier_sessions_dep_urls() { +async fn a_cold_session_reuses_dep_urls_only_for_the_same_bytes() { crate::require_fixture!("vite"); let app = plain_esm_app(); - let first = { + let session = || async { let server = app.serve().await; let urls = dep_urls(&server.text("/main.js").await); for url in &urls { - server.text(url).await; + assert_eq!(server.get(url).await.status, 200, "{url}"); } urls }; - std::fs::remove_dir_all(oj_cache::cache_root(&app.root).join("deps")).unwrap(); + let first = session().await; + assert!(!first.is_empty()); + let deps = oj_cache::cache_root(&app.root).join("deps"); + std::fs::remove_dir_all(&deps).unwrap(); + let second = session().await; + assert_eq!(first, second, "the same bundle keeps its URLs"); + + std::fs::remove_dir_all(&deps).unwrap(); + app.write(&[( + "node_modules/plain-esm/index.js", + "export const hi = () => 2;\n", + )]); let server = app.serve().await; - let second = dep_urls(&server.text("/main.js").await); - assert_eq!(first.len(), second.len(), "{first:?} vs {second:?}"); - for (a, b) in first.iter().zip(&second) { - assert_ne!(a, b, "a cold session minted a URL an earlier one served"); - server.text(b).await; - } + // The plan's URLs are the earlier ones until the commit finds the bytes + // moved; then every URL moves and the page reloads onto new ones. + let deadline = Instant::now() + Duration::from_secs(30); + let third = loop { + let urls = dep_urls(&server.text("/main.js").await); + if urls.iter().all(|u| !first.contains(u)) { + break urls; + } + assert!( + Instant::now() < deadline, + "an edited dependency kept an earlier session's URL: {urls:?}" + ); + tokio::time::sleep(Duration::from_millis(50)).await; + }; + let plain = third.iter().find(|u| u.contains("plain-esm")).unwrap(); + assert!( + server.text(plain).await.contains("2"), + "the new bytes serve" + ); } // Vite's cached _metadata.json: a warm session reuses the persisted versions, diff --git a/crates/oj_server/tests/dev/store.rs b/crates/oj_server/tests/dev/store.rs new file mode 100644 index 000000000..d94e2980c --- /dev/null +++ b/crates/oj_server/tests/dev/store.rs @@ -0,0 +1,792 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2026 Raphael Amorim + +//! The oj store under the dev server when the store itself misbehaves or is +//! shared: a poisoned or corrupt entry, two servers on one store at once, +//! and a compile input that changed between sessions. (A store that cannot +//! be written or is deleted underneath is `oj_cache`'s to test: the run's +//! store is every test's here.) + +use std::path::PathBuf; +use std::time::Duration; + +use crate::App; + +/// An app whose entry carries `marker`, so its store entries are this +/// test's alone in the run's shared store. +fn app(marker: &str) -> App { + App::new(&[ + ( + "index.html", + "", + ), + ( + "src/main.ts", + &format!( + "import {{ util }} from \"./util\";\nexport const main = util + \"-{marker}\";\n" + ), + ), + ( + "src/util.ts", + &format!("export const util: string = \"util-{marker}\";\n"), + ), + ]) +} + +fn dev(app: &App) -> oj_server::DevServer { + oj_server::DevServer { + store: true, + ..app.dev() + } +} + +/// The shared store's entries whose text contains `needle`. +fn shared_entries(needle: &str) -> Vec { + fn walk(dir: &std::path::Path, needle: &str, out: &mut Vec) { + for e in std::fs::read_dir(dir).into_iter().flatten().flatten() { + let path = e.path(); + if path.is_dir() { + walk(&path, needle, out); + } else if path.extension().is_some_and(|x| x == "json") + && std::fs::read_to_string(&path).is_ok_and(|s| s.contains(needle)) + { + out.push(path); + } + } + } + let mut out = Vec::new(); + walk(&crate::store_modules_dir(), needle, &mut out); + out +} + +/// Cache writes are asynchronous: waits until `needle` names at least +/// `count` shared entries. +async fn wait_for_entries(needle: &str, count: usize) -> Vec { + let deadline = std::time::Instant::now() + Duration::from_secs(10); + loop { + let found = shared_entries(needle); + if found.len() >= count { + return found; + } + assert!( + std::time::Instant::now() < deadline, + "{needle}: {} shared entries, wanted {count}", + found.len() + ); + tokio::time::sleep(Duration::from_millis(50)).await; + } +} + +// Garbage under a key, and an entry that names another checkout (a store +// copied from elsewhere, another oj's write): the server serves a fresh +// compile and the store ends up with a good entry, never the poison. +#[tokio::test(flavor = "multi_thread")] +async fn a_poisoned_shared_entry_is_recompiled_not_served() { + let marker = "poison-store"; + let app = app(marker); + { + let server = crate::serve(dev(&app)).await; + assert!(server.text("/src/main.ts").await.contains(marker)); + } + let entries = wait_for_entries(marker, 1).await; + let entry = entries + .iter() + .find(|p| std::fs::read_to_string(p).unwrap().contains("util-")) + .cloned() + .unwrap_or_else(|| entries[0].clone()); + let good = std::fs::read(&entry).unwrap(); + + for poison in [ + b"{ not json at all".to_vec(), + good[..good.len() / 2].to_vec(), + serde_json::to_vec(&oj_cache::CachedModule { + code: "import x from \"/@fs//other/checkout/x.js\"; export const main = \"POISON\";" + .into(), + imports: vec!["/@fs//other/checkout/x.js".into()], + kind: "esm".into(), + ..Default::default() + }) + .unwrap(), + ] { + std::fs::write(&entry, &poison).unwrap(); + let server = crate::serve(dev(&app)).await; + let main = server.text("/src/main.ts").await; + assert!(main.contains(marker), "{main}"); + assert!(!main.contains("POISON"), "{main}"); + assert!(!main.contains("/other/checkout"), "{main}"); + drop(server); + // The poison is gone: removed on read, and the recompile rewrote it. + let deadline = std::time::Instant::now() + Duration::from_secs(10); + loop { + let now = std::fs::read(&entry).unwrap_or_default(); + if now != poison && !now.is_empty() { + break; + } + assert!( + std::time::Instant::now() < deadline, + "the poisoned entry was neither removed nor rewritten" + ); + tokio::time::sleep(Duration::from_millis(50)).await; + } + let module: oj_cache::CachedModule = + serde_json::from_slice(&std::fs::read(&entry).unwrap()).unwrap(); + assert!(module.is_relocatable()); + assert!(!module.code.contains("POISON")); + } +} + +// Two servers of two checkouts on one store at once, hammered in parallel: +// both serve the same bytes for every module, whichever compiled first. +#[tokio::test(flavor = "multi_thread")] +async fn two_servers_on_one_store_serve_identical_bytes() { + let marker = "twin-store"; + let (a, b) = (app(marker), app(marker)); + let extra: Vec<(String, String)> = (0..12) + .map(|i| { + ( + format!("src/m{i}.ts"), + format!("import {{ util }} from \"./util\";\nexport const m{i} = util + {i};\n"), + ) + }) + .collect(); + for app in [&a, &b] { + let files: Vec<(&str, &str)> = extra + .iter() + .map(|(p, c)| (p.as_str(), c.as_str())) + .collect(); + app.write(&files); + } + let (sa, sb) = tokio::join!(crate::serve(dev(&a)), crate::serve(dev(&b))); + let mut urls = vec!["/src/main.ts".to_string(), "/src/util.ts".to_string()]; + urls.extend((0..12).map(|i| format!("/src/m{i}.ts"))); + async fn fetch_all(server: &crate::Server, urls: Vec) -> Vec { + let mut out = Vec::new(); + for url in urls { + out.push(server.text(&url).await); + } + out + } + for round in 0..3 { + let (from_a, from_b) = tokio::join!( + fetch_all(&sa, urls.clone()), + fetch_all(&sb, urls.iter().rev().cloned().collect::>()) + ); + let from_b: Vec = from_b.into_iter().rev().collect(); + for ((url, ta), tb) in urls.iter().zip(&from_a).zip(&from_b) { + assert_eq!(ta, tb, "round {round}: {url} differs between the servers"); + if url.ends_with("main.ts") || url.ends_with("util.ts") { + assert!(ta.contains(marker), "{url}: {ta}"); + } else { + assert!(ta.contains("util"), "{url}: {ta}"); + } + for root in [&a.root, &b.root] { + let root = root.to_string_lossy(); + assert!(!ta.contains(&*root), "{url} names the checkout {root}"); + } + } + } + drop((sa, sb)); + // Each module is one shared entry: the twin never wrote a duplicate. + let entries = wait_for_entries(marker, 1).await; + let mut codes: Vec = entries + .iter() + .map(|p| { + serde_json::from_slice::(&std::fs::read(p).unwrap()) + .unwrap() + .code + }) + .collect(); + let total = codes.len(); + codes.sort(); + codes.dedup(); + assert_eq!( + codes.len(), + total, + "two entries hold the same compiled bytes" + ); +} + +// A compile input outside the module changed between sessions (tsconfig, +// package.json, the config graph: the salt of every key): the second session +// misses, compiles under its own key and leaves both entries in the store, +// never a stale hit under the old one. +#[tokio::test(flavor = "multi_thread")] +async fn a_config_edit_between_sessions_is_a_miss() { + let marker = "config-salt-store"; + let app = app(marker); + app.write(&[("tsconfig.json", "{\"compilerOptions\":{}}")]); + let session = || async { + let server = crate::serve(dev(&app)).await; + server.text("/src/main.ts").await + }; + let first = session().await; + // Both modules name the marker (util's string, main's suffix). + let before = wait_for_entries(marker, 2).await.len(); + assert_eq!(session().await, first, "an unchanged session hits"); + tokio::time::sleep(Duration::from_millis(300)).await; + assert_eq!(shared_entries(marker).len(), before, "a hit writes nothing"); + app.write(&[( + "tsconfig.json", + "{\"compilerOptions\":{\"useDefineForClassFields\":true}}", + )]); + assert_eq!(session().await, first, "the same source still serves"); + let after = wait_for_entries(marker, before + 2).await; + assert_eq!( + after.len(), + before + 2, + "both modules again, under the new salt" + ); + app.write(&[("package.json", "{\"name\":\"renamed\"}")]); + session().await; + assert_eq!( + wait_for_entries(marker, before + 4).await.len(), + before + 4, + "package.json is in the salt too" + ); +} + +/// A checkout laid out as a workspace: a hoisted `node_modules` above the +/// app, as pnpm and yarn workspaces leave it. `App::new`'s dir is the +/// workspace; the app the server runs is `mono/app` under it. +fn workspace_app(marker: &str) -> (App, PathBuf) { + let app = App::new(&[ + ( + "mono/node_modules/hoisted/package.json", + r#"{"name":"hoisted","version":"1.0.0","type":"module","main":"index.js"}"#, + ), + ( + "mono/node_modules/hoisted/index.js", + "export const hoisted = \"hoisted\";\n", + ), + ("mono/node_modules/hoisted/data.json", "{\"n\":1}\n"), + ( + "mono/app/package.json", + r#"{"name":"app","version":"1.0.0"}"#, + ), + ( + "mono/app/index.html", + "", + ), + ( + "mono/app/src/main.ts", + &format!( + "import {{ hoisted }} from \"hoisted\";\nimport data from \"hoisted/data.json\";\nexport const main = hoisted + data.n + \"-{marker}\";\n" + ), + ), + ("secret.txt", "not for serving\n"), + ]); + let root = app.root.join("mono/app"); + (app, root) +} + +fn dev_at(app: &App, root: &std::path::Path) -> oj_server::DevServer { + oj_server::DevServer { + root: root.to_path_buf(), + store: true, + ..app.dev() + } +} + +// A file of a dependency hoisted above the app root that the optimizer +// leaves alone (its JSON) is served at `/@fs/@mono/`, the same URL in +// every checkout of the workspace, so the importer's entry is shared: the +// second checkout serves the first's bytes and writes no entry of its own, +// and the hoisted file serves under that URL in both. +#[tokio::test(flavor = "multi_thread")] +async fn a_hoisted_dependency_is_shared_across_workspace_checkouts() { + let marker = "hoisted-store"; + let (a, root_a) = workspace_app(marker); + let (b, root_b) = workspace_app(marker); + let main_a = { + let server = crate::serve(dev_at(&a, &root_a)).await; + let main = server.text("/src/main.ts").await; + assert!( + main.contains("/@fs/@mono/node_modules/hoisted/data.json"), + "the hoisted import is workspace-relative:\n{main}" + ); + assert!(!main.contains(&*a.root.to_string_lossy()), "{main}"); + let dep = server + .get("/@fs/@mono/node_modules/hoisted/data.json") + .await; + assert_eq!(dep.status, 200); + main + }; + let before = wait_for_entries(marker, 1).await.len(); + let server = crate::serve(dev_at(&b, &root_b)).await; + assert_eq!( + server.text("/src/main.ts").await, + main_a, + "the second checkout serves the first's bytes" + ); + let dep = server + .get("/@fs/@mono/node_modules/hoisted/data.json") + .await; + assert_eq!( + dep.status, 200, + "the @mono URL resolves against B's workspace" + ); + tokio::time::sleep(Duration::from_millis(500)).await; + assert_eq!( + shared_entries(marker).len(), + before, + "B compiled main.ts again" + ); +} + +// `/@fs/@mono/` resolves against the workspace, never past it: a traversal +// that would reach a file beside the workspace is refused like any other +// `/@fs` path outside the allow list. +#[tokio::test(flavor = "multi_thread")] +async fn a_mono_url_cannot_climb_out_of_the_workspace() { + let (app, root) = workspace_app("mono-traversal"); + let server = crate::serve(dev_at(&app, &root)).await; + server.text("/src/main.ts").await; + for url in [ + "/@fs/@mono/../secret.txt", + "/@fs/@mono/node_modules/../../secret.txt", + "/@fs/@mono/%2e%2e/secret.txt", + ] { + let response = server.get(url).await; + assert_ne!( + response.status, 200, + "{url} served a file outside the workspace" + ); + assert!( + !response.body.contains("not for serving"), + "{url} leaked the file" + ); + } +} + +/// The `/@oj-deps/` URLs a served module imports. +fn dep_urls(code: &str) -> Vec { + code.split('"') + .filter(|s| s.starts_with("/@oj-deps/")) + .map(str::to_string) + .collect() +} + +/// An app with a pre-bundled dependency of its own, `served-dep`, whose +/// entry `src/main.ts` imports it. +fn dep_app(marker: &str, dep_body: &str) -> App { + App::new(&[ + ("package.json", r#"{"name":"dep-urls","version":"1.0.0"}"#), + ( + "node_modules/served-dep/package.json", + r#"{"name":"served-dep","version":"1.0.0","type":"module","main":"index.js"}"#, + ), + ("node_modules/served-dep/index.js", dep_body), + ( + "index.html", + "", + ), + ( + "src/main.ts", + &format!( + "import {{ dep }} from \"served-dep\";\nexport const main = dep + \"-{marker}\";\n" + ), + ), + ]) +} + +/// The dep URLs `main.ts` imports once the optimizer committed its bundle +/// (the URLs are provisional until then). +async fn committed_dep_urls(server: &crate::Server, app: &App) -> Vec { + let deadline = std::time::Instant::now() + Duration::from_secs(30); + loop { + let urls = dep_urls(&server.text("/src/main.ts").await); + let manifest = oj_cache::cache_root(&app.root).join("deps"); + let committed = std::fs::read_dir(&manifest) + .into_iter() + .flatten() + .flatten() + .any(|e| e.file_name().to_string_lossy().ends_with(".json")); + if committed && !urls.is_empty() { + return urls; + } + assert!( + std::time::Instant::now() < deadline, + "the optimizer never committed" + ); + tokio::time::sleep(Duration::from_millis(100)).await; + } +} + +// Two checkouts bundle the same dependency bytes: with the ledger in the +// store, both mint the same immutable URLs, so the modules compiled against +// them are one entry. A checkout whose dependency differs never serves its +// bytes under a URL the others hand out. +#[tokio::test(flavor = "multi_thread")] +async fn checkouts_bundling_the_same_dependency_mint_the_same_urls() { + let marker = "dep-urls-store"; + let same = "export const dep = 1;\n"; + let (a, b) = (dep_app(marker, same), dep_app(marker, same)); + let urls_a = { + let server = crate::serve(dev(&a)).await; + committed_dep_urls(&server, &a).await + }; + let urls_b = { + let server = crate::serve(dev(&b)).await; + committed_dep_urls(&server, &b).await + }; + assert_eq!(urls_a, urls_b, "same bytes, same URLs across checkouts"); + let other = dep_app(marker, "export const dep = 2;\n"); + let server = crate::serve(dev(&other)).await; + let deadline = std::time::Instant::now() + Duration::from_secs(30); + let urls_other = loop { + let urls = committed_dep_urls(&server, &other).await; + if urls.iter().all(|u| !urls_a.contains(u)) { + break urls; + } + assert!( + std::time::Instant::now() < deadline, + "other bytes kept a URL the first checkouts serve: {urls:?}" + ); + tokio::time::sleep(Duration::from_millis(100)).await; + }; + assert_eq!(urls_other.len(), urls_a.len()); + assert!(server.text(&urls_other[0]).await.contains("2")); +} + +// An `import.meta.glob` expansion is a store entry's input too: a file added +// under the pattern while no server ran makes the next session's hit a miss +// (the glob row re-expands against this checkout), never a stale listing. +#[tokio::test(flavor = "multi_thread")] +async fn a_file_added_under_a_glob_between_sessions_is_a_miss() { + let marker = "glob-trace-store"; + let app = App::new(&[ + ( + "index.html", + "", + ), + ( + "src/main.ts", + &format!("export const pages = import.meta.glob(\"./pages/*.ts\");\nexport const tag = \"{marker}\";\n"), + ), + ("src/pages/a.ts", "export default 1;\n"), + ]); + let first = { + let server = crate::serve(dev(&app)).await; + server.text("/src/main.ts").await + }; + assert!(first.contains("./pages/a.ts"), "{first}"); + assert!(!first.contains("./pages/b.ts")); + wait_for_entries(marker, 1).await; + app.write(&[("src/pages/b.ts", "export default 2;\n")]); + let server = crate::serve(dev(&app)).await; + let second = server.text("/src/main.ts").await; + assert!( + second.contains("./pages/b.ts"), + "the stored expansion was served without the new page:\n{second}" + ); +} + +/// A config whose plugin reads an optional side file during `transform` and +/// takes a default when it is missing: `transforms.log` counts its runs. +const OPTIONAL_THEME_PLUGIN: &str = r#"import fs from "node:fs"; +const here = new URL(".", import.meta.url).pathname; +export default { + plugins: [{ + name: "optional-theme", + transform(code, id) { + if (!id.split("?")[0].endsWith("/src/main.ts")) return null; + fs.appendFileSync(here + "transforms.log", id + "\n"); + let theme = "default"; + try { + theme = fs.readFileSync(here + "theme.txt", "utf8").trim(); + } catch {} + return { code: code.replace("__THEME__", theme), map: null }; + }, + }], +}; +"#; + +fn transforms(app: &App) -> usize { + std::fs::read_to_string(app.root.join("transforms.log")) + .unwrap_or_default() + .lines() + .count() +} + +// A side file the plugin looked for and did not find is an input of the +// entry too: the fallback it took is baked in. Creating the file between +// sessions is a miss (the row records the absence), so the next session +// transforms again and serves the file's value, as Vite would. +#[tokio::test(flavor = "multi_thread")] +async fn a_side_file_created_after_a_transform_missed_it_is_a_miss() { + let marker = "optional-theme-store"; + let app = App::new(&[ + ("vite.config.mjs", OPTIONAL_THEME_PLUGIN), + ( + "index.html", + "", + ), + ( + "src/main.ts", + &format!("export const theme = \"__THEME__-{marker}\";\n"), + ), + ]); + let session = || async { + let server = crate::serve(dev(&app)).await; + server.text("/src/main.ts").await + }; + let first = session().await; + assert!(first.contains(&format!("default-{marker}")), "{first}"); + assert_eq!(transforms(&app), 1); + wait_for_entries(marker, 1).await; + assert!(session().await.contains(&format!("default-{marker}"))); + assert_eq!(transforms(&app), 1, "a warm hit runs no transform"); + app.write(&[("theme.txt", "dark\n")]); + let third = session().await; + assert!( + third.contains(&format!("dark-{marker}")), + "the entry compiled without the file was served after it appeared:\n{third}" + ); + assert_eq!(transforms(&app), 2); + // The file read is now a traced input: an edit misses too. + wait_for_entries(&format!("dark-{marker}"), 1).await; + app.write(&[("theme.txt", "light\n")]); + assert!(session().await.contains(&format!("light-{marker}"))); + assert_eq!(transforms(&app), 3); +} + +// A plugin that collects state from every module's transform (UnoCSS's +// shape) sees no module a persistent hit skips: with one active, app modules +// compile each session and are never persisted; the session still works. +#[tokio::test(flavor = "multi_thread")] +async fn app_modules_compile_each_session_under_a_collector_plugin() { + let marker = "collector-store"; + let app = App::new(&[ + ( + "vite.config.mjs", + r#"import fs from "node:fs"; +const here = new URL(".", import.meta.url).pathname; +export default { + plugins: [{ + name: "unocss:collector", + transform(code, id) { + if (id.split("?")[0].endsWith("/src/main.ts")) fs.appendFileSync(here + "transforms.log", id + "\n"); + return null; + }, + }], +}; +"#, + ), + ( + "index.html", + "", + ), + ( + "src/main.ts", + &format!("export const main = \"{marker}\";\n"), + ), + ]); + for session in 1..=3 { + let server = crate::serve(dev(&app)).await; + assert!(server.text("/src/main.ts").await.contains(marker)); + assert_eq!( + transforms(&app), + session, + "session {session} transformed afresh" + ); + } + tokio::time::sleep(Duration::from_millis(500)).await; + assert!( + shared_entries(marker).is_empty(), + "an app module was persisted under a collector plugin" + ); +} + +// A source file outside the app root but in the workspace (a monorepo +// package) is named by its `/@fs/@mono/` url in its own debug info +// (the sourcemap's `sources`), so its entry carries no checkout's path, goes +// to the shared store, and the second checkout hits it. +#[tokio::test(flavor = "multi_thread")] +async fn a_workspace_package_source_is_path_free_and_shared() { + let marker = "ws-package-store"; + let checkout = + || { + App::new(&[ + ("mono/node_modules/.keep", ""), + ( + "mono/packages/ui/label.ts", + &format!("export const label: string = \"{marker}\";\n"), + ), + ("mono/app/package.json", r#"{"name":"app","version":"1.0.0"}"#), + ( + "mono/app/index.html", + "", + ), + ( + "mono/app/src/main.ts", + "import { label } from \"../../packages/ui/label\";\nexport const main = label;\n", + ), + ]) + }; + let (a, b) = (checkout(), checkout()); + let url = "/@fs/@mono/packages/ui/label.ts"; + let label_a = { + let server = crate::serve(dev_at(&a, &a.root.join("mono/app"))).await; + let main = server.text("/src/main.ts").await; + assert!(main.contains(url), "{main}"); + let label = server.get(url).await; + assert_eq!(label.status, 200, "{}", label.body); + assert!(label.body.contains(marker)); + label.body + }; + let entries = wait_for_entries(marker, 1).await; + let package = entries + .iter() + .map(|p| { + serde_json::from_slice::(&std::fs::read(p).unwrap()).unwrap() + }) + .find(|m| m.code.contains("label")) + .expect("the package's entry is in the shared store"); + let map = package.map_json.clone().unwrap_or_default(); + assert!(map.contains(url), "the map names the served url: {map}"); + for root in [&a.root, &b.root] { + let root = root.to_string_lossy(); + assert!(!map.contains(&*root), "the map names {root}: {map}"); + assert!(!package.code.contains(&*root)); + } + let before = entries.len(); + let server = crate::serve(dev_at(&b, &b.root.join("mono/app"))).await; + server.text("/src/main.ts").await; + assert_eq!(server.get(url).await.body, label_a, "B serves A's bytes"); + tokio::time::sleep(Duration::from_millis(500)).await; + assert_eq!( + shared_entries(marker).len(), + before, + "B compiled the package again" + ); +} + +// An import the entry resolved to a file that moved since (`./util` to +// `util/index.ts` on a branch switch, the importer untouched): the next +// session misses, resolves anew and serves the file where it is, instead of +// a hit whose import 404s. +#[tokio::test(flavor = "multi_thread")] +async fn an_import_whose_target_moved_between_sessions_is_a_miss() { + let marker = "moved-import-store"; + let app = app(marker); + let first = { + let server = crate::serve(dev(&app)).await; + server.text("/src/main.ts").await + }; + assert!(first.contains("\"/src/util.ts\""), "{first}"); + wait_for_entries(marker, 2).await; + std::fs::create_dir_all(app.root.join("src/util")).unwrap(); + std::fs::rename( + app.root.join("src/util.ts"), + app.root.join("src/util/index.ts"), + ) + .unwrap(); + let server = crate::serve(dev(&app)).await; + let second = server.text("/src/main.ts").await; + assert!( + second.contains("\"/src/util/index.ts\""), + "the entry with the old resolution was served:\n{second}" + ); + assert_eq!(server.get("/src/util/index.ts").await.status, 200); +} + +/// A config whose plugin rewrites the side file it reads during +/// `transform`: the entry's output comes from the file as it was, its +/// digest from the file as it is. +const REWRITING_THEME_PLUGIN: &str = r#"import fs from "node:fs"; +const here = new URL(".", import.meta.url).pathname; +export default { + plugins: [{ + name: "rewriting-theme", + transform(code, id) { + if (!id.split("?")[0].endsWith("/src/main.ts")) return null; + const theme = fs.readFileSync(here + "theme.txt", "utf8").trim(); + fs.writeFileSync(here + "theme.txt", theme + "+"); + return { code: code.replace("__THEME__", theme), map: null }; + }, + }], +}; +"#; + +// A side file written while the transform that read it ran (here by the +// transform itself; an editor's save in the same instant is the same race) +// is digested as it is now, next to output built from what it was. Such an +// entry is never persisted: the next session transforms again. +#[tokio::test(flavor = "multi_thread")] +async fn a_side_file_written_during_its_transform_is_not_persisted() { + let marker = "unsettled-theme-store"; + let app = App::new(&[ + ("vite.config.mjs", REWRITING_THEME_PLUGIN), + ("theme.txt", "dark\n"), + ( + "index.html", + "", + ), + ( + "src/main.ts", + &format!("export const theme = \"__THEME__-{marker}\";\n"), + ), + ]); + let session = || async { + let server = crate::serve(dev(&app)).await; + server.text("/src/main.ts").await + }; + assert!(session().await.contains(&format!("dark-{marker}"))); + tokio::time::sleep(Duration::from_millis(500)).await; + assert!( + shared_entries(marker).is_empty(), + "an entry whose side file was written under it was persisted" + ); + assert!(!crate::warm_transform_virtual::cached_module_contains( + &oj_cache::cache_root(&app.root), + marker + )); + let second = session().await; + assert!( + second.contains(&format!("dark+-{marker}")), + "the entry built from the older file was served:\n{second}" + ); +} + +// The app's plugin file is in the salt when it is an `oj.plugins.mjs` (run +// in a vite config's place): an edit to it between sessions is a miss, and +// the edited plugin's output is served. +#[tokio::test(flavor = "multi_thread")] +async fn an_oj_plugins_file_edit_between_sessions_is_a_miss() { + let marker = "oj-plugins-salt-store"; + let plugin = |tag: &str| { + format!( + r#"export default [{{ + name: "tagger", + transform(code, id) {{ + if (!id.split("?")[0].endsWith("/src/main.ts")) return null; + return {{ code: code.replace("__TAG__", "{tag}"), map: null }}; + }}, +}}]; +"# + ) + }; + let app = App::new(&[ + ("oj.plugins.mjs", &plugin("one")), + ( + "index.html", + "", + ), + ( + "src/main.ts", + &format!("export const tag = \"__TAG__-{marker}\";\n"), + ), + ]); + let session = || async { + let server = crate::serve(dev(&app)).await; + server.text("/src/main.ts").await + }; + assert!(session().await.contains(&format!("one-{marker}"))); + wait_for_entries(marker, 1).await; + app.write(&[("oj.plugins.mjs", &plugin("two"))]); + let second = session().await; + assert!( + second.contains(&format!("two-{marker}")), + "the entry of the old plugin file was served:\n{second}" + ); +} diff --git a/crates/oj_server/tests/dev/stylex.rs b/crates/oj_server/tests/dev/stylex.rs index d517a0805..f4fe1ea5e 100644 --- a/crates/oj_server/tests/dev/stylex.rs +++ b/crates/oj_server/tests/dev/stylex.rs @@ -315,6 +315,131 @@ async fn ssr_compiles_feed_the_same_sheet() { assert!(css.contains("color: teal"), "{css}"); } +#[tokio::test(flavor = "multi_thread")] +async fn the_disk_cache_carries_each_modules_rules() { + require_fixture!("vite"); + let app = app("{}"); + let dev = || oj_server::DevServer { + store: true, + ..app.dev() + }; + { + let server = crate::serve(dev()).await; + server.text("/src/main.ts").await; + // A warm start serves this entry without compiling, so the rules must + // travel in it. Cache writes are asynchronous. + let cache = oj_cache::cache_root(&app.root); + let deadline = std::time::Instant::now() + Duration::from_secs(10); + // Relocatable entries persist to the shared store, pinned ones to + // the app's cache. + while !persisted(&cache, "\"stylex_rules\"", "color:red") + && !persisted(&crate::store_modules_dir(), "\"stylex_rules\"", "color:red") + { + assert!( + std::time::Instant::now() < deadline, + "main.ts never persisted its rules" + ); + tokio::time::sleep(Duration::from_millis(50)).await; + } + } + let server = crate::serve(dev()).await; + server.text("/src/main.ts").await; + let css = server.text("/virtual:stylex.css").await; + assert!(css.contains("color: red"), "{css}"); +} + +/// Whether a persisted module under `dir` mentions both needles. +// Two checkouts of one StyleX app share compiled modules through the oj +// store: the plugin's fingerprint keys every module, so it must not carry +// the checkout's path. The second checkout serves the first's entry for +// main.ts (it writes none of its own) and its rules still reach the sheet. +#[tokio::test(flavor = "multi_thread")] +async fn a_second_checkout_serves_the_firsts_compiled_module() { + require_fixture!("vite"); + // A color no other test compiles, so the store entries are this test's; + // one whose name is its shortest spelling, which the sheet keeps. + let color = "tan"; + let (a, b) = (app("{}"), app("{}")); + for checkout in [&a, &b] { + checkout.write(&[("src/main.ts", &main_ts(color))]); + } + let dev = |app: &App| oj_server::DevServer { + store: true, + ..app.dev() + }; + let store = crate::store_modules_dir(); + let entries = || count_persisted(&store, "\"stylex_rules\"", color); + { + let server = crate::serve(dev(&a)).await; + server.text("/src/main.ts").await; + let deadline = std::time::Instant::now() + Duration::from_secs(10); + while entries() == 0 { + assert!( + std::time::Instant::now() < deadline, + "the first checkout never shared main.ts" + ); + tokio::time::sleep(Duration::from_millis(50)).await; + } + } + let shared = entries(); + // The shared entry (its sourcemap included) names no checkout. + for checkout in [&a, &b] { + let path = checkout.root.to_string_lossy(); + assert!( + !persisted(&store, color, &path), + "a shared entry carries {path}" + ); + } + let server = crate::serve(dev(&b)).await; + server.text("/src/main.ts").await; + let css = server.text("/virtual:stylex.css").await; + assert!(css.contains(&format!("color: {color}")), "{css}"); + // A miss would compile and write its own entry (asynchronously). + tokio::time::sleep(Duration::from_millis(500)).await; + assert_eq!( + entries(), + shared, + "the second checkout compiled main.ts again" + ); +} + +/// How many persisted entries under `dir` contain both `a` and `b`. +fn count_persisted(dir: &std::path::Path, a: &str, b: &str) -> usize { + std::fs::read_dir(dir) + .into_iter() + .flatten() + .flatten() + .map(|e| { + let path = e.path(); + if path.is_dir() { + count_persisted(&path, a, b) + } else { + usize::from( + path.extension().is_some_and(|x| x == "json") + && std::fs::read_to_string(&path) + .is_ok_and(|s| s.contains(a) && s.contains(b)), + ) + } + }) + .sum() +} + +fn persisted(dir: &std::path::Path, a: &str, b: &str) -> bool { + std::fs::read_dir(dir) + .into_iter() + .flatten() + .flatten() + .any(|e| { + let path = e.path(); + if path.is_dir() { + persisted(&path, a, b) + } else { + path.extension().is_some_and(|x| x == "json") + && std::fs::read_to_string(&path).is_ok_and(|s| s.contains(a) && s.contains(b)) + } + }) +} + #[tokio::test(flavor = "multi_thread")] async fn the_runtime_restyles_the_page_on_an_edit() { if crate::browser::skip() { diff --git a/crates/oj_server/tests/dev/warm_transform_virtual.rs b/crates/oj_server/tests/dev/warm_transform_virtual.rs new file mode 100644 index 000000000..a0bfbd63a --- /dev/null +++ b/crates/oj_server/tests/dev/warm_transform_virtual.rs @@ -0,0 +1,155 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2026 Raphael Amorim + +//! Regression: a plugin `transform` can append an import of a virtual it +//! serves from in-memory state filled during that transform (wyw-in-js keeps +//! each module's extracted CSS in a `cssLookup` its `load` serves). The +//! persistent cache keeps the transformed code across restarts; serving it on +//! a warm start without re-running the transform leaves the plugin's map +//! empty and the virtual import 404s. oj re-transforms a cached module that +//! imports such a virtual. The restart is a second `build_app` in the same +//! process over the kept cache, with a fresh plugin host (fresh map). + +use std::path::Path; +use std::time::Duration; + +use crate::{App, Server}; + +const VITE_CONFIG: &str = r#"const cssStore = {}; +export default { + plugins: [ + { + name: "stateful-virtual-css", + enforce: "pre", + resolveId(id) { + const clean = id.split("?", 1)[0]; + return clean in cssStore ? clean : null; + }, + load(id) { + const clean = id.split("?", 1)[0]; + return clean in cssStore ? cssStore[clean] : null; + }, + transform(code, id) { + const clean = id.split("?", 1)[0]; + if (!clean.endsWith("/main.tsx")) return null; + const virt = clean.replace(/\.tsx$/, ".stateful.css"); + cssStore[virt] = ".injected { color: rebeccapurple }"; + return { code: code + "\nimport " + JSON.stringify(virt) + ";\n", map: null }; + }, + }, + ], +}; +"#; + +fn virt_url_from(main: &str) -> String { + regex::Regex::new(r#"import\s+"([^"]*\.stateful\.css)""#) + .unwrap() + .captures(main) + .map(|c| c[1].to_string()) + .unwrap_or_else(|| panic!("main.tsx must import the injected virtual css:\n{main}")) +} + +/// Harness addition: whether a persisted module entry +/// (`//.json`) holds `needle`. Other cache files (the +/// graph snapshot) name the virtual's url too, so only entries count. Cache +/// writes go through a background thread, so the warm run waits for the cold +/// run's entry instead of racing it, and fails rather than passing vacuously +/// when the cache is off. +pub(crate) fn cached_module_contains(cache: &Path, needle: &str) -> bool { + let is_hex = |s: &str, n: usize| s.len() == n && s.bytes().all(|b| b.is_ascii_hexdigit()); + let Ok(shards) = std::fs::read_dir(cache) else { + return false; + }; + shards + .flatten() + .filter(|d| d.file_name().to_str().is_some_and(|n| is_hex(n, 2))) + .filter_map(|d| std::fs::read_dir(d.path()).ok()) + .flat_map(|entries| entries.flatten()) + .any(|e| { + let path = e.path(); + path.extension().is_some_and(|x| x == "json") + && path + .file_stem() + .and_then(|s| s.to_str()) + .is_some_and(|s| is_hex(s, 64)) + && std::fs::read_to_string(&path).is_ok_and(|s| s.contains(needle)) + }) +} + +async fn serve_cached(app: &App) -> Server { + let mut dev = app.dev(); + dev.store = true; + crate::serve(dev).await +} + +#[tokio::test(flavor = "multi_thread")] +async fn plugin_virtual_still_serves_after_a_warm_start() { + let app = App::new(&[ + ("package.json", r#"{"name":"warmvirt","version":"1.0.0"}"#), + ( + "index.html", + r#"t
"#, + ), + ("main.tsx", "export const app = \"hi\";\n"), + ("vite.config.js", VITE_CONFIG), + ]); + let cache = oj_cache::cache_root(&app.root); + + // Cold: the transform runs, the virtual is populated and served. + { + let server = serve_cached(&app).await; + let main = server.text("/main.tsx").await; + let virt = virt_url_from(&main); + let css = server.get(&virt).await; + assert_eq!(css.status, 200, "cold: virtual css serves:\n{}", css.body); + let ctype = css + .headers + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or_default(); + assert!( + ctype.contains("javascript"), + "cold: virtual css wrapped as a JS module: {ctype}" + ); + assert!( + css.body.contains("rebeccapurple"), + "cold: extracted CSS present:\n{}", + css.body + ); + + let deadline = tokio::time::Instant::now() + Duration::from_secs(10); + // Relocatable entries persist to the shared store, pinned ones to + // the app's cache. + while !cached_module_contains(&cache, ".stateful.css") + && !cached_module_contains(&crate::store_modules_dir(), ".stateful.css") + { + assert!( + tokio::time::Instant::now() < deadline, + "the cold run never persisted main.tsx under {}", + cache.display() + ); + tokio::time::sleep(Duration::from_millis(50)).await; + } + if let Some(host) = &server.built.plugin_host { + host.shutdown(); + } + } + + // Warm: cache kept, fresh plugin host (empty map). The re-transform must + // repopulate the virtual so it serves instead of 404ing. + assert!(cache.exists(), "cache persisted for the warm run"); + let server = serve_cached(&app).await; + let main = server.text("/main.tsx").await; + let virt = virt_url_from(&main); + let css = server.get(&virt).await; + assert_eq!( + css.status, 200, + "warm: virtual css must still serve (was 404 before the fix):\n{}", + css.body + ); + assert!( + css.body.contains("rebeccapurple"), + "warm: extracted CSS present:\n{}", + css.body + ); +} diff --git a/crates/oj_stylex/src/options.rs b/crates/oj_stylex/src/options.rs index f8fbbee0d..7c419ad56 100644 --- a/crates/oj_stylex/src/options.rs +++ b/crates/oj_stylex/src/options.rs @@ -1,4 +1,4 @@ -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::sync::Arc; use serde_json::Value; @@ -190,6 +190,45 @@ impl ResolvedOptions { .get(index) .map(ImportSource::from_specifier) } + + /// Recomputes [`Self::cache_repr`] with the paths under `root` (the + /// `rootDir` and alias targets) spelled `/`. The compile names + /// a file by its package- or rootDir-relative path, never absolutely, so + /// two checkouts whose options differ only in where the checkout lives + /// compile identically and may share cache entries. A path outside + /// `root` keeps its absolute spelling. + pub fn relocate_cache_repr(&mut self, root: &Path) { + let canonical = std::fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf()); + let rel = |p: &Path| { + [root, canonical.as_path()].iter().find_map(|r| { + let rest = p.strip_prefix(r).ok()?; + Some(format!( + "/{}", + rest.to_string_lossy().replace('\\', "/") + )) + }) + }; + let mut copy = self.clone(); + copy.cache_repr = String::new(); + if let Some(dir) = copy + .unstable_module_resolution + .as_mut() + .and_then(|m| m.root_dir.as_mut()) + && let Some(r) = rel(dir) + { + *dir = PathBuf::from(r); + } + if let Some(aliases) = copy.aliases.as_mut() { + for (_, targets) in Arc::make_mut(aliases).iter_mut() { + for target in targets.iter_mut() { + if let Some(r) = rel(Path::new(target.as_str())) { + *target = r; + } + } + } + } + self.cache_repr = format!("{copy:?}"); + } } impl Default for ResolvedOptions { diff --git a/crates/oj_stylex/src/plugin.rs b/crates/oj_stylex/src/plugin.rs index adf81723d..3fe5647f4 100644 --- a/crates/oj_stylex/src/plugin.rs +++ b/crates/oj_stylex/src/plugin.rs @@ -183,9 +183,12 @@ impl StylexPlugin { } }); let compiler = Value::Object(compiler); - let options = CompilerOptions::from_json(&compiler) + let mut options = CompilerOptions::from_json(&compiler) .and_then(|o| o.resolve()) .map_err(|e| format!("{PLUGIN_NAME}: {e}"))?; + // The default rootDir is the app root: keyed absolutely, no two + // checkouts of an app would ever share a compiled module. + options.relocate_cache_repr(root); let mut sheet = Map::new(); sheet.insert( "useLayers".into(), @@ -200,9 +203,10 @@ impl StylexPlugin { .map_err(|e| format!("{PLUGIN_NAME}: {e}"))?; let fingerprint = blake3::hash( format!( - "{}:{}:{compiler}", + "{}:{}:{}", crate::cache::compiler_fingerprint(), - options.cache_repr + options.cache_repr, + root_relative_json(&compiler, root) ) .as_bytes(), ) @@ -392,6 +396,32 @@ impl StylexPlugin { /// depend on an import source's package (or `@stylexjs/stylex`), plus /// `externalPackages`. Vite keeps them out of dependency pre-bundling, so the /// transform reaches their modules. Found from the package.json nearest +/// `value` with every string naming a path under `root` spelled +/// `/`, for keys that must agree across checkouts of one app (see +/// [`crate::options::ResolvedOptions::relocate_cache_repr`]). +fn root_relative_json(value: &Value, root: &Path) -> Value { + let canonical = std::fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf()); + fn walk(v: &Value, roots: &[&Path]) -> Value { + match v { + Value::String(s) => roots + .iter() + .find_map(|r| Path::new(s).strip_prefix(r).ok()) + .map_or_else( + || v.clone(), + |rest| Value::String(format!("/{}", rest.to_string_lossy())), + ), + Value::Array(items) => Value::Array(items.iter().map(|i| walk(i, roots)).collect()), + Value::Object(map) => Value::Object( + map.iter() + .map(|(k, v)| (k.clone(), walk(v, roots))) + .collect(), + ), + other => other.clone(), + } + } + walk(value, &[root, canonical.as_path()]) +} + /// `root`, each dependency where Node's `require.resolve("/package.json")` /// would find it. pub fn dependency_packages(user: &Value, root: &Path) -> Vec { @@ -683,6 +713,42 @@ mod tests { StylexPlugin::new(&user, Path::new("/app"), false, false).unwrap() } + // The fingerprint keys every compiled module of a StyleX app: two + // checkouts of one app must agree on it, while options that change the + // compile, a rootDir outside the app among them, still move it. + #[test] + fn the_fingerprint_is_the_same_in_every_checkout() { + let at = |root: &str, user: Value| { + StylexPlugin::new(&user, Path::new(root), false, false) + .unwrap() + .fingerprint() + .to_string() + }; + let aliased = |root: &str| json!({ "aliases": { "@/*": [format!("{root}/src/*")] } }); + assert_eq!(at("/wt-a/app", json!({})), at("/wt-b/app", json!({}))); + assert_eq!( + at("/wt-a/app", aliased("/wt-a/app")), + at("/wt-b/app", aliased("/wt-b/app")) + ); + assert_ne!( + at("/wt-a/app", json!({})), + at("/wt-a/app", aliased("/wt-a/app")) + ); + assert_ne!( + at("/wt-a/app", json!({})), + at("/wt-a/app", json!({ "classNamePrefix": "q" })) + ); + let pinned = + json!({ "unstable_moduleResolution": { "type": "commonJS", "rootDir": "/shared/a" } }); + let other = + json!({ "unstable_moduleResolution": { "type": "commonJS", "rootDir": "/shared/b" } }); + assert_ne!( + at("/wt-a/app", pinned), + at("/wt-a/app", other), + "a rootDir outside the app keys absolutely" + ); + } + #[test] fn gate_is_the_plugins_include_and_import_scan() { let p = plugin(json!({})); diff --git a/e2e/cross-worktree-cache.mjs b/e2e/cross-worktree-cache.mjs new file mode 100644 index 000000000..9483944e9 --- /dev/null +++ b/e2e/cross-worktree-cache.mjs @@ -0,0 +1,184 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2026 Raphael Amorim +// +// pulp P1 capstone: two worktrees with identical content share one module +// store. Worktree A compiles and populates the shared store; worktree B, a +// fresh directory that has never built anything, must serve byte-identical +// modules WITHOUT recompiling (the store's entries stay untouched), and +// nothing served may contain either worktree's absolute path. + +import { spawn, execSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import assert from "node:assert/strict"; +import { fileURLToPath } from "node:url"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const repo = path.join(here, ".."); +const oj = path.join(repo, "target", "debug", "oj"); +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +execSync("cargo build -p oj", { cwd: repo, stdio: "inherit" }); + +// One isolated shared store for this test run. +const store = fs.mkdtempSync(path.join(os.tmpdir(), "oj-xwt-store-")); +const modulesDir = path.join(store, "v1", "modules"); + +function makeApp(label) { + const app = fs.mkdtempSync(path.join(os.tmpdir(), `oj-xwt-${label}-`)); + fs.mkdirSync(path.join(app, "src"), { recursive: true }); + fs.writeFileSync(path.join(app, "package.json"), JSON.stringify({ name: "xwt", version: "1.0.0" })); + fs.writeFileSync(path.join(app, "package-lock.json"), JSON.stringify({ lockfileVersion: 3 })); + fs.writeFileSync( + path.join(app, "index.html"), + `x
`, + ); + fs.writeFileSync(path.join(app, "main.tsx"), `import { App } from "./src/App.tsx";\nconsole.log(App);\n`); + // JSX so the dev __source/sourcemap path-independence is exercised. The + // automatic runtime needs a resolvable react: a tiny stub is enough (and + // identical in both worktrees, like a real install would be). + fs.writeFileSync( + path.join(app, "src", "App.tsx"), + `export function App() {\n return
hello
;\n}\n`, + ); + const react = path.join(app, "node_modules", "react"); + fs.mkdirSync(react, { recursive: true }); + fs.writeFileSync( + path.join(react, "package.json"), + JSON.stringify({ + name: "react", + version: "19.0.0", + exports: { + ".": "./index.js", + "./jsx-runtime": "./jsx-runtime.js", + "./jsx-dev-runtime": "./jsx-dev-runtime.js", + }, + }), + ); + fs.writeFileSync(path.join(react, "index.js"), "export default {};\n"); + const rt = + "export const Fragment = Symbol.for('react.fragment');\nexport function jsxDEV(t, p) { return { t, p }; }\nexport const jsx = jsxDEV;\nexport const jsxs = jsxDEV;\n"; + fs.writeFileSync(path.join(react, "jsx-runtime.js"), rt); + fs.writeFileSync(path.join(react, "jsx-dev-runtime.js"), rt); + return app; +} + +function listModuleEntries() { + const out = new Map(); + let shards; + try { + shards = fs.readdirSync(modulesDir); + } catch { + return out; + } + for (const shard of shards) { + const dir = path.join(modulesDir, shard); + if (!/^[0-9a-f]{2}$/.test(shard) || !fs.statSync(dir).isDirectory()) continue; + for (const f of fs.readdirSync(dir)) { + if (f.endsWith(".json")) out.set(`${shard}/${f}`, fs.statSync(path.join(dir, f)).mtimeMs); + } + } + return out; +} + +function localModuleEntries(app) { + let n = 0; + const root = path.join(app, ".oj-cache"); + const walk = (dir) => { + let ents; + try { + ents = fs.readdirSync(dir, { withFileTypes: true }); + } catch { + return; + } + for (const e of ents) { + const p = path.join(dir, e.name); + if (e.isDirectory()) walk(p); + else if (e.isFile() && e.name.endsWith(".json") && /^[0-9a-f]{2}$/.test(path.basename(dir))) n++; + } + }; + walk(root); + return n; +} + +async function serveAndFetch(app, port) { + const log = path.join(app, "server.log"); + const logFd = fs.openSync(log, "w"); + const proc = spawn(oj, ["dev", app, "--port", String(port), "--store"], { + stdio: ["ignore", logFd, logFd], + env: { ...process.env, OJ_STORE_DIR: store }, + }); + try { + let up = false; + for (let i = 0; i < 120 && !up; i++) { + try { + up = (await fetch(`http://localhost:${port}/`)).ok; + } catch {} + if (!up) await sleep(100); + } + assert.ok(up, "oj never came up"); + const bodies = {}; + for (const url of ["/main.tsx", "/src/App.tsx"]) { + const r = await fetch(`http://localhost:${port}${url}`); + if (r.status !== 200) console.error(fs.readFileSync(log, "utf8")); + assert.equal(r.status, 200, `${url} serves`); + bodies[url] = await r.text(); + } + // Cache writes are async; give the writer a moment. + for (let i = 0; i < 30 && listModuleEntries().size < 2; i++) await sleep(150); + await sleep(300); + return bodies; + } finally { + try { + execSync(`pkill -P ${proc.pid}`); + } catch {} + try { + proc.kill("SIGKILL"); + } catch {} + try { + execSync(`lsof -ti:${port} -sTCP:LISTEN | xargs -r kill -9`); + } catch {} + await sleep(500); + } +} + +let failed = false; +try { + const appA = makeApp("a"); + const appB = makeApp("b"); + + // Worktree A compiles and populates the shared store. + const bodiesA = await serveAndFetch(appA, 5317); + const afterA = listModuleEntries(); + assert.ok(afterA.size >= 2, `worktree A must populate the shared store (got ${afterA.size} entries)`); + + // Worktree B has never built anything. + const bodiesB = await serveAndFetch(appB, 5318); + const afterB = listModuleEntries(); + + for (const url of ["/main.tsx", "/src/App.tsx"]) { + assert.equal(bodiesB[url], bodiesA[url], `${url}: worktree B must serve worktree A's exact bytes`); + assert.ok( + !bodiesB[url].includes(appA) && !bodiesB[url].includes(appB), + `${url}: served module must contain no worktree path`, + ); + } + assert.ok(bodiesB["/src/App.tsx"].includes("/src/App.tsx"), "jsx __source / map name the module by its served path"); + + // The store proves B hit instead of recompiling: no new entries, and no + // entry rewritten (identical mtimes). + assert.equal(afterB.size, afterA.size, "worktree B must add no module entries"); + for (const [name, mtime] of afterA) { + assert.equal(afterB.get(name), mtime, `entry ${name} must not be rewritten by a hit`); + } + // And nothing landed in B's per-app cache: every entry was relocatable. + assert.equal(localModuleEntries(appB), 0, "no pinned entries for this app shape"); + + console.log(`CROSS-WORKTREE CACHE VERIFIED: ${afterA.size} shared entries, B served A's bytes, zero recompiles`); +} catch (err) { + failed = true; + console.error(`FAIL: ${err.message}`); +} finally { + process.exit(failed ? 1 : 0); +} diff --git a/e2e/start-css-modules.mjs b/e2e/start-css-modules.mjs index d1e45aeb0..dfccb5ebd 100644 --- a/e2e/start-css-modules.mjs +++ b/e2e/start-css-modules.mjs @@ -194,14 +194,28 @@ try { html.includes("css-module-badge"), `dev /about did not render:\n${html.slice(0, 800)}\n---\n${log.slice(-1500)}`, ); - const chunks = filesUnder(path.join(app, ".oj-cache"), ".js").map((f) => fs.readFileSync(f, "utf8")); + // The served client bundle, by its chunk index: a boot that restored the + // bundle from the oj store serves the chunks from there, not the build dir. + const startDir = path.join(app, ".oj-cache", "v1", "start"); + const index = JSON.parse(fs.readFileSync(path.join(startDir, "client-chunks.json"), "utf8")); + const chunks = await Promise.all( + index.files + .filter((f) => f.name.endsWith(".js")) + .map(async (f) => (await fetch(`http://localhost:${PORT}/@oj-start/${f.name}`)).text()), + ); const hrefs = [...html.matchAll(/]*rel="stylesheet"[^>]*href="([^"]+)"/g)].map((m) => m[1]); const sheets = await Promise.all( hrefs.map(async (h) => (await fetch(new URL(h, `http://localhost:${PORT}/`))).text()), ); const devClasses = checkStyles("dev", html, chunks, sheets); - const hero = fs.realpathSync(path.join(app, "src", "hero.png")); - checkInline("dev", html, chunks, (u) => u === `/@oj-start/fs${hero}`); + // In-root assets are served root-relative (`@ws/`), the same in every + // worktree; the URL must still serve the image. + checkInline("dev", html, chunks, (u) => u === "/@oj-start/fs/@ws/src/hero.png"); + const heroRes = await fetch(`http://localhost:${PORT}/@oj-start/fs/@ws/src/hero.png`); + must( + heroRes.ok && Buffer.from(await heroRes.arrayBuffer()).equals(fs.readFileSync(path.join(app, "src", "hero.png"))), + `dev: the inline sheet's image url does not serve the image (${heroRes.status})`, + ); console.log(`start dev: ${Object.values(devClasses).join(", ")} agree on server, client and sheet`); srv.kill("SIGKILL"); diff --git a/e2e/store-concurrent.mjs b/e2e/store-concurrent.mjs new file mode 100644 index 000000000..d981e138f --- /dev/null +++ b/e2e/store-concurrent.mjs @@ -0,0 +1,169 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2026 Raphael Amorim +// +// Two `oj dev --store` processes on one empty store at once, two checkouts +// of one app, hammered in parallel: every module serves the same bytes from +// both, no entry in the store is torn and no temp file is left behind. One +// server is then killed mid-burst (SIGKILL, as a sandbox dies) and a third +// boots in its place over the same store and serves the same bytes. + +import { spawn, execSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import assert from "node:assert/strict"; +import { fileURLToPath } from "node:url"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const repo = path.join(here, ".."); +const oj = path.join(repo, "target", "debug", "oj"); +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +execSync("cargo build -p oj", { cwd: repo, stdio: "inherit" }); + +const store = fs.mkdtempSync(path.join(os.tmpdir(), "oj-concurrent-store-")); +const modulesDir = path.join(store, "v1", "modules"); +const MODULES = 24; + +function makeApp(label) { + const app = fs.mkdtempSync(path.join(os.tmpdir(), `oj-concurrent-${label}-`)); + fs.mkdirSync(path.join(app, "src"), { recursive: true }); + fs.writeFileSync(path.join(app, "package.json"), JSON.stringify({ name: "concurrent", version: "1.0.0" })); + fs.writeFileSync(path.join(app, "package-lock.json"), JSON.stringify({ lockfileVersion: 3 })); + fs.writeFileSync( + path.join(app, "index.html"), + `c`, + ); + const imports = []; + for (let i = 0; i < MODULES; i++) { + fs.writeFileSync( + path.join(app, "src", `m${i}.ts`), + `import { base } from "./base";\nexport const m${i}: string = base + "-" + ${i} + "-" + ${"x".repeat(40)}.length;\n`, + ); + imports.push(`import { m${i} } from "./m${i}";`); + } + fs.writeFileSync(path.join(app, "src", "base.ts"), `export const base: string = "base";\n`); + fs.writeFileSync(path.join(app, "src", "main.ts"), `${imports.join("\n")}\nconsole.log(${Array.from({ length: MODULES }, (_, i) => `m${i}`).join(", ")});\n`); + return app; +} + +const urls = ["/src/main.ts", "/src/base.ts", ...Array.from({ length: MODULES }, (_, i) => `/src/m${i}.ts`)]; + +function start(app, port) { + const log = path.join(app, `server-${port}.log`); + const fd = fs.openSync(log, "a"); + const proc = spawn(oj, ["dev", app, "--port", String(port), "--store"], { + stdio: ["ignore", fd, fd], + env: { ...process.env, OJ_STORE_DIR: store }, + }); + return { proc, port, log }; +} + +async function waitUp(server) { + for (let i = 0; i < 200; i++) { + try { + if ((await fetch(`http://localhost:${server.port}/`)).ok) return; + } catch {} + if (server.proc.exitCode !== null) break; + await sleep(100); + } + throw new Error(`server on ${server.port} never came up:\n${fs.readFileSync(server.log, "utf8").slice(-2000)}`); +} + +async function burst(server) { + const shuffled = [...urls].sort(() => Math.random() - 0.5); + const bodies = await Promise.all( + shuffled.map(async (url) => { + const r = await fetch(`http://localhost:${server.port}${url}`); + assert.equal(r.status, 200, `${url} on ${server.port}`); + return [url, await r.text()]; + }), + ); + return new Map(bodies); +} + +function kill(server) { + try { + execSync(`pkill -P ${server.proc.pid}`); + } catch {} + try { + server.proc.kill("SIGKILL"); + } catch {} + try { + execSync(`lsof -ti:${server.port} -sTCP:LISTEN | xargs -r kill -9`); + } catch {} +} + +function storeEntries() { + const out = []; + let shards; + try { + shards = fs.readdirSync(modulesDir); + } catch { + return out; + } + for (const shard of shards) { + for (const f of fs.readdirSync(path.join(modulesDir, shard))) out.push(path.join(modulesDir, shard, f)); + } + return out; +} + +function checkStoreWhole(when) { + const entries = storeEntries(); + const tmp = entries.filter((p) => path.basename(p).includes("tmp")); + assert.equal(tmp.length, 0, `${when}: temp files left in the store: ${tmp.join(", ")}`); + for (const p of entries) { + let parsed; + try { + parsed = JSON.parse(fs.readFileSync(p, "utf8")); + } catch (e) { + assert.fail(`${when}: torn entry ${p}: ${e.message}`); + } + assert.equal(typeof parsed.code, "string", `${when}: ${p} is no module`); + } + return entries.length; +} + +let failed = false; +const servers = []; +try { + const appA = makeApp("a"); + const appB = makeApp("b"); + const a = start(appA, 5331); + const b = start(appB, 5332); + servers.push(a, b); + await Promise.all([waitUp(a), waitUp(b)]); + + // Both servers compile the same cold app at once and race into the store. + for (let round = 0; round < 4; round++) { + const [fromA, fromB] = await Promise.all([burst(a), burst(b)]); + for (const url of urls) { + assert.equal(fromB.get(url), fromA.get(url), `round ${round}: ${url} differs between the servers`); + assert.ok(!fromA.get(url).includes(appA) && !fromA.get(url).includes(appB), `${url} names a checkout`); + } + } + const settled = checkStoreWhole("after the bursts"); + assert.ok(settled >= urls.length, `expected at least ${urls.length} entries, got ${settled}`); + + // A kills mid-burst; B keeps serving; C boots over the same store in A's place. + const dying = burst(a).catch(() => null); + await sleep(30); + kill(a); + await dying; + const stillB = await burst(b); + checkStoreWhole("after the kill"); + const c = start(appA, 5333); + servers.push(c); + await waitUp(c); + const fromC = await burst(c); + for (const url of urls) assert.equal(fromC.get(url), stillB.get(url), `${url} differs after the restart`); + checkStoreWhole("after the restart"); + console.log(`PASS store-concurrent (${urls.length} modules, ${settled} store entries, a kill survived)`); +} catch (err) { + failed = true; + console.error(`FAIL store-concurrent: ${err.message}`); +} finally { + for (const s of servers) kill(s); + await sleep(300); + process.exit(failed ? 1 : 0); +} diff --git a/e2e/store-flag.mjs b/e2e/store-flag.mjs new file mode 100644 index 000000000..4b921576f --- /dev/null +++ b/e2e/store-flag.mjs @@ -0,0 +1,116 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2026 Raphael Amorim +// +// `oj dev --store[=DIR]` is the one switch for the oj store: it turns the +// persistent module cache on and (with DIR) relocates the shared store. This +// proves the flag alone persists modules into the given store, that the +// entries are relocatable (nothing lands in the app's own cache), and that +// without the flag nothing persists at all, wherever `OJ_STORE_DIR` points. + +import { spawn, execSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import assert from "node:assert/strict"; +import { fileURLToPath } from "node:url"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const repo = path.join(here, ".."); +const oj = path.join(repo, "target", "debug", "oj"); +const port = 5321; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +execSync("cargo build -p oj", { cwd: repo, stdio: "inherit" }); + +const app = fs.mkdtempSync(path.join(os.tmpdir(), "oj-storeflag-")); +const store = fs.mkdtempSync(path.join(os.tmpdir(), "oj-storeflag-store-")); +fs.writeFileSync(path.join(app, "package.json"), JSON.stringify({ name: "sf", version: "1.0.0" })); +fs.writeFileSync( + path.join(app, "index.html"), + `t`, +); +fs.writeFileSync(path.join(app, "main.tsx"), `export const value: number = 41 + 1;\nconsole.log(value);\n`); + +// The flag must work with NO env help: strip the store var. +const env = { ...process.env }; +delete env.OJ_STORE_DIR; + +function entriesUnder(root) { + let n = 0; + const walk = (dir) => { + let ents; + try { + ents = fs.readdirSync(dir, { withFileTypes: true }); + } catch { + return; + } + for (const e of ents) { + const p = path.join(dir, e.name); + if (e.isDirectory()) walk(p); + else if (e.isFile() && e.name.endsWith(".json") && /^[0-9a-f]{2}$/.test(path.basename(dir))) n++; + } + }; + walk(root); + return n; +} +const storeEntries = () => entriesUnder(path.join(store, "v1", "modules")); +const appEntries = () => entriesUnder(path.join(app, ".oj-cache")); + +async function runAndCount(args, runEnv = env) { + fs.rmSync(path.join(app, ".oj-cache"), { recursive: true, force: true }); + fs.rmSync(path.join(store, "v1"), { recursive: true, force: true }); + const proc = spawn(oj, ["dev", app, "--port", String(port), ...args], { + stdio: "ignore", + env: runEnv, + }); + try { + let up = false; + for (let i = 0; i < 120 && !up; i++) { + try { + up = (await fetch(`http://localhost:${port}/`)).ok; + } catch {} + if (!up) await sleep(100); + } + assert.ok(up, "oj never came up"); + const r = await fetch(`http://localhost:${port}/main.tsx`); + assert.equal(r.status, 200, "module serves"); + for (let i = 0; i < 20 && storeEntries() === 0; i++) await sleep(150); + await sleep(300); + return { store: storeEntries(), app: appEntries() }; + } finally { + try { + execSync(`pkill -P ${proc.pid}`); + } catch {} + try { + proc.kill("SIGKILL"); + } catch {} + try { + execSync(`lsof -ti:${port} -sTCP:LISTEN | xargs -r kill -9`); + } catch {} + await sleep(500); + } +} + +let failed = false; +try { + const withStore = await runAndCount([`--store=${store}`]); + assert.ok(withStore.store > 0, `--store=DIR must persist module entries into DIR (got ${withStore.store})`); + assert.equal(withStore.app, 0, `relocatable entries belong to the store, not the app (got ${withStore.app})`); + + // Without the flag the store is off, even with OJ_STORE_DIR pointing at one. + const without = await runAndCount([], { ...env, OJ_STORE_DIR: store }); + assert.equal( + without.store + without.app, + 0, + `without --store nothing persists (got ${without.store + without.app} entries)`, + ); + + console.log( + `PASS store-flag (--store wrote ${withStore.store} entries to the store, 0 to the app; without it 0)`, + ); +} catch (err) { + failed = true; + console.error(`FAIL store-flag: ${err.message}`); +} finally { + process.exit(failed ? 1 : 0); +} diff --git a/e2e/store-remote.mjs b/e2e/store-remote.mjs new file mode 100644 index 000000000..00ac04312 --- /dev/null +++ b/e2e/store-remote.mjs @@ -0,0 +1,203 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2026 Raphael Amorim +// +// pulp P3, the wire: `oj store serve` is a six-endpoint substituter; dev +// servers read through it on local misses and push relocatable entries with +// a write token. This runs the whole fleet loop — worktree A compiles and +// pushes; worktree B, with an EMPTY local store at a different absolute +// path, serves A's exact bytes via the remote and back-fills its local +// store — plus the protocol's contract: write-once (409), token gating +// (401), and CAS self-verification (422 on digest mismatch). + +import { spawn, execSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import assert from "node:assert/strict"; +import { fileURLToPath } from "node:url"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const repo = path.join(here, ".."); +const oj = path.join(repo, "target", "debug", "oj"); +const SRV_PORT = 5398; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +execSync("cargo build -p oj", { cwd: repo, stdio: "inherit" }); + +const WRITE_TOKEN = "e2e-write-secret"; +const srvDir = fs.mkdtempSync(path.join(os.tmpdir(), "oj-remote-srv-")); + +function makeApp(label) { + const app = fs.mkdtempSync(path.join(os.tmpdir(), `oj-remote-${label}-`)); + fs.writeFileSync(path.join(app, "package.json"), JSON.stringify({ name: "rw", version: "1.0.0" })); + fs.writeFileSync(path.join(app, "package-lock.json"), JSON.stringify({ lockfileVersion: 3 })); + fs.writeFileSync( + path.join(app, "index.html"), + `t`, + ); + fs.writeFileSync(path.join(app, "main.tsx"), `export const value: number = 41 + 1;\nconsole.log(value);\n`); + return app; +} + +function countEntries(dir) { + let n = 0; + const walk = (d) => { + let ents; + try { + ents = fs.readdirSync(d, { withFileTypes: true }); + } catch { + return; + } + for (const e of ents) { + if (e.isDirectory()) walk(path.join(d, e.name)); + else if (e.name.endsWith(".json")) n++; + } + }; + walk(dir); + return n; +} + +async function devAndFetch(app, store, port, extraEnv) { + const env = { ...process.env, ...extraEnv }; + delete env.OJ_STORE_DIR; + const proc = spawn(oj, ["dev", app, "--port", String(port), `--store=${store}`], { + stdio: "ignore", + env, + }); + try { + let up = false; + for (let i = 0; i < 150 && !up; i++) { + try { + up = (await fetch(`http://localhost:${port}/`)).ok; + } catch {} + if (!up) await sleep(100); + } + assert.ok(up, "dev server never came up"); + const r = await fetch(`http://localhost:${port}/main.tsx`); + assert.equal(r.status, 200); + const body = await r.text(); + await sleep(1200); // cache writer + push queue + return body; + } finally { + try { + execSync(`pkill -P ${proc.pid}`); + } catch {} + try { + proc.kill("SIGKILL"); + } catch {} + try { + execSync(`lsof -ti:${port} -sTCP:LISTEN | xargs -r kill -9`); + } catch {} + await sleep(400); + } +} + +// ---- the substituter ---- +const srv = spawn(oj, ["store", "serve", "--dir", srvDir, "--port", String(SRV_PORT)], { + stdio: "ignore", + env: { ...process.env, OJ_STORE_WRITE_TOKEN: WRITE_TOKEN }, +}); + +let failed = false; +try { + let up = false; + for (let i = 0; i < 100 && !up; i++) { + try { + up = ( + await fetch(`http://localhost:${SRV_PORT}/v1/cas/missing`, { + method: "POST", + body: JSON.stringify({ digests: [] }), + }) + ).ok; + } catch {} + if (!up) await sleep(100); + } + assert.ok(up, "store server never came up"); + const base = `http://localhost:${SRV_PORT}`; + + // ---- protocol contract ---- + const hex = (s) => s.padEnd(64, "0"); + // AC: write without token refused; write-once; read back. + const key = hex("ab"); + let r = await fetch(`${base}/v1/ac/modules/${key}`, { method: "PUT", body: "{}" }); + assert.equal(r.status, 401, "AC PUT without token must be refused"); + r = await fetch(`${base}/v1/ac/modules/${key}`, { + method: "PUT", + headers: { authorization: `Bearer ${WRITE_TOKEN}` }, + body: JSON.stringify({ probe: 1 }), + }); + assert.equal(r.status, 201, "first AC PUT publishes"); + r = await fetch(`${base}/v1/ac/modules/${key}`, { + method: "PUT", + headers: { authorization: `Bearer ${WRITE_TOKEN}` }, + body: JSON.stringify({ probe: 2 }), + }); + assert.equal(r.status, 409, "AC entries are write-once"); + r = await fetch(`${base}/v1/ac/modules/${key}`); + assert.deepEqual(await r.json(), { probe: 1 }, "the first write is what reads back"); + + // CAS: digest mismatch refused; publish + HEAD + missing. + const blob = "hello store"; + const digest = execSync(`printf '%s' "${blob}" | b3sum --no-names 2>/dev/null || true`).toString().trim(); + if (digest.length === 64) { + r = await fetch(`${base}/v1/cas/${hex("ff")}`, { + method: "PUT", + headers: { authorization: `Bearer ${WRITE_TOKEN}` }, + body: blob, + }); + assert.equal(r.status, 422, "a CAS name must be its content's digest"); + r = await fetch(`${base}/v1/cas/${digest}`, { + method: "PUT", + headers: { authorization: `Bearer ${WRITE_TOKEN}` }, + body: blob, + }); + assert.equal(r.status, 201); + r = await fetch(`${base}/v1/cas/${digest}`, { method: "HEAD" }); + assert.equal(r.status, 200); + r = await fetch(`${base}/v1/cas/missing`, { + method: "POST", + body: JSON.stringify({ digests: [digest, hex("ee")] }), + }); + assert.deepEqual(await r.json(), { missing: [hex("ee")] }); + } + + // ---- the fleet loop ---- + const appA = makeApp("a"); + const appB = makeApp("b"); + const storeA = fs.mkdtempSync(path.join(os.tmpdir(), "oj-remote-storeA-")); + const storeB = fs.mkdtempSync(path.join(os.tmpdir(), "oj-remote-storeB-")); + + const bodyA = await devAndFetch(appA, storeA, 5396, { + OJ_STORE_REMOTE: base, + OJ_STORE_TOKEN: WRITE_TOKEN, + OJ_STORE_PUSH: "1", + }); + const pushed = countEntries(path.join(srvDir, "ac", "modules")); + assert.ok(pushed > 0, `worktree A must push its module entries (got ${pushed})`); + + // B: different absolute path, EMPTY local store, read-only remote access. + assert.equal(countEntries(path.join(storeB, "v1", "modules")), 0); + const bodyB = await devAndFetch(appB, storeB, 5397, { + OJ_STORE_REMOTE: base, + }); + assert.equal(bodyB, bodyA, "worktree B must serve worktree A's exact bytes via the wire"); + assert.ok(countEntries(path.join(storeB, "v1", "modules")) > 0, "the read-through must back-fill B's local store"); + + console.log( + `PASS store-remote (write-once 409, tokens 401, CAS 422, A pushed ${pushed} entries, B served A's bytes from the wire and back-filled locally)`, + ); +} catch (err) { + failed = true; + console.error(`FAIL store-remote: ${err.message}`); +} finally { + try { + execSync(`pkill -P ${srv.pid}`); + } catch {} + try { + srv.kill("SIGKILL"); + } catch {} + try { + execSync(`lsof -ti:${SRV_PORT} -sTCP:LISTEN | xargs -r kill -9`); + } catch {} + process.exit(failed ? 1 : 0); +} diff --git a/e2e/trace-staleness.mjs b/e2e/trace-staleness.mjs new file mode 100644 index 000000000..80fd5b846 --- /dev/null +++ b/e2e/trace-staleness.mjs @@ -0,0 +1,163 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2026 Raphael Amorim +// +// pulp P2 constructive traces: a plugin transform that READS a side file +// (without declaring it) bakes that file's content into its output. Before +// traces, a warm restart served the stale output after the side file changed; +// now the cached entry records the read with a digest and a mismatch is a +// miss. This runs the exact scenario: serve v1, warm-restart (still v1, from +// cache), edit the side file, warm-restart again, and demand v2. + +import { spawn, execSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import assert from "node:assert/strict"; +import { fileURLToPath } from "node:url"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const repo = path.join(here, ".."); +const oj = path.join(repo, "target", "debug", "oj"); +const port = 5323; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +execSync("cargo build -p oj", { cwd: repo, stdio: "inherit" }); + +const app = fs.mkdtempSync(path.join(os.tmpdir(), "oj-trace-")); +const store = fs.mkdtempSync(path.join(os.tmpdir(), "oj-trace-store-")); +fs.writeFileSync(path.join(app, "package.json"), JSON.stringify({ name: "trace", version: "1.0.0" })); +fs.writeFileSync( + path.join(app, "index.html"), + `t`, +); +fs.writeFileSync( + path.join(app, "main.tsx"), + `export const banner: string = "__EXTRA__/__NAMED__";\nconsole.log(banner);\n`, +); +fs.writeFileSync(path.join(app, "extra.txt"), "v1"); +fs.writeFileSync(path.join(app, "named.txt"), "n1"); +// A second module whose only dynamic input is an import.meta.glob listing. +fs.mkdirSync(path.join(app, "globbed")); +fs.writeFileSync(path.join(app, "globbed", "a.ts"), "export const a = 1;\n"); +fs.writeFileSync(path.join(app, "glob.tsx"), `export const mods = import.meta.glob("./globbed/*.ts");\n`); +// A plugin that reads TWO side files the cache key knows nothing about: +// extra.txt through the default node:fs import (the JS-level patched module +// object sees it) and named.txt through a NAMED esm import (invisible to the +// JS patch under Deno; only the Rust TracingFs ops layer sees it). +fs.writeFileSync( + path.join(app, "oj.plugins.mjs"), + `import fsmod from "node:fs"; +import { readFileSync as namedRead } from "node:fs"; +export default [ + { + name: "side-file-injector", + transform(code, id) { + if (!id.split("?")[0].endsWith("main.tsx")) return null; + const extra = fsmod.readFileSync(${JSON.stringify(path.join(app, "extra.txt"))}, "utf8").trim(); + const named = namedRead(${JSON.stringify(path.join(app, "named.txt"))}, "utf8").trim(); + return { code: code.replace("__EXTRA__", extra).replace("__NAMED__", named), map: null }; + }, + }, +]; +`, +); + +const env = { ...process.env, OJ_STORE_DIR: store }; + +async function bootAndFetch(extraEnv = {}, url = "/main.tsx") { + const proc = spawn(oj, ["dev", app, "--port", String(port), "--store"], { + stdio: "ignore", + env: { ...env, ...extraEnv }, + }); + try { + let up = false; + for (let i = 0; i < 150 && !up; i++) { + try { + up = (await fetch(`http://localhost:${port}/`)).ok; + } catch {} + if (!up) await sleep(100); + } + assert.ok(up, "oj never came up"); + const r = await fetch(`http://localhost:${port}${url}`); + assert.equal(r.status, 200); + const body = await r.text(); + await sleep(600); // async cache writer + return body; + } finally { + try { + execSync(`pkill -P ${proc.pid}`); + } catch {} + try { + proc.kill("SIGKILL"); + } catch {} + try { + execSync(`lsof -ti:${port} -sTCP:LISTEN | xargs -r kill -9`); + } catch {} + await sleep(500); + } +} + +let failed = false; +try { + const first = await bootAndFetch(); + assert.ok(first.includes('"v1"') || first.includes("v1"), `cold boot bakes v1: ${first.slice(0, 200)}`); + + // Warm boot under the verifier: hits recompile and compare; a pure plugin + // must produce no divergence and identical output. + const warm = await bootAndFetch({ OJ_VERIFY_HITS: "1" }); + assert.ok(warm.includes("v1"), "unchanged side file: warm boot still serves v1 (from cache)"); + + fs.writeFileSync(path.join(app, "extra.txt"), "v2"); + const after = await bootAndFetch(); + assert.ok( + after.includes("v2") && !after.includes("v1/"), + `edited side file must re-transform, got: ${after.slice(0, 200)}`, + ); + + // The named-import file: only the Rust TracingFs layer can see this read. + fs.writeFileSync(path.join(app, "named.txt"), "n2"); + const afterNamed = await bootAndFetch(); + assert.ok( + afterNamed.includes("n2") && !afterNamed.includes("/n1"), + `named-esm-import side file must re-transform via TracingFs, got: ${afterNamed.slice(0, 200)}`, + ); + + // And deleting the side file must fail loudly, never serve stale. + fs.rmSync(path.join(app, "extra.txt")); + const gone = await bootAndFetch().then( + (b) => b, + () => "BOOT_FAILED_OK", + ); + assert.ok( + !gone.includes('"v2"') || gone.includes("error"), + "deleted side file must not serve the stale v2 module silently", + ); + + // Glob trace rows: an added file under an import.meta.glob pattern must + // re-expand across a warm restart (the silent stale case before glob rows). + const glob1 = await bootAndFetch({}, "/glob.tsx"); + assert.ok(glob1.includes("globbed/a.ts"), `glob lists a.ts: ${glob1.slice(0, 200)}`); + const globWarm = await bootAndFetch({}, "/glob.tsx"); + assert.ok(globWarm.includes("globbed/a.ts"), "unchanged listing still serves"); + fs.writeFileSync(path.join(app, "globbed", "b.ts"), "export const b = 2;\n"); + const glob2 = await bootAndFetch({}, "/glob.tsx"); + assert.ok( + glob2.includes("globbed/b.ts"), + `created file under the glob must re-expand on a warm boot: ${glob2.slice(0, 300)}`, + ); + fs.rmSync(path.join(app, "globbed", "a.ts")); + const glob3 = await bootAndFetch({}, "/glob.tsx"); + assert.ok( + !glob3.includes("globbed/a.ts") && glob3.includes("globbed/b.ts"), + `deleted file under the glob must drop out on a warm boot: ${glob3.slice(0, 300)}`, + ); + + console.log( + "PASS trace-staleness (warm hit, default-import edit re-transforms, NAMED-import edit re-transforms via TracingFs, no stale serve on delete, verifier clean on pure hits, glob add+delete re-expand)", + ); +} catch (err) { + failed = true; + console.error(`FAIL trace-staleness: ${err.message}`); +} finally { + process.exit(failed ? 1 : 0); +} From deba4dfa68617f30aec1dbf50ef84d9443f4b026 Mon Sep 17 00:00:00 2001 From: Raphael Amorim Date: Fri, 4 Dec 2026 00:34:34 +0000 Subject: [PATCH 2/3] oj store: a sheet's imports and listed directories in the trace, nothing of the store's work without it, a trust boundary and budgets A stylesheet's @imported files were graph imports and not trace rows, so an edit to one between sessions served the sheet with the old file inlined; they are rows now, with Sass partials and PostCSS deps. The directories a plugin listed, its existence checks, reads by URL, Buffer or descriptor, and relative paths are rows too, and a `/@fs/@mono/` import must name a file in the reader's workspace. Without --store a server did the store's work anyway: the dep ledger hashed every bundled file on each commit, the engine traced every read, the pipeline digested every row, the salt read the config graph and the writer thread ran. All of it is behind the flag now, and `oj dev` without it clears an inherited OJ_STORE_DIR for itself and its children. The key covers the tool build (version plus a source digest), the root's place in its workspace, linked packages by content and patch files by content. A whole-second mtime within two seconds before a compile counts as racy; a stamp with nanoseconds compares exactly. The store directory must be the user's own and not writable by others; temp files are exclusive with a random suffix; the modules directory has a 2 GiB budget and a stale-temp sweep, the shared bytecode directory a 1 GiB one and the V8 flags in its name; Start pins name the process and the generation window is per app and config. The wire compares tokens in constant time, admits only servable entries, keeps a quota, purges on DELETE, streams off the runtime; its client trips on slow answers, probes after a cooldown, bounds its push queue and never asks for a stamped key. --- CHANGELOG.md | 7 +- README.md | 11 +- crates/oj/src/main.rs | 95 ++- crates/oj_cache/src/integrity.rs | 48 +- crates/oj_cache/src/lib.rs | 364 ++++++++++- crates/oj_cache/src/start_bundle/mod.rs | 51 +- crates/oj_cache/src/start_bundle/persist.rs | 34 +- crates/oj_cache/src/start_bundle/prune.rs | 23 +- crates/oj_cache/src/start_bundle/tests.rs | 130 ++++ crates/oj_cache/src/start_codegen.rs | 10 +- crates/oj_cache/src/store.rs | 177 ++++- crates/oj_env/src/knobs.rs | 8 +- crates/oj_js/src/code_cache.rs | 141 +++- crates/oj_js/src/tracing_fs.rs | 276 +++++++- crates/oj_server/build.rs | 54 ++ crates/oj_server/src/assets/plugin-host.mjs | 94 ++- crates/oj_server/src/lib.rs | 190 +++++- crates/oj_server/src/module_pipeline.rs | 283 ++++++-- crates/oj_server/src/optimize.rs | 66 +- crates/oj_server/src/plugins/host.rs | 37 +- crates/oj_server/src/rewrite.rs | 8 + crates/oj_server/src/store_remote.rs | 517 +++++++++++++-- crates/oj_server/src/store_server.rs | 647 ++++++++++++++++--- crates/oj_server/src/tests.rs | 156 +++++ crates/oj_server/tests/dev/determinism.rs | 23 +- crates/oj_server/tests/dev/optimize_plan.rs | 13 +- crates/oj_server/tests/dev/store.rs | 262 ++++++++ crates/oj_server/tests/optimize_prebundle.rs | 5 + e2e/cross-worktree-cache.mjs | 8 +- e2e/store-concurrent.mjs | 13 +- e2e/store-flag.mjs | 33 +- e2e/store-remote.mjs | 53 +- e2e/trace-staleness.mjs | 41 +- e2e/unit/plugin-host-read-trace.test.mjs | 72 +++ 34 files changed, 3547 insertions(+), 403 deletions(-) create mode 100644 e2e/unit/plugin-host-read-trace.test.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md index f0c22bdc5..4643204cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,7 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed - The goldens and the TanStack Start fixture (`e2e/fixtures/start-app`) are recorded from Vite 8.4.0, the release, in place of 8.4.0-beta.1; rolldown stays 1.3.2, the crate oj builds with (8.4.0 declares `~1.3.2`; 8.4.1 declares `~1.3.4`, whose Rust crates are not published, and its build import analysis hands rolldown a field 1.3.2 rejects). Recorded from `/tmp`, so a recording carries no path depth of the machine it was made on. -- Compiled modules are path-free: the compiler names an in-root module by its served path (`/src/App.tsx`) in the jsx dev `__source` and the sourcemap `sources` entry, so the bytes are identical in every worktree. `fs_allow`/`watch_files` metadata and `/@id/...?importer=` params encode `ws:`/`mono:`-relative and decode against the serving worktree. Sourcemaps from earlier transforms (StyleX, plugins) name in-root files by served path too. +- Compiled modules are path-free, with or without the store: the compiler names an in-root module by its served path (`/src/App.tsx`) in the jsx dev `__source` and the sourcemap `sources` entry (Vite names it by its absolute path), so the bytes are identical in every worktree. `fs_allow`/`watch_files` metadata and `/@id/...?importer=` params encode `ws:`/`mono:`-relative and decode against the serving worktree. Sourcemaps from earlier transforms (StyleX, plugins) name in-root files by served path too. - Files outside the app root but inside the workspace (hoisted node_modules, monorepo packages) are served at `/@fs/@mono/`, which each server resolves against its own workspace root, so cached artifacts that import them share across worktrees. - The V8 code cache keys modules by their root-relative identity instead of the absolute `file://` URL and lives in the shared store, so worktrees of one app share every entry and `node_modules` bytecode is shared across apps with the same layout. Old per-app `code-cache` directories can be deleted. - The Start client-bundle store is shared across worktrees (bundle format 6, rebuilt once): closure keys, the stored closure, the inputs outside the closure (the route trees, the config and its imports) and the bundle's `import.meta.glob` patterns are root-relative, and dev asset URLs are `/@oj-start/fs/@ws/`, resolved against the serving root. A generation whose globs reach outside the root stays keyed to the root that built it. `current` and the memo stay per root; each root mirrors its `current` into `pins/`, and eviction never removes a generation (or its blobs) a fresh pin protects; pins unrefreshed for 7 days stop protecting. A worktree with no `current` probes the most recently used shared generations, so the first `oj dev` in a new worktree restores the bundle another one built. A generation's StyleX rules and its plugin-served-stylesheet mark travel with it as attachments. @@ -26,6 +26,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - The deps prebundle key hashes `resolve.alias` targets root- or workspace-relative, so one vite.config in two worktrees yields one prebundle key. - Dep URL versions are content-derived instead of per session. Each `/@oj-deps/` URL is recorded write-once with its file's content hash in a ledger (in the oj store, else the app's cache), and versions are salted with the ledger's epoch instead of a per-process timestamp. Restarts and worktrees that bundle the same bytes mint the same URLs, so modules compiled against them are shared. Other bytes under a URL an earlier session served move every URL to a version of the new bytes and reload the page, so an `immutable` URL never names two bundles. Wiping the ledger starts a new epoch, which moves every URL. - The dev server records the config's imported files per config file instead of in one process-wide slot, so two apps in one process never hash or watch each other's config imports. +- Without the store a dev server does none of the store's work: no module key salt (the config graph, every tsconfig and the lockfile by content), no plugin read tracing in the engine (a read costs one atomic load), no trace digests, no dependency ledger (versions are per session, as Vite's `sessionTimestamp`) and no cache writer thread. `oj dev` without `--store` clears an inherited `OJ_STORE_DIR` for itself and its children, so an exported variable alone shares nothing (it used to share the Start bundle, codegen and bytecode while the module cache stayed off); `--store` with no directory to resolve exits with an error instead of running without it. +- The module key covers more of what shapes an entry: the tool build (the package version plus a digest of the sources it was built from, so two builds of one version never serve each other's output through a shared store), the root's place in its workspace (two checkouts whose roots sit at different depths name in-workspace files differently), the manifests and entry files of packages linked into `node_modules` from outside it (a workspace plugin changes without a lockfile change), and patch files by content (the patches directory's mtime differs per checkout and kept worktrees from sharing). +- A warm hit verifies more: a stylesheet's `@import`ed files, Sass partials and PostCSS dependencies are trace rows (an edit to an imported file between sessions served the sheet with the old file inlined); the directories a plugin listed (`readdir`, `opendir`) are rows digesting their names; existence checks (`exists`, `stat`, `access`, `realpath`, a read-only `open`), reads by file `URL` or `Buffer` path and reads through a descriptor are rows; relative paths are recorded against the process's directory; an entry whose `/@fs/@mono/` import names no file in the reading server's workspace is a miss. A side file stamped in a whole second within two seconds before its compile started counts as written during it (a filesystem that keeps whole seconds may stamp a later write below the compile's start); a stamp with nanoseconds compares exactly, so a fresh checkout persists from its first boot. +- The shared store directory is a trust boundary: it is created with mode 0700, and an existing one owned by another user or writable by group or others is refused (one line on stderr, the server keeps its own cache). Temp files are created exclusively with a random suffix, so a symlink planted at a predictable name is never followed. The modules directory is kept under 2 GiB (oldest entries first, once per boot, off the boot path; an entry served is touched when its stamp is older than six hours) and temp files of killed processes are swept after an hour. The plugin host's bytecode directory has a 1 GiB budget when it is the store's, in place of the per-app 128 MiB that had every app's boot evict the others, and its directory name carries a digest of the V8 flags. A Start bundle pin names the process as well as the root, so two sandboxes running the app at the same path over one store protect their own generations, and the generation window is counted per app and config. +- `oj store serve` defaults to the user's store directory (`--dir` for another; it no longer creates `oj-store/` under the current directory), keeps a byte quota (`--max-bytes`, 10 GiB by default, 507 past it, counted on boot), stores only entries it could serve (relocatable module JSON, else 422), purges a key or blob on `DELETE` under the write token, compares tokens in constant time, and streams bodies off the runtime's workers. A dev server's read-through counts an answer slower than 500 ms as a failure, trips after three, and after 30 s lets one probe decide; its pushes are queued (256 entries or 64 MiB, a full queue drops and says so once), stop while the breaker is open, and never fetch a body past 16 MiB. Stamped keys (this session's HMR state) are never asked of a substituter. ### Fixed diff --git a/README.md b/README.md index e2f3bec95..56507165a 100644 --- a/README.md +++ b/README.md @@ -127,18 +127,21 @@ oxlint comes from the project (`node_modules/.bin/oxlint`, from the current dire ```sh oj dev --store # the store at $XDG_CACHE_HOME/oj/store (else ~/.cache/oj/store) oj dev --store=/srv/oj-store # a directory of your choosing (also OJ_STORE_DIR) -oj store serve --dir /srv/oj-store --port 5399 # an HTTP substituter over a store +oj store serve --port 5399 # an HTTP substituter over the same store (--dir for another) OJ_STORE_REMOTE=http://host:5399 oj dev --store # read through to it; OJ_STORE_PUSH=1 also pushes ``` How it works: -- The store is off unless `OJ_STORE_DIR` is set, which `--store` does for the server and every child process. A plain `oj dev` writes nothing outside the app. +- `--store` is the one switch: it sets `OJ_STORE_DIR` for the server and every child process, and `oj dev` without it clears an inherited `OJ_STORE_DIR` for itself and its children. A plain `oj dev` writes nothing outside the app, computes no store keys and traces no plugin reads. +- A key covers the tool build (version plus a digest of its sources), the dependency epoch (lockfiles, patch files by content, package.json), the config graph, every tsconfig at the root, the PostCSS config and browserslist, the resolver settings, the root's place in its workspace, and the manifests and entry files of packages linked into `node_modules` from outside it (a workspace plugin). A stylesheet's `@import`ed files are verified like a plugin's side reads. - An entry is named by content, never by path: the module's source and every input that shapes its output (the compile mode and import stamps, the lockfiles, every `tsconfig*.json`, the config file and the files it imports, the PostCSS config, the env it inlines) hashed under a worktree-independent key. Paths inside an artifact are root-relative (`/src/App.tsx`) or workspace-relative (`/@fs/@mono/`), so two checkouts compute the same name and serve the same bytes, sourcemaps included. An artifact that still names a checkout (an import from outside the workspace) stays in that app's own cache. - A warm hit is verified before it is served: the side files a plugin read while transforming (recorded through `node:fs` and the engine's file system) and the files an `import.meta.glob` expanded to are digested again, and a mismatch, a file that appeared or one that moved is a miss, never a stale serve. Plugins that collect state from every transform (UnoCSS's shape) keep app modules out of the store for the session. - It holds the compiled module cache, the V8 bytecode cache of the plugin host, the TanStack Start client bundle (a cold worktree restores the generation its sources hash to) and the dependency URL ledger, so two checkouts bundling the same dependency bytes mint the same `/@oj-deps/...?v=` URLs. -- Writes are atomic and write-once: two servers on one store, or two pushers of one key, leave one whole entry and never a torn one. A store that cannot be written costs sharing, not correctness. A corrupt or foreign entry is dropped on read. -- `oj store serve` publishes a store over HTTP with read and write bearer tokens (`OJ_STORE_READ_TOKEN`, `OJ_STORE_WRITE_TOKEN`; a dev server sends `OJ_STORE_TOKEN`). A dev server asks it only on a local miss, with a 2 s connect and 5 s fetch timeout, and stops asking for the session after three failures in a row. +- Writes are atomic and write-once: two servers on one store, or two pushers of one key, leave one whole entry and never a torn one. Temp files are created exclusively (never through a planted symlink). A store that cannot be written costs sharing, not correctness. A corrupt or foreign entry is dropped on read. +- The store directory is a trust boundary: it is created with mode 0700, and one owned by another user or writable by group or others is refused with one line on stderr (the server runs with its own cache instead). Entries are not signed; whoever can write the directory, or holds the wire's write token, decides what every reader serves. +- It is a cache with a budget: the modules directory is kept under 2 GiB (oldest entries first, once per boot, off the boot path) and temp files of killed processes are swept after an hour; the plugin host's bytecode directory has a 1 GiB budget when shared; the Start bundle store keeps a window of generations per app and config, protected by per-process pins. +- `oj store serve` publishes a store over HTTP with read and write bearer tokens (`OJ_STORE_READ_TOKEN`, `OJ_STORE_WRITE_TOKEN`; a dev server sends `OJ_STORE_TOKEN`), under a byte quota (`--max-bytes`, 10 GiB by default; a write past it is a 507). It stores only entries it could serve (relocatable module JSON; anything else is a 422), and `DELETE` under the write token purges a key. A dev server asks it only on a local miss of an unstamped key, with a 2 s connect and 5 s fetch timeout; an answer slower than 500 ms counts as a failure, three in a row stop the asking, and after 30 s one probe decides whether to resume. Pushes are queued (256 entries or 64 MiB; a full queue drops) and carry the module's source map with `sourcesContent`, so push only to a substituter as private as the checkout. ## Quickstart diff --git a/crates/oj/src/main.rs b/crates/oj/src/main.rs index 535d7ad09..d7fff5204 100644 --- a/crates/oj/src/main.rs +++ b/crates/oj/src/main.rs @@ -69,15 +69,26 @@ fn debug_with_scopes(debug: Option<&str>, scopes: &str) -> String { #[derive(Subcommand)] enum StoreCommand { - /// Serve DIR as a remote oj store (the six-endpoint substituter). + /// Serve a store directory as a remote oj store (the HTTP substituter). + /// Entries are write-once; an operator holding OJ_STORE_WRITE_TOKEN + /// purges one with `DELETE /v1/ac/{ns}/{key}` (or `/v1/cas/{digest}`), + /// which is the only way an entry leaves. Serve { - /// Directory holding the served entries (created if missing). - #[arg(long, default_value = "oj-store")] - dir: PathBuf, + /// Directory holding the served entries (created if missing). Without + /// it: OJ_STORE_DIR, else the per-user store `oj dev --store` uses + /// ($XDG_CACHE_HOME/oj/store, else ~/.cache/oj/store). The wire keeps + /// its entries under ac/ and cas/ there, beside the local store's own. + #[arg(long, value_name = "DIR")] + dir: Option, #[arg(long, default_value_t = 5399)] port: u16, #[arg(long, default_value = "127.0.0.1")] host: String, + /// The most bytes ac/ and cas/ together may hold (counted on boot, so + /// it holds across restarts). A PUT that would go over answers 507 + /// and stores nothing. + #[arg(long, value_name = "BYTES", default_value_t = oj_server::store_server::DEFAULT_MAX_BYTES)] + max_bytes: u64, }, } @@ -638,6 +649,12 @@ fn main() -> anyhow::Result<()> { // engine, the plugin host, one-shot builders all read OJ_STORE_DIR), so // the store's dir is exported before the snapshot below: the given DIR, // else the user's cache dir. + // Without the flag the store is off, wherever `OJ_STORE_DIR` points: the + // variable is cleared for this process and its children (the engine, + // the plugin host, the builders), so nothing of theirs is shared either. + if let Command::Dev { store: None, .. } = &cli.command { + std::env::remove_var("OJ_STORE_DIR"); + } if let Command::Dev { store: Some(store), .. } = &cli.command @@ -649,9 +666,12 @@ fn main() -> anyhow::Result<()> { ); match dir { Some(dir) => std::env::set_var("OJ_STORE_DIR", dir), - None => eprintln!( - "oj: --store: no store directory (set OJ_STORE_DIR, XDG_CACHE_HOME or HOME)" - ), + None => { + eprintln!( + "oj: --store: no store directory (set OJ_STORE_DIR, XDG_CACHE_HOME or HOME)" + ); + std::process::exit(2); + } } } // The startup writes above are oj's only direct process-env access. Snapshot @@ -810,8 +830,25 @@ async fn run(cli: Cli, rolldown: tokio::runtime::Handle) -> anyhow::Result<()> { Ok(()) } Command::Store { action } => match action { - StoreCommand::Serve { dir, port, host } => { - if let Err(e) = oj_server::store_server::serve(dir, &host, port).await { + StoreCommand::Serve { + dir, + port, + host, + max_bytes, + } => { + // The same dir `oj dev --store` lands in, never one made + // beside whatever the shell happens to be in. + let Some(dir) = store_dir_for( + dir.as_deref(), + std::env::var_os("OJ_STORE_DIR").map(PathBuf::from), + default_store_dir(), + ) else { + eprintln!( + "oj store serve: no store directory (pass --dir, or set OJ_STORE_DIR, XDG_CACHE_HOME or HOME)" + ); + std::process::exit(2); + }; + if let Err(e) = oj_server::store_server::serve(dir, &host, port, max_bytes).await { eprintln!("oj store: {e}"); std::process::exit(1); } @@ -1087,6 +1124,46 @@ mod store_flag_tests { assert_eq!(store_dir_for(None, None, None), None); } + // `store serve` names no directory of its own: without --dir it goes + // where `oj dev --store` goes (the same store_dir_for chain), never to + // an `oj-store/` made beside whatever the shell is in. + #[test] + fn store_serve_takes_no_dir_of_its_own_and_a_quota() { + let parse = |args: &[&str]| match Cli::try_parse_from(args).expect("parse").command { + Command::Store { + action: StoreCommand::Serve { dir, max_bytes, .. }, + } => (dir, max_bytes), + _ => panic!("expected store serve"), + }; + assert_eq!( + parse(&["oj", "store", "serve"]), + (None, oj_server::store_server::DEFAULT_MAX_BYTES) + ); + assert_eq!( + parse(&[ + "oj", + "store", + "serve", + "--dir", + "/srv/oj", + "--max-bytes", + "1024" + ]), + (Some(PathBuf::from("/srv/oj")), 1024) + ); + let default = Some(PathBuf::from("/home/u/.cache/oj/store")); + assert_eq!( + store_dir_for(None, None, default.clone()), + default, + "no --dir: the per-user store" + ); + assert_eq!( + store_dir_for(None, Some(PathBuf::from("/ci/store")), default), + Some(PathBuf::from("/ci/store")), + "no --dir: OJ_STORE_DIR before the per-user store" + ); + } + #[test] fn the_old_cache_flags_are_gone() { for flag in ["--enable-cache", "--no-cache"] { diff --git a/crates/oj_cache/src/integrity.rs b/crates/oj_cache/src/integrity.rs index b2430960d..d8335535c 100644 --- a/crates/oj_cache/src/integrity.rs +++ b/crates/oj_cache/src/integrity.rs @@ -4,7 +4,9 @@ use std::fmt; use std::fs; use std::io; +use std::io::Write as _; use std::path::Path; +use std::sync::atomic::{AtomicU64, Ordering}; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; @@ -68,20 +70,62 @@ pub fn atomic_write(path: &Path, bytes: &[u8]) -> io::Result<()> { .file_name() .and_then(|n| n.to_str()) .unwrap_or("artifact"); - let tmp = dir.join(format!(".{name}.tmp-{}", std::process::id())); + let tmp = dir.join(format!(".{name}.tmp-{}", temp_tag())); write_via_tmp(&tmp, path, bytes) } /// Writes `bytes` to `tmp`, then renames it over `path`, so readers see the /// old file or the new one, never a partial write. `tmp` is removed on failure. pub(crate) fn write_via_tmp(tmp: &Path, path: &Path, bytes: &[u8]) -> io::Result<()> { - let result = fs::write(tmp, bytes).and_then(|()| fs::rename(tmp, path)); + let result = write_new(tmp, bytes).and_then(|()| fs::rename(tmp, path)); if result.is_err() { let _ = fs::remove_file(tmp); } result } +/// Creates `tmp` and writes `bytes` to it. The file must not exist: a path +/// something else planted there first (a symlink into another directory, +/// in a shared store) is refused instead of followed, which plain +/// `fs::write` would do. +pub(crate) fn write_new(tmp: &Path, bytes: &[u8]) -> io::Result<()> { + let mut file = open_new(tmp)?; + file.write_all(bytes) +} + +/// [`write_new`] without the bytes: the caller streams them in. +pub(crate) fn open_new(tmp: &Path) -> io::Result { + fs::File::options().write(true).create_new(true).open(tmp) +} + +/// The suffix of a temp name: the pid, a per-process counter and a random +/// part. The counter keeps threads of one process apart, the random part +/// keeps the name from being predicted (and so pre-planted) by anything +/// else that can write the directory. +pub(crate) fn temp_tag() -> String { + static SEQ: AtomicU64 = AtomicU64::new(0); + let seq = SEQ.fetch_add(1, Ordering::Relaxed); + format!("{}-{seq}-{}", std::process::id(), random_tag()) +} + +/// Twelve hex characters nothing outside this process can predict: a hash +/// of the pid, the clock, a counter and an address the loader randomized. +pub(crate) fn random_tag() -> String { + static SEQ: AtomicU64 = AtomicU64::new(0); + let seq = SEQ.fetch_add(1, Ordering::Relaxed); + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos()); + let marker = &seq as *const u64 as usize; + let mut hasher = blake3::Hasher::new(); + hasher.update(&std::process::id().to_le_bytes()); + hasher.update(&now.to_le_bytes()); + hasher.update(&seq.to_le_bytes()); + hasher.update(&marker.to_le_bytes()); + hasher.update(&(random_tag as fn() -> String as usize).to_le_bytes()); + hasher.finalize().to_hex()[..12].to_string() +} + /// Parses a JSON cache file. An unparseable file is removed, so a corrupt /// entry is a miss once and then gone, never served. pub(crate) fn read_json_or_remove(path: &Path) -> Option { diff --git a/crates/oj_cache/src/lib.rs b/crates/oj_cache/src/lib.rs index 0f8b560ca..d4a0c4552 100644 --- a/crates/oj_cache/src/lib.rs +++ b/crates/oj_cache/src/lib.rs @@ -3,7 +3,6 @@ use std::fs; use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering}; pub mod config_extract; pub mod integrity; @@ -185,6 +184,17 @@ pub struct TraceRow { pub digest: String, } +/// A trace row's tag (`glob:`, `dir:`) and what follows it; a plain path +/// has no tag. +fn split_row_tag(entry: &str) -> (&'static str, String) { + for tag in ["glob:", "dir:"] { + if let Some(inner) = entry.strip_prefix(tag) { + return (tag, inner.to_string()); + } + } + ("", entry.to_string()) +} + impl CachedModule { /// The on-disk form: absolute paths under `root` become `ws:` so the /// stored artifact means the same thing in every worktree. Fields it @@ -195,12 +205,10 @@ impl CachedModule { pub fn relocated_for_store(&self, root: &Path, workspace: &Path) -> CachedModule { let mut out = self.clone(); let relocate = |entry: &mut String| { - // Glob rows carry their pattern behind a `glob:` tag; the inner - // pattern relocates like a path. - let (prefix, inner) = match entry.strip_prefix("glob:") { - Some(inner) => ("glob:", inner.to_string()), - None => ("", entry.clone()), - }; + // Glob rows carry their pattern behind a `glob:` tag and listed + // directories theirs behind `dir:`; the inner path relocates + // like any other. + let (prefix, inner) = split_row_tag(entry); if let Some(rel) = crate::store::rel_key(root, Path::new(&inner)) { *entry = format!("{prefix}ws:{rel}"); } else if let Some(rel) = crate::store::rel_key(workspace, Path::new(&inner)) { @@ -223,10 +231,7 @@ impl CachedModule { pub fn rehomed(&self, root: &Path, workspace: &Path) -> CachedModule { let mut out = self.clone(); let rehome = |entry: &mut String| { - let (prefix, inner) = match entry.strip_prefix("glob:") { - Some(inner) => ("glob:", inner.to_string()), - None => ("", entry.clone()), - }; + let (prefix, inner) = split_row_tag(entry); if let Some(rel) = inner.strip_prefix("ws:") { *entry = format!("{prefix}{}", root.join(rel).to_string_lossy()); } else if let Some(rel) = inner.strip_prefix("mono:") { @@ -251,8 +256,8 @@ impl CachedModule { /// encoding at generation time). pub fn is_relocatable(&self) -> bool { let path_free = |s: &str| { - let s = s.strip_prefix("glob:").unwrap_or(s); - s.starts_with("ws:") || s.starts_with("mono:") || !Path::new(s).is_absolute() + let s = split_row_tag(s).1; + s.starts_with("ws:") || s.starts_with("mono:") || !Path::new(&s).is_absolute() }; // Served-URL fields: /@fs/ and /@oj-pkg/ pin an entry // to one checkout (the latter hex-encodes an absolute entry path). @@ -369,6 +374,8 @@ impl PersistentCache { // points into one checkout (another oj's write, a damaged // store) is dropped, never served, whatever `put` admitted. if module.is_relocatable() { + // A hit is a use: `prune_shared` evicts by mtime. + touch_if_stale(&path); return Some(module); } let _ = fs::remove_file(&path); @@ -412,13 +419,31 @@ impl PersistentCache { if fs::create_dir_all(parent).is_err() { return false; } - // Per-write sequence: threads of one process may put the same key - // concurrently and must not share a temp file. - let seq = TEMP_SEQ.fetch_add(1, Ordering::Relaxed); - let tmp = path.with_extension(format!("tmp-{}-{seq}", std::process::id())); + // The temp name carries a per-process counter (threads of one + // process may put the same key at once) and a random part, and the + // file is created new: a name planted ahead of the write (a symlink + // out of a shared store) fails the write instead of being followed. + let tmp = path.with_extension(format!("tmp-{}", integrity::temp_tag())); integrity::write_via_tmp(&tmp, &path, bytes).is_ok() } + /// Bounds the shared modules directory, at boot and never on the + /// request path: temp files older than [`SHARED_TMP_MAX_AGE`] (a writer + /// killed mid-write) go, then entries go least recently used first + /// until the directory fits three quarters of `max_bytes` (the slack + /// keeps one boot from trimming a trickle). Nothing else ever deletes a + /// shared entry, and every edit of every app on the machine adds one, so + /// without this the directory only grows. Use is the entry's mtime, + /// which [`Self::get`] bumps on a hit (atime is unreliable). Nothing + /// happens without a shared directory; the app's own cache is bounded + /// by its checkout's life. + pub fn prune_shared(&self, max_bytes: u64) { + let Some(shared) = self.shared.as_deref() else { + return; + }; + prune_modules_dir(shared, max_bytes, SHARED_TMP_MAX_AGE); + } + /// `//.json`; `None` for anything but a lowercase /// blake3 hex digest, so a key can never escape the cache dir. fn path_in(dir: &Path, key: &str) -> Option { @@ -429,7 +454,87 @@ impl PersistentCache { } } -static TEMP_SEQ: AtomicU64 = AtomicU64::new(0); +/// The budget [`PersistentCache::prune_shared`] is called with by default: +/// generous, since the directory serves every app and worktree of the user. +pub const SHARED_MODULES_MAX_BYTES: u64 = 2 << 30; +/// A shared temp file older than this was left by a dead writer; a live +/// write takes milliseconds. +pub const SHARED_TMP_MAX_AGE: std::time::Duration = std::time::Duration::from_secs(60 * 60); +/// A hit bumps an entry's mtime only when it is older than this, so a warm +/// boot of thousands of modules costs one stat per hit and a rare touch, +/// and eviction still sees a day's use. +const TOUCH_GRANULARITY: std::time::Duration = std::time::Duration::from_secs(6 * 60 * 60); + +/// Marks the entry at `path` used now when its mtime is older than +/// [`TOUCH_GRANULARITY`]. Best effort: a failure costs eviction order only. +fn touch_if_stale(path: &Path) { + let stale = fs::metadata(path) + .and_then(|m| m.modified()) + .ok() + .and_then(|m| m.elapsed().ok()) + .is_none_or(|age| age > TOUCH_GRANULARITY); + if !stale { + return; + } + if let Ok(file) = fs::File::options().append(true).open(path) { + let _ = file.set_times(fs::FileTimes::new().set_modified(std::time::SystemTime::now())); + } +} + +/// The sweep behind [`PersistentCache::prune_shared`], over `//`: +/// `.tmp-` files older than `tmp_max_age` are removed, then `.json` entries +/// oldest mtime first until the rest fits three quarters of `max_bytes`. +fn prune_modules_dir(dir: &Path, max_bytes: u64, tmp_max_age: std::time::Duration) { + let Ok(shards) = fs::read_dir(dir) else { + return; + }; + let now = std::time::SystemTime::now(); + let mut entries: Vec<(std::time::SystemTime, u64, PathBuf)> = Vec::new(); + for shard in shards.flatten() { + let name = shard.file_name(); + let name = name.to_string_lossy(); + if name.len() != 2 || !is_lower_hex(&name) { + continue; + } + let Ok(files) = fs::read_dir(shard.path()) else { + continue; + }; + for e in files.flatten() { + let Ok(meta) = e.metadata() else { + continue; + }; + if !meta.is_file() { + continue; + } + let name = e.file_name(); + let name = name.to_string_lossy(); + let modified = meta.modified().unwrap_or(std::time::UNIX_EPOCH); + if name.contains(".tmp-") { + if now + .duration_since(modified) + .is_ok_and(|age| age > tmp_max_age) + { + let _ = fs::remove_file(e.path()); + } + } else if name.ends_with(".json") { + entries.push((modified, meta.len(), e.path())); + } + } + } + let mut total: u64 = entries.iter().map(|(_, len, _)| len).sum(); + if total <= max_bytes { + return; + } + entries.sort(); + for (_, len, path) in entries { + if total <= max_bytes / 4 * 3 { + break; + } + if fs::remove_file(&path).is_ok() { + total -= len; + } + } +} #[cfg(test)] mod tests { @@ -825,6 +930,42 @@ mod tests { assert_eq!(rehomed.trace[1].digest, "d2"); } + #[test] + fn dir_trace_rows_relocate_behind_their_tag() { + let module = CachedModule { + trace: vec![ + TraceRow { + id: "dir:/wt-a/mono/app/src/icons".into(), + digest: "d".into(), + }, + TraceRow { + id: "dir:/wt-a/mono/packages/ui".into(), + digest: "e".into(), + }, + ], + ..Default::default() + }; + let stored = + module.relocated_for_store(Path::new("/wt-a/mono/app"), Path::new("/wt-a/mono")); + assert_eq!(stored.trace[0].id, "dir:ws:src/icons"); + assert_eq!(stored.trace[1].id, "dir:mono:packages/ui"); + assert!(stored.is_relocatable()); + let rehomed = stored.rehomed(Path::new("/b/app"), Path::new("/b")); + assert_eq!(rehomed.trace[0].id, "dir:/b/app/src/icons"); + assert_eq!(rehomed.trace[1].id, "dir:/b/packages/ui"); + let pinned = CachedModule { + trace: vec![TraceRow { + id: "dir:/elsewhere/icons".into(), + digest: "d".into(), + }], + ..Default::default() + }; + assert!( + !pinned.is_relocatable(), + "a listed directory outside the workspace pins the entry" + ); + } + #[test] fn glob_trace_rows_relocate_behind_their_tag() { let module = CachedModule { @@ -1048,6 +1189,7 @@ mod store_stress_tests { //! read by servers that trust it: these pin what must hold under races, //! torn files and entries another process put there. use super::*; + use std::sync::atomic::Ordering; fn base(label: &str) -> PathBuf { let dir = @@ -1326,3 +1468,189 @@ mod store_removal_tests { assert!(shared.is_dir(), "the write recreated the store"); } } + +#[cfg(test)] +mod store_prune_tests { + //! The shared modules directory is bounded at boot: dead writers' temp + //! files go after an hour, entries go least recently used first past the + //! budget, and a hit counts as use. + use super::*; + use std::time::{Duration, SystemTime}; + + fn base(label: &str) -> PathBuf { + let dir = + std::env::temp_dir().join(format!("oj-store-prune-{}-{label}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + dir + } + + fn cache(base: &Path) -> PersistentCache { + PersistentCache::new(base.join("wt/.oj-cache/v1"), "0.0.1-test") + .with_shared(Some(base.join("store/modules"))) + } + + fn set_mtime(path: &Path, t: SystemTime) { + let f = fs::File::options().append(true).open(path).unwrap(); + f.set_times(fs::FileTimes::new().set_modified(t)).unwrap(); + } + + fn module(n: usize) -> CachedModule { + CachedModule { + code: format!("export const x = {n};{}", "/".repeat(200)), + ..Default::default() + } + } + + fn key_of(cache: &PersistentCache, n: usize) -> String { + cache.disk_key(&module_key( + &source_hash(b"src"), + &format!("/src/m{n}.ts"), + "dev", + )) + } + + #[test] + fn stale_temp_files_are_swept_and_a_recent_one_stays() { + let base = base("tmp"); + let cache = cache(&base); + let shard = base.join("store/modules/aa"); + fs::create_dir_all(&shard).unwrap(); + let dead = shard.join(format!("{}.tmp-1-1", "a".repeat(64))); + let live = shard.join(format!("{}.tmp-2-2", "b".repeat(64))); + fs::write(&dead, b"half").unwrap(); + fs::write(&live, b"half").unwrap(); + set_mtime(&dead, SystemTime::now() - Duration::from_secs(2 * 60 * 60)); + cache.prune_shared(SHARED_MODULES_MAX_BYTES); + assert!(!dead.exists(), "a temp file past the gate is swept"); + assert!(live.exists(), "a recent one may be a live write"); + // The app's own cache is never swept by it. + let local = base.join("wt/.oj-cache/v1/aa"); + fs::create_dir_all(&local).unwrap(); + let local_tmp = local.join(format!("{}.tmp-1-1", "c".repeat(64))); + fs::write(&local_tmp, b"half").unwrap(); + set_mtime( + &local_tmp, + SystemTime::now() - Duration::from_secs(2 * 60 * 60), + ); + cache.prune_shared(SHARED_MODULES_MAX_BYTES); + assert!(local_tmp.exists()); + } + + #[test] + fn entries_over_the_budget_go_least_recently_used_first() { + let base = base("budget"); + let cache = cache(&base); + let mut paths = Vec::new(); + for n in 0..10 { + let key = key_of(&cache, n); + cache.put(&key, &module(n)); + let path = base + .join("store/modules") + .join(&key[..2]) + .join(format!("{key}.json")); + // Entry n was last used n minutes ago: 0 is the newest. + set_mtime( + &path, + SystemTime::now() - Duration::from_secs(60 * (n as u64 + 1)), + ); + paths.push(path); + } + let each = fs::metadata(&paths[0]).unwrap().len(); + let total = each * 10; + cache.prune_shared(total); + assert!(paths.iter().all(|p| p.exists()), "under budget: untouched"); + let budget = each * 6; + cache.prune_shared(budget); + let left: u64 = paths + .iter() + .filter_map(|p| fs::metadata(p).ok()) + .map(|m| m.len()) + .sum(); + assert!(left <= budget, "{left} > {budget}"); + assert!(left <= budget / 4 * 3, "trimmed with slack: {left}"); + for (n, path) in paths.iter().enumerate() { + match n { + 0..4 => { + assert!(path.exists(), "entry {n} is among the newest"); + assert!(cache.get(&key_of(&cache, n)).is_some()); + } + 6..10 => assert!(!path.exists(), "entry {n} is among the oldest"), + _ => {} + } + } + } + + #[test] + fn a_hit_marks_an_old_entry_used() { + let base = base("touch"); + let cache = cache(&base); + let key = key_of(&cache, 1); + cache.put(&key, &module(1)); + let path = base + .join("store/modules") + .join(&key[..2]) + .join(format!("{key}.json")); + let old = SystemTime::now() - Duration::from_secs(24 * 60 * 60); + set_mtime(&path, old); + assert!(cache.get(&key).is_some()); + let touched = fs::metadata(&path).unwrap().modified().unwrap(); + assert!( + touched.duration_since(old).unwrap() > Duration::from_secs(23 * 60 * 60), + "the hit bumped the mtime" + ); + // A fresh entry is not rewritten on every hit. + let before = fs::metadata(&path).unwrap().modified().unwrap(); + std::thread::sleep(Duration::from_millis(20)); + assert!(cache.get(&key).is_some()); + assert_eq!(fs::metadata(&path).unwrap().modified().unwrap(), before); + } + + #[test] + fn a_prune_without_a_shared_dir_is_a_no_op() { + let base = base("local-only"); + let cache = PersistentCache::new(base.join("wt/.oj-cache/v1"), "0.0.1-test"); + let key = key_of(&cache, 1); + cache.put(&key, &module(1)); + cache.prune_shared(0); + assert!(cache.get(&key).is_some()); + } +} + +#[cfg(all(test, unix))] +mod store_symlink_tests { + //! A temp path something else planted (a symlink out of a shared store) + //! is never written through: the write fails and the target is whole. + use super::*; + + #[test] + fn a_planted_symlink_at_a_temp_path_is_not_followed() { + let base = std::env::temp_dir().join(format!("oj-store-symlink-{}", std::process::id())); + let _ = fs::remove_dir_all(&base); + let shard = base.join("store/modules/aa"); + fs::create_dir_all(&shard).unwrap(); + let target = base.join("victim"); + fs::write(&target, b"untouched").unwrap(); + let key = format!("aa{}", "0".repeat(62)); + let entry = shard.join(format!("{key}.json")); + let tmp = shard.join(format!("{key}.tmp-planted")); + std::os::unix::fs::symlink(&target, &tmp).unwrap(); + let result = integrity::write_via_tmp(&tmp, &entry, b"{\"code\":\"evil\"}"); + assert!(result.is_err(), "the write refused the planted path"); + assert_eq!(fs::read(&target).unwrap(), b"untouched"); + assert!(!entry.exists(), "no entry came of it"); + assert!( + fs::symlink_metadata(&tmp).is_err(), + "the failed write cleared the planted name" + ); + } + + #[test] + fn temp_names_are_not_predictable() { + let a = integrity::temp_tag(); + let b = integrity::temp_tag(); + assert_ne!(a, b); + let random = |tag: &str| tag.rsplit('-').next().unwrap().to_string(); + assert_ne!(random(&a), random(&b), "the random part differs per write"); + assert_eq!(random(&a).len(), 12); + } +} diff --git a/crates/oj_cache/src/start_bundle/mod.rs b/crates/oj_cache/src/start_bundle/mod.rs index 67a9de220..e1d86f4d1 100644 --- a/crates/oj_cache/src/start_bundle/mod.rs +++ b/crates/oj_cache/src/start_bundle/mod.rs @@ -36,7 +36,10 @@ pub const DEFAULT_PRUNE_BUDGET_BYTES: u64 = 1024 * 1024 * 1024; /// long editing session cannot accumulate one generation per save. pub const KEEP_GENERATIONS: usize = 8; /// The shared store serves every worktree and app on the machine, so its -/// generation window is wider than a single app's. +/// generation window is wider than a single app's. Either window counts +/// the generations of one salt (one app, mode, tool version and config), +/// so one app's churn never evicts another's; the boot-time budget prune +/// bounds the directory as a whole. pub const SHARED_KEEP_GENERATIONS: usize = 32; /// Cold-worktree probe: with no per-root `current`, try this many of the most /// recently used shared generations' closures as key predictions. @@ -57,9 +60,9 @@ const CLOSURE_FILE: &str = "closure.json"; const MEMO_FILE: &str = "memo.json"; const MANIFEST_FILE: &str = "manifest.json"; const CURRENT_FILE: &str = "current"; -/// Per-root pin files inside the shared dir: `pins/` names the -/// generation that root currently serves, so one worktree's eviction can -/// never delete blobs another running server reads live. +/// Pin files inside the shared dir: `pins/-` names the +/// generation a running process at that root serves, so one worktree's +/// eviction can never delete blobs another running server reads live. const PINS_DIR: &str = "pins"; /// A pin whose file has not been refreshed for this long belongs to a /// worktree that is gone (deleted checkout, abandoned sandbox): eviction may @@ -321,8 +324,7 @@ impl StartBundleStore { // Canonical, so rolldown's realpath ids and macOS /var symlink // spellings both relativize. let root_canon = fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf()); - let pin_id = - blake3::hash(root_canon.as_os_str().as_encoded_bytes()).to_hex()[..16].to_string(); + let pin_id = pin_id_for(&root_canon, process_pin_session()); Self { root: root_canon, root_spelled: root.to_path_buf(), @@ -339,6 +341,24 @@ impl StartBundleStore { } } + /// This store pinning under `session` instead of the process's own id: + /// what a second server at this root in another process would hold. + /// Tests stand two sandboxes up in one process with it. + pub fn pin_session(mut self, session: &str) -> Self { + self.pin_id = pin_id_for(&self.root, session); + self + } + + /// Rewrites this process's pin for the generation it serves (the root's + /// `current`), so a server that has not persisted or restored for a + /// while still holds its blobs past [`PIN_MAX_AGE`]. Cheap; a caller + /// with a long-lived server calls it on a timer. + pub fn refresh_pin(&self) { + if let Some(key) = read_current(&self.local) { + self.write_current(&key); + } + } + /// This store with the contents of `files` in its key: inputs of the /// bundle that no closure lists (a missing one keys as missing). A /// generation built from other contents is then no restore's match. The @@ -737,6 +757,25 @@ impl StartBundleStore { } } +/// The pin file name of `root` under `session`: the root's hash, so pins of +/// one checkout sort together, and the session, so two processes at the +/// same path (sandboxes run their app at one path over one store) never +/// share a pin. Sharing one, the second process's pin named only its own +/// generation and the first's lost its protection, and eviction swept the +/// blobs from under a running server. +fn pin_id_for(root: &Path, session: &str) -> String { + let root = &blake3::hash(root.as_os_str().as_encoded_bytes()).to_hex()[..16]; + format!("{root}-{session}") +} + +/// This process's pin session: random, made once. Every store of this +/// process (one per persist) rewrites the same pin file, so a process leaves +/// one pin behind, which ages out after [`PIN_MAX_AGE`]. +fn process_pin_session() -> &'static str { + static SESSION: std::sync::OnceLock = std::sync::OnceLock::new(); + SESSION.get_or_init(integrity::random_tag) +} + /// A generation dir: anything in the store dir but the blob store, the pins /// and `.tmp-` staging. fn is_generation_dir(e: &fs::DirEntry) -> bool { diff --git a/crates/oj_cache/src/start_bundle/persist.rs b/crates/oj_cache/src/start_bundle/persist.rs index 5f9bcaf69..3b4746aeb 100644 --- a/crates/oj_cache/src/start_bundle/persist.rs +++ b/crates/oj_cache/src/start_bundle/persist.rs @@ -5,6 +5,8 @@ use std::collections::BTreeMap; use std::fs; use std::path::{Path, PathBuf}; +use crate::integrity; + use super::memo::{build_memo, read_memo, verified_digests, write_memo}; use super::{ hash_file, par_map, read_chunk_index, read_closure, read_css_urls, read_manifest, touch, @@ -132,24 +134,32 @@ impl StartBundleStore { ids: &[String], globs: &str, ) -> Option<()> { + // A fresh staging dir under an unpredictable name, created (not + // reused) so nothing planted at the path is written through, and + // every file in it created new. let tmp = self .dir - .join(format!(".tmp-{}-{}", key.get(..16)?, std::process::id())); - let _ = fs::remove_dir_all(&tmp); - fs::create_dir_all(&tmp).ok()?; + .join(format!(".tmp-{}-{}", key.get(..16)?, integrity::temp_tag())); + fs::create_dir_all(&self.dir).ok()?; + fs::create_dir(&tmp).ok()?; + let copy = |name: &str| { + fs::read(start_dir.join(name)) + .and_then(|bytes| integrity::write_new(&tmp.join(name), &bytes)) + .is_ok() + }; let staged = ARTIFACTS .into_iter() .filter(|name| *name != GLOB_SCOPES_FILE) - .all(|name| fs::copy(start_dir.join(name), tmp.join(name)).is_ok()) - && fs::write(tmp.join(GLOB_SCOPES_FILE), globs).is_ok() + .all(copy) + && integrity::write_new(&tmp.join(GLOB_SCOPES_FILE), globs.as_bytes()).is_ok() && serde_json::to_vec(ids) - .is_ok_and(|bytes| fs::write(tmp.join(CLOSURE_FILE), bytes).is_ok()); + .is_ok_and(|bytes| integrity::write_new(&tmp.join(CLOSURE_FILE), &bytes).is_ok()); if !staged { let _ = fs::remove_dir_all(&tmp); return None; } let bytes = serde_json::to_vec(manifest).ok()?; - if fs::write(tmp.join(MANIFEST_FILE), bytes).is_err() { + if integrity::write_new(&tmp.join(MANIFEST_FILE), &bytes).is_err() { let _ = fs::remove_dir_all(&tmp); return None; } @@ -187,14 +197,20 @@ fn store_chunk_blobs( /// Copies `src` to `blobs/` via a `.tmp-` file and rename. A failed /// rename still succeeds when a racing writer already committed the blob. +/// The temp file is created new under an unpredictable name, never opened +/// through a path something else put there first. fn write_blob(src: &Path, blobs: &Path, hash: &str) -> bool { let blob = blobs.join(hash); let tmp = blobs.join(format!( ".tmp-{}-{}", hash.get(..16).unwrap_or(hash), - std::process::id() + integrity::temp_tag() )); - if fs::copy(src, &tmp).is_err() { + let copied = fs::File::open(src).and_then(|mut from| { + let mut to = integrity::open_new(&tmp)?; + std::io::copy(&mut from, &mut to).map(|_| ()) + }); + if copied.is_err() { let _ = fs::remove_file(&tmp); return false; } diff --git a/crates/oj_cache/src/start_bundle/prune.rs b/crates/oj_cache/src/start_bundle/prune.rs index 9d1b6356d..b4fd1c85a 100644 --- a/crates/oj_cache/src/start_bundle/prune.rs +++ b/crates/oj_cache/src/start_bundle/prune.rs @@ -61,11 +61,12 @@ impl StartBundleStore { let prev = self.sweeper.lock().ok().and_then(|mut s| s.take()); let dir = self.dir.clone(); let protected = self.protected_keys(); + let salt_id = self.salt_id(); let handle = std::thread::spawn(move || { if let Some(prev) = prev { let _ = prev.join(); } - enforce_window_blocking(&dir, max_generations, &protected); + enforce_window_blocking(&dir, &salt_id, max_generations, &protected); }); if let Ok(mut slot) = self.sweeper.lock() { *slot = Some(handle); @@ -224,8 +225,13 @@ fn evict_oldest( } } -fn enforce_window_blocking(dir: &Path, max_generations: usize, protected: &HashSet) { - let evicted = rename_aside_overflow(dir, protected, max_generations); +fn enforce_window_blocking( + dir: &Path, + salt_id: &str, + max_generations: usize, + protected: &HashSet, +) { + let evicted = rename_aside_overflow(dir, salt_id, protected, max_generations); if evicted.is_empty() { return; } @@ -243,10 +249,14 @@ fn enforce_window_blocking(dir: &Path, max_generations: usize, protected: &HashS } } -/// Renames the oldest generations beyond the window to `.tmp-evict-` dirs -/// and returns them. A protected generation is never a candidate. +/// Renames the oldest generations of this salt beyond the window to +/// `.tmp-evict-` dirs and returns them. A protected generation is never a +/// candidate, and a generation of another salt (another app, mode or +/// config in the shared dir) is neither counted nor touched: its own +/// store's window sizes it, and the budget prune bounds them all. fn rename_aside_overflow( dir: &Path, + salt_id: &str, protected: &HashSet, max_generations: usize, ) -> Vec { @@ -259,6 +269,9 @@ fn rename_aside_overflow( if !is_generation_dir(&e) { continue; } + if !read_manifest(&e.path()).is_some_and(|m| m.salt_id == salt_id) { + continue; + } if protected.contains(e.file_name().to_string_lossy().as_ref()) { kept += 1; continue; diff --git a/crates/oj_cache/src/start_bundle/tests.rs b/crates/oj_cache/src/start_bundle/tests.rs index b3acf7d0a..157aeecb4 100644 --- a/crates/oj_cache/src/start_bundle/tests.rs +++ b/crates/oj_cache/src/start_bundle/tests.rs @@ -1524,3 +1524,133 @@ fn keyed_by_files_tells_missing_from_empty_and_keeps_file_boundaries() { assert_ne!(ab_c, a_bc, "contents keep their file boundaries"); assert_eq!(a_bc, key(), "the same inputs key the same"); } + +// Sandboxes run their app at one path (say /app) over one shared store. Two +// of them are two processes with one root hash: with one pin file between +// them, the second's pin named only its own generation, and the first's +// chunks were swept from under its running server. +#[test] +fn two_servers_at_one_root_path_keep_their_own_pins() { + let shared = shared_base("same-path"); + let fx = Fixture::new("same-path"); + let local_a = shared.join("sandbox-a/.oj-cache/start-bundle"); + let local_b = shared.join("sandbox-b/.oj-cache/start-bundle"); + let store_a = StartBundleStore::at_dirs( + &fx.root, + shared.join("start-bundle"), + local_a, + SHARED_KEEP_GENERATIONS, + "0.0.1-test", + VerifyMode::Standard, + "development", + ); + // B is another process: its own pin session. + let store_b = StartBundleStore::at_dirs( + &fx.root, + shared.join("start-bundle"), + local_b, + SHARED_KEEP_GENERATIONS, + "0.0.1-test", + VerifyMode::Standard, + "development", + ) + .pin_session("other-process"); + assert_ne!(store_a.pin_id, store_b.pin_id); + assert_eq!( + store_a.pin_id.split('-').next(), + store_b.pin_id.split('-').next(), + "one root hash" + ); + + let (key_a, pinned_a) = store_a.persist(&fx.start).unwrap(); + // B churns one more generation than the window holds, each a distinct + // closure, while A serves its generation live. + for i in 0..=SHARED_KEEP_GENERATIONS { + fx.write_module("a.tsx", &format!("export const a = {i} + 1000;")); + fx.write_build(&format!("bundle-b{i}")); + store_b.persist(&fx.start).unwrap(); + } + store_b.join_eviction(); + store_b.prune(DEFAULT_PRUNE_BUDGET_BYTES); + + assert!( + shared.join("start-bundle").join(&key_a).is_dir(), + "A's generation survives B's window" + ); + for (name, chunk) in pinned_a.chunks() { + assert!(chunk.path.is_file(), "A's chunk {name} was swept"); + } + let pins = fs::read_dir(shared.join("start-bundle").join(PINS_DIR)) + .unwrap() + .count(); + assert_eq!(pins, 2, "one pin per process"); + + // A idle for a long time refreshes its pin without persisting. + let pin_a = shared + .join("start-bundle") + .join(PINS_DIR) + .join(&store_a.pin_id); + let old = SystemTime::now() - Duration::from_secs(8 * 24 * 60 * 60); + set_mtime(&pin_a, old); + store_a.refresh_pin(); + let age = fs::metadata(&pin_a).unwrap().modified().unwrap(); + assert!(age.duration_since(old).unwrap() > Duration::from_secs(24 * 60 * 60)); + assert_eq!(fs::read_to_string(&pin_a).unwrap().trim(), key_a); +} + +// The window counts the generations of one salt: another app (here another +// mode) churning through the shared dir never evicts this one's generations, +// pinned or not. The byte budget is what bounds the directory as a whole. +#[test] +fn the_generation_window_is_per_salt() { + let shared = shared_base("window-salt"); + let a = Fixture::new("window-salt-a"); + let b = Fixture::new("window-salt-b"); + let store_a = split_store_at(&a.root, &shared, 2); + let (key_a, _) = store_a.persist(&a.start).unwrap(); + // A is gone: no pin protects its generation. + let _ = fs::remove_file( + shared + .join("start-bundle") + .join(PINS_DIR) + .join(&store_a.pin_id), + ); + let local_b = crate::cache_root(&b.root).join("start-bundle"); + let store_b = StartBundleStore::at_dirs( + &b.root, + shared.join("start-bundle"), + local_b, + 2, + "0.0.1-test", + VerifyMode::Standard, + "staging", + ); + for i in 0..4 { + b.write_module("a.tsx", &format!("export const a = {i};")); + b.write_build(&format!("bundle-b{i}")); + store_b.persist(&b.start).unwrap(); + std::thread::sleep(Duration::from_millis(20)); + } + store_b.join_eviction(); + assert!( + shared.join("start-bundle").join(&key_a).is_dir(), + "another salt's window leaves A's generation alone" + ); + let own = fs::read_dir(shared.join("start-bundle")) + .unwrap() + .flatten() + .filter(is_generation_dir) + .filter(|e| read_manifest(&e.path()).is_some_and(|m| m.salt_id == store_b.salt_id())) + .count(); + assert_eq!(own, 2, "B's own window holds"); + // The same churn under A's salt does evict it. + let store_b_dev = split_store_at(&b.root, &shared, 2); + for i in 0..4 { + b.write_module("a.tsx", &format!("export const a = {i} + 50;")); + b.write_build(&format!("bundle-b-dev{i}")); + store_b_dev.persist(&b.start).unwrap(); + std::thread::sleep(Duration::from_millis(20)); + } + store_b_dev.join_eviction(); + assert!(!shared.join("start-bundle").join(&key_a).is_dir()); +} diff --git a/crates/oj_cache/src/start_codegen.rs b/crates/oj_cache/src/start_codegen.rs index c0880df16..9d8fbf21c 100644 --- a/crates/oj_cache/src/start_codegen.rs +++ b/crates/oj_cache/src/start_codegen.rs @@ -196,11 +196,13 @@ impl StartCodegenStore { /// to `entry`. Losing the rename to a concurrent writer of the same key is /// fine: that entry holds the same content. fn publish_entry(&self, key: &str, entry: &Path, outputs: &[(&str, &Path)]) -> Option<()> { + // A fresh staging dir under an unpredictable name, created rather + // than reused, so nothing planted at the path is written through. let tmp = self .dir - .join(format!(".tmp-{}-{}", key.get(..16)?, std::process::id())); - let _ = fs::remove_dir_all(&tmp); - fs::create_dir_all(&tmp).ok()?; + .join(format!(".tmp-{}-{}", key.get(..16)?, integrity::temp_tag())); + fs::create_dir_all(&self.dir).ok()?; + fs::create_dir(&tmp).ok()?; if stage_entry(&tmp, outputs).is_none() { let _ = fs::remove_dir_all(&tmp); return None; @@ -394,7 +396,7 @@ fn stage_entry(tmp: &Path, outputs: &[(&str, &Path)]) -> Option<()> { let mut manifest: HashMap = HashMap::new(); for (name, src) in outputs { let bytes = fs::read(src).ok()?; - fs::write(tmp.join(name), &bytes).ok()?; + integrity::write_new(&tmp.join(name), &bytes).ok()?; manifest.insert((*name).to_string(), ExpectedFile::of(&bytes)); } write_entry_manifest(tmp, &manifest).ok() diff --git a/crates/oj_cache/src/store.rs b/crates/oj_cache/src/store.rs index 46e7cdd0b..d13fcecdf 100644 --- a/crates/oj_cache/src/store.rs +++ b/crates/oj_cache/src/store.rs @@ -12,27 +12,112 @@ //! scratch scripts that resolve bare imports relative to where they live, //! per-root pointer state (`current` files, memo maps), and any artifact //! that still embeds the app root. +//! +//! The store is a trust boundary: every oj on the machine serves what it +//! finds there without recompiling. So the directory has to be this user's +//! alone, as sshd treats `~/.ssh`: one owned by someone else, or writable by +//! the group or the world, is refused for the whole process, and one oj +//! creates is private (mode 0700). +use std::fs; use std::path::{Path, PathBuf}; +use std::sync::OnceLock; /// Bumped when the layout of the shared store changes shape; an older layout /// is simply a different directory, never misread. pub const STORE_VERSION: u32 = 1; /// The shared store directory, or `None` when the store is off (no -/// `OJ_STORE_DIR`, which `oj dev --store` sets for itself and every child), -/// in which case callers fall back to the per-app `cache_root` and lose -/// sharing, never correctness. +/// `OJ_STORE_DIR`, which `oj dev --store` sets for itself and every child) +/// or refused (see [`trusted_store_root_in`]), in which case callers fall +/// back to the per-app `cache_root` and lose sharing, never correctness. +/// Decided once per process: the env is a snapshot, and the directory's +/// ownership is checked when it is first used, not on every call. pub fn store_root() -> Option { - store_root_in(oj_env::get().knobs.store_dir.as_deref()) + static ROOT: OnceLock> = OnceLock::new(); + ROOT.get_or_init(|| trusted_store_root_in(oj_env::get().knobs.store_dir.as_deref())) + .clone() } /// [`store_root`] with the base dir given: the version segment is appended, -/// mirroring `cache_root`. +/// mirroring `cache_root`. Pure: no check of what is on disk. pub fn store_root_in(base: Option<&Path>) -> Option { Some(base?.join(format!("v{STORE_VERSION}"))) } +/// [`store_root_in`] for a directory about to be used: the base and the +/// version directory inside it are created private when missing, and an +/// existing one must be a directory this user owns that nobody else can +/// write (on Unix; elsewhere only its existence is checked). Anything else +/// is refused with one line on stderr, and the store is off: a directory +/// another user can write is one they can plant entries and symlinks in. +pub fn trusted_store_root_in(base: Option<&Path>) -> Option { + let base = base?; + let versioned = store_root_in(Some(base))?; + for dir in [base, versioned.as_path()] { + if let Err(reason) = ensure_private_dir(dir) { + eprintln!( + "oj: store: {} {reason}; the store is off for this process", + dir.display() + ); + return None; + } + } + Some(versioned) +} + +/// Creates `dir` with mode 0700 when it is missing (its parents with the +/// process umask, like any cache dir), then checks what is there. +fn ensure_private_dir(dir: &Path) -> Result<(), String> { + if fs::symlink_metadata(dir).is_err() { + if let Some(parent) = dir.parent() { + let _ = fs::create_dir_all(parent); + } + let mut builder = fs::DirBuilder::new(); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt as _; + builder.mode(0o700); + } + // Losing the creation to another oj of this user is fine: the + // check below sees what it made. + let _ = builder.create(dir); + } + let meta = fs::metadata(dir).map_err(|e| format!("cannot be read ({e})"))?; + if !meta.is_dir() { + return Err("is not a directory".to_string()); + } + check_private(&meta) +} + +#[cfg(unix)] +fn check_private(meta: &fs::Metadata) -> Result<(), String> { + use std::os::unix::fs::MetadataExt as _; + extern "C" { + fn geteuid() -> u32; + } + // SAFETY: geteuid takes no arguments and cannot fail. + let uid = unsafe { geteuid() }; + if meta.uid() != uid { + return Err(format!( + "is owned by uid {}, not this user (uid {uid})", + meta.uid() + )); + } + if meta.mode() & 0o022 != 0 { + return Err(format!( + "is writable by others (mode {:o})", + meta.mode() & 0o777 + )); + } + Ok(()) +} + +#[cfg(not(unix))] +fn check_private(_meta: &fs::Metadata) -> Result<(), String> { + Ok(()) +} + /// Root-relative identity for a path under `root`, with forward slashes on /// every platform: the form that makes a key or artifact mean the same thing /// in every worktree. A path outside `root` comes back `None`; callers treat @@ -171,3 +256,85 @@ mod tests { ); } } + +#[cfg(all(test, unix))] +mod trust_tests { + //! The store directory is refused unless it is this user's alone. + use super::*; + use std::os::unix::fs::PermissionsExt as _; + + fn base(label: &str) -> PathBuf { + let dir = + std::env::temp_dir().join(format!("oj-store-trust-{}-{label}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + dir + } + + #[test] + fn a_missing_store_is_created_private() { + let base = base("create"); + let root = trusted_store_root_in(Some(&base.join("nested/store"))).unwrap(); + assert_eq!(root, base.join("nested/store/v1")); + for dir in [base.join("nested/store"), root] { + let mode = fs::metadata(&dir).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o700, "{} is private", dir.display()); + } + } + + #[test] + fn a_store_others_can_write_is_refused_and_everything_stays_local() { + let base = base("world-writable"); + let store = base.join("store"); + fs::create_dir_all(&store).unwrap(); + fs::set_permissions(&store, fs::Permissions::from_mode(0o777)).unwrap(); + assert_eq!(trusted_store_root_in(Some(&store)), None, "world-writable"); + fs::set_permissions(&store, fs::Permissions::from_mode(0o770)).unwrap(); + assert_eq!(trusted_store_root_in(Some(&store)), None, "group-writable"); + fs::set_permissions(&store, fs::Permissions::from_mode(0o755)).unwrap(); + let root = trusted_store_root_in(Some(&store)).unwrap(); + // The version dir inside is checked the same way. + fs::set_permissions(&root, fs::Permissions::from_mode(0o777)).unwrap(); + assert_eq!( + trusted_store_root_in(Some(&store)), + None, + "v1 world-writable" + ); + fs::set_permissions(&root, fs::Permissions::from_mode(0o700)).unwrap(); + assert_eq!(trusted_store_root_in(Some(&store)), Some(root.clone())); + + // What a refusal means for the module cache: the shared half is off, + // reads and writes go to the app's own cache. + fs::set_permissions(&store, fs::Permissions::from_mode(0o777)).unwrap(); + let shared = trusted_store_root_in(Some(&store)).map(|r| r.join("modules")); + let cache = crate::PersistentCache::new(base.join("app/.oj-cache/v1"), "0.0.1-test") + .with_shared(shared); + let key = cache.disk_key(&crate::module_key( + &crate::source_hash(b"src"), + "/src/a.ts", + "dev", + )); + let module = crate::CachedModule { + code: "export const x = 1;".into(), + ..Default::default() + }; + cache.put(&key, &module); + assert_eq!(cache.get(&key).as_ref(), Some(&module)); + assert!(base.join("app/.oj-cache/v1").join(&key[..2]).is_dir()); + assert!(!root.join("modules").exists(), "nothing reached the store"); + } + + #[test] + fn a_file_or_a_symlink_in_the_stores_place_is_refused() { + let base = base("not-a-dir"); + fs::create_dir_all(&base).unwrap(); + fs::write(base.join("file"), b"").unwrap(); + assert_eq!(trusted_store_root_in(Some(&base.join("file"))), None); + // A symlink to a directory of this user is a directory of this user. + fs::create_dir_all(base.join("real")).unwrap(); + std::os::unix::fs::symlink(base.join("real"), base.join("link")).unwrap(); + assert_eq!( + trusted_store_root_in(Some(&base.join("link"))), + Some(base.join("link/v1")) + ); + } +} diff --git a/crates/oj_env/src/knobs.rs b/crates/oj_env/src/knobs.rs index 155b14b93..6b0f223f3 100644 --- a/crates/oj_env/src/knobs.rs +++ b/crates/oj_env/src/knobs.rs @@ -30,8 +30,9 @@ pub struct Knobs { pub cache_dir: Option, /// The shared oj store's base dir, `OJ_STORE_DIR`: `oj dev --store` sets it /// (to the given DIR, else `$XDG_CACHE_HOME/oj/store`, else - /// `$HOME/.cache/oj/store`) for itself and every child. Unset or empty, - /// there is no shared store (`None`). + /// `$HOME/.cache/oj/store`) for itself and every child, and `oj dev` + /// without the flag clears an inherited one for itself and its children. + /// Unset or empty, there is no shared store (`None`). pub store_dir: Option, /// `OJ_STORE_REMOTE`, when non-empty: the remote store dev servers read /// through (and push to under `store_push`). @@ -39,6 +40,9 @@ pub struct Knobs { /// `OJ_STORE_TOKEN`, when non-empty: the bearer the remote store gets. pub store_token: Option, /// `OJ_STORE_PUSH` truthy: relocatable entries are pushed to the remote. + /// A pushed entry carries the module's source map with `sourcesContent`, + /// so this sends the app's own source to the substituter: push only to + /// one that is as private as the checkout. pub store_push: bool, /// `OJ_STORE_READ_TOKEN`, when non-empty: `oj store serve` requires it on /// reads (unset = public reads). diff --git a/crates/oj_js/src/code_cache.rs b/crates/oj_js/src/code_cache.rs index dfeaf83b9..0a03a2a3b 100644 --- a/crates/oj_js/src/code_cache.rs +++ b/crates/oj_js/src/code_cache.rs @@ -162,7 +162,23 @@ pub fn consume_only() { /// bytecode — it only keeps incompatible generations from piling up as dead /// weight. pub fn engine_abi_key() -> String { - format!("v8-{}", deno_core::v8::VERSION_STRING) + engine_abi_key_for(deno_core::v8::VERSION_STRING, V8_FLAGS) +} + +/// The V8 flags oj sets beyond deno_core's own defaults: none today. Listed +/// here because they are part of the bytecode ABI as much as the version is +/// (a flag that changes code generation makes every cached entry a +/// rejection, which the cache would then rewrite on every boot), so the +/// key folds them in and a flag change starts a new directory instead. +pub const V8_FLAGS: &str = ""; + +/// [`engine_abi_key`] for the given V8 version and flags. With no flags the +/// key is the version alone, the name every existing cache dir has. +pub fn engine_abi_key_for(version: &str, flags: &str) -> String { + if flags.is_empty() { + return format!("v8-{version}"); + } + format!("v8-{version}-{:016x}", hash64(flags.as_bytes())) } /// Stable across processes: `DefaultHasher::new()` is keyless SipHash, so two @@ -452,9 +468,13 @@ impl FsCodeCache { /// Atomic publish: write-then-rename, so a concurrent reader never sees a /// torn half-write. The tmp name carries a process-wide sequence beside the -/// pid: several caches can write the same entry, and a pid-only suffix let -/// two writers rename a torn file into place. +/// pid (several caches can write the same entry, and a pid-only suffix let +/// two writers rename a torn file into place) and a random part, and the +/// tmp file is created new: in a shared directory, a name something else +/// planted ahead of the write (a symlink out of the store) fails the write +/// instead of being followed. fn write_entry(path: &std::path::Path, bytes: &[u8]) { + use std::io::Write as _; if path .parent() .is_some_and(|dir| std::fs::create_dir_all(dir).is_err()) @@ -463,12 +483,36 @@ fn write_entry(path: &std::path::Path, bytes: &[u8]) { } static TMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); let seq = TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - let tmp = path.with_extension(format!("tmp{}-{seq}", std::process::id())); - if std::fs::write(&tmp, bytes).is_ok() && std::fs::rename(&tmp, path).is_err() { + let tmp = path.with_extension(format!( + "tmp{}-{seq}-{:x}", + std::process::id(), + random_tag() + )); + let written = std::fs::File::options() + .write(true) + .create_new(true) + .open(&tmp) + .and_then(|mut file| file.write_all(bytes)); + if written.is_err() || std::fs::rename(&tmp, path).is_err() { let _ = std::fs::remove_file(&tmp); } } +/// A number nothing outside this process predicts, for temp names: a hash +/// of the pid, the clock and a stack address the loader randomized. +fn random_tag() -> u64 { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos()); + let marker = &now as *const u128 as usize; + let mut hasher = std::hash::DefaultHasher::new(); + hasher.write_u32(std::process::id()); + hasher.write_u128(now); + hasher.write_usize(marker); + hasher.write_usize(random_tag as fn() -> u64 as usize); + hasher.finish() +} + /// One-shot bundle names collapse to a stable key. Vite's loadConfigFromFile /// writes `.timestamp--.mjs` and oj's fallback config /// loader `oj-vite-config--.tmp.mjs`, a fresh name per load: @@ -518,6 +562,22 @@ pub const STALE_TMP_MAX_AGE: std::time::Duration = std::time::Duration::from_sec /// staying negligible next to an app checkout. pub const DEFAULT_MAX_BYTES: u64 = 128 << 20; +/// The budget for a directory the shared store holds, which every app and +/// worktree of the user warms: with the per-app budget there, each app's +/// boot pruned the others' bytecode and every boot was a cold one. +pub const SHARED_MAX_BYTES: u64 = 1 << 30; + +/// The budget to prune with when `OJ_CODE_CACHE_MAX_BYTES` is unset: +/// [`SHARED_MAX_BYTES`] for a directory in the shared store, else +/// [`DEFAULT_MAX_BYTES`]. +pub fn default_max_bytes(shared: bool) -> u64 { + if shared { + SHARED_MAX_BYTES + } else { + DEFAULT_MAX_BYTES + } +} + impl CodeCache for FsCodeCache { fn get_sync( &self, @@ -610,6 +670,77 @@ mod tests { assert!(!key.contains(crate_version)); } } + + // The flags are part of the ABI: a flag that changes code generation + // must start a new directory, not turn every entry into a rejection the + // cache rewrites each boot. No flags keeps the plain version name. + #[test] + fn v8_flags_partition_the_cache_directory() { + assert_eq!(engine_abi_key_for("13.0.1", ""), "v8-13.0.1"); + let a = engine_abi_key_for("13.0.1", "--no-lazy"); + let b = engine_abi_key_for("13.0.1", "--no-lazy --max-lazy"); + assert_ne!(a, b, "two flag strings, two directories"); + assert_ne!(a, "v8-13.0.1"); + assert!(a.starts_with("v8-13.0.1-"), "{a}"); + assert_eq!(a, engine_abi_key_for("13.0.1", "--no-lazy"), "stable"); + } + + // Under the store one directory serves every app. Two apps that each + // write more than the per-app budget must both stay warm after each + // one's boot prune, which the shared budget allows for. + #[test] + fn two_apps_on_one_shared_directory_keep_each_others_entries() { + let dir = tempfile::tempdir().unwrap(); + let store = dir.path().join("cc"); + let per_app: u64 = 2_000; + let shared = per_app * 8; + // The shared budget holds several apps' working sets. + const _: () = assert!(SHARED_MAX_BYTES >= DEFAULT_MAX_BYTES * 8); + assert_eq!(default_max_bytes(false), DEFAULT_MAX_BYTES); + assert_eq!(default_max_bytes(true), SHARED_MAX_BYTES); + let roots = [dir.path().join("a"), dir.path().join("b")]; + for (i, root) in roots.iter().enumerate() { + std::fs::create_dir_all(root.join("src")).unwrap(); + std::fs::write( + root.join("package.json"), + format!("{{\"name\":\"app-{i}\"}}"), + ) + .unwrap(); + } + let payload = vec![0u8; 92]; + let caches: Vec = roots + .iter() + .map(|r| FsCodeCache::with_roots(store.clone(), vec![r.clone()])) + .collect(); + // Each app writes 3,000 bytes: over its own budget, under a quarter + // of the shared one. + for (cache, root) in caches.iter().zip(&roots) { + for i in 0..30u64 { + let spec = Url::from_file_path(root.join(format!("src/m{i}.js"))).unwrap(); + cache.put(&spec, CodeCacheType::EsModule, i, &payload); + } + } + flush_at_exit(); + // Both apps boot and prune with the shared budget. + for cache in &caches { + cache.prune_entries(shared); + } + for (cache, root) in caches.iter().zip(&roots) { + for i in 0..30u64 { + let spec = Url::from_file_path(root.join(format!("src/m{i}.js"))).unwrap(); + assert!( + cache.get(&spec, CodeCacheType::EsModule, i).is_some(), + "{} m{i} survived the other app's boot", + root.display() + ); + } + } + // The per-app budget there is what evicted: one boot leaves less + // than both apps' entries. + caches[1].prune_entries(per_app); + let left = std::fs::read_dir(&store).unwrap().count(); + assert!(left < 60, "the per-app budget evicts across apps: {left}"); + } } #[cfg(test)] diff --git a/crates/oj_js/src/tracing_fs.rs b/crates/oj_js/src/tracing_fs.rs index 3de02942f..241ee3097 100644 --- a/crates/oj_js/src/tracing_fs.rs +++ b/crates/oj_js/src/tracing_fs.rs @@ -1,12 +1,17 @@ // SPDX-License-Identifier: MIT // Copyright (c) 2026 Raphael Amorim -//! A [`FileSystem`] wrapper that records content reads (pulp P2): the one -//! seam every fs binding style crosses — `Deno.*` ops, `node:fs` CJS, and -//! named ESM imports alike — so plugin reads the JS-level interposition -//! cannot see still land in the trace. Delegates every operation verbatim; -//! recording happens on `open` with read intent and on the `read_file` -//! family (RealFs overrides the trait's open-routed defaults). +//! A [`FileSystem`] wrapper that records what a plugin looked at (pulp P2): +//! the one seam every fs binding style crosses — `Deno.*` ops, `node:fs` CJS, +//! and named ESM imports alike — so plugin reads the JS-level interposition +//! cannot see still land in the trace. Delegates every operation verbatim. +//! Content reads (`open` with read intent, the `read_file` family) and +//! existence checks (`stat`, `lstat`, `exists`, `realpath`, `read_link`, +//! `is_file`, `is_dir`) are file rows: a check's answer is as much an input +//! as a file's bytes, and the row's semantics already cover both directions +//! (a missing file is a digest-less row, a present one its digest). +//! Directory listings (`read_dir`) are directory rows, kept apart because +//! their digest is of the listing, not of any bytes. //! //! Generated against deno_fs 0.169.0's trait surface; `cargo test //! -p oj_js tracing_fs` carries a coverage guard that fails when a @@ -39,42 +44,129 @@ use deno_runtime::deno_permissions::CheckedPathBuf; /// interleave on one isolate, so Rust-side attribution is impossible — the /// JS-side AsyncLocalStorage buckets carry the precise attribution, and this /// log is the safety net for reads they cannot see). +/// +/// Off by default: a host whose outputs are never persisted (no store) opens +/// no window, and a read then costs one relaxed atomic load, no lock. #[derive(Debug, Default)] pub struct ReadLog { - windows: Mutex>>, + windows: Mutex>, next: std::sync::atomic::AtomicU64, + /// Windows open now: the hot path's cheap "nothing to do" check. + open: std::sync::atomic::AtomicUsize, + enabled: std::sync::atomic::AtomicBool, +} + +/// The window id `begin` hands out while tracing is off: nothing to finish. +const NO_WINDOW: u64 = u64::MAX; + +/// What one open window has seen so far. +#[derive(Debug, Default)] +struct Window { + files: std::collections::HashSet, + dirs: std::collections::HashSet, +} + +/// What a window saw by the time it was finished: files whose bytes or +/// existence the isolate looked at, and directories it listed. Paths are +/// absolute (a relative one is resolved against the process cwd when it is +/// recorded, the cwd the isolate's op used). +#[derive(Debug, Default, PartialEq, Eq)] +pub struct Reads { + pub files: Vec, + pub dirs: Vec, +} + +impl Reads { + pub fn is_empty(&self) -> bool { + self.files.is_empty() && self.dirs.is_empty() + } +} + +/// A recorded path, as the trace rows tell them apart. +#[derive(Clone, Copy)] +enum Kind { + File, + Dir, } impl ReadLog { + /// Whether windows open at all. Only a server that persists what the + /// plugins produce needs the trace; everyone else keeps the fast path. + pub fn set_enabled(&self, on: bool) { + self.enabled.store(on, std::sync::atomic::Ordering::Release); + } + pub fn begin(&self) -> u64 { + if !self.enabled.load(std::sync::atomic::Ordering::Acquire) { + return NO_WINDOW; + } let id = self.next.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - self.windows - .lock() - .unwrap_or_else(|e| e.into_inner()) - .insert(id, Default::default()); + let mut windows = self.windows.lock().unwrap_or_else(|e| e.into_inner()); + windows.insert(id, Default::default()); + self.open + .store(windows.len(), std::sync::atomic::Ordering::Release); id } - pub fn finish(&self, id: u64) -> Vec { - self.windows - .lock() - .unwrap_or_else(|e| e.into_inner()) - .remove(&id) - .map(|set| set.into_iter().collect()) - .unwrap_or_default() + pub fn finish(&self, id: u64) -> Reads { + if id == NO_WINDOW { + return Reads::default(); + } + let mut windows = self.windows.lock().unwrap_or_else(|e| e.into_inner()); + let seen = windows.remove(&id); + self.open + .store(windows.len(), std::sync::atomic::Ordering::Release); + seen.map(|w| Reads { + files: w.files.into_iter().collect(), + dirs: w.dirs.into_iter().collect(), + }) + .unwrap_or_default() } + /// A file whose bytes or existence the isolate looked at. fn record(&self, path: &Path) { + self.record_as(Kind::File, path); + } + + /// A directory the isolate listed. + fn record_dir(&self, path: &Path) { + self.record_as(Kind::Dir, path); + } + + fn record_as(&self, kind: Kind, path: &Path) { + if self.open.load(std::sync::atomic::Ordering::Acquire) == 0 { + return; + } let mut windows = self.windows.lock().unwrap_or_else(|e| e.into_inner()); if windows.is_empty() { return; } - for set in windows.values_mut() { - set.insert(path.to_path_buf()); + // The op resolved a relative path against the process cwd; the + // server that digests the row may run from another directory. + let path = if path.is_absolute() { + path.to_path_buf() + } else { + match std::env::current_dir() { + Ok(cwd) => cwd.join(path), + Err(_) => path.to_path_buf(), + } + }; + for w in windows.values_mut() { + match kind { + Kind::File => w.files.insert(path.clone()), + Kind::Dir => w.dirs.insert(path.clone()), + }; } } } +/// Whether an open reads the file or probes it: a write-only or append +/// open makes bytes rather than depending on them (a plugin's log line +/// during its transform is not an input of its output). +fn looks_at(options: &OpenOptions) -> bool { + options.read || !(options.write || options.append) +} + #[derive(Debug)] pub struct TracingFs { inner: RealFs, @@ -89,6 +181,10 @@ impl TracingFs { fn record(&self, path: &Path) { self.log.record(path); } + + fn record_dir(&self, path: &Path) { + self.log.record_dir(path); + } } #[async_trait::async_trait(?Send)] @@ -110,7 +206,7 @@ impl FileSystem for TracingFs { } fn open_sync(&self, path: &CheckedPath, options: OpenOptions) -> FsResult> { - if options.read { + if looks_at(&options) { self.record(path.as_ref()); } self.inner.open_sync(path, options) @@ -121,7 +217,7 @@ impl FileSystem for TracingFs { path: CheckedPathBuf, options: OpenOptions, ) -> FsResult> { - if options.read { + if looks_at(&options) { self.record(path.as_ref()); } self.inner.open_async(path, options).await @@ -223,18 +319,22 @@ impl FileSystem for TracingFs { } fn stat_sync(&self, path: &CheckedPath) -> FsResult { + self.record(path.as_ref()); self.inner.stat_sync(path) } async fn stat_async(&self, path: CheckedPathBuf) -> FsResult { + self.record(path.as_ref()); self.inner.stat_async(path).await } fn lstat_sync(&self, path: &CheckedPath) -> FsResult { + self.record(path.as_ref()); self.inner.lstat_sync(path) } async fn lstat_async(&self, path: CheckedPathBuf) -> FsResult { + self.record(path.as_ref()); self.inner.lstat_async(path).await } @@ -247,18 +347,22 @@ impl FileSystem for TracingFs { } fn realpath_sync(&self, path: &CheckedPath) -> FsResult { + self.record(path.as_ref()); self.inner.realpath_sync(path) } async fn realpath_async(&self, path: CheckedPathBuf) -> FsResult { + self.record(path.as_ref()); self.inner.realpath_async(path).await } fn read_dir_sync(&self, path: &CheckedPath) -> FsResult> { + self.record_dir(path.as_ref()); self.inner.read_dir_sync(path) } async fn read_dir_async(&self, path: CheckedPathBuf) -> FsResult { + self.record_dir(path.as_ref()); self.inner.read_dir_async(path).await } @@ -305,10 +409,12 @@ impl FileSystem for TracingFs { } fn read_link_sync(&self, path: &CheckedPath) -> FsResult { + self.record(path.as_ref()); self.inner.read_link_sync(path) } async fn read_link_async(&self, path: CheckedPathBuf) -> FsResult { + self.record(path.as_ref()); self.inner.read_link_async(path).await } @@ -407,18 +513,22 @@ impl FileSystem for TracingFs { } fn is_file_sync(&self, path: &CheckedPath) -> bool { + self.record(path.as_ref()); self.inner.is_file_sync(path) } fn is_dir_sync(&self, path: &CheckedPath) -> bool { + self.record(path.as_ref()); self.inner.is_dir_sync(path) } fn exists_sync(&self, path: &CheckedPath) -> bool { + self.record(path.as_ref()); self.inner.exists_sync(path) } async fn exists_async(&self, path: CheckedPathBuf) -> FsResult { + self.record(path.as_ref()); self.inner.exists_async(path).await } @@ -440,18 +550,38 @@ impl FileSystem for TracingFs { mod tests { use super::*; + #[test] + fn a_log_that_is_off_opens_no_window_and_records_nothing() { + let log = ReadLog::default(); + let id = log.begin(); + log.record(Path::new("/one.txt")); + assert!(log.finish(id).is_empty(), "off by default: no window"); + assert_eq!(log.open.load(std::sync::atomic::Ordering::Acquire), 0); + assert!(log.windows.lock().unwrap().is_empty()); + log.set_enabled(true); + let id = log.begin(); + log.record(Path::new("/two.txt")); + assert_eq!(log.finish(id).files, vec![PathBuf::from("/two.txt")]); + assert_eq!( + log.open.load(std::sync::atomic::Ordering::Acquire), + 0, + "the counter follows the windows" + ); + } + #[test] fn reads_are_charged_to_every_open_window_and_only_then() { let log = ReadLog::default(); + log.set_enabled(true); // No window open: recording is a no-op (the hot steady-state). log.record(Path::new("/idle.txt")); let a = log.begin(); log.record(Path::new("/one.txt")); let b = log.begin(); log.record(Path::new("/two.txt")); - let got_a = log.finish(a); + let got_a = log.finish(a).files; log.record(Path::new("/three.txt")); - let got_b = log.finish(b); + let got_b = log.finish(b).files; assert!(got_a.contains(&PathBuf::from("/one.txt"))); assert!( got_a.contains(&PathBuf::from("/two.txt")), @@ -479,6 +609,7 @@ mod tests { std::fs::write(&file, b"hello").unwrap(); let log = Arc::new(ReadLog::default()); + log.set_enabled(true); let fs = TracingFs::new(log.clone()); let id = log.begin(); let checked = CheckedPathBuf::unsafe_new(file.clone()); @@ -486,7 +617,7 @@ mod tests { .read_file_sync(&checked.as_checked_path(), OpenOptions::read()) .unwrap(); assert_eq!(&*read, b"hello", "delegation is verbatim"); - let seen = log.finish(id); + let seen = log.finish(id).files; assert!( seen.contains(&file), "the read landed in the window: {seen:?}" @@ -503,8 +634,101 @@ mod tests { .unwrap(); let seen = log.finish(id); assert!( - !seen.contains(&out), + !seen.files.contains(&out), "write-only open is not a content read" ); + assert!(seen.dirs.is_empty()); + } + + /// A temp dir of this test's own, with a file in it. + fn scratch(tag: &str) -> (PathBuf, PathBuf) { + let dir = std::env::temp_dir().join(format!("oj-tracingfs-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("input.txt"); + std::fs::write(&file, b"hello").unwrap(); + (dir, file) + } + + #[test] + fn a_directory_listing_is_a_directory_row_not_a_file_row() { + use deno_runtime::deno_permissions::CheckedPathBuf; + let (dir, file) = scratch("readdir"); + let log = Arc::new(ReadLog::default()); + log.set_enabled(true); + let fs = TracingFs::new(log.clone()); + let id = log.begin(); + let checked = CheckedPathBuf::unsafe_new(dir.clone()); + let entries = fs.read_dir_sync(&checked.as_checked_path()).unwrap(); + assert_eq!(entries.len(), 1, "delegation is verbatim"); + let seen = log.finish(id); + assert_eq!(seen.dirs, vec![dir.clone()]); + assert!( + !seen.files.contains(&dir) && !seen.files.contains(&file), + "a listing names no file: {seen:?}" + ); + } + + #[test] + fn existence_checks_are_file_rows() { + use deno_runtime::deno_permissions::CheckedPathBuf; + let (dir, file) = scratch("exists"); + let missing = dir.join("absent.txt"); + let log = Arc::new(ReadLog::default()); + log.set_enabled(true); + let fs = TracingFs::new(log.clone()); + let id = log.begin(); + let present = CheckedPathBuf::unsafe_new(file.clone()); + let absent = CheckedPathBuf::unsafe_new(missing.clone()); + assert!(fs.exists_sync(&present.as_checked_path())); + assert!(!fs.exists_sync(&absent.as_checked_path())); + assert!(fs.stat_sync(&absent.as_checked_path()).is_err()); + let link = dir.join("input.lnk"); + let checked_link = CheckedPathBuf::unsafe_new(link.clone()); + fs.lstat_sync(&checked_link.as_checked_path()).ok(); + fs.realpath_sync(&present.as_checked_path()).unwrap(); + assert!(fs.is_file_sync(&present.as_checked_path())); + // An open that probes without reading or writing is a check too + // (RealFs refuses the mode-less open; the probe was still made). + let probe = CheckedPathBuf::unsafe_new(dir.join("probe.txt")); + let mut options = OpenOptions::read(); + options.read = false; + fs.open_sync(&probe.as_checked_path(), options).ok(); + let seen = log.finish(id); + for p in [&file, &missing, &link, &dir.join("probe.txt")] { + assert!(seen.files.contains(p), "{p:?} not in {seen:?}"); + } + assert!(seen.dirs.is_empty(), "a check lists nothing: {seen:?}"); + } + + #[test] + fn a_relative_path_is_recorded_against_the_process_cwd() { + let log = ReadLog::default(); + log.set_enabled(true); + let id = log.begin(); + log.record(Path::new("package.json")); + log.record_dir(Path::new("src")); + let seen = log.finish(id); + let cwd = std::env::current_dir().unwrap(); + assert_eq!(seen.files, vec![cwd.join("package.json")]); + assert_eq!(seen.dirs, vec![cwd.join("src")]); + } + + #[test] + fn checks_and_listings_cost_nothing_with_no_window_open() { + use deno_runtime::deno_permissions::CheckedPathBuf; + let (dir, file) = scratch("idle"); + let log = Arc::new(ReadLog::default()); + log.set_enabled(true); + let fs = TracingFs::new(log.clone()); + let checked_dir = CheckedPathBuf::unsafe_new(dir.clone()); + let checked_file = CheckedPathBuf::unsafe_new(file.clone()); + fs.read_dir_sync(&checked_dir.as_checked_path()).unwrap(); + fs.exists_sync(&checked_file.as_checked_path()); + fs.stat_sync(&checked_file.as_checked_path()).unwrap(); + assert!(log.windows.lock().unwrap().is_empty(), "nothing was kept"); + // The next window starts empty: nothing leaked from the idle period. + let id = log.begin(); + assert!(log.finish(id).is_empty()); } } diff --git a/crates/oj_server/build.rs b/crates/oj_server/build.rs index d24ba1eaa..1aa8d62f0 100644 --- a/crates/oj_server/build.rs +++ b/crates/oj_server/build.rs @@ -2,6 +2,7 @@ // Copyright (c) 2026 Raphael Amorim fn main() { + source_id(); // Test binaries load napi addons (the dep optimizer's rolldown), which // resolve napi_* symbols against the running executable. Keep all global // symbols exported from test executables, as crates/oj_js/build.rs does; @@ -12,3 +13,56 @@ fn main() { #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] println!("cargo:rustc-link-arg-tests=-rdynamic"); } + +/// `OJ_SOURCE_ID`: a digest of the sources of every crate that shapes +/// compiled output, plus the lockfile. Two builds of one package version +/// from different sources (a nightly, a branch, a dirty tree) then salt +/// their persistent caches apart, where the version alone would let one +/// serve the other's compiler output. +fn source_id() { + use std::hash::Hasher; + let crates = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(".."); + let mut files = Vec::new(); + for name in [ + "oj_cache", + "oj_compiler", + "oj_config", + "oj_css", + "oj_env", + "oj_js", + "oj_resolver", + "oj_server", + "oj_stylex", + ] { + let src = crates.join(name).join("src"); + println!("cargo:rerun-if-changed={}", src.display()); + walk(&src, &mut files); + } + let lock = crates.join("../Cargo.lock"); + println!("cargo:rerun-if-changed={}", lock.display()); + files.push(lock); + files.sort(); + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + for file in files { + if let Ok(bytes) = std::fs::read(&file) { + let rel = file.strip_prefix(&crates).unwrap_or(&file); + hasher.write(rel.to_string_lossy().as_bytes()); + hasher.write(&bytes); + } + } + println!("cargo:rustc-env=OJ_SOURCE_ID={:016x}", hasher.finish()); +} + +fn walk(dir: &std::path::Path, out: &mut Vec) { + for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() { + let path = entry.path(); + if path.is_dir() { + walk(&path, out); + } else if path + .extension() + .is_some_and(|e| e == "rs" || e == "mjs" || e == "js") + { + out.push(path); + } + } +} diff --git a/crates/oj_server/src/assets/plugin-host.mjs b/crates/oj_server/src/assets/plugin-host.mjs index 862e155bd..4929a120b 100644 --- a/crates/oj_server/src/assets/plugin-host.mjs +++ b/crates/oj_server/src/assets/plugin-host.mjs @@ -2461,30 +2461,79 @@ let emitCounter = 0; // `chunkFileNames` before generateBundle so `this.getFileName(refId)` resolves. const transformEmitStore = new AsyncLocalStorage(); -// Patch the shared node:fs CJS object so plugin reads during a transform land -// in the active read bucket. The host's own reads use named ESM imports bound -// before this patch, so they are never recorded. +// Patch the shared node:fs CJS object so what a plugin looks at during a +// transform lands in the active read bucket: the files it reads or checks +// for (readFile, exists, stat, access, realpath, open: a check's answer is an +// input as much as a file's bytes) and the directories it lists (readdir, +// opendir). A path is taken as node:fs takes it, a string, a file URL or a +// Buffer, and a relative one is resolved against the cwd the call used, so +// the server digests the right file from wherever it runs. A descriptor read +// (readFileSync(fd)) is covered by the openSync that made the descriptor. +// The host's own reads use named ESM imports bound before this patch, so +// they are never recorded. (() => { try { const req = createRequire(import.meta.url); const fsmod = req("fs"); - const record = (p) => { + const pathOf = (p) => { + if (typeof p === "string") return p; + if (p instanceof URL) return p.protocol === "file:" ? fileURLToPath(p) : null; + if (ArrayBuffer.isView(p)) return new TextDecoder().decode(p); + return null; + }; + const record = (kind, p) => { const bucket = transformReadStore.getStore(); - if (bucket && typeof p === "string") bucket.add(p); + if (!bucket) return; + const path = pathOf(p); + if (path != null) bucket[kind].add(pathResolve(path)); }; - const wrap = (obj, name, pathArg) => { - const orig = obj[name]; + // open with a flag that writes makes bytes rather than depending on them + // (a plugin's log line during its transform is not an input): only an + // open that reads, or probes with no mode at all, is recorded. + const O_WRONLY = fsmod.constants?.O_WRONLY ?? 1; + const O_RDWR = fsmod.constants?.O_RDWR ?? 2; + const opensToRead = (flags) => { + if (flags == null || typeof flags === "function") return true; + if (typeof flags === "string") return flags.startsWith("r"); + if (typeof flags === "number") return (flags & (O_WRONLY | O_RDWR)) === 0; + return false; + }; + const wrap = (obj, name, kind, when = () => true) => { + const orig = obj?.[name]; if (typeof orig !== "function" || orig.__ojTraced) return; const patched = function (...args) { - record(args[pathArg]); + if (when(args[1])) record(kind, args[0]); return orig.apply(this, args); }; + // realpathSync.native and the like ride on the function object. + Object.assign(patched, orig); patched.__ojTraced = true; obj[name] = patched; }; - wrap(fsmod, "readFileSync", 0); - wrap(fsmod, "readFile", 0); - if (fsmod.promises) wrap(fsmod.promises, "readFile", 0); + for (const name of [ + "readFileSync", + "readFile", + "existsSync", + "exists", + "statSync", + "stat", + "lstatSync", + "lstat", + "accessSync", + "access", + "realpathSync", + "realpath", + ]) + wrap(fsmod, name, "files"); + wrap(fsmod.realpathSync, "native", "files"); + wrap(fsmod.realpath, "native", "files"); + wrap(fsmod, "openSync", "files", opensToRead); + wrap(fsmod, "open", "files", opensToRead); + for (const name of ["readdirSync", "readdir", "opendirSync", "opendir"]) wrap(fsmod, name, "dirs"); + const promises = fsmod.promises; + for (const name of ["readFile", "stat", "lstat", "access", "realpath"]) wrap(promises, name, "files"); + wrap(promises, "open", "files", opensToRead); + for (const name of ["readdir", "opendir"]) wrap(promises, name, "dirs"); } catch {} })(); @@ -2600,12 +2649,14 @@ function decoratePluginError(e, plugin, id) { const watchedFiles = new Set(); const transformWatchStore = new AsyncLocalStorage(); -// Files a plugin hook READS during a transform (pulp P2 constructive traces): -// the dev server digests them into the cached entry so a warm hit re-verifies -// them instead of serving output whose side inputs changed. Recording happens -// by patching the node:fs module object below; plugins that bind NAMED esm -// imports of node:fs bypass the patch (Deno's syncBuiltinESMExports is a -// no-op) and are covered by the Rust TracingFs ops layer instead. +// What a plugin hook looks at during a transform (pulp P2 constructive +// traces), `{ files, dirs }`: the files it reads or checks for and the +// directories it lists. The dev server digests them into the cached entry so +// a warm hit re-verifies them instead of serving output whose side inputs +// changed. Recording happens by patching the node:fs module object above; +// plugins that bind NAMED esm imports of node:fs bypass the patch (Deno's +// syncBuiltinESMExports is a no-op) and are covered by the Rust TracingFs +// ops layer instead. const transformReadStore = new AsyncLocalStorage(); // Per-transform map of oj-resolved imports (spec -> id) the Rust side computes and // passes in, so a plugin's `this.resolve` during transform is a local lookup rather @@ -6460,7 +6511,8 @@ async function transform(c, code, id, resolvedJson, phase, priorJson) { JSON.stringify({ code: current, watchFiles: [...bucket], - readFiles: [...readBucket], + readFiles: [...readBucket.files], + readDirs: [...readBucket.dirs], maps, mapPlugins, mapBroken, @@ -6487,7 +6539,7 @@ async function transform(c, code, id, resolvedJson, phase, priorJson) { for (const { p, fn } of pluginsWithHook(c, "moduleParsed")) await fn.call(ctxFor(c, p), info); return result(); }; - const readBucket = new Set(); + const readBucket = { files: new Set(), dirs: new Set() }; return transformWatchStore.run(bucket, () => transformEmitStore.run(chunkBucket, () => transformResolveStore.run({ importer: id, map: resolveMap }, () => transformReadStore.run(readBucket, runLoop)), @@ -8656,7 +8708,9 @@ async function run(hook, args, c) { // from a virtual (UnoCSS's uno.css, WindiCSS): the dev server compiles app // modules each session for them instead of serving its persistent cache. return String( - c.plugins.some((p) => p && typeof p.name === "string" && /^(unocss|windicss|vite-plugin-windicss)\b/.test(p.name)), + c.plugins.some( + (p) => p && typeof p.name === "string" && /^(unocss|windicss|vite-plugin-windicss)\b/.test(p.name), + ), ); } if (hook === "getHasLoad") { diff --git a/crates/oj_server/src/lib.rs b/crates/oj_server/src/lib.rs index 29d31e48d..fad57a7a0 100644 --- a/crates/oj_server/src/lib.rs +++ b/crates/oj_server/src/lib.rs @@ -311,7 +311,11 @@ pub fn prepare_cache_root(root: &Path) { let budget = match oj_env::get().knobs.code_cache_max_bytes { Some(0) => None, Some(bytes) => Some(bytes), - None => Some(oj_js::code_cache::DEFAULT_MAX_BYTES), + // One directory for every app and worktree under the store: a + // budget sized for an app alone would have each boot evict the rest. + None => Some(oj_js::code_cache::default_max_bytes( + oj_cache::store::store_root().is_some(), + )), }; std::thread::spawn(move || { let cache = oj_js::code_cache::FsCodeCache::new(current); @@ -1662,7 +1666,19 @@ fn module_cache_config_salt( // internal consistency, not realpath identity. let workspace = oj_cache::store::workspace_root(root); let mut hasher = blake3::Hasher::new(); + // The root's own place in the workspace: entries name in-workspace files + // outside the root by their `/@fs/@mono/` url, which a reader + // expands against ITS workspace, so two checkouts whose roots sit at + // different depths (a stray `node_modules` above one of them) must not + // share a key. + hasher.update(b"\0pos="); + hasher.update( + oj_cache::store::rel_key(&workspace, root) + .unwrap_or_default() + .as_bytes(), + ); optimize::hash_lockfiles(root, &mut hasher); + hash_linked_packages(root, &workspace, &mut hasher); // Every tsconfig at the root, not the top one alone: the resolver follows // `references` and `extends`, and Vite's template keeps `paths` in // tsconfig.app.json. @@ -1737,6 +1753,94 @@ fn module_cache_config_salt( format!("cfg={}", hasher.finalize().to_hex()) } +/// The persistent cache's tool identity: the package version and a digest +/// of the sources it was built from (`OJ_SOURCE_ID`, from the build +/// script), so two builds of one version never serve each other's compiler +/// output through a shared store. +pub(crate) const fn tool_version() -> &'static str { + concat!(env!("CARGO_PKG_VERSION"), "+", env!("OJ_SOURCE_ID")) +} + +/// Packages linked into `node_modules` from outside any registry layout (a +/// workspace package, `npm link`, a `file:` dependency): a plugin among +/// them changes without a lockfile or manifest change, so each one's +/// manifest and the files it names as entries are salted by content. A +/// registry install (pnpm's `.pnpm` links, a plain directory) is the +/// lockfile's to describe. Other files of a linked package are not read: a +/// plugin spread over many modules is served by the next release's +/// manifest or version bump, as webpack's `buildDependencies` leaves it. +fn hash_linked_packages(root: &Path, workspace: &Path, hasher: &mut blake3::Hasher) { + let modules = root.join("node_modules"); + let mut links: Vec = Vec::new(); + for entry in std::fs::read_dir(&modules).into_iter().flatten().flatten() { + let path = entry.path(); + let scoped = entry.file_name().to_string_lossy().starts_with('@'); + if scoped && !path.is_symlink() { + links.extend( + std::fs::read_dir(&path) + .into_iter() + .flatten() + .flatten() + .map(|e| e.path()), + ); + } else { + links.push(path); + } + } + links.retain(|p| p.is_symlink()); + links.sort(); + for link in links { + let Ok(target) = std::fs::canonicalize(&link) else { + continue; + }; + if target.components().any(|c| c.as_os_str() == "node_modules") { + continue; + } + let Ok(manifest) = std::fs::read(target.join("package.json")) else { + continue; + }; + hasher.update(b"\0link="); + hasher.update(oj_cache::store::salt_key(root, workspace, &link).as_bytes()); + hasher.update(&manifest); + for entry in manifest_entry_files(&manifest) { + if let Ok(bytes) = std::fs::read(target.join(&entry)) { + hasher.update(b"\0"); + hasher.update(entry.as_bytes()); + hasher.update(&bytes); + } + } + } +} + +/// The relative files a package manifest names as entries: `main`, +/// `module` and every string leaf under `exports`, at most 32. +fn manifest_entry_files(manifest: &[u8]) -> Vec { + fn leaves(value: &serde_json::Value, out: &mut Vec) { + match value { + serde_json::Value::String(s) if s.starts_with("./") || !s.contains('/') => { + out.push(s.trim_start_matches("./").to_string()); + } + serde_json::Value::String(s) => out.push(s.clone()), + serde_json::Value::Object(map) => map.values().for_each(|v| leaves(v, out)), + serde_json::Value::Array(items) => items.iter().for_each(|v| leaves(v, out)), + _ => {} + } + } + let Ok(json) = serde_json::from_slice::(manifest) else { + return Vec::new(); + }; + let mut out = Vec::new(); + for key in ["main", "module", "exports"] { + if let Some(value) = json.get(key) { + leaves(value, &mut out); + } + } + out.sort(); + out.dedup(); + out.truncate(32); + out +} + /// Whether a stored entry's code or sourcemap names one of `dirs` as a path: /// the directory followed by a separator, so a root `/app` is not found in /// a route string `"/app-settings"`. A directory with no name of its own @@ -1847,6 +1951,7 @@ fn fs_allow_list( set } +#[allow(clippy::too_many_arguments)] fn optimized_deps( root: &Path, config: &oj_config::OjConfig, @@ -1855,6 +1960,7 @@ fn optimized_deps( host: Option>, plugin_names: Vec, rolldown: &tokio::runtime::Handle, + store: bool, ) -> optimize::OptimizedDeps { let (include, exclude, entries) = oj_config::optimize_deps_lists(config); optimize::OptimizedDeps::prepare( @@ -1893,6 +1999,7 @@ fn optimized_deps( }, host, rolldown, + store, ) } @@ -1928,7 +2035,19 @@ fn spawn_state_tasks( } }); } - { + if let Some(host) = &state.plugins { + host.set_trace_reads(state.persistent_cache); + } + // The shared modules directory's budget, once per boot and off its + // path: stale temp files of killed processes, then the oldest entries + // past the budget. + if state.persistent_cache { + let st = Arc::clone(state); + std::thread::spawn(move || st.cache.prune_shared(oj_cache::SHARED_MODULES_MAX_BYTES)); + } + // Without the store nothing is ever sent (`store_module` checks first): + // no writer thread, and the channel's sender simply outlives it. + if state.persistent_cache { let state = Arc::clone(state); std::thread::spawn(move || { while let Some((key, module)) = write_rx.blocking_recv() { @@ -2653,36 +2772,42 @@ impl DevServer { ssr_aliases: oj_config::resolve_alias(&config, "ssr"), persistent_cache: self.store, config_file: config_file.clone(), - cache: PersistentCache::new(oj_cache::cache_root(&root), env!("CARGO_PKG_VERSION")) - // Relocatable entries go to the shared per-user store, where - // worktree B hits what worktree A compiled; pinned entries - // (/@fs imports and friends) stay in this app's cache. - .with_shared(oj_cache::store::store_root().map(|s| s.join("modules"))) - .with_salt_extra(&installed.digest) - // Everything else that shapes compiled output: the plugin - // chain and its options (config graph, lockfile epoch), the - // resolver config, tsconfig paths. A config edit is a clean - // miss, never a stale hit. - .with_salt_extra(&module_cache_config_salt( - &root, - &client_settings(&config), - plugins::vite_config_file(&root, config_file.as_deref()).as_deref(), - )) - // A cached compile embeds the JSX runtime import; a changed - // importSource/runtime must not serve the old module. - .with_salt_extra(&format!("jsx={jsx:?}")) - // A cached module embeds its asset URLs (origin, base, - // inlined svgs). - .with_salt_extra(&format!( - "asset-urls={:?}:{:?}:{:?}", - config.server.as_ref().and_then(|s| s.origin.as_deref()), - config.base, - config.build.as_ref().map(|b| ( - b.assets_inline_limit, - b.assets_inline_limit_envs.as_ref(), - b.assets_inline_limit_fn, - )), - )), + cache: if !self.store { + // Nothing is read from or written to it: no salt to compute + // (the config graph, every tsconfig, the lockfile by content). + PersistentCache::new(oj_cache::cache_root(&root), tool_version()) + } else { + PersistentCache::new(oj_cache::cache_root(&root), tool_version()) + // Relocatable entries go to the shared per-user store, where + // worktree B hits what worktree A compiled; pinned entries + // (/@fs imports and friends) stay in this app's cache. + .with_shared(oj_cache::store::store_root().map(|s| s.join("modules"))) + .with_salt_extra(&installed.digest) + // Everything else that shapes compiled output: the plugin + // chain and its options (config graph, lockfile epoch), the + // resolver config, tsconfig paths. A config edit is a clean + // miss, never a stale hit. + .with_salt_extra(&module_cache_config_salt( + &root, + &client_settings(&config), + plugins::vite_config_file(&root, config_file.as_deref()).as_deref(), + )) + // A cached compile embeds the JSX runtime import; a changed + // importSource/runtime must not serve the old module. + .with_salt_extra(&format!("jsx={jsx:?}")) + // A cached module embeds its asset URLs (origin, base, + // inlined svgs). + .with_salt_extra(&format!( + "asset-urls={:?}:{:?}:{:?}", + config.server.as_ref().and_then(|s| s.origin.as_deref()), + config.base, + config.build.as_ref().map(|b| ( + b.assets_inline_limit, + b.assets_inline_limit_envs.as_ref(), + b.assets_inline_limit_fn, + )), + )) + }, cache_writes: write_tx, plugins_use_module_parsed: caps.use_module_parsed, collector_plugins: caps.collects_from_transforms, @@ -2825,6 +2950,7 @@ impl DevServer { plugin_host.clone(), plugin_names, &self.rolldown, + self.store, )), optimize_view: { let (_include, exclude, _entries) = oj_config::optimize_deps_lists(&config); diff --git a/crates/oj_server/src/module_pipeline.rs b/crates/oj_server/src/module_pipeline.rs index ab420631f..ac8e00a97 100644 --- a/crates/oj_server/src/module_pipeline.rs +++ b/crates/oj_server/src/module_pipeline.rs @@ -178,9 +178,21 @@ pub(crate) async fn ensure_module_as( let mut verify_against: Option> = None; if state.persistent_cache && !session_only(false) { let disk_key = state.cache.disk_key(&key); - let hit = match persistent_hit(state, &disk_key, is_dep, imports_stamp) { + // Entry reads, trace re-digests and glob listings are disk work: + // off the async workers, which keep answering other requests. + let local = { + let (st, dk) = (Arc::clone(state), disk_key.clone()); + tokio::task::spawn_blocking(move || persistent_hit(&st, &dk, is_dep, imports_stamp)) + .await + .ok() + .flatten() + }; + let hit = match local { Some(module) => Some(module), - None => remote_hit(state, &disk_key, is_dep, imports_stamp).await, + // A stamped key is this session's alone (never persisted, by + // anyone): nothing to ask a substituter for. + None if imports_stamp == 0 => remote_hit(state, &disk_key, is_dep, imports_stamp).await, + None => None, }; if let Some(module) = hit { if verify_hit_sampled() { @@ -272,6 +284,7 @@ pub(crate) async fn ensure_module_as( .await?; transformed.watch_files.extend(normal.watch_files); transformed.read_files.extend(normal.read_files); + transformed.read_dirs.extend(normal.read_dirs); normal.code } else { source @@ -377,26 +390,54 @@ pub(crate) async fn ensure_module_as( // Constructive trace: digest every side file the plugin read, so // a warm hit can prove those inputs unchanged. The module's own // source is already in the key; host scratch is oj's machinery. - let own = file.to_string_lossy(); - let scratch = oj_cache::cache_base(&state.root); - module.trace = transformed - .read_files - .iter() - .filter(|p| p.as_str() != own && !Path::new(p.as_str()).starts_with(&scratch)) - // A file the plugin looked for and did not find is an input too - // (it took a fallback): its row has no digest, and a warm hit - // that finds the file is a miss. - .map(|p| { - trace_unsettled |= modified_since(Path::new(p), compile_started); - oj_cache::TraceRow { - id: p.clone(), - digest: std::fs::read(p) - .map(|bytes| blake3::hash(&bytes).to_hex().to_string()) - .unwrap_or_default(), - } - }) - .collect(); - module.trace.extend(glob_rows); + // Nothing is persisted without the store: no rows, no digests. + // The compile's own rows (a sheet's inlined files) come first. + if state.persistent_cache { + let own = file.to_string_lossy(); + let scratch = oj_cache::cache_base(&state.root); + let plugin_rows: Vec = transformed + .read_files + .iter() + .filter(|p| p.as_str() != own && !Path::new(p.as_str()).starts_with(&scratch)) + // A file the plugin looked for and did not find is an input + // too (it took a fallback): its row has no digest, and a + // warm hit that finds the file is a miss. + .map(|p| { + trace_unsettled |= modified_since(Path::new(p), compile_started); + oj_cache::TraceRow { + id: p.clone(), + digest: std::fs::read(p) + .map(|bytes| blake3::hash(&bytes).to_hex().to_string()) + .unwrap_or_default(), + } + }) + .collect(); + module.trace.extend(plugin_rows); + // A directory a hook listed: its row digests the names in + // it, so a file added or removed under it is a miss. + module.trace.extend( + transformed + .read_dirs + .iter() + .filter(|p| !Path::new(p.as_str()).starts_with(&scratch)) + .map(|p| { + trace_unsettled |= modified_since(Path::new(p), compile_started); + oj_cache::TraceRow { + id: format!("dir:{p}"), + digest: dir_listing_digest(Path::new(p)), + } + }), + ); + module.trace.extend(glob_rows); + } + // A sheet's rows (the files it inlined) were digested by the + // compile: one saved while it ran is this session's alone too. + if module.kind == "css" { + trace_unsettled |= module + .trace + .iter() + .any(|row| modified_since(Path::new(&row.id), compile_started)); + } Arc::new(module) } Ok(Err(err)) => { @@ -607,10 +648,69 @@ fn store_module( /// Whether `file` was written at or after `since`: a side file a transform /// read with an mtime no older than the compile may have been read before /// that write. A file that is not there was not written. +/// Whether `file` may have changed at or after `since`. An mtime is only as +/// fine as its filesystem: on a mount that keeps whole seconds (some +/// network and overlay mounts, FAT) a write just after `since` is stamped +/// below it. Such a stamp has no sub-second part, and one within the two +/// seconds before `since` then counts as racy, as git treats an index entry +/// stamped in the commit's second; a stamp with nanoseconds compares +/// exactly, so a fresh checkout (every file written moments before the +/// first boot) persists as it should. fn modified_since(file: &Path, since: std::time::SystemTime) -> bool { - std::fs::metadata(file) - .and_then(|m| m.modified()) - .is_ok_and(|mtime| mtime >= since) + let Ok(mtime) = std::fs::metadata(file).and_then(|m| m.modified()) else { + return false; + }; + if mtime >= since { + return true; + } + let whole_second = mtime + .duration_since(std::time::UNIX_EPOCH) + .is_ok_and(|d| d.subsec_nanos() == 0); + whole_second && mtime + RACY_MTIME_WINDOW >= since +} + +/// The digest of a directory's listing (its entry names, sorted), for a +/// `dir:` trace row; empty when the directory cannot be read, which a hit +/// treats as "looked for, not there". +fn dir_listing_digest(dir: &Path) -> String { + let Ok(entries) = std::fs::read_dir(dir) else { + return String::new(); + }; + let mut names: Vec = entries + .flatten() + .map(|e| e.file_name().to_string_lossy().into_owned()) + .collect(); + names.sort(); + blake3::hash(names.join("\n").as_bytes()) + .to_hex() + .to_string() +} + +/// The coarsest mtime granularity a store may sit on (FAT, some NFS and +/// virtiofs mounts round to 1 s or 2 s). +const RACY_MTIME_WINDOW: std::time::Duration = std::time::Duration::from_secs(2); + +/// The files a sheet pulled in (`@import`s inlined into its output, Sass +/// partials, PostCSS dependencies) as constructive-trace rows: inputs of the +/// entry that change without the sheet's own bytes, so a warm hit re-digests +/// them. The sheet itself is in the key already. +fn css_trace_rows(sheet: &Path, deps: &[PathBuf]) -> Vec { + let mut files: Vec = deps + .iter() + .map(|p| normalize(p)) + .filter(|p| p != sheet) + .collect(); + files.sort(); + files.dedup(); + files + .into_iter() + .map(|file| oj_cache::TraceRow { + digest: std::fs::read(&file) + .map(|bytes| blake3::hash(&bytes).to_hex().to_string()) + .unwrap_or_default(), + id: file.to_string_lossy().into_owned(), + }) + .collect() } async fn file_stamp(file: &Path) -> Option { @@ -807,7 +907,7 @@ pub(crate) fn served_map_sources(root: &Path, map: String) -> String { let Ok(mut json) = serde_json::from_str::(&map) else { return map; }; - let canonical = std::fs::canonicalize(root).ok(); + let canonical = canonical_root(root); let Some(sources) = json.get_mut("sources").and_then(|s| s.as_array_mut()) else { return map; }; @@ -831,6 +931,19 @@ pub(crate) fn served_map_sources(root: &Path, map: String) -> String { } } +/// `canonicalize(root)`, once per root: a plugin map is rewritten per module +/// and the root does not move while a server runs. +fn canonical_root(root: &Path) -> Option { + static ROOTS: std::sync::Mutex>>> = + std::sync::Mutex::new(None); + let mut roots = ROOTS.lock().unwrap_or_else(|e| e.into_inner()); + roots + .get_or_insert_with(HashMap::new) + .entry(root.to_path_buf()) + .or_insert_with(|| std::fs::canonicalize(root).ok()) + .clone() +} + /// The affirmative patterns a module's globs expand, resolved as the compile /// resolves them (root-led and aliased ones included), so a trace row lists /// what the expansion actually read. @@ -1040,26 +1153,32 @@ fn persistent_hit( // plugin-served virtual of the session that compiled it, or a file that // moved since (`./Foo` to `Foo/index.tsx` on a branch switch, the // importer untouched). A compile resolves it anew; the hit would 404. - let needs_retransform = - !is_dep && imports_a_plugin_virtual(&module.imports, &state.root, &state.dir_cache); + let needs_retransform = !is_dep + && imports_a_plugin_virtual( + &module.imports, + &state.root, + &state.workspace_root_dir, + &state.dir_cache, + ); // Constructive-trace verification: every side input recorded at build // time must still digest the same, or the entry is a miss. File rows // re-hash the file (unreadable counts as changed); glob rows re-expand // the pattern against THIS worktree. Empty for plugin-less, glob-less // modules, which cost nothing. - let trace_stale = module - .trace - .iter() - .any(|row| match row.id.strip_prefix("glob:") { - Some(pattern) => { - glob_listing_digest(&state.root, &state.workspace_root_dir, pattern) != row.digest - } - None => match std::fs::read(&row.id) { - Ok(bytes) => blake3::hash(&bytes).to_hex().to_string() != row.digest, - // Looked for and not found at compile time: still not there. - Err(_) => !row.digest.is_empty(), - }, - }); + let trace_stale = module.trace.iter().any(|row| { + if let Some(pattern) = row.id.strip_prefix("glob:") { + return glob_listing_digest(&state.root, &state.workspace_root_dir, pattern) + != row.digest; + } + if let Some(dir) = row.id.strip_prefix("dir:") { + return dir_listing_digest(Path::new(dir)) != row.digest; + } + match std::fs::read(&row.id) { + Ok(bytes) => blake3::hash(&bytes).to_hex().to_string() != row.digest, + // Looked for and not found at compile time: still not there. + Err(_) => !row.digest.is_empty(), + } + }); (!needs_retransform && !trace_stale).then_some(module) } @@ -1069,15 +1188,21 @@ fn persistent_hit( /// same admission path as a local hit: rehome, the stamp check, the /// plugin-virtual check, and trace verification against this worktree. async fn remote_hit( - state: &ServerState, + state: &Arc, disk_key: &str, is_dep: bool, imports_stamp: u64, ) -> Option> { let remote = state.remote_store.as_ref()?; let stored = remote.fetch_module(disk_key).await?; - state.cache.put(disk_key, &stored); - persistent_hit(state, disk_key, is_dep, imports_stamp) + let (st, dk) = (Arc::clone(state), disk_key.to_string()); + tokio::task::spawn_blocking(move || { + st.cache.put(&dk, &stored); + persistent_hit(&st, &dk, is_dep, imports_stamp) + }) + .await + .ok() + .flatten() } /// A disk hit skipped the plugin chain, so its `moduleParsed` never fired on @@ -1105,6 +1230,8 @@ pub(crate) struct Transformed { pub(crate) watch_files: Vec, /// Side files the plugin hooks read, for the entry's trace. read_files: Vec, + /// Directories the plugin hooks listed, for the entry's trace. + read_dirs: Vec, maps: Vec, } @@ -1131,6 +1258,7 @@ pub(crate) async fn plugin_transform_phase( ) -> Result { let untouched = |code| Transformed { read_files: Vec::new(), + read_dirs: Vec::new(), code, watch_files: Vec::new(), maps: Vec::new(), @@ -1164,6 +1292,7 @@ pub(crate) async fn plugin_transform_phase( code: t.code, watch_files: t.watch_files, read_files: t.reads, + read_dirs: t.read_dirs, maps: t.maps, }), // Vite fails the request with the plugin's error (code frame in the @@ -1597,6 +1726,11 @@ impl CompileJob { None => oj_css::compile_css_dev(&self.url, &self.source, dev_sourcemap, &resolve)?, }; let dep_imports = css_dep_imports(state, &self.file, &self.css.deps); + let trace = if state.persistent_cache { + css_trace_rows(&self.file, &self.css.deps) + } else { + Vec::new() + }; // A CSS module's class map changes on edit, so it cannot self-accept // (Vite's css-analysis): the update climbs to the importing component. let is_css_module = self.css.exports.is_some(); @@ -1609,6 +1743,7 @@ impl CompileJob { kind: "css".into(), imports: dep_imports, css_exports: self.css.exports.unwrap_or_default(), + trace, ..code_module(output.css) }) } @@ -2730,6 +2865,66 @@ pub(crate) fn interop_node_builtins(source: &str, file: &Path) -> Option #[cfg(test)] mod tests { + #[test] + fn modified_since_counts_the_racy_seconds_before_the_compile() { + let dir = std::env::temp_dir().join(format!("oj-racy-mtime-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("side.txt"); + std::fs::write(&file, b"x").unwrap(); + let now = std::time::SystemTime::now(); + let set = |ago: std::time::Duration, back: bool| { + let at = if back { now - ago } else { now + ago }; + std::fs::File::open(&file) + .unwrap() + .set_modified(at) + .unwrap(); + }; + let s = std::time::Duration::from_secs; + let whole = |t: std::time::SystemTime| { + let secs = t.duration_since(std::time::UNIX_EPOCH).unwrap().as_secs(); + std::time::SystemTime::UNIX_EPOCH + s(secs) + }; + let at = |t: std::time::SystemTime| { + std::fs::File::open(&file).unwrap().set_modified(t).unwrap(); + }; + set(s(10), true); + assert!(!super::modified_since(&file, now), "an old file is settled"); + // A fine-grained stamp just before the compile: settled (a fresh + // checkout is written moments before its first boot). + let fine = now - std::time::Duration::from_millis(300); + assert!( + fine.duration_since(std::time::UNIX_EPOCH) + .unwrap() + .subsec_nanos() + != 0 + ); + at(fine); + assert!( + !super::modified_since(&file, now), + "nanoseconds compare exactly" + ); + at(whole(now - s(1))); + assert!( + super::modified_since(&file, now), + "a whole-second stamp in the second before the compile is racy" + ); + at(whole(now - s(10))); + assert!( + !super::modified_since(&file, now), + "an old whole-second stamp is settled" + ); + set(s(0), false); + assert!(super::modified_since(&file, now), "at the compile's start"); + set(s(5), false); + assert!(super::modified_since(&file, now), "after it"); + assert!( + !super::modified_since(&dir.join("missing.txt"), now), + "a missing file is not a racy write" + ); + let _ = std::fs::remove_dir_all(&dir); + } + use super::{for_url_variants, graph_url, import_node, sheet_url}; use std::path::PathBuf; diff --git a/crates/oj_server/src/optimize.rs b/crates/oj_server/src/optimize.rs index 498e595ef..e53bfa12c 100644 --- a/crates/oj_server/src/optimize.rs +++ b/crates/oj_server/src/optimize.rs @@ -194,9 +194,8 @@ struct DepLedger { } impl DepLedger { - /// The ledger under `dir`: in the shared oj store when there is one, so - /// worktrees share URLs, else in the app's cache (outside the deps dir, - /// so clearing pre-bundles keeps it). `None` when it cannot be written. + /// The ledger under `dir`, the shared oj store's, so worktrees share + /// URLs. `None` when it cannot be written. fn open(dir: PathBuf, deps: PathBuf) -> Option { std::fs::create_dir_all(&dir).ok()?; let fresh = format!("{}-{}", session_timestamp(), std::process::id()); @@ -208,11 +207,12 @@ impl DepLedger { (!epoch.is_empty()).then_some(Self { dir, epoch, deps }) } - fn for_app(root: &Path, deps: &Path) -> Option { + /// The store's ledger for an app's `deps` dir. Without the store there + /// is no ledger: a session mints its own versions (Vite's + /// sessionTimestamp) and never re-reads a bundle to vouch for its bytes. + fn in_store(deps: &Path) -> Option { Self::open( - oj_cache::store::store_root() - .map(|store| store.join("dep-ledger")) - .unwrap_or_else(|| oj_cache::cache_root(root).join("dep-ledger")), + oj_cache::store::store_root()?.join("dep-ledger"), deps.to_path_buf(), ) } @@ -870,10 +870,15 @@ impl OptimizedDeps { input: OptimizeInput, host: Option>, rolldown: &tokio::runtime::Handle, + store: bool, ) -> Self { let dir = oj_cache::cache_root(root).join("deps"); let hash = lockfile_hash(root, version, &input); - let ledger = DepLedger::for_app(root, &dir); + let ledger = if store { + DepLedger::in_store(&dir) + } else { + None + }; let epoch = ledger .as_ref() .map_or_else(session_timestamp, |l| l.epoch.clone()); @@ -1458,7 +1463,9 @@ const LOCKFILES: &[(&str, Option<&str>)] = &[ ]; /// Fold every lockfile in the nearest ancestor directory that has one (Vite's -/// lookupFile), plus its patch-package dir mtime, into `hasher`. +/// lookupFile), plus the patch files beside it by name and content (Vite +/// hashes the patches dir's mtime, which differs per checkout and would keep +/// two worktrees of one app from sharing a single entry), into `hasher`. pub(crate) fn hash_lockfiles(root: &Path, hasher: &mut blake3::Hasher) { let mut dir = Some(root); while let Some(d) = dir { @@ -1469,14 +1476,7 @@ pub(crate) fn hash_lockfiles(root: &Path, hasher: &mut blake3::Hasher) { hasher.update(name.as_bytes()); hasher.update(&bytes); if let Some(patches) = patches { - if let Ok(meta) = std::fs::metadata(d.join(patches)) { - if meta.is_dir() { - if let Ok(mtime) = meta.modified() { - hasher.update(b"\0p"); - hasher.update(format!("{mtime:?}").as_bytes()); - } - } - } + hash_patch_files(&d.join(patches), hasher); } } } @@ -1487,6 +1487,27 @@ pub(crate) fn hash_lockfiles(root: &Path, hasher: &mut blake3::Hasher) { } } +/// The files of a patch directory (`patches/`, patch-package's and pnpm's), +/// sorted by name, each with its content. +fn hash_patch_files(dir: &Path, hasher: &mut blake3::Hasher) { + let mut files: Vec = std::fs::read_dir(dir) + .into_iter() + .flatten() + .flatten() + .map(|e| e.path()) + .filter(|p| p.is_file()) + .collect(); + files.sort(); + for file in files { + if let Ok(bytes) = std::fs::read(&file) { + hasher.update(b"\0p"); + hasher.update(file.file_name().unwrap_or_default().as_encoded_bytes()); + hasher.update(b"\0"); + hasher.update(&bytes); + } + } +} + /// Folds each entry of each list into `hasher`, prefixed by its list's tag. fn hash_tagged_lists(hasher: &mut blake3::Hasher, lists: &[(&[u8], &Vec)]) { for (tag, list) in lists { @@ -1951,12 +1972,17 @@ mod tests { let installed = key(); assert_ne!(bare, installed, "node_modules/.package-lock.json"); - // patch-package: a `patches/` directory next to an npm lockfile is part - // of the key (Vite's checkPatchesDir), so re-patching a dep re-bundles. + // patch-package: the patch files next to an npm lockfile are part of + // the key by content (Vite's checkPatchesDir keys the dir's mtime), + // so re-patching a dep re-bundles and an empty dir changes nothing. std::fs::create_dir_all(root.join("patches")).unwrap(); + assert_eq!(installed, key(), "an empty patches dir is no input"); + std::fs::write(root.join("patches/dep+1.0.0.patch"), "--- a\n+++ b\n").unwrap(); let patched = key(); - assert_ne!(installed, patched, "patches dir"); + assert_ne!(installed, patched, "a patch file"); assert_eq!(patched, key(), "deterministic while nothing changes"); + std::fs::write(root.join("patches/dep+1.0.0.patch"), "--- a\n+++ c\n").unwrap(); + assert_ne!(patched, key(), "a patch's content"); } #[test] diff --git a/crates/oj_server/src/plugins/host.rs b/crates/oj_server/src/plugins/host.rs index da86728df..38b2e1124 100644 --- a/crates/oj_server/src/plugins/host.rs +++ b/crates/oj_server/src/plugins/host.rs @@ -1349,6 +1349,13 @@ impl PluginHost { Ok(host) } + /// Whether transforms open TracingFs windows (the constructive trace a + /// persisted entry is verified by). Off, a read in the isolates costs + /// one atomic load; a server without the store has no use for the rows. + pub fn set_trace_reads(&self, on: bool) { + self.core.read_log.set_enabled(on); + } + pub async fn transform( &self, code: &str, @@ -1386,23 +1393,27 @@ impl PluginHost { )) } - /// The host's reply with the reads the TracingFs window saw folded in: - /// one no plugin answered (no reply) read nothing of its own. + /// The host's reply with what the TracingFs window saw folded in, files + /// into `reads` and listings into `read_dirs`, each sorted and deduped + /// with the host's own buckets: one no plugin answered (no reply) read + /// nothing of its own. fn with_fs_reads( raw: Option, code: &str, - fs_reads: Vec, + fs_reads: oj_js::tracing_fs::Reads, ) -> HostTransform { let had_reply = raw.is_some(); let mut t = HostTransform::parse(raw, code); if had_reply { - t.reads.extend( - fs_reads - .into_iter() - .map(|p| p.to_string_lossy().into_owned()), - ); + let strings = |paths: Vec| { + paths.into_iter().map(|p| p.to_string_lossy().into_owned()) + }; + t.reads.extend(strings(fs_reads.files)); t.reads.sort(); t.reads.dedup(); + t.read_dirs.extend(strings(fs_reads.dirs)); + t.read_dirs.sort(); + t.read_dirs.dedup(); } t } @@ -3883,9 +3894,13 @@ pub struct HostTransform { /// (vite:oxc's strip returns `"js"`): rolldown then runs no TypeScript /// transform of its own over the lowered code. pub module_type: Option, - /// Side files the transform hooks read (pulp P2): the host's - /// per-hook `readFiles` plus the TracingFs window, sorted and deduped. + /// Side files the transform hooks read or checked for (pulp P2): the + /// host's per-hook `readFiles` plus the TracingFs window, sorted and + /// deduped. Absolute paths; a missing file is one the hooks looked for. pub reads: Vec, + /// Directories the transform hooks listed (`readDirs` plus the window's + /// listings): an entry added or removed under one changes the output. + pub read_dirs: Vec, } impl HostTransform { @@ -3912,6 +3927,7 @@ impl HostTransform { self.module_type = next.module_type; } self.reads.extend(next.reads); + self.read_dirs.extend(next.read_dirs); } /// A reply that is not the host's JSON is the code itself; none leaves @@ -3954,6 +3970,7 @@ impl HostTransform { .map(str::to_string), chunks: emitted_chunks(&v), reads: str_array("readFiles"), + read_dirs: str_array("readDirs"), module_type: v .get("moduleType") .and_then(|n| n.as_str()) diff --git a/crates/oj_server/src/rewrite.rs b/crates/oj_server/src/rewrite.rs index c3eae1fc3..a30618441 100644 --- a/crates/oj_server/src/rewrite.rs +++ b/crates/oj_server/src/rewrite.rs @@ -12,10 +12,18 @@ pub(crate) type DirCache = std::collections::HashMap< pub(crate) fn imports_a_plugin_virtual( imports: &[String], root: &Path, + workspace: &Path, dir_cache: &Mutex, ) -> bool { imports.iter().any(|imp| { let p = imp.split('?').next().unwrap_or(imp); + // An in-workspace file outside the root is named relative to the + // workspace that compiled it; the reader's workspace may be laid + // out otherwise (a hoisted vs an isolated install), so the file + // must be where this server would look for it. + if let Some(rel) = p.strip_prefix("/@fs/@mono/") { + return !is_file_cached(dir_cache, &workspace.join(rel)); + } if !p.starts_with('/') || p.starts_with("/@") || p.contains("://") { return false; } diff --git a/crates/oj_server/src/store_remote.rs b/crates/oj_server/src/store_remote.rs index 4b779b3a0..8d51d77ce 100644 --- a/crates/oj_server/src/store_remote.rs +++ b/crates/oj_server/src/store_remote.rs @@ -6,8 +6,11 @@ //! substituter is read through and the entry is written back locally, so the //! fleet's second sandbox pays one HTTP GET instead of a compile. Pushing is //! separate and explicit: the dev server pushes only when `OJ_STORE_PUSH=1` -//! AND a token is set — untrusted contexts hold read-only tokens and the +//! AND a token is set. Untrusted contexts hold read-only tokens and the //! server's write-once entries bound what even a leaked write token can do. +//! A pushed entry carries the module's source map with `sourcesContent`, so +//! `OJ_STORE_PUSH` sends the app's own source to the substituter: push only +//! to one that is as private as the checkout. //! //! Trust at the consuming edge: a fetched entry is admitted only if its //! stored form passes `CachedModule::is_relocatable` (a remote can never pin @@ -15,32 +18,85 @@ //! key the CLIENT computed (a remote cannot choose which module its bytes //! stand in for). Entry signing is designed (Nix narinfo model) but not yet //! wired; until then the write token is the trust boundary. +//! +//! The remote is on the request path, so it is held to a budget: a fetch +//! that fails OR takes longer than [`SLOW_FETCH`] is a strike, three strikes +//! open the breaker, and an open breaker lets one probe through after +//! [`COOLDOWN`] to see whether the remote is back. Pushes queue behind a +//! bound and are dropped, not waited for, when the queue is full or the +//! breaker is open. -use std::sync::Arc; -use std::time::Duration; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; use oj_cache::CachedModule; -/// A substituter is on the request path: a connect that takes longer than -/// this, or a whole fetch longer than [`READ_TIMEOUT`], counts as a failure. -const CONNECT_TIMEOUT: Duration = Duration::from_secs(2); -const READ_TIMEOUT: Duration = Duration::from_secs(5); -/// Consecutive failures after which the remote is not asked again. -const TRIPS_AFTER: usize = 3; +/// A connect that takes longer than this counts as a failure. +pub(crate) const CONNECT_TIMEOUT: Duration = Duration::from_secs(2); +/// The most a whole fetch (headers and body) may take before it fails. +pub(crate) const FETCH_TIMEOUT: Duration = Duration::from_secs(5); +/// The most one push may take; the pusher is off the request path, so it +/// may be patient, but not forever. +pub(crate) const PUSH_TIMEOUT: Duration = Duration::from_secs(5); +/// A fetch that answers, hit or miss, but slower than this is a strike: a +/// substituter that takes half a second per miss is slower than compiling. +pub(crate) const SLOW_FETCH: Duration = Duration::from_millis(500); +/// Consecutive strikes that open the breaker. +pub(crate) const TRIPS_AFTER: usize = 3; +/// How long an open breaker leaves the remote alone before one probe. +pub(crate) const COOLDOWN: Duration = Duration::from_secs(30); +/// The push queue's bounds: entries waiting and the bytes they hold. +pub(crate) const PUSH_QUEUE_ENTRIES: usize = 256; +pub(crate) const PUSH_QUEUE_BYTES: usize = 64 * 1024 * 1024; +/// The largest entry body a fetch reads; the wire never stores a larger one. +pub(crate) const MAX_ENTRY_BYTES: usize = crate::store_server::MAX_AC_BYTES; + +/// The knobs a test turns; production takes the constants. +#[derive(Clone, Copy)] +pub(crate) struct Tuning { + pub cooldown: Duration, + pub slow_fetch: Duration, + pub queue_entries: usize, + pub queue_bytes: usize, +} + +impl Default for Tuning { + fn default() -> Self { + Tuning { + cooldown: COOLDOWN, + slow_fetch: SLOW_FETCH, + queue_entries: PUSH_QUEUE_ENTRIES, + queue_bytes: PUSH_QUEUE_BYTES, + } + } +} + +/// The breaker: closed while the remote answers in budget, open after +/// [`TRIPS_AFTER`] strikes in a row, half-open (one probe in flight) once +/// the cooldown has passed. The probe's outcome closes or re-opens it. +#[derive(Default)] +struct Breaker { + strikes: usize, + open_since: Option, + probing: bool, +} pub struct RemoteStore { base: String, token: Option, push: bool, client: reqwest::Client, - /// Read-throughs that failed in a row (a connect error, a timeout, a 5xx). - /// Past [`TRIPS_AFTER`] the remote is left alone for the rest of the - /// session: a substituter that is down must not turn every cold compile - /// into a wait. A success starts the count over. - failures: std::sync::atomic::AtomicUsize, + tuning: Tuning, + breaker: Mutex, /// Fire-and-forget pushes run on their own small thread to keep the - /// cache writer thread off the network. - push_tx: std::sync::mpsc::Sender<(String, Vec)>, + /// cache writer thread off the network. The channel is bounded by + /// entries; `queued_bytes` bounds it by size. + push_tx: std::sync::mpsc::SyncSender<(String, Vec)>, + queued_bytes: AtomicUsize, + /// Pushes that never left: queue full, or the breaker open. Logged once. + dropped: AtomicUsize, + drop_logged: AtomicBool, } impl RemoteStore { @@ -60,21 +116,35 @@ impl RemoteStore { base: &str, token: Option, push: bool, + ) -> Option> { + Self::connect_with(base, token, push, Tuning::default()) + } + + pub(crate) fn connect_with( + base: &str, + token: Option, + push: bool, + tuning: Tuning, ) -> Option> { let base = base.trim_end_matches('/').to_string(); let client = reqwest::Client::builder() .connect_timeout(CONNECT_TIMEOUT) - .timeout(READ_TIMEOUT) + .timeout(FETCH_TIMEOUT) .build() .ok()?; - let (push_tx, push_rx) = std::sync::mpsc::channel::<(String, Vec)>(); + let (push_tx, push_rx) = + std::sync::mpsc::sync_channel::<(String, Vec)>(tuning.queue_entries); let store = Arc::new(RemoteStore { base, token, push, client, - failures: std::sync::atomic::AtomicUsize::new(0), + tuning, + breaker: Mutex::new(Breaker::default()), push_tx, + queued_bytes: AtomicUsize::new(0), + dropped: AtomicUsize::new(0), + drop_logged: AtomicBool::new(false), }); if store.push { let pusher = Arc::clone(&store); @@ -84,7 +154,19 @@ impl RemoteStore { .build() .expect("push runtime"); while let Ok((url, body)) = push_rx.recv() { - let req = pusher.authed(pusher.client.put(&url)).body(body); + pusher.queued_bytes.fetch_sub(body.len(), Ordering::Relaxed); + // A remote that is not answering reads is not sent + // writes either: the queue drains instead of piling up + // behind a timeout per entry. (A look, not `tripped()`: + // the probe slot belongs to a fetch, which reports back.) + if pusher.held_open() { + pusher.drop_push(); + continue; + } + let req = pusher + .authed(pusher.client.put(&url)) + .timeout(PUSH_TIMEOUT) + .body(body); // Best-effort: 409 means someone else already published // this key, which is success; errors only cost sharing. let _ = rt.block_on(async { req.send().await }); @@ -94,18 +176,69 @@ impl RemoteStore { Some(store) } - /// Whether the remote is left alone for the rest of the session. + /// Whether the remote is left alone right now. An open breaker whose + /// cooldown has passed answers `false` exactly once: that caller is the + /// probe, and its result decides for everyone else. pub(crate) fn tripped(&self) -> bool { - self.failures.load(std::sync::atomic::Ordering::Relaxed) >= TRIPS_AFTER + let mut b = self.breaker.lock().unwrap_or_else(|e| e.into_inner()); + match b.open_since { + None => false, + Some(_) if b.probing => true, + Some(since) if since.elapsed() >= self.tuning.cooldown => { + b.probing = true; + false + } + Some(_) => true, + } } - fn failed(&self) { - let before = self - .failures - .fetch_add(1, std::sync::atomic::Ordering::Relaxed); - if before + 1 == TRIPS_AFTER { + /// Whether the breaker is open, without touching the probe. + fn held_open(&self) -> bool { + self.breaker + .lock() + .unwrap_or_else(|e| e.into_inner()) + .open_since + .is_some() + } + + fn struck(&self, why: &str) { + let mut b = self.breaker.lock().unwrap_or_else(|e| e.into_inner()); + if b.probing { + // The probe failed: another cooldown, quietly. + b.probing = false; + b.open_since = Some(Instant::now()); + return; + } + b.strikes += 1; + if b.strikes >= TRIPS_AFTER && b.open_since.is_none() { + b.open_since = Some(Instant::now()); + eprintln!( + "oj: store: {} {why} {TRIPS_AFTER} times; not asked again for {}s", + self.base, + self.tuning.cooldown.as_secs() + ); + } + } + + fn answered_in_budget(&self) { + let mut b = self.breaker.lock().unwrap_or_else(|e| e.into_inner()); + if b.open_since.is_some() { + eprintln!("oj: store: {} answers again", self.base); + } + *b = Breaker::default(); + } + + /// Pushes dropped so far (queue full, or the breaker open). + #[cfg(test)] + pub(crate) fn dropped_pushes(&self) -> usize { + self.dropped.load(Ordering::Relaxed) + } + + fn drop_push(&self) { + self.dropped.fetch_add(1, Ordering::Relaxed); + if !self.drop_logged.swap(true, Ordering::Relaxed) { eprintln!( - "oj: store: {} did not answer {TRIPS_AFTER} times; not asked again this session", + "oj: store: pushes to {} are being dropped (queue full or remote not answering); sharing suffers, nothing else does", self.base ); } @@ -125,25 +258,32 @@ impl RemoteStore { return None; } let url = format!("{}/v1/ac/modules/{key}", self.base); + let started = Instant::now(); let answered = async { let resp = self.authed(self.client.get(&url)).send().await.ok()?; - let status = resp.status(); - if status.is_server_error() { + if resp.status().is_server_error() { return None; } - Some((status, resp)) + Some(resp) } .await; - let Some((status, resp)) = answered else { - self.failed(); + let Some(resp) = answered else { + self.struck("did not answer"); return None; }; - self.failures.store(0, std::sync::atomic::Ordering::Relaxed); - if status != reqwest::StatusCode::OK { - return None; + let body = if resp.status() == reqwest::StatusCode::OK { + read_capped(resp, MAX_ENTRY_BYTES).await + } else { + None + }; + // The clock covers the body too: a hit that trickles in is as slow + // as a miss that does. + if started.elapsed() > self.tuning.slow_fetch { + self.struck("answered slowly"); + } else { + self.answered_in_budget(); } - let bytes = resp.bytes().await.ok()?; - let module: CachedModule = serde_json::from_slice(&bytes).ok()?; + let module: CachedModule = serde_json::from_slice(&body?).ok()?; // The admission gate, applied to what the WIRE delivered: nothing // that pins a checkout crosses into this worktree, whatever the // server said. @@ -151,18 +291,50 @@ impl RemoteStore { } /// Queue a stored-form entry for push. Called from the cache writer - /// thread; never blocks on the network. + /// thread; never blocks on the network, and never waits on the queue: + /// a full queue drops the entry. pub fn push_module(&self, key: &str, stored: &CachedModule) { if !self.push { return; } - if let Ok(body) = serde_json::to_vec(stored) { - let url = format!("{}/v1/ac/modules/{key}", self.base); - let _ = self.push_tx.send((url, body)); + let Ok(body) = serde_json::to_vec(stored) else { + return; + }; + if body.len() > MAX_ENTRY_BYTES { + return; + } + let url = format!("{}/v1/ac/modules/{key}", self.base); + let queued = self.queued_bytes.fetch_add(body.len(), Ordering::Relaxed) + body.len(); + if queued > self.tuning.queue_bytes { + self.queued_bytes.fetch_sub(body.len(), Ordering::Relaxed); + self.drop_push(); + return; + } + let len = body.len(); + if self.push_tx.try_send((url, body)).is_err() { + self.queued_bytes.fetch_sub(len, Ordering::Relaxed); + self.drop_push(); } } } +/// The body of `resp`, or None once it is longer than `cap`: the declared +/// length is checked first, then the bytes as they come, so a remote that +/// lies about its length is still read no further than the cap. +async fn read_capped(mut resp: reqwest::Response, cap: usize) -> Option> { + if resp.content_length().is_some_and(|len| len > cap as u64) { + return None; + } + let mut body = Vec::with_capacity(resp.content_length().unwrap_or(0).min(cap as u64) as usize); + while let Some(chunk) = resp.chunk().await.ok()? { + if body.len() + chunk.len() > cap { + return None; + } + body.extend_from_slice(&chunk); + } + Some(body) +} + #[cfg(test)] mod tests { //! The consuming edge of the wire, against a live substituter in this @@ -175,7 +347,7 @@ mod tests { } async fn substituter(dir: &std::path::Path) -> String { - let state = crate::store_server::state(dir.to_path_buf(), None, Some("w".into())); + let state = crate::store_server::state(dir.to_path_buf(), None, Some("w".into()), u64::MAX); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let addr = listener.local_addr().unwrap(); tokio::spawn(async move { @@ -211,17 +383,34 @@ mod tests { fs_allow: vec!["ws:node_modules/dep".into()], ..Default::default() }; - for (k, module) in [(key(1), &poison), (key(2), &good)] { - let status = client - .put(format!("{base}/v1/ac/modules/{k}")) - .bearer_auth("w") - .body(serde_json::to_vec(module).unwrap()) - .send() - .await - .unwrap() - .status(); - assert_eq!(status, reqwest::StatusCode::CREATED); - } + // The server refuses the poison; it is planted on disk behind the + // server's back, as a compromised or older server would hold it, so + // the client's own gate is what this test exercises. + let status = client + .put(format!("{base}/v1/ac/modules/{}", key(1))) + .bearer_auth("w") + .body(serde_json::to_vec(&poison).unwrap()) + .send() + .await + .unwrap() + .status(); + assert_eq!(status, reqwest::StatusCode::UNPROCESSABLE_ENTITY); + let planted = dir.path().join("ac/modules").join(&key(1)[..2]); + std::fs::create_dir_all(&planted).unwrap(); + std::fs::write( + planted.join(format!("{}.json", key(1))), + serde_json::to_vec(&poison).unwrap(), + ) + .unwrap(); + let status = client + .put(format!("{base}/v1/ac/modules/{}", key(2))) + .bearer_auth("w") + .body(serde_json::to_vec(&good).unwrap()) + .send() + .await + .unwrap() + .status(); + assert_eq!(status, reqwest::StatusCode::CREATED); let remote = RemoteStore::connect(&base, Some("w".into()), true).unwrap(); assert_eq!( remote.fetch_module(&key(1)).await, @@ -271,8 +460,66 @@ mod tests { #[cfg(test)] mod breaker_tests { + //! The budget a remote is held to on the request path: strikes for not + //! answering and for answering slowly, the cooldown and the probe, the + //! bound on the push queue, and the cap on a fetched body. use super::*; - use std::time::Instant; + use axum::extract::State; + use axum::http::StatusCode; + use axum::response::IntoResponse; + use axum::routing::get; + use std::sync::atomic::AtomicU64; + + /// A substituter stand-in whose behaviour a test turns: a miss that + /// takes `delay_ms`, or a hit of `hit_bytes` bytes of code, PUTs that + /// take `put_delay_ms`, and a count of what it saw. + #[derive(Default)] + struct Stub { + delay_ms: AtomicU64, + hit_bytes: AtomicUsize, + puts: AtomicUsize, + put_delay_ms: AtomicU64, + gets: AtomicUsize, + } + + async fn stand_in() -> (String, Arc) { + let stub = Arc::new(Stub::default()); + async fn on_get(State(s): State>) -> axum::response::Response { + s.gets.fetch_add(1, Ordering::Relaxed); + let delay = s.delay_ms.load(Ordering::Relaxed); + if delay > 0 { + tokio::time::sleep(Duration::from_millis(delay)).await; + } + match s.hit_bytes.load(Ordering::Relaxed) { + 0 => StatusCode::NOT_FOUND.into_response(), + n => { + let module = CachedModule { + code: "x".repeat(n), + ..Default::default() + }; + serde_json::to_vec(&module).unwrap().into_response() + } + } + } + async fn on_put(State(s): State>) -> StatusCode { + let delay = s.put_delay_ms.load(Ordering::Relaxed); + if delay > 0 { + tokio::time::sleep(Duration::from_millis(delay)).await; + } + s.puts.fetch_add(1, Ordering::Relaxed); + StatusCode::CREATED + } + let app = axum::Router::new() + .route("/v1/ac/modules/{key}", get(on_get).put(on_put)) + .layer(axum::extract::DefaultBodyLimit::max(MAX_ENTRY_BYTES)) + .with_state(Arc::clone(&stub)); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { + let _ = axum::serve(listener, app).await; + }); + (format!("http://{addr}"), stub) + } // A substituter that is down (here: a port nothing listens on) costs a // few fast failures, then nothing: the breaker trips and later misses @@ -307,4 +554,164 @@ mod breaker_tests { "a tripped remote is not asked" ); } + + // A remote that answers every miss, slowly, is as bad as one that is + // down: the slow 404s are strikes, the breaker opens, and after the + // cooldown one probe goes through. A probe that is still slow re-opens + // it; a probe in budget closes it for good. + #[tokio::test(flavor = "multi_thread")] + async fn slow_misses_trip_the_breaker_and_a_probe_follows_the_cooldown() { + let (base, stub) = stand_in().await; + let tuning = Tuning { + cooldown: Duration::from_millis(300), + slow_fetch: Duration::from_millis(50), + ..Tuning::default() + }; + let remote = RemoteStore::connect_with(&base, None, false, tuning).unwrap(); + let key = "ab".repeat(32); + stub.delay_ms.store(120, Ordering::Relaxed); + for i in 0..TRIPS_AFTER { + assert_eq!(remote.fetch_module(&key).await, None); + assert_eq!( + remote.tripped(), + i + 1 == TRIPS_AFTER, + "after {} slow 404s", + i + 1 + ); + } + assert_eq!(stub.gets.load(Ordering::Relaxed), TRIPS_AFTER); + for _ in 0..20 { + assert_eq!(remote.fetch_module(&key).await, None); + } + assert_eq!( + stub.gets.load(Ordering::Relaxed), + TRIPS_AFTER, + "an open breaker asks nothing" + ); + + // Cooldown over, still slow: exactly one probe, then open again. + tokio::time::sleep(Duration::from_millis(350)).await; + assert_eq!(remote.fetch_module(&key).await, None); + assert_eq!( + stub.gets.load(Ordering::Relaxed), + TRIPS_AFTER + 1, + "the probe" + ); + for _ in 0..20 { + assert_eq!(remote.fetch_module(&key).await, None); + } + assert_eq!( + stub.gets.load(Ordering::Relaxed), + TRIPS_AFTER + 1, + "a failed probe re-opens the breaker" + ); + + // Cooldown over, the remote is quick again: the probe closes it. + stub.delay_ms.store(0, Ordering::Relaxed); + stub.hit_bytes.store(8, Ordering::Relaxed); + tokio::time::sleep(Duration::from_millis(350)).await; + assert_eq!( + remote.fetch_module(&key).await.map(|m| m.code), + Some("xxxxxxxx".into()) + ); + assert!(!remote.tripped()); + for _ in 0..5 { + assert!(remote.fetch_module(&key).await.is_some()); + } + assert_eq!(stub.gets.load(Ordering::Relaxed), TRIPS_AFTER + 1 + 6); + } + + // Pushes never pile up: the queue is bounded by entries and by bytes, + // what does not fit is dropped (and said once), and while the breaker + // is open the pusher drops what it dequeues instead of sending it. + #[tokio::test(flavor = "multi_thread")] + async fn the_push_queue_is_bounded_and_the_pusher_stops_while_tripped() { + let module = CachedModule { + code: "export const x = 1;".into(), + ..Default::default() + }; + let body_len = serde_json::to_vec(&module).unwrap().len(); + let tuning = Tuning { + cooldown: Duration::from_secs(600), + slow_fetch: Duration::from_millis(20), + queue_entries: 4, + queue_bytes: body_len * 3, + }; + + // The breaker is open (slow misses tripped it): the pusher takes + // every queued push and drops it, and the stub sees no PUT. + let (base, stub) = stand_in().await; + let remote = RemoteStore::connect_with(&base, Some("w".into()), true, tuning).unwrap(); + stub.delay_ms.store(60, Ordering::Relaxed); + for _ in 0..TRIPS_AFTER { + assert_eq!(remote.fetch_module(&"ab".repeat(32)).await, None); + } + assert!(remote.tripped()); + stub.delay_ms.store(0, Ordering::Relaxed); + for i in 0..10u8 { + remote.push_module(&format!("{i:02x}").repeat(32), &module); + } + tokio::time::sleep(Duration::from_millis(300)).await; + assert_eq!( + stub.puts.load(Ordering::Relaxed), + 0, + "nothing is pushed to a remote the breaker holds open" + ); + assert_eq!(remote.dropped_pushes(), 10, "every push was dropped"); + assert_eq!( + remote.queued_bytes.load(Ordering::Relaxed), + 0, + "the queue's byte count is back to nothing" + ); + + // The breaker is closed but the remote takes its time over a PUT: + // the queue holds three bodies, the rest are dropped at enqueue, + // and every push is either sent or counted as dropped. + let (base, stub) = stand_in().await; + stub.put_delay_ms.store(40, Ordering::Relaxed); + let remote = RemoteStore::connect_with(&base, Some("w".into()), true, tuning).unwrap(); + for i in 0..32u8 { + remote.push_module(&format!("{i:02x}").repeat(32), &module); + } + let dropped = remote.dropped_pushes(); + assert!( + dropped >= 32 - 4, + "32 pushes into a queue of three bodies: {dropped} dropped" + ); + tokio::time::sleep(Duration::from_millis(400)).await; + assert_eq!( + stub.puts.load(Ordering::Relaxed) + dropped, + 32, + "a push is sent or dropped, never lost" + ); + assert_eq!(remote.queued_bytes.load(Ordering::Relaxed), 0); + } + + // A remote that answers a hit with more than the wire's largest entry + // is refused at the cap, not read to the end. + #[tokio::test(flavor = "multi_thread")] + async fn an_oversized_body_is_refused() { + let (base, stub) = stand_in().await; + let tuning = Tuning { + slow_fetch: Duration::from_secs(30), + ..Tuning::default() + }; + let remote = RemoteStore::connect_with(&base, None, false, tuning).unwrap(); + let key = "ab".repeat(32); + stub.hit_bytes.store(MAX_ENTRY_BYTES, Ordering::Relaxed); + assert_eq!( + remote.fetch_module(&key).await, + None, + "a body one JSON wrapper over the cap" + ); + assert!( + !remote.tripped(), + "a refused body is not a strike by itself" + ); + stub.hit_bytes.store(1024, Ordering::Relaxed); + assert_eq!( + remote.fetch_module(&key).await.map(|m| m.code.len()), + Some(1024) + ); + } } diff --git a/crates/oj_server/src/store_server.rs b/crates/oj_server/src/store_server.rs index 38303487d..b1dbe30c2 100644 --- a/crates/oj_server/src/store_server.rs +++ b/crates/oj_server/src/store_server.rs @@ -1,85 +1,164 @@ // SPDX-License-Identifier: MIT // Copyright (c) 2026 Raphael Amorim -//! The oj store's wire (pulp P3): a deliberately boring six-endpoint HTTP -//! substituter, shaped like Metro's store and Nix's substituters had a child. +//! The oj store's wire (pulp P3): a deliberately boring HTTP substituter, +//! shaped like Metro's store and Nix's substituters had a child. //! //! ```text -//! GET /v1/ac/{ns}/{key} action-cache entry (modules: the CachedModule JSON) -//! PUT /v1/ac/{ns}/{key} write-once: 201, or 409 if present -//! GET /v1/cas/{blake3} content-addressed blob -//! HEAD /v1/cas/{blake3} -//! PUT /v1/cas/{blake3} write-once; body must match its digest -//! POST /v1/cas/missing {"digests":[..]} -> {"missing":[..]} +//! GET /v1/ac/{ns}/{key} action-cache entry (modules: the CachedModule JSON) +//! PUT /v1/ac/{ns}/{key} write-once: 201, or 409 if present +//! DELETE /v1/ac/{ns}/{key} operator purge (write token): 204, or 404 +//! GET /v1/cas/{blake3} content-addressed blob +//! HEAD /v1/cas/{blake3} +//! PUT /v1/cas/{blake3} write-once; body must match its digest +//! DELETE /v1/cas/{blake3} operator purge (write token): 204, or 404 +//! POST /v1/cas/missing {"digests":[..]} -> {"missing":[..]} //! ``` //! //! Write-once entries and split read/write tokens are the CREEP lesson //! (CVE-2025-36852): in a shared first-write-wins cache with one credential, //! anyone who can open a PR can poison what main will later hit. Here a PUT //! can never replace, untrusted consumers hold read-only tokens, and a bad -//! entry costs one key. +//! entry costs one key. Write-once also means the first writer wins for +//! good, so an operator holding the write token can DELETE a key (the one +//! way an entry ever leaves) and let the next honest push take it. +//! +//! What a write token can do is bounded three ways: an AC body must be a +//! `CachedModule` that passes `is_relocatable` (an entry no client would +//! ever admit is never stored), a CAS body must hash to its name, and the +//! store as a whole has a byte quota (`max_bytes`): a PUT that would take it +//! over answers 507 and writes nothing. //! //! Auth: `OJ_STORE_READ_TOKEN` (unset = public reads) and -//! `OJ_STORE_WRITE_TOKEN` (unset = writes refused), both bearer tokens. +//! `OJ_STORE_WRITE_TOKEN` (unset = writes refused), both bearer tokens, +//! compared in constant time. Entries are not signed: the write token is +//! the trust boundary (see `store_remote`). use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; -use axum::body::Bytes; +use axum::body::{Body, Bytes}; use axum::extract::{Path as AxPath, State}; use axum::http::{header, HeaderMap, StatusCode}; use axum::response::{IntoResponse, Response}; use axum::routing::{get, post}; use axum::Router; +use futures_util::stream; +use tokio::io::AsyncReadExt; -const MAX_BLOB_BYTES: usize = 64 * 1024 * 1024; -const MAX_AC_BYTES: usize = 16 * 1024 * 1024; +pub const MAX_BLOB_BYTES: usize = 64 * 1024 * 1024; +pub const MAX_AC_BYTES: usize = 16 * 1024 * 1024; +/// The byte quota `oj store serve` applies when none is given. +pub const DEFAULT_MAX_BYTES: u64 = 10 * 1024 * 1024 * 1024; +/// A file is served in reads of this size, never loaded whole. +const STREAM_CHUNK: usize = 256 * 1024; pub struct StoreServer { dir: PathBuf, read_token: Option, write_token: Option, + /// The most bytes `ac/` and `cas/` together may hold. + max_bytes: u64, + /// What they hold now: counted on boot, kept by every PUT and DELETE. + used: AtomicU64, } /// A server over `dir` with its tokens (`None` read token: public reads; -/// `None` write token: writes refused). +/// `None` write token: writes refused) and its byte quota. Counts what `dir` +/// already holds, so a quota holds across restarts. pub(crate) fn state( dir: PathBuf, read_token: Option, write_token: Option, + max_bytes: u64, ) -> Arc { + let used = bytes_under(&dir.join("ac")) + bytes_under(&dir.join("cas")); Arc::new(StoreServer { dir, read_token, write_token, + max_bytes, + used: AtomicU64::new(used), }) } -/// The six endpoints over `state`. +impl StoreServer { + /// Bytes the store holds, as the quota sees them. + pub(crate) fn used_bytes(&self) -> u64 { + self.used.load(Ordering::Relaxed) + } + + /// Takes `len` bytes of quota, or none when they would not fit. + fn reserve(&self, len: u64) -> Result<(), StatusCode> { + let mut used = self.used.load(Ordering::Relaxed); + loop { + if used.saturating_add(len) > self.max_bytes { + return Err(StatusCode::INSUFFICIENT_STORAGE); + } + match self.used.compare_exchange_weak( + used, + used + len, + Ordering::Relaxed, + Ordering::Relaxed, + ) { + Ok(_) => return Ok(()), + Err(now) => used = now, + } + } + } + + fn release(&self, len: u64) { + self.used.fetch_sub(len, Ordering::Relaxed); + } +} + +/// The size of every regular file under `dir` (0 for a dir that is not there). +fn bytes_under(dir: &Path) -> u64 { + let mut total = 0; + for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() { + let path = entry.path(); + if path.is_dir() { + total += bytes_under(&path); + } else if let Ok(meta) = entry.metadata() { + total += meta.len(); + } + } + total +} + +/// The endpoints over `state`. pub(crate) fn router(state: Arc) -> Router { Router::new() - .route("/v1/ac/{ns}/{key}", get(ac_get).put(ac_put)) - .route("/v1/cas/{hash}", get(cas_get).head(cas_head).put(cas_put)) + .route( + "/v1/ac/{ns}/{key}", + get(ac_get).put(ac_put).delete(ac_delete), + ) + .route( + "/v1/cas/{hash}", + get(cas_get).head(cas_head).put(cas_put).delete(cas_delete), + ) .route("/v1/cas/missing", post(cas_missing)) // axum's default body limit is 2 MiB, under both of ours. .layer(axum::extract::DefaultBodyLimit::max(MAX_BLOB_BYTES)) .with_state(state) } -pub async fn serve(dir: PathBuf, host: &str, port: u16) -> Result<(), String> { +pub async fn serve(dir: PathBuf, host: &str, port: u16, max_bytes: u64) -> Result<(), String> { + std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; let state = state( dir, oj_env::get().knobs.store_read_token.clone(), oj_env::get().knobs.store_write_token.clone(), + max_bytes, ); - std::fs::create_dir_all(&state.dir).map_err(|e| e.to_string())?; let app = router(Arc::clone(&state)); let addr = format!("{host}:{port}"); let listener = tokio::net::TcpListener::bind(&addr) .await .map_err(|e| format!("bind {addr}: {e}"))?; eprintln!( - "oj store: serving {} on http://{addr} (reads {}, writes {})", + "oj store: serving {} on http://{addr} (reads {}, writes {}, {} of {} MiB used)", state.dir.display(), if state.read_token.is_some() { "token" @@ -91,6 +170,8 @@ pub async fn serve(dir: PathBuf, host: &str, port: u16) -> Result<(), String> { } else { "DISABLED" }, + state.used_bytes() >> 20, + state.max_bytes >> 20, ); axum::serve(listener, app).await.map_err(|e| e.to_string()) } @@ -103,20 +184,27 @@ fn bearer(headers: &HeaderMap) -> Option<&str> { .strip_prefix("Bearer ") } +/// Token equality that takes the same time whatever the first differing +/// byte is, so a caller cannot grow a guess one byte at a time. Only the +/// length is answered early, and the length of a token is no secret. +pub(crate) fn same_token(given: &str, expected: &str) -> bool { + let (a, b) = (given.as_bytes(), expected.as_bytes()); + a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 +} + +fn presents(headers: &HeaderMap, token: Option<&str>) -> bool { + matches!((bearer(headers), token), (Some(b), Some(t)) if same_token(b, t)) +} + fn can_read(s: &StoreServer, headers: &HeaderMap) -> bool { - match &s.read_token { - None => true, - // The write token also reads: a pusher must be able to probe. - Some(t) => { - let b = bearer(headers); - b == Some(t.as_str()) - || (s.write_token.as_deref().is_some() && b == s.write_token.as_deref()) - } - } + // The write token also reads: a pusher must be able to probe. + s.read_token.is_none() + || presents(headers, s.read_token.as_deref()) + || presents(headers, s.write_token.as_deref()) } fn can_write(s: &StoreServer, headers: &HeaderMap) -> bool { - matches!((&s.write_token, bearer(headers)), (Some(t), Some(b)) if b == t) + presents(headers, s.write_token.as_deref()) } fn valid_hex(s: &str, len: usize) -> bool { @@ -146,6 +234,15 @@ fn cas_path(s: &StoreServer, hash: &str) -> Option { valid_hex(hash, 64).then(|| s.dir.join("cas").join(&hash[..2]).join(hash)) } +/// Whether an AC body is an entry some client could admit: a `CachedModule` +/// nothing in which pins a checkout. `modules` is the only namespace with a +/// shape today; the others take the same gate until they have their own. +fn admissible_entry(body: &[u8]) -> bool { + body.len() <= MAX_AC_BYTES + && serde_json::from_slice::(body) + .is_ok_and(|module| module.is_relocatable()) +} + /// Write-once publish: the bytes go to a temp file of this request's own and /// are hard-linked into place, so a reader never sees a partial entry and /// two writers of one key cannot mix: the link either creates the name or @@ -156,8 +253,8 @@ fn write_once(path: &Path, bytes: &[u8]) -> Result<(), StatusCode> { } let parent = path.parent().ok_or(StatusCode::INTERNAL_SERVER_ERROR)?; std::fs::create_dir_all(parent).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; - static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); - let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + static SEQ: AtomicU64 = AtomicU64::new(0); + let seq = SEQ.fetch_add(1, Ordering::Relaxed); let tmp = path.with_extension(format!("tmp-{}-{seq}", std::process::id())); std::fs::write(&tmp, bytes).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; let linked = std::fs::hard_link(&tmp, path); @@ -169,6 +266,77 @@ fn write_once(path: &Path, bytes: &[u8]) -> Result<(), StatusCode> { } } +/// `write_once` under the quota and off the runtime: a key the store +/// already holds is a conflict whatever the quota says (its bytes are +/// counted already); otherwise the bytes are reserved first, written on the +/// blocking pool, and given back when nothing landed. +async fn store(s: &StoreServer, path: PathBuf, body: Bytes) -> Result<(), StatusCode> { + if tokio::fs::metadata(&path).await.is_ok() { + return Err(StatusCode::CONFLICT); + } + let len = body.len() as u64; + s.reserve(len)?; + let written = tokio::task::spawn_blocking(move || write_once(&path, &body)) + .await + .unwrap_or(Err(StatusCode::INTERNAL_SERVER_ERROR)); + if written.is_err() { + s.release(len); + } + written +} + +/// Removes `path` and gives its bytes back to the quota: 204, or 404. +async fn purge(s: &StoreServer, path: PathBuf) -> StatusCode { + let removed = tokio::task::spawn_blocking(move || { + let len = std::fs::metadata(&path).ok()?.len(); + std::fs::remove_file(&path).ok()?; + Some(len) + }) + .await + .ok() + .flatten(); + match removed { + Some(len) => { + s.release(len); + StatusCode::NO_CONTENT + } + None => StatusCode::NOT_FOUND, + } +} + +/// The file at `path` as a streamed body, or 404. Only the open is awaited +/// here; the reads run as the client takes the bytes. +async fn file_body(path: &Path, content_type: &'static str, immutable: bool) -> Response { + let Ok(file) = tokio::fs::File::open(path).await else { + return StatusCode::NOT_FOUND.into_response(); + }; + let len = file.metadata().await.ok().map(|m| m.len()); + let chunks = stream::unfold(file, |mut file| async move { + let mut buf = vec![0u8; STREAM_CHUNK]; + match file.read(&mut buf).await { + Ok(0) => None, + Ok(n) => { + buf.truncate(n); + Some((Ok::<_, std::io::Error>(Bytes::from(buf)), file)) + } + Err(e) => Some((Err(e), file)), + } + }); + let mut response = Body::from_stream(chunks).into_response(); + let headers = response.headers_mut(); + headers.insert(header::CONTENT_TYPE, content_type.parse().unwrap()); + if let Some(len) = len { + headers.insert(header::CONTENT_LENGTH, len.into()); + } + if immutable { + headers.insert( + header::CACHE_CONTROL, + "public, max-age=31536000, immutable".parse().unwrap(), + ); + } + response +} + async fn ac_get( State(s): State>, AxPath((ns, key)): AxPath<(String, String)>, @@ -180,10 +348,7 @@ async fn ac_get( let Some(path) = ac_path(&s, &ns, &key) else { return StatusCode::BAD_REQUEST.into_response(); }; - match std::fs::read(&path) { - Ok(bytes) => ([(header::CONTENT_TYPE, "application/json")], bytes).into_response(), - Err(_) => StatusCode::NOT_FOUND.into_response(), - } + file_body(&path, "application/json", false).await } async fn ac_put( @@ -198,15 +363,29 @@ async fn ac_put( let Some(path) = ac_path(&s, &ns, &key) else { return StatusCode::BAD_REQUEST.into_response(); }; - if body.len() > MAX_AC_BYTES || serde_json::from_slice::(&body).is_err() { + if !admissible_entry(&body) { return StatusCode::UNPROCESSABLE_ENTITY.into_response(); } - match write_once(&path, &body) { + match store(&s, path, body).await { Ok(()) => StatusCode::CREATED.into_response(), Err(code) => code.into_response(), } } +async fn ac_delete( + State(s): State>, + AxPath((ns, key)): AxPath<(String, String)>, + headers: HeaderMap, +) -> Response { + if !can_write(&s, &headers) { + return StatusCode::UNAUTHORIZED.into_response(); + } + let Some(path) = ac_path(&s, &ns, &key) else { + return StatusCode::BAD_REQUEST.into_response(); + }; + purge(&s, path).await.into_response() +} + async fn cas_get( State(s): State>, AxPath(hash): AxPath, @@ -218,17 +397,7 @@ async fn cas_get( let Some(path) = cas_path(&s, &hash) else { return StatusCode::BAD_REQUEST.into_response(); }; - match std::fs::read(&path) { - Ok(bytes) => ( - [ - (header::CONTENT_TYPE, "application/octet-stream"), - (header::CACHE_CONTROL, "public, max-age=31536000, immutable"), - ], - bytes, - ) - .into_response(), - Err(_) => StatusCode::NOT_FOUND.into_response(), - } + file_body(&path, "application/octet-stream", true).await } async fn cas_head( @@ -239,10 +408,12 @@ async fn cas_head( if !can_read(&s, &headers) { return StatusCode::UNAUTHORIZED.into_response(); } - match cas_path(&s, &hash) { - Some(path) if path.is_file() => StatusCode::OK.into_response(), - Some(_) => StatusCode::NOT_FOUND.into_response(), - None => StatusCode::BAD_REQUEST.into_response(), + let Some(path) = cas_path(&s, &hash) else { + return StatusCode::BAD_REQUEST.into_response(); + }; + match tokio::fs::metadata(&path).await { + Ok(meta) if meta.is_file() => StatusCode::OK.into_response(), + _ => StatusCode::NOT_FOUND.into_response(), } } @@ -262,11 +433,18 @@ async fn cas_put( return StatusCode::PAYLOAD_TOO_LARGE.into_response(); } // CAS self-verification: the name IS the digest, so a tampered or - // corrupted upload cannot land under an honest name. - if blake3::hash(&body).to_hex().to_string() != hash { + // corrupted upload cannot land under an honest name. Hashing 64 MiB is + // real work, so it runs off the runtime too. + let digest = { + let body = body.clone(); + tokio::task::spawn_blocking(move || blake3::hash(&body).to_hex().to_string()) + .await + .unwrap_or_default() + }; + if digest != hash { return StatusCode::UNPROCESSABLE_ENTITY.into_response(); } - match write_once(&path, &body) { + match store(&s, path, body).await { Ok(()) => StatusCode::CREATED.into_response(), // A CAS conflict is success by definition: identical content. Err(StatusCode::CONFLICT) => StatusCode::OK.into_response(), @@ -274,6 +452,20 @@ async fn cas_put( } } +async fn cas_delete( + State(s): State>, + AxPath(hash): AxPath, + headers: HeaderMap, +) -> Response { + if !can_write(&s, &headers) { + return StatusCode::UNAUTHORIZED.into_response(); + } + let Some(path) = cas_path(&s, &hash) else { + return StatusCode::BAD_REQUEST.into_response(); + }; + purge(&s, path).await.into_response() +} + #[derive(serde::Deserialize)] struct MissingReq { digests: Vec, @@ -290,11 +482,16 @@ async fn cas_missing( let Ok(req) = serde_json::from_slice::(&body) else { return StatusCode::BAD_REQUEST.into_response(); }; - let missing: Vec<&String> = req - .digests - .iter() - .filter(|h| !matches!(cas_path(&s, h), Some(p) if p.is_file())) - .collect(); + let mut missing: Vec<&String> = Vec::new(); + for digest in &req.digests { + let present = match cas_path(&s, digest) { + Some(path) => tokio::fs::metadata(path).await.is_ok_and(|m| m.is_file()), + None => false, + }; + if !present { + missing.push(digest); + } + } ( [(header::CONTENT_TYPE, "application/json")], serde_json::json!({ "missing": missing }).to_string(), @@ -312,11 +509,19 @@ mod tests { use axum::http::{Method, Request}; use tower::ServiceExt; - fn key(n: u8) -> String { + pub(super) fn key(n: u8) -> String { format!("{n:02x}").repeat(32) } - async fn call( + pub(super) fn entry(code: &str) -> Vec { + serde_json::to_vec(&oj_cache::CachedModule { + code: code.into(), + ..Default::default() + }) + .unwrap() + } + + pub(super) async fn call( app: &Router, method: Method, uri: &str, @@ -354,8 +559,13 @@ mod tests { #[tokio::test] async fn names_that_are_no_digest_or_namespace_are_refused_and_write_nothing() { let dir = tempfile::tempdir().unwrap(); - let app = router(state(dir.path().to_path_buf(), None, Some("w".into()))); - let module = serde_json::to_vec(&oj_cache::CachedModule::default()).unwrap(); + let app = router(state( + dir.path().to_path_buf(), + None, + Some("w".into()), + u64::MAX, + )); + let module = entry(""); for uri in [ format!("/v1/ac/modules/{}", &key(1)[..63]), format!("/v1/ac/modules/{}X", &key(1)[..63]), @@ -370,6 +580,8 @@ mod tests { assert_eq!(put, StatusCode::BAD_REQUEST, "PUT {uri}"); let (get, _) = call(&app, Method::GET, &uri, None, Vec::new()).await; assert_eq!(get, StatusCode::BAD_REQUEST, "GET {uri}"); + let (del, _) = call(&app, Method::DELETE, &uri, Some("w"), Vec::new()).await; + assert_eq!(del, StatusCode::BAD_REQUEST, "DELETE {uri}"); } assert!( files_under(dir.path()).is_empty(), @@ -385,13 +597,10 @@ mod tests { dir.path().to_path_buf(), Some("r".into()), Some("w".into()), + u64::MAX, )); let uri = format!("/v1/ac/modules/{}", key(3)); - let module = serde_json::to_vec(&oj_cache::CachedModule { - code: "export const x = 1;".into(), - ..Default::default() - }) - .unwrap(); + let module = entry("export const x = 1;"); let (status, _) = call(&app, Method::PUT, &uri, None, module.clone()).await; assert_eq!(status, StatusCode::UNAUTHORIZED, "no token"); let (status, _) = call(&app, Method::PUT, &uri, Some("r"), module.clone()).await; @@ -402,11 +611,7 @@ mod tests { ); let (status, _) = call(&app, Method::PUT, &uri, Some("w"), module.clone()).await; assert_eq!(status, StatusCode::CREATED); - let other = serde_json::to_vec(&oj_cache::CachedModule { - code: "export const x = 2;".into(), - ..Default::default() - }) - .unwrap(); + let other = entry("export const x = 2;"); let (status, _) = call(&app, Method::PUT, &uri, Some("w"), other).await; assert_eq!(status, StatusCode::CONFLICT, "write once"); let (status, _) = call(&app, Method::GET, &uri, None, Vec::new()).await; @@ -427,17 +632,14 @@ mod tests { "a body that is no entry is refused before the key is looked at" ); let fresh = format!("/v1/ac/modules/{}", key(4)); - let (status, _) = call(&app, Method::PUT, &fresh, Some("w"), b"not json".to_vec()).await; - assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "an entry is JSON"); - let (status, _) = call( - &app, - Method::PUT, - &fresh, - Some("w"), - vec![b'['; MAX_AC_BYTES + 1], - ) - .await; - assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "bounded"); + for (body, why) in [ + (b"not json".to_vec(), "an entry is JSON"), + (b"{\"probe\":1}".to_vec(), "an entry is a CachedModule"), + (vec![b'['; MAX_AC_BYTES + 1], "bounded"), + ] { + let (status, _) = call(&app, Method::PUT, &fresh, Some("w"), body).await; + assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{why}"); + } let (status, _) = call(&app, Method::GET, &fresh, Some("r"), Vec::new()).await; assert_eq!( status, @@ -446,10 +648,68 @@ mod tests { ); } + // The server applies the client's admission gate too: an entry that + // names a checkout could never be served anywhere, so it is never + // stored, and a planted one cannot take a key from an honest push. + #[tokio::test] + async fn an_entry_that_pins_a_checkout_is_refused_by_the_server() { + let dir = tempfile::tempdir().unwrap(); + let app = router(state( + dir.path().to_path_buf(), + None, + Some("w".into()), + u64::MAX, + )); + let uri = format!("/v1/ac/modules/{}", key(7)); + let pinned = [ + oj_cache::CachedModule { + code: "import x from \"/@fs//other/checkout/x.js\";".into(), + imports: vec!["/@fs//other/checkout/x.js".into()], + ..Default::default() + }, + oj_cache::CachedModule { + code: "export {};".into(), + watch_files: vec!["/other/checkout/tailwind.config.ts".into()], + ..Default::default() + }, + oj_cache::CachedModule { + code: "export {};".into(), + require_map: vec![("sib".into(), "/@oj-pkg/6162".into())], + ..Default::default() + }, + ]; + for module in &pinned { + let body = serde_json::to_vec(module).unwrap(); + let (status, _) = call(&app, Method::PUT, &uri, Some("w"), body).await; + assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{module:?}"); + } + let (status, _) = call(&app, Method::GET, &uri, None, Vec::new()).await; + assert_eq!(status, StatusCode::NOT_FOUND, "the key is still free"); + assert_eq!(app_state_used(dir.path()), 0, "nothing was stored"); + let relocatable = oj_cache::CachedModule { + code: "import x from \"/@fs/@mono/packages/x.js\";".into(), + imports: vec!["/@fs/@mono/packages/x.js".into()], + fs_allow: vec!["ws:node_modules/dep".into()], + ..Default::default() + }; + let body = serde_json::to_vec(&relocatable).unwrap(); + let (status, _) = call(&app, Method::PUT, &uri, Some("w"), body).await; + assert_eq!(status, StatusCode::CREATED, "an honest push takes it"); + } + + fn app_state_used(dir: &Path) -> u64 { + bytes_under(&dir.join("ac")) + bytes_under(&dir.join("cas")) + } + #[tokio::test] async fn blobs_are_named_by_their_digest() { let dir = tempfile::tempdir().unwrap(); - let app = router(state(dir.path().to_path_buf(), None, Some("w".into()))); + let app = router(state( + dir.path().to_path_buf(), + None, + Some("w".into()), + u64::MAX, + )); let bytes = b"chunk bytes".to_vec(); let digest = blake3::hash(&bytes).to_hex().to_string(); let wrong = format!("/v1/cas/{}", key(5)); @@ -484,6 +744,207 @@ mod tests { let (status, _) = call(&app, Method::PUT, &right, None, Vec::new()).await; assert_eq!(status, StatusCode::UNAUTHORIZED); } + + // The largest blob the wire takes goes in and comes back whole, through + // the blocking pool and the streamed body rather than one read on the + // runtime. + #[tokio::test(flavor = "multi_thread")] + async fn the_largest_blob_round_trips() { + let dir = tempfile::tempdir().unwrap(); + let s = state( + dir.path().to_path_buf(), + None, + Some("w".into()), + MAX_BLOB_BYTES as u64, + ); + let app = router(Arc::clone(&s)); + let bytes: Vec = (0..MAX_BLOB_BYTES).map(|i| (i % 251) as u8).collect(); + let digest = blake3::hash(&bytes).to_hex().to_string(); + let uri = format!("/v1/cas/{digest}"); + let (status, _) = call(&app, Method::PUT, &uri, Some("w"), bytes.clone()).await; + assert_eq!(status, StatusCode::CREATED); + assert_eq!(s.used_bytes(), MAX_BLOB_BYTES as u64); + let (status, body) = call(&app, Method::GET, &uri, None, Vec::new()).await; + assert_eq!(status, StatusCode::OK); + assert!(body == bytes, "the blob came back changed"); + let mut over = bytes.clone(); + over.push(0); + let over_digest = blake3::hash(&over).to_hex().to_string(); + let (status, _) = call( + &app, + Method::PUT, + &format!("/v1/cas/{over_digest}"), + Some("w"), + over, + ) + .await; + assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE); + } + + #[test] + fn tokens_compare_whole_and_in_constant_time() { + assert!(same_token("secret", "secret")); + assert!(!same_token("secret", "secreT")); + assert!(!same_token("secre", "secret")); + assert!(!same_token("secrets", "secret")); + assert!(!same_token("", "secret")); + assert!(same_token("", "")); + // The fold visits every byte: a difference anywhere, not only in + // the first byte, is found, and no early return exists to time. + let expected = "a".repeat(64); + for i in 0..64 { + let mut guess = expected.clone().into_bytes(); + guess[i] = b'b'; + assert!(!same_token(std::str::from_utf8(&guess).unwrap(), &expected)); + } + } +} + +#[cfg(test)] +mod quota_tests { + //! What a write token can fill: the byte quota over `ac/` and `cas/`, + //! counted on boot and kept by every write and purge. + use super::tests::{call, entry, key}; + use super::*; + use axum::http::Method; + + #[tokio::test] + async fn a_put_over_the_quota_is_refused_and_counts_nothing() { + let dir = tempfile::tempdir().unwrap(); + let module = entry("export const x = 1;"); + let quota = module.len() as u64 * 2 + 1; + let s = state(dir.path().to_path_buf(), None, Some("w".into()), quota); + let app = router(Arc::clone(&s)); + assert_eq!(s.used_bytes(), 0); + for n in [1, 2] { + let uri = format!("/v1/ac/modules/{}", key(n)); + let (status, _) = call(&app, Method::PUT, &uri, Some("w"), module.clone()).await; + assert_eq!(status, StatusCode::CREATED, "entry {n} fits"); + assert_eq!(s.used_bytes(), module.len() as u64 * n as u64); + } + let third = format!("/v1/ac/modules/{}", key(3)); + let (status, _) = call(&app, Method::PUT, &third, Some("w"), module.clone()).await; + assert_eq!(status, StatusCode::INSUFFICIENT_STORAGE); + assert_eq!( + s.used_bytes(), + module.len() as u64 * 2, + "a refused write takes no quota" + ); + let (status, _) = call(&app, Method::GET, &third, None, Vec::new()).await; + assert_eq!(status, StatusCode::NOT_FOUND, "and lands nothing"); + // A blob is under the same quota as an entry. + let blob = b"x".to_vec(); + let digest = blake3::hash(&blob).to_hex().to_string(); + let (status, _) = call( + &app, + Method::PUT, + &format!("/v1/cas/{digest}"), + Some("w"), + blob, + ) + .await; + assert_eq!(status, StatusCode::CREATED, "one byte still fits"); + assert_eq!(s.used_bytes(), quota); + // A write that is a conflict costs nothing: the bytes already count. + let first = format!("/v1/ac/modules/{}", key(1)); + let (status, _) = call(&app, Method::PUT, &first, Some("w"), module.clone()).await; + assert_eq!(status, StatusCode::CONFLICT); + assert_eq!(s.used_bytes(), quota); + } + + #[tokio::test] + async fn the_quota_counts_what_the_dir_already_holds() { + let dir = tempfile::tempdir().unwrap(); + let module = entry("export const x = 1;"); + { + let s = state(dir.path().to_path_buf(), None, Some("w".into()), u64::MAX); + let app = router(s); + let uri = format!("/v1/ac/modules/{}", key(1)); + let (status, _) = call(&app, Method::PUT, &uri, Some("w"), module.clone()).await; + assert_eq!(status, StatusCode::CREATED); + let blob = b"blob".to_vec(); + let digest = blake3::hash(&blob).to_hex().to_string(); + let (status, _) = call( + &app, + Method::PUT, + &format!("/v1/cas/{digest}"), + Some("w"), + blob, + ) + .await; + assert_eq!(status, StatusCode::CREATED); + } + // A file outside ac/ and cas/ (the local store's own entries, when + // the server is pointed at the per-user dir) is not the wire's. + std::fs::create_dir_all(dir.path().join("v1/modules")).unwrap(); + std::fs::write(dir.path().join("v1/modules/local.json"), b"x".repeat(100)).unwrap(); + let restarted = state(dir.path().to_path_buf(), None, Some("w".into()), u64::MAX); + assert_eq!(restarted.used_bytes(), module.len() as u64 + 4); + let full = state( + dir.path().to_path_buf(), + None, + Some("w".into()), + module.len() as u64 + 4, + ); + let app = router(full); + let uri = format!("/v1/ac/modules/{}", key(2)); + let (status, _) = call(&app, Method::PUT, &uri, Some("w"), module).await; + assert_eq!( + status, + StatusCode::INSUFFICIENT_STORAGE, + "a restart does not reset the quota" + ); + } + + // The one way an entry leaves: an operator with the write token purges + // the key, its bytes go back to the quota, and the next push takes it. + #[tokio::test] + async fn a_purge_frees_the_key_and_its_bytes() { + let dir = tempfile::tempdir().unwrap(); + let module = entry("export const x = 1;"); + let s = state( + dir.path().to_path_buf(), + Some("r".into()), + Some("w".into()), + module.len() as u64, + ); + let app = router(Arc::clone(&s)); + let uri = format!("/v1/ac/modules/{}", key(1)); + let (status, _) = call(&app, Method::PUT, &uri, Some("w"), module.clone()).await; + assert_eq!(status, StatusCode::CREATED); + for token in [None, Some("r")] { + let (status, _) = call(&app, Method::DELETE, &uri, token, Vec::new()).await; + assert_eq!(status, StatusCode::UNAUTHORIZED, "{token:?} cannot purge"); + } + let (status, _) = call(&app, Method::GET, &uri, Some("r"), Vec::new()).await; + assert_eq!(status, StatusCode::OK, "still there"); + let (status, _) = call(&app, Method::DELETE, &uri, Some("w"), Vec::new()).await; + assert_eq!(status, StatusCode::NO_CONTENT); + assert_eq!(s.used_bytes(), 0); + let (status, _) = call(&app, Method::GET, &uri, Some("r"), Vec::new()).await; + assert_eq!(status, StatusCode::NOT_FOUND); + let (status, _) = call(&app, Method::DELETE, &uri, Some("w"), Vec::new()).await; + assert_eq!(status, StatusCode::NOT_FOUND, "purged once"); + let better = entry("export const x = 2;"); + let (status, _) = call(&app, Method::PUT, &uri, Some("w"), better.clone()).await; + assert_eq!(status, StatusCode::CREATED, "the key is free again"); + let (_, body) = call(&app, Method::GET, &uri, Some("r"), Vec::new()).await; + assert_eq!(body, better); + // Blobs purge the same way. + let (status, _) = call(&app, Method::DELETE, &uri, Some("w"), Vec::new()).await; + assert_eq!(status, StatusCode::NO_CONTENT); + let blob = b"blob".to_vec(); + let digest = blake3::hash(&blob).to_hex().to_string(); + let blob_uri = format!("/v1/cas/{digest}"); + let (status, _) = call(&app, Method::PUT, &blob_uri, Some("w"), blob).await; + assert_eq!(status, StatusCode::CREATED); + assert_eq!(s.used_bytes(), 4); + let (status, _) = call(&app, Method::DELETE, &blob_uri, Some("w"), Vec::new()).await; + assert_eq!(status, StatusCode::NO_CONTENT); + assert_eq!(s.used_bytes(), 0); + let (status, _) = call(&app, Method::HEAD, &blob_uri, Some("r"), Vec::new()).await; + assert_eq!(status, StatusCode::NOT_FOUND); + } } #[cfg(test)] @@ -494,12 +955,13 @@ mod race_tests { use tower::ServiceExt; // Two sandboxes pushing one key at once, many times over: exactly one - // write is created, the rest are conflicts, and what is stored is one - // writer's whole body, never a mix. + // write is created, the rest are conflicts, what is stored is one + // writer's whole body, never a mix, and the quota counts that one body. #[tokio::test(flavor = "multi_thread")] async fn racing_puts_of_one_key_create_it_once_and_whole() { let dir = tempfile::tempdir().unwrap(); - let app = router(state(dir.path().to_path_buf(), None, Some("w".into()))); + let s = state(dir.path().to_path_buf(), None, Some("w".into()), u64::MAX); + let app = router(Arc::clone(&s)); let key = "ab".repeat(32); let uri = format!("/v1/ac/modules/{key}"); let bodies: Vec> = (0..24) @@ -541,6 +1003,11 @@ mod race_tests { bodies.contains(&stored), "the stored entry is no writer's body" ); + assert_eq!( + s.used_bytes(), + stored.len() as u64, + "the losers gave their bytes back" + ); let leftovers: Vec<_> = std::fs::read_dir(dir.path().join("ac/modules/ab")) .unwrap() .flatten() diff --git a/crates/oj_server/src/tests.rs b/crates/oj_server/src/tests.rs index 158e7c327..9bd299ae2 100644 --- a/crates/oj_server/src/tests.rs +++ b/crates/oj_server/src/tests.rs @@ -3458,6 +3458,157 @@ fn salt_settings(root: &Path) -> oj_resolver::ResolveSettings { } } +// Entries name in-workspace files outside the root by their `/@fs/@mono/` +// url, expanded against the reader's workspace: two roots at different +// depths of their workspaces must not share a key, however alike their files. +#[test] +fn module_cache_salt_covers_the_roots_place_in_its_workspace() { + fn at(label: &str, depth: &str) -> PathBuf { + let mono = std::env::temp_dir().join(format!("oj-salt-pos-{}-{label}", std::process::id())); + let _ = std::fs::remove_dir_all(&mono); + let app = mono.join(depth); + std::fs::create_dir_all(mono.join("node_modules")).unwrap(); + std::fs::create_dir_all(&app).unwrap(); + std::fs::write(app.join("package.json"), br#"{"name":"app"}"#).unwrap(); + std::fs::write(app.join("package-lock.json"), br#"{"lockfileVersion":3}"#).unwrap(); + app + } + let (shallow, deep) = (at("a", "app"), at("b", "packages/web/app")); + let settings = |root: &Path| oj_resolver::ResolveSettings { + alias: vec![], + ..salt_settings(root) + }; + assert_ne!( + module_cache_config_salt(&shallow, &settings(&shallow), None), + module_cache_config_salt(&deep, &settings(&deep), None), + "the root's position in the workspace is an input" + ); + let twin = at("c", "app"); + assert_eq!( + module_cache_config_salt(&shallow, &settings(&shallow), None), + module_cache_config_salt(&twin, &settings(&twin), None), + "the same position in another checkout salts alike" + ); +} + +// A package linked into node_modules from outside any registry layout (a +// workspace plugin, `npm link`) changes without a lockfile change: its +// manifest and entry files are in the salt by content. A registry install +// reached through a link (pnpm's `.pnpm`) is the lockfile's. +#[cfg(unix)] +#[test] +fn module_cache_salt_covers_linked_packages_by_content() { + let root = salt_fixture("linked"); + let settings = salt_settings(&root); + let base = module_cache_config_salt(&root, &settings, None); + let outside = root + .parent() + .unwrap() + .join(format!("oj-salt-linked-pkg-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&outside); + std::fs::create_dir_all(&outside).unwrap(); + std::fs::write( + outside.join("package.json"), + br#"{"name":"my-plugin","main":"index.js","exports":{".":"./index.js","./extra":"./extra.js"}}"#, + ) + .unwrap(); + std::fs::write(outside.join("index.js"), b"export default 1\n").unwrap(); + std::fs::write(outside.join("extra.js"), b"export const x = 1\n").unwrap(); + let modules = root.join("node_modules"); + std::fs::create_dir_all(&modules).unwrap(); + std::os::unix::fs::symlink(&outside, modules.join("my-plugin")).unwrap(); + let linked = module_cache_config_salt(&root, &settings, None); + assert_ne!(base, linked, "a linked package joins the salt"); + std::fs::write(outside.join("index.js"), b"export default 2\n").unwrap(); + let edited = module_cache_config_salt(&root, &settings, None); + assert_ne!(linked, edited, "its entry file by content"); + std::fs::write(outside.join("extra.js"), b"export const x = 2\n").unwrap(); + assert_ne!( + edited, + module_cache_config_salt(&root, &settings, None), + "every exports target by content" + ); + // A pnpm-style link into the registry layout is not read. + let registry = modules.join(".pnpm/reg@1.0.0/node_modules/reg"); + std::fs::create_dir_all(®istry).unwrap(); + std::fs::write( + registry.join("package.json"), + br#"{"name":"reg","main":"index.js"}"#, + ) + .unwrap(); + std::fs::write(registry.join("index.js"), b"1").unwrap(); + std::os::unix::fs::symlink(®istry, modules.join("reg")).unwrap(); + let with_registry = module_cache_config_salt(&root, &settings, None); + std::fs::write(registry.join("index.js"), b"2").unwrap(); + assert_eq!( + with_registry, + module_cache_config_salt(&root, &settings, None), + "a registry install's bytes are the lockfile's to describe" + ); + let _ = std::fs::remove_dir_all(&outside); +} + +// Patch files are in the dependency epoch by content, never by the patches +// directory's mtime (which differs per checkout). +#[test] +fn lockfile_hash_covers_patch_files_by_content_not_mtime() { + fn fixture(label: &str) -> PathBuf { + let root = + std::env::temp_dir().join(format!("oj-salt-patches-{}-{label}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(root.join("patches")).unwrap(); + std::fs::write(root.join("package-lock.json"), br#"{"lockfileVersion":3}"#).unwrap(); + std::fs::write(root.join("patches/dep+1.0.0.patch"), b"--- a\n+++ b\n").unwrap(); + root + } + let hash = |root: &Path| { + let mut hasher = blake3::Hasher::new(); + optimize::hash_lockfiles(root, &mut hasher); + hasher.finalize().to_hex().to_string() + }; + let a = fixture("a"); + std::thread::sleep(std::time::Duration::from_millis(20)); + let b = fixture("b"); + assert_eq!(hash(&a), hash(&b), "same patches, other mtimes: one epoch"); + std::fs::write(b.join("patches/dep+1.0.0.patch"), b"--- a\n+++ c\n").unwrap(); + assert_ne!(hash(&a), hash(&b), "a patch's content is the epoch's"); +} + +#[test] +fn the_tool_version_carries_a_source_id() { + let (version, id) = tool_version().split_once('+').expect("version+source id"); + assert_eq!(version, env!("CARGO_PKG_VERSION")); + assert_eq!(id.len(), 16, "{id}"); + assert!(id.chars().all(|c| c.is_ascii_hexdigit()), "{id}"); +} + +// An entry's `/@fs/@mono/` import must name a file in the READER's +// workspace: another layout (a hoisted vs an isolated install) is a miss, +// never a hit whose import 404s. +#[test] +fn mono_imports_must_exist_in_the_readers_workspace() { + let ws = std::env::temp_dir().join(format!("oj-ipv-mono-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&ws); + let root = ws.join("app"); + std::fs::create_dir_all(ws.join("packages/ui")).unwrap(); + std::fs::create_dir_all(&root).unwrap(); + std::fs::write(ws.join("packages/ui/x.ts"), "export {}\n").unwrap(); + let dc = Mutex::new(DirCache::new()); + assert!(!imports_a_plugin_virtual( + &["/@fs/@mono/packages/ui/x.ts".to_string()], + &root, + &ws, + &dc + )); + assert!(imports_a_plugin_virtual( + &["/@fs/@mono/packages/ui/gone.ts?import".to_string()], + &root, + &ws, + &dc + )); + let _ = std::fs::remove_dir_all(&ws); +} + #[test] fn module_cache_salt_is_worktree_independent() { let a = salt_fixture("wt-a"); @@ -3684,6 +3835,7 @@ fn imports_a_plugin_virtual_flags_only_missing_fs_paths() { assert!(!imports_a_plugin_virtual( &["/src/real.ts".to_string()], r, + r, &dc )); assert!(!imports_a_plugin_virtual( @@ -3693,6 +3845,7 @@ fn imports_a_plugin_virtual_flags_only_missing_fs_paths() { "https://cdn/x.js".to_string() ], r, + r, &dc, )); assert!(imports_a_plugin_virtual( @@ -3701,16 +3854,19 @@ fn imports_a_plugin_virtual_flags_only_missing_fs_paths() { "/Users/nope/x.wyw-in-js.css".to_string() ], r, + r, &dc, )); assert!(imports_a_plugin_virtual( &["/src/gone.css".to_string()], r, + r, &dc )); assert!(!imports_a_plugin_virtual( &["/src/real.ts?import".to_string()], r, + r, &dc )); std::fs::remove_dir_all(&root).ok(); diff --git a/crates/oj_server/tests/dev/determinism.rs b/crates/oj_server/tests/dev/determinism.rs index d0cc513e5..cdab77209 100644 --- a/crates/oj_server/tests/dev/determinism.rs +++ b/crates/oj_server/tests/dev/determinism.rs @@ -405,9 +405,30 @@ async fn the_store_changes_no_bytes() { let server = crate::serve(dev(&without, false)).await; snapshot(&server, &without, marker).await }; + // Dep URL versions are the one planned difference: the store's ledger + // derives them from the bundle's bytes, a server without it from its + // session, as Vite does. + let unversioned = |s: &str| { + let mut out = String::new(); + let mut rest = s; + while let Some(i) = rest.find("?v=") { + out.push_str(&rest[..i + 3]); + rest = &rest[i + 3..]; + let end = rest + .find(|c: char| !c.is_ascii_hexdigit()) + .unwrap_or(rest.len()); + rest = &rest[end..]; + } + out.push_str(rest); + out + }; for (((url, a), (_, b)), (_, c)) in stored.iter().zip(&hits).zip(&fresh) { assert_eq!(a, b, "{url}: the hit differs from the compile it stored"); - assert_eq!(a, c, "{url}: the store's bytes differ from a plain compile"); + assert_eq!( + unversioned(a), + unversioned(c), + "{url}: the store's bytes differ from a plain compile" + ); } } diff --git a/crates/oj_server/tests/dev/optimize_plan.rs b/crates/oj_server/tests/dev/optimize_plan.rs index bd384ace4..13a91e6dd 100644 --- a/crates/oj_server/tests/dev/optimize_plan.rs +++ b/crates/oj_server/tests/dev/optimize_plan.rs @@ -281,9 +281,14 @@ async fn a_vanished_versioned_dep_file_is_outdated_not_missing() { #[tokio::test(flavor = "multi_thread")] async fn a_cold_session_reuses_dep_urls_only_for_the_same_bytes() { crate::require_fixture!("vite"); + // The ledger lives in the store: a cold session without it mints anew. let app = plain_esm_app(); let session = || async { - let server = app.serve().await; + let server = crate::serve(oj_server::DevServer { + store: true, + ..app.dev() + }) + .await; let urls = dep_urls(&server.text("/main.js").await); for url in &urls { assert_eq!(server.get(url).await.status, 200, "{url}"); @@ -302,7 +307,11 @@ async fn a_cold_session_reuses_dep_urls_only_for_the_same_bytes() { "node_modules/plain-esm/index.js", "export const hi = () => 2;\n", )]); - let server = app.serve().await; + let server = crate::serve(oj_server::DevServer { + store: true, + ..app.dev() + }) + .await; // The plan's URLs are the earlier ones until the commit finds the bytes // moved; then every URL moves and the page reloads onto new ones. let deadline = Instant::now() + Duration::from_secs(30); diff --git a/crates/oj_server/tests/dev/store.rs b/crates/oj_server/tests/dev/store.rs index d94e2980c..7ea44fe31 100644 --- a/crates/oj_server/tests/dev/store.rs +++ b/crates/oj_server/tests/dev/store.rs @@ -245,6 +245,83 @@ async fn a_config_edit_between_sessions_is_a_miss() { ); } +// A stylesheet inlines the files it `@import`s: inputs of its entry that +// change without the sheet's own bytes. An edit to one between sessions is +// a miss that serves the new content, never the old inlined bytes; the +// unchanged sheet still hits. +#[tokio::test(flavor = "multi_thread")] +async fn a_css_import_edited_between_sessions_is_a_miss() { + let marker = "css-import-store"; + let app = App::new(&[ + ( + "index.html", + "", + ), + ( + "src/index.css", + &format!("@import \"./vars.css\";\n.{marker} {{ color: var(--c); }}\n"), + ), + ("src/vars.css", ":root { --c: red; }\n"), + ]); + let session = || async { + let server = crate::serve(dev(&app)).await; + server.text("/src/index.css").await + }; + let first = session().await; + assert!(first.contains("red"), "{first}"); + let before = wait_for_entries(marker, 1).await.len(); + assert_eq!(session().await, first, "unchanged imports hit"); + tokio::time::sleep(Duration::from_millis(300)).await; + assert_eq!(shared_entries(marker).len(), before, "a hit writes nothing"); + app.write(&[("src/vars.css", ":root { --c: blue; }\n")]); + let second = session().await; + assert!( + second.contains("blue") && !second.contains("red"), + "the sheet's old import was served:\n{second}" + ); +} + +// The nearest tsconfig decides a file's class-field semantics, and the key +// carries the decision: an edit to a nested tsconfig between sessions is a +// miss with the new output, not a hit under the old settings. +#[tokio::test(flavor = "multi_thread")] +async fn a_nested_tsconfig_edit_between_sessions_is_a_miss() { + let marker = "nested-tsconfig-store"; + let app = App::new(&[ + ( + "index.html", + "", + ), + ( + "src/tsconfig.json", + r#"{"compilerOptions":{"target":"ES2022","useDefineForClassFields":false}}"#, + ), + ( + "src/main.ts", + &format!("export class Box {{ label = \"{marker}\"; }}\n"), + ), + ]); + let session = || async { + let server = crate::serve(dev(&app)).await; + server.text("/src/main.ts").await + }; + let first = session().await; + wait_for_entries(marker, 1).await; + assert_eq!(session().await, first, "unchanged settings hit"); + app.write(&[( + "src/tsconfig.json", + r#"{"compilerOptions":{"target":"ES2022","useDefineForClassFields":true}}"#, + )]); + // What a restart does: the compiler's tsconfig lookups start over. + oj_compiler::tsconfig::clear_cache(); + let second = session().await; + assert_ne!( + second, first, + "the nested tsconfig's new semantics were not served" + ); + assert!(second.contains(marker)); +} + /// A checkout laid out as a workspace: a hoisted `node_modules` above the /// app, as pnpm and yarn workspaces leave it. `App::new`'s dir is the /// workspace; the app the server runs is `mono/app` under it. @@ -448,6 +525,33 @@ async fn checkouts_bundling_the_same_dependency_mint_the_same_urls() { assert!(server.text(&urls_other[0]).await.contains("2")); } +// Without the store there is no ledger: each session mints its own dep +// versions, as Vite's sessionTimestamp does, and never re-reads a bundle to +// vouch for its bytes. +#[tokio::test(flavor = "multi_thread")] +async fn without_the_store_each_session_mints_its_own_dep_urls() { + let app = dep_app("dep-urls-no-store", "export const dep = 1;\n"); + let session = || async { + let server = crate::serve(app.dev()).await; + committed_dep_urls(&server, &app).await + }; + let first = session().await; + // A warm restart keeps the manifest's versions, as Vite's does; a cold + // one (the deps cache cleared) has no ledger to vouch for the bytes. + assert_eq!(session().await, first, "a warm restart keeps its versions"); + std::fs::remove_dir_all(oj_cache::cache_root(&app.root).join("deps")).unwrap(); + let second = session().await; + assert_eq!(first.len(), second.len()); + assert_ne!( + first, second, + "a cold session without the store reused a version" + ); + assert!( + !oj_cache::cache_root(&app.root).join("dep-ledger").exists(), + "a ledger was written without the store" + ); +} + // An `import.meta.glob` expansion is a store entry's input too: a file added // under the pattern while no server ran makes the next session's hit a miss // (the glob row re-expands against this checkout), never a stale listing. @@ -790,3 +894,161 @@ async fn an_oj_plugins_file_edit_between_sessions_is_a_miss() { "the entry of the old plugin file was served:\n{second}" ); } + +// Tracing coverage + +/// Dates `rel` a while back: a side input written in the seconds before a +/// compile counts as written under it (the racy mtime window), and the +/// entry is not persisted. The fixtures here are older than that. +fn settle(app: &App, rel: &str) { + std::fs::File::open(app.root.join(rel)) + .unwrap() + .set_modified(std::time::SystemTime::now() - Duration::from_secs(10)) + .unwrap(); +} + +/// A config whose plugin lists a directory during `transform` and bakes the +/// entry count in: a route or icon enumerator's shape. +const LISTING_PLUGIN: &str = r#"import fs from "node:fs"; +const here = new URL(".", import.meta.url).pathname; +export default { + plugins: [{ + name: "icon-count", + transform(code, id) { + if (!id.split("?")[0].endsWith("/src/main.ts")) return null; + const count = fs.readdirSync(here + "icons").length; + return { code: code.replace("__COUNT__", String(count)), map: null }; + }, + }], +}; +"#; + +// A directory the plugin listed is an input of the entry: the listing is +// traced as a directory row, and a file added under it between sessions is +// a miss, so the next session counts it. +#[tokio::test(flavor = "multi_thread")] +async fn a_file_added_under_a_listed_directory_between_sessions_is_a_miss() { + let marker = "listed-dir-store"; + let app = App::new(&[ + ("vite.config.mjs", LISTING_PLUGIN), + ("icons/a.svg", ""), + ( + "index.html", + "", + ), + ( + "src/main.ts", + &format!("export const icons = \"__COUNT__-{marker}\";\n"), + ), + ]); + settle(&app, "icons"); + let session = || async { + let server = crate::serve(dev(&app)).await; + server.text("/src/main.ts").await + }; + let first = session().await; + assert!(first.contains(&format!("\"1-{marker}\"")), "{first}"); + wait_for_entries(marker, 1).await; + app.write(&[("icons/b.svg", "")]); + let second = session().await; + assert!( + second.contains(&format!("\"2-{marker}\"")), + "the entry with the old listing was served:\n{second}" + ); +} + +/// A config whose plugin checks for a side file during `transform` without +/// reading it: the check's answer picks the output. +const FLAG_PLUGIN: &str = r#"import fs from "node:fs"; +const here = new URL(".", import.meta.url).pathname; +export default { + plugins: [{ + name: "flag-check", + transform(code, id) { + if (!id.split("?")[0].endsWith("/src/main.ts")) return null; + const flag = fs.existsSync(here + "flag.txt") ? "a" : "b"; + return { code: code.replace("__FLAG__", flag), map: null }; + }, + }], +}; +"#; + +// An existence check is a file row with the read's meaning: the file the +// plugin looked for and did not find is a digest-less row, and a session +// that finds it is a miss. +#[tokio::test(flavor = "multi_thread")] +async fn a_file_created_after_a_transform_checked_for_it_is_a_miss() { + let marker = "flag-check-store"; + let app = App::new(&[ + ("vite.config.mjs", FLAG_PLUGIN), + ( + "index.html", + "", + ), + ( + "src/main.ts", + &format!("export const flag = \"__FLAG__-{marker}\";\n"), + ), + ]); + let session = || async { + let server = crate::serve(dev(&app)).await; + server.text("/src/main.ts").await + }; + let first = session().await; + assert!(first.contains(&format!("\"b-{marker}\"")), "{first}"); + wait_for_entries(marker, 1).await; + app.write(&[("flag.txt", "")]); + let second = session().await; + assert!( + second.contains(&format!("\"a-{marker}\"")), + "the entry built without the flag was served after it appeared:\n{second}" + ); +} + +/// A config whose plugin reads its side file by a file URL, as a module +/// next to its own source does (`new URL("./x", import.meta.url)`). +const URL_THEME_PLUGIN: &str = r#"import fs from "node:fs"; +export default { + plugins: [{ + name: "url-theme", + transform(code, id) { + if (!id.split("?")[0].endsWith("/src/main.ts")) return null; + const theme = fs.readFileSync(new URL("./theme.txt", import.meta.url), "utf8").trim(); + return { code: code.replace("__THEME__", theme), map: null }; + }, + }], +}; +"#; + +// A read by URL is traced like one by path: the file's edit between +// sessions is a miss. +#[tokio::test(flavor = "multi_thread")] +async fn a_side_file_read_by_url_and_edited_between_sessions_is_a_miss() { + let marker = "url-theme-store"; + let app = App::new(&[ + ("vite.config.mjs", URL_THEME_PLUGIN), + ("theme.txt", "dark\n"), + ( + "index.html", + "", + ), + ( + "src/main.ts", + &format!("export const theme = \"__THEME__-{marker}\";\n"), + ), + ]); + settle(&app, "theme.txt"); + let session = || async { + let server = crate::serve(dev(&app)).await; + server.text("/src/main.ts").await + }; + let first = session().await; + assert!(first.contains(&format!("\"dark-{marker}\"")), "{first}"); + wait_for_entries(marker, 1).await; + app.write(&[("theme.txt", "light\n")]); + let second = session().await; + assert!( + second.contains(&format!("\"light-{marker}\"")), + "the entry built from the old file was served:\n{second}" + ); +} diff --git a/crates/oj_server/tests/optimize_prebundle.rs b/crates/oj_server/tests/optimize_prebundle.rs index 73b0d1457..c2bd0d75c 100644 --- a/crates/oj_server/tests/optimize_prebundle.rs +++ b/crates/oj_server/tests/optimize_prebundle.rs @@ -38,6 +38,7 @@ async fn the_optimizer_plans_commits_and_reruns() { input(), None, &tokio::runtime::Handle::current(), + false, ); // The scan's plan releases compiles first; the dep's own request waits // for the bundle's commit. @@ -70,6 +71,7 @@ async fn the_optimizer_plans_commits_and_reruns() { input(), None, &tokio::runtime::Handle::current(), + false, ) .ready() .await; @@ -105,6 +107,7 @@ async fn the_optimizer_plans_commits_and_reruns() { input(), None, &tokio::runtime::Handle::current(), + false, ); let before = deps.ready().await; assert!(!before.contains_key("latedep"), "not scanned, not bundled"); @@ -184,6 +187,7 @@ async fn the_optimizer_plans_commits_and_reruns() { input(), None, &tokio::runtime::Handle::current(), + false, ); let warm2 = after.ready().await; assert!( @@ -280,6 +284,7 @@ async fn a_failed_initial_run_turns_discovery_off() { input, None, &tokio::runtime::Handle::current(), + false, ); // The plan names the dep first; the failed commit replaces it. let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60); diff --git a/e2e/cross-worktree-cache.mjs b/e2e/cross-worktree-cache.mjs index 9483944e9..7172129cc 100644 --- a/e2e/cross-worktree-cache.mjs +++ b/e2e/cross-worktree-cache.mjs @@ -13,6 +13,7 @@ import os from "node:os"; import path from "node:path"; import assert from "node:assert/strict"; import { fileURLToPath } from "node:url"; +import { rmrf } from "./util.mjs"; const here = path.dirname(fileURLToPath(import.meta.url)); const repo = path.join(here, ".."); @@ -24,9 +25,12 @@ execSync("cargo build -p oj", { cwd: repo, stdio: "inherit" }); // One isolated shared store for this test run. const store = fs.mkdtempSync(path.join(os.tmpdir(), "oj-xwt-store-")); const modulesDir = path.join(store, "v1", "modules"); +// Every temp dir this run makes, removed at exit. +const tempDirs = [store]; function makeApp(label) { const app = fs.mkdtempSync(path.join(os.tmpdir(), `oj-xwt-${label}-`)); + tempDirs.push(app); fs.mkdirSync(path.join(app, "src"), { recursive: true }); fs.writeFileSync(path.join(app, "package.json"), JSON.stringify({ name: "xwt", version: "1.0.0" })); fs.writeFileSync(path.join(app, "package-lock.json"), JSON.stringify({ lockfileVersion: 3 })); @@ -136,9 +140,6 @@ async function serveAndFetch(app, port) { try { proc.kill("SIGKILL"); } catch {} - try { - execSync(`lsof -ti:${port} -sTCP:LISTEN | xargs -r kill -9`); - } catch {} await sleep(500); } } @@ -180,5 +181,6 @@ try { failed = true; console.error(`FAIL: ${err.message}`); } finally { + for (const dir of tempDirs) await rmrf(dir); process.exit(failed ? 1 : 0); } diff --git a/e2e/store-concurrent.mjs b/e2e/store-concurrent.mjs index d981e138f..4df321457 100644 --- a/e2e/store-concurrent.mjs +++ b/e2e/store-concurrent.mjs @@ -13,6 +13,7 @@ import os from "node:os"; import path from "node:path"; import assert from "node:assert/strict"; import { fileURLToPath } from "node:url"; +import { rmrf } from "./util.mjs"; const here = path.dirname(fileURLToPath(import.meta.url)); const repo = path.join(here, ".."); @@ -23,10 +24,13 @@ execSync("cargo build -p oj", { cwd: repo, stdio: "inherit" }); const store = fs.mkdtempSync(path.join(os.tmpdir(), "oj-concurrent-store-")); const modulesDir = path.join(store, "v1", "modules"); +// Every temp dir this run makes, removed at exit. +const tempDirs = [store]; const MODULES = 24; function makeApp(label) { const app = fs.mkdtempSync(path.join(os.tmpdir(), `oj-concurrent-${label}-`)); + tempDirs.push(app); fs.mkdirSync(path.join(app, "src"), { recursive: true }); fs.writeFileSync(path.join(app, "package.json"), JSON.stringify({ name: "concurrent", version: "1.0.0" })); fs.writeFileSync(path.join(app, "package-lock.json"), JSON.stringify({ lockfileVersion: 3 })); @@ -43,7 +47,10 @@ function makeApp(label) { imports.push(`import { m${i} } from "./m${i}";`); } fs.writeFileSync(path.join(app, "src", "base.ts"), `export const base: string = "base";\n`); - fs.writeFileSync(path.join(app, "src", "main.ts"), `${imports.join("\n")}\nconsole.log(${Array.from({ length: MODULES }, (_, i) => `m${i}`).join(", ")});\n`); + fs.writeFileSync( + path.join(app, "src", "main.ts"), + `${imports.join("\n")}\nconsole.log(${Array.from({ length: MODULES }, (_, i) => `m${i}`).join(", ")});\n`, + ); return app; } @@ -89,9 +96,6 @@ function kill(server) { try { server.proc.kill("SIGKILL"); } catch {} - try { - execSync(`lsof -ti:${server.port} -sTCP:LISTEN | xargs -r kill -9`); - } catch {} } function storeEntries() { @@ -165,5 +169,6 @@ try { } finally { for (const s of servers) kill(s); await sleep(300); + for (const dir of tempDirs) await rmrf(dir); process.exit(failed ? 1 : 0); } diff --git a/e2e/store-flag.mjs b/e2e/store-flag.mjs index 4b921576f..d4db6bbdb 100644 --- a/e2e/store-flag.mjs +++ b/e2e/store-flag.mjs @@ -13,6 +13,7 @@ import os from "node:os"; import path from "node:path"; import assert from "node:assert/strict"; import { fileURLToPath } from "node:url"; +import { rmrf } from "./util.mjs"; const here = path.dirname(fileURLToPath(import.meta.url)); const repo = path.join(here, ".."); @@ -54,6 +55,24 @@ function entriesUnder(root) { return n; } const storeEntries = () => entriesUnder(path.join(store, "v1", "modules")); +// Every file under a dir: the store's bundles, codegen and bytecode included. +function filesUnder(root) { + let n = 0; + const walk = (dir) => { + let ents; + try { + ents = fs.readdirSync(dir, { withFileTypes: true }); + } catch { + return; + } + for (const e of ents) { + if (e.isDirectory()) walk(path.join(dir, e.name)); + else n++; + } + }; + walk(root); + return n; +} const appEntries = () => entriesUnder(path.join(app, ".oj-cache")); async function runAndCount(args, runEnv = env) { @@ -84,9 +103,6 @@ async function runAndCount(args, runEnv = env) { try { proc.kill("SIGKILL"); } catch {} - try { - execSync(`lsof -ti:${port} -sTCP:LISTEN | xargs -r kill -9`); - } catch {} await sleep(500); } } @@ -97,20 +113,23 @@ try { assert.ok(withStore.store > 0, `--store=DIR must persist module entries into DIR (got ${withStore.store})`); assert.equal(withStore.app, 0, `relocatable entries belong to the store, not the app (got ${withStore.app})`); - // Without the flag the store is off, even with OJ_STORE_DIR pointing at one. + // Without the flag the store is off, even with OJ_STORE_DIR pointing at one: + // no module entry, and nothing else under the store either (the inherited + // variable is cleared for the server and its children). const without = await runAndCount([], { ...env, OJ_STORE_DIR: store }); assert.equal( without.store + without.app, 0, `without --store nothing persists (got ${without.store + without.app} entries)`, ); + assert.equal(filesUnder(store), 0, "without --store nothing lands under the store dir"); - console.log( - `PASS store-flag (--store wrote ${withStore.store} entries to the store, 0 to the app; without it 0)`, - ); + console.log(`PASS store-flag (--store wrote ${withStore.store} entries to the store, 0 to the app; without it 0)`); } catch (err) { failed = true; console.error(`FAIL store-flag: ${err.message}`); } finally { + await rmrf(app); + await rmrf(store); process.exit(failed ? 1 : 0); } diff --git a/e2e/store-remote.mjs b/e2e/store-remote.mjs index 00ac04312..20a2a6c42 100644 --- a/e2e/store-remote.mjs +++ b/e2e/store-remote.mjs @@ -7,7 +7,9 @@ // pushes; worktree B, with an EMPTY local store at a different absolute // path, serves A's exact bytes via the remote and back-fills its local // store — plus the protocol's contract: write-once (409), token gating -// (401), and CAS self-verification (422 on digest mismatch). +// (401), the server's admission gate (422 for a body no client could admit), +// an operator purge (DELETE under the write token), and CAS +// self-verification (422 on digest mismatch). import { spawn, execSync } from "node:child_process"; import fs from "node:fs"; @@ -15,10 +17,11 @@ import os from "node:os"; import path from "node:path"; import assert from "node:assert/strict"; import { fileURLToPath } from "node:url"; +import { rmrf } from "./util.mjs"; const here = path.dirname(fileURLToPath(import.meta.url)); const repo = path.join(here, ".."); -const oj = path.join(repo, "target", "debug", "oj"); +const oj = path.join(process.env.CARGO_TARGET_DIR || path.join(repo, "target"), "debug", "oj"); const SRV_PORT = 5398; const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); @@ -26,9 +29,12 @@ execSync("cargo build -p oj", { cwd: repo, stdio: "inherit" }); const WRITE_TOKEN = "e2e-write-secret"; const srvDir = fs.mkdtempSync(path.join(os.tmpdir(), "oj-remote-srv-")); +// Every temp dir this run makes, removed at exit. +const tempDirs = [srvDir]; function makeApp(label) { const app = fs.mkdtempSync(path.join(os.tmpdir(), `oj-remote-${label}-`)); + tempDirs.push(app); fs.writeFileSync(path.join(app, "package.json"), JSON.stringify({ name: "rw", version: "1.0.0" })); fs.writeFileSync(path.join(app, "package-lock.json"), JSON.stringify({ lockfileVersion: 3 })); fs.writeFileSync( @@ -85,9 +91,6 @@ async function devAndFetch(app, store, port, extraEnv) { try { proc.kill("SIGKILL"); } catch {} - try { - execSync(`lsof -ti:${port} -sTCP:LISTEN | xargs -r kill -9`); - } catch {} await sleep(400); } } @@ -117,24 +120,45 @@ try { // ---- protocol contract ---- const hex = (s) => s.padEnd(64, "0"); - // AC: write without token refused; write-once; read back. + // AC: write without token refused; a body no client could admit refused; + // write-once; read back; purge under the write token frees the key. const key = hex("ab"); - let r = await fetch(`${base}/v1/ac/modules/${key}`, { method: "PUT", body: "{}" }); + const entry = (code, extra = {}) => + JSON.stringify({ code, map_json: null, imports: [], is_boundary: false, ...extra }); + const probe1 = entry("export const probe = 1;"); + const authed = { authorization: `Bearer ${WRITE_TOKEN}` }; + let r = await fetch(`${base}/v1/ac/modules/${key}`, { method: "PUT", body: probe1 }); assert.equal(r.status, 401, "AC PUT without token must be refused"); r = await fetch(`${base}/v1/ac/modules/${key}`, { method: "PUT", - headers: { authorization: `Bearer ${WRITE_TOKEN}` }, + headers: authed, body: JSON.stringify({ probe: 1 }), }); + assert.equal(r.status, 422, "an AC body must be a CachedModule"); + r = await fetch(`${base}/v1/ac/modules/${key}`, { + method: "PUT", + headers: authed, + body: entry("export {};", { imports: ["/@fs//other/checkout/x.js"] }), + }); + assert.equal(r.status, 422, "an entry that pins a checkout is refused by the server"); + r = await fetch(`${base}/v1/ac/modules/${key}`, { method: "PUT", headers: authed, body: probe1 }); assert.equal(r.status, 201, "first AC PUT publishes"); r = await fetch(`${base}/v1/ac/modules/${key}`, { method: "PUT", - headers: { authorization: `Bearer ${WRITE_TOKEN}` }, - body: JSON.stringify({ probe: 2 }), + headers: authed, + body: entry("export const probe = 2;"), }); assert.equal(r.status, 409, "AC entries are write-once"); r = await fetch(`${base}/v1/ac/modules/${key}`); - assert.deepEqual(await r.json(), { probe: 1 }, "the first write is what reads back"); + assert.deepEqual(await r.json(), JSON.parse(probe1), "the first write is what reads back"); + r = await fetch(`${base}/v1/ac/modules/${key}`, { method: "DELETE" }); + assert.equal(r.status, 401, "a purge takes the write token"); + r = await fetch(`${base}/v1/ac/modules/${key}`, { method: "DELETE", headers: authed }); + assert.equal(r.status, 204, "an operator purges a key"); + r = await fetch(`${base}/v1/ac/modules/${key}`); + assert.equal(r.status, 404, "a purged key is gone"); + r = await fetch(`${base}/v1/ac/modules/${key}`, { method: "PUT", headers: authed, body: probe1 }); + assert.equal(r.status, 201, "and free to take again"); // CAS: digest mismatch refused; publish + HEAD + missing. const blob = "hello store"; @@ -166,6 +190,7 @@ try { const appB = makeApp("b"); const storeA = fs.mkdtempSync(path.join(os.tmpdir(), "oj-remote-storeA-")); const storeB = fs.mkdtempSync(path.join(os.tmpdir(), "oj-remote-storeB-")); + tempDirs.push(storeA, storeB); const bodyA = await devAndFetch(appA, storeA, 5396, { OJ_STORE_REMOTE: base, @@ -184,7 +209,7 @@ try { assert.ok(countEntries(path.join(storeB, "v1", "modules")) > 0, "the read-through must back-fill B's local store"); console.log( - `PASS store-remote (write-once 409, tokens 401, CAS 422, A pushed ${pushed} entries, B served A's bytes from the wire and back-filled locally)`, + `PASS store-remote (write-once 409, tokens 401, admission 422, purge 204, CAS 422, A pushed ${pushed} entries, B served A's bytes from the wire and back-filled locally)`, ); } catch (err) { failed = true; @@ -196,8 +221,6 @@ try { try { srv.kill("SIGKILL"); } catch {} - try { - execSync(`lsof -ti:${SRV_PORT} -sTCP:LISTEN | xargs -r kill -9`); - } catch {} + for (const dir of tempDirs) await rmrf(dir); process.exit(failed ? 1 : 0); } diff --git a/e2e/trace-staleness.mjs b/e2e/trace-staleness.mjs index 80fd5b846..5b189e49b 100644 --- a/e2e/trace-staleness.mjs +++ b/e2e/trace-staleness.mjs @@ -14,6 +14,7 @@ import os from "node:os"; import path from "node:path"; import assert from "node:assert/strict"; import { fileURLToPath } from "node:url"; +import { rmrf } from "./util.mjs"; const here = path.dirname(fileURLToPath(import.meta.url)); const repo = path.join(here, ".."); @@ -40,6 +41,11 @@ fs.writeFileSync(path.join(app, "named.txt"), "n1"); fs.mkdirSync(path.join(app, "globbed")); fs.writeFileSync(path.join(app, "globbed", "a.ts"), "export const a = 1;\n"); fs.writeFileSync(path.join(app, "glob.tsx"), `export const mods = import.meta.glob("./globbed/*.ts");\n`); +// A third module whose plugin output comes from a directory listing and an +// existence check, neither of which reads a byte. +fs.mkdirSync(path.join(app, "icons")); +fs.writeFileSync(path.join(app, "icons", "a.svg"), ""); +fs.writeFileSync(path.join(app, "dir.tsx"), `export const shape: string = "__ICONS__/__FLAG__";\n`); // A plugin that reads TWO side files the cache key knows nothing about: // extra.txt through the default node:fs import (the JS-level patched module // object sees it) and named.txt through a NAMED esm import (invisible to the @@ -58,6 +64,15 @@ export default [ return { code: code.replace("__EXTRA__", extra).replace("__NAMED__", named), map: null }; }, }, + { + name: "listing-and-check", + transform(code, id) { + if (!id.split("?")[0].endsWith("dir.tsx")) return null; + const icons = fsmod.readdirSync(${JSON.stringify(path.join(app, "icons"))}).length; + const flag = fsmod.existsSync(${JSON.stringify(path.join(app, "flag.txt"))}) ? "flag" : "noflag"; + return { code: code.replace("__ICONS__", String(icons)).replace("__FLAG__", flag), map: null }; + }, + }, ]; `, ); @@ -90,9 +105,6 @@ async function bootAndFetch(extraEnv = {}, url = "/main.tsx") { try { proc.kill("SIGKILL"); } catch {} - try { - execSync(`lsof -ti:${port} -sTCP:LISTEN | xargs -r kill -9`); - } catch {} await sleep(500); } } @@ -152,12 +164,33 @@ try { `deleted file under the glob must drop out on a warm boot: ${glob3.slice(0, 300)}`, ); + // Directory rows and existence checks: a plugin that lists a directory or + // checks for a file reads no bytes, and still bakes the answer in. + const dir1 = await bootAndFetch({}, "/dir.tsx"); + assert.ok(dir1.includes("1/noflag"), `cold boot counts one icon and no flag: ${dir1.slice(0, 200)}`); + const dirWarm = await bootAndFetch({}, "/dir.tsx"); + assert.ok(dirWarm.includes("1/noflag"), "unchanged listing and absence still serve"); + fs.writeFileSync(path.join(app, "icons", "b.svg"), ""); + const dir2 = await bootAndFetch({}, "/dir.tsx"); + assert.ok( + dir2.includes("2/noflag"), + `a file added under a listed directory must re-transform on a warm boot: ${dir2.slice(0, 200)}`, + ); + fs.writeFileSync(path.join(app, "flag.txt"), ""); + const dir3 = await bootAndFetch({}, "/dir.tsx"); + assert.ok( + dir3.includes("2/flag"), + `a file created after a transform checked for it must re-transform on a warm boot: ${dir3.slice(0, 200)}`, + ); + console.log( - "PASS trace-staleness (warm hit, default-import edit re-transforms, NAMED-import edit re-transforms via TracingFs, no stale serve on delete, verifier clean on pure hits, glob add+delete re-expand)", + "PASS trace-staleness (warm hit, default-import edit re-transforms, NAMED-import edit re-transforms via TracingFs, no stale serve on delete, verifier clean on pure hits, glob add+delete re-expand, listed dir add and existence check re-transform)", ); } catch (err) { failed = true; console.error(`FAIL trace-staleness: ${err.message}`); } finally { + await rmrf(app); + await rmrf(store); process.exit(failed ? 1 : 0); } diff --git a/e2e/unit/plugin-host-read-trace.test.mjs b/e2e/unit/plugin-host-read-trace.test.mjs new file mode 100644 index 000000000..474ff7193 --- /dev/null +++ b/e2e/unit/plugin-host-read-trace.test.mjs @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: MIT +// Copyright (c) 2026 Raphael Amorim + +// The plugin host's read trace (pulp P2): what a transform hook looks at +// through node:fs comes back with the reply, files under `readFiles` and +// directory listings under `readDirs`, so the server can digest each into the +// cached entry. A check (existsSync, statSync, openSync) is a file row like a +// read: its answer is an input of the output. Paths come back absolute, a +// relative one resolved against the host's cwd; URL and Buffer paths are +// taken as node:fs takes them. (A NAMED esm import of node:fs or +// node:fs/promises binds past the patched module object; under oj the Rust +// TracingFs layer covers those.) +import { test } from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { rpcSidecar, tmpProject } from "./harness.mjs"; + +test("plugin-host reports the files a transform read or checked and the directories it listed", async () => { + const fx = tmpProject({ prefix: "oj-rt-" }); + fx.write("icons/a.svg", ""); + fx.write("theme.txt", "dark"); + fx.write("src/entry.js", "export const x = 1;\n"); + const entry = path.join(fx.root, "src/entry.js"); + fx.write( + "oj.plugins.mjs", + `import fs from "node:fs"; + export default [{ + name: "looks-around", + async transform(code, id) { + if (!id.endsWith("entry.js")) return null; + const icons = fs.readdirSync(new URL("./icons/", import.meta.url)); + await fs.promises.readdir(${JSON.stringify(path.join(fx.root, "src"))}); + const flag = fs.existsSync("flag.txt") ? "a" : "b"; + fs.statSync(Buffer.from(${JSON.stringify(path.join(fx.root, "package.json"))})); + const fd = fs.openSync(${JSON.stringify(path.join(fx.root, "theme.txt"))}, "r"); + const theme = fs.readFileSync(fd, "utf8"); + fs.closeSync(fd); + // A write-only open makes bytes rather than reading them. + const log = fs.openSync("transforms.log", "a"); + fs.closeSync(log); + return { code: code + "// " + icons.length + flag + theme, map: null }; + }, + }];\n`, + ); + const host = rpcSidecar("plugin-host.mjs", { + args: [path.join(fx.root, "oj.plugins.mjs"), JSON.stringify({ root: fx.root })], + env: { OJ_CACHE_ROOT: fx.root }, + cwd: fx.root, + }); + try { + const res = await host.send({ id: 1, hook: "transform", args: ["export const x = 1;\n", entry] }); + assert.equal(res.error, undefined, `transform must not error: ${res.error}`); + const out = JSON.parse(res.result); + assert.ok(out.code.endsWith("// 1bdark"), out.code); + const real = (p) => fs.realpathSync(path.join(fx.root, p)); + const dirs = out.readDirs.map((p) => fs.realpathSync(p)); + assert.deepEqual(dirs.sort(), [real("icons"), real("src")].sort(), "a URL and a promises listing"); + const files = out.readFiles; + const expected = { + "existsSync, relative, resolved against the cwd": path.join(fx.root, "flag.txt"), + "statSync with a Buffer path": path.join(fx.root, "package.json"), + "openSync for reading": path.join(fx.root, "theme.txt"), + }; + for (const [what, p] of Object.entries(expected)) assert.ok(files.includes(p), `${what}: ${p} in ${files}`); + assert.ok(!files.includes(path.join(fx.root, "transforms.log")), `a write-only open is not an input: ${files}`); + for (const p of [...files, ...out.readDirs]) assert.ok(path.isAbsolute(p), `absolute: ${p}`); + } finally { + host.close(); + fx.cleanup(); + } +}); From bf3ecfce7f89ad4702d5f471a73abb6831011445 Mon Sep 17 00:00:00 2001 From: Raphael Amorim Date: Fri, 4 Dec 2026 07:35:28 +0000 Subject: [PATCH 3/3] oj store: dependency versions from the inputs, a host-exact trace, the build id everywhere it keys The dependency ledger's epoch, a nonce minted per store, reached every module key through the dependency URL version, so two stores never shared a module entry and a substituter could never answer for one. With a ledger a version now comes from the pre-bundle hash and the dependency names alone, as Vite's committed browserHash, so two stores that bundle one plan mint one URL from the first boot on. The ledger still records what each URL served, and other bytes under a recorded URL re-mint a version from the bytes and reload. A first attempt derived every version from the bundled bytes; that left a cold boot's compiles under a version no later session computed. The trace is the host's own per-hook account, plus what the engine's shared window saw that no hook in flight read through the host: each reply lists the reads it made through the patched node:fs, and those leave its window share. A file-reading plugin no longer cross-charges its reads to every module compiled while it ran. An entry over 256 rows stays in memory. Sass @use and CSS @import searches record the candidates they missed, so a partial or sheet added later that shadows the hit is a miss; PostCSS plugin reads are traced through the CSS engine's own window and a declared dir-dependency stays a directory row. A stamp within 20 ms before the compile's start counts as racy. A module hard-invalidated by an edit this session compiles under a key with the invalidation counter and is not persisted. The tool build id reaches Start bundles, codegen, the ledger and the pre-seed stamp, and covers the embedded assets and the bundler fork; packages linked above the app are in the salt; build, preview, lint and typecheck clear an inherited OJ_STORE_DIR. The substituter probe is a lease that clears itself when its request is dropped and expires after the fetch timeout; at most 16 fetches are in flight. The wire sweeps a crashed PUT's temp files, caps the missing query at 4,096 digests, and every temp file is exclusive. Start bundle pins name the boot and the process, age out after an hour, are refreshed every ten minutes and ignored once the process is gone. --- CHANGELOG.md | 4 + README.md | 6 +- crates/oj/src/main.rs | 31 +- crates/oj/src/start_dev.rs | 23 +- crates/oj_cache/src/integrity.rs | 4 +- crates/oj_cache/src/start_bundle/mod.rs | 167 ++++++++--- crates/oj_cache/src/start_bundle/tests.rs | 191 +++++++++++++ crates/oj_cache/src/start_codegen.rs | 24 +- crates/oj_css/src/imports.rs | 222 +++++++++++++-- crates/oj_css/src/lib.rs | 11 +- crates/oj_css/src/resolve.rs | 26 +- crates/oj_css/src/sass.rs | 105 ++++++- crates/oj_server/build.rs | 9 +- crates/oj_server/src/assets/plugin-host.mjs | 57 +++- crates/oj_server/src/css_engine.rs | 118 +++++++- crates/oj_server/src/css_serve.rs | 102 ++++++- crates/oj_server/src/lib.rs | 40 +-- crates/oj_server/src/module_pipeline.rs | 216 ++++++++++---- crates/oj_server/src/optimize.rs | 172 ++++++++---- crates/oj_server/src/plugins/host.rs | 109 ++++++- crates/oj_server/src/preseed.rs | 2 +- crates/oj_server/src/store_remote.rs | 255 +++++++++++++++-- crates/oj_server/src/store_server.rs | 180 +++++++++++- crates/oj_server/src/tests.rs | 41 +++ crates/oj_server/tests/dev/store.rs | 296 ++++++++++++++++++++ e2e/unit/plugin-host-read-trace.test.mjs | 3 + 26 files changed, 2152 insertions(+), 262 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4643204cb..e1aad3f06 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - A warm hit verifies more: a stylesheet's `@import`ed files, Sass partials and PostCSS dependencies are trace rows (an edit to an imported file between sessions served the sheet with the old file inlined); the directories a plugin listed (`readdir`, `opendir`) are rows digesting their names; existence checks (`exists`, `stat`, `access`, `realpath`, a read-only `open`), reads by file `URL` or `Buffer` path and reads through a descriptor are rows; relative paths are recorded against the process's directory; an entry whose `/@fs/@mono/` import names no file in the reading server's workspace is a miss. A side file stamped in a whole second within two seconds before its compile started counts as written during it (a filesystem that keeps whole seconds may stamp a later write below the compile's start); a stamp with nanoseconds compares exactly, so a fresh checkout persists from its first boot. - The shared store directory is a trust boundary: it is created with mode 0700, and an existing one owned by another user or writable by group or others is refused (one line on stderr, the server keeps its own cache). Temp files are created exclusively with a random suffix, so a symlink planted at a predictable name is never followed. The modules directory is kept under 2 GiB (oldest entries first, once per boot, off the boot path; an entry served is touched when its stamp is older than six hours) and temp files of killed processes are swept after an hour. The plugin host's bytecode directory has a 1 GiB budget when it is the store's, in place of the per-app 128 MiB that had every app's boot evict the others, and its directory name carries a digest of the V8 flags. A Start bundle pin names the process as well as the root, so two sandboxes running the app at the same path over one store protect their own generations, and the generation window is counted per app and config. - `oj store serve` defaults to the user's store directory (`--dir` for another; it no longer creates `oj-store/` under the current directory), keeps a byte quota (`--max-bytes`, 10 GiB by default, 507 past it, counted on boot), stores only entries it could serve (relocatable module JSON, else 422), purges a key or blob on `DELETE` under the write token, compares tokens in constant time, and streams bodies off the runtime's workers. A dev server's read-through counts an answer slower than 500 ms as a failure, trips after three, and after 30 s lets one probe decide; its pushes are queued (256 entries or 64 MiB, a full queue drops and says so once), stop while the breaker is open, and never fetch a body past 16 MiB. Stamped keys (this session's HMR state) are never asked of a substituter. +- With the store, dependency URL versions come from the inputs alone (the pre-bundle hash and the dependency names, as Vite's committed browserHash), not from a per-store epoch: two stores, two machines, a fresh sandbox and a substituter that bundled one plan mint the same `/@oj-deps/...?v=` URLs, so the modules compiled against them are one entry everywhere (under an epoch no two stores ever shared a module key), from a checkout's first boot on. The ledger still records what each URL served, and other bytes under a recorded URL re-mint a version from the bytes and reload, as before. +- A plugin's trace is the host's own account of what the hook read (exact, per hook) plus whatever the engine's shared window saw that no hook in flight read through the host (a named `node:fs` import bound before the patch). A module beside a plugin that scans a thousand files is no longer charged those files, and an entry with more than 256 rows stays in memory. The racy-mtime rule also counts a stamp within 20 ms before the compile's start (the kernel stamps files from a coarser clock than the one the compile read). A module hard-invalidated by an edit this session is not persisted: its key carries the process's invalidation counter, which no other session computes. The tool build id reaches every shared artifact (Start bundles, codegen, the dependency ledger and the pre-seed stamp), and covers embedded assets and the bundler fork. Packages linked into the workspace's `node_modules` above the app are salted like the app's own. `oj build`, `preview`, `lint` and `typecheck` clear an inherited `OJ_STORE_DIR` as a flagless `oj dev` does; the commands a server spawns keep it. +- A stylesheet's `@import` and a Sass `@use` record the paths they looked for and did not find ahead of the file they resolved to (a partial or sheet added there later shadows the hit and is a miss), the files a PostCSS plugin reads on its own are traced through the CSS engine's own read window, and a declared `dir-dependency` is a listing row per directory walked, so a file added under it is a miss. +- A substituter probe that the browser's navigation cut short (hyper drops the handler) no longer leaves the breaker open for the session: the probe is a lease that clears itself when dropped and expires after the fetch timeout; at most 16 fetches are in flight at once, and a tripped breaker answers waiters at once. The wire sweeps the temp files of crashed PUTs after an hour before counting its quota, caps `POST /v1/cas/missing` at 4,096 digests (400 past it), and writes every temp file exclusively with a random suffix, as the dependency ledger and the Start bundle and codegen touch files do now. A Start bundle pin names the boot and the process as well as the root, ages out after an hour instead of seven days, is refreshed every ten minutes by a running server and ignored once its process is gone (same boot, no `/proc/`), and the pins directory is read once per persist. ### Fixed diff --git a/README.md b/README.md index 56507165a..2bf2991b6 100644 --- a/README.md +++ b/README.md @@ -134,14 +134,14 @@ OJ_STORE_REMOTE=http://host:5399 oj dev --store # read through to it; OJ_STORE_ How it works: - `--store` is the one switch: it sets `OJ_STORE_DIR` for the server and every child process, and `oj dev` without it clears an inherited `OJ_STORE_DIR` for itself and its children. A plain `oj dev` writes nothing outside the app, computes no store keys and traces no plugin reads. -- A key covers the tool build (version plus a digest of its sources), the dependency epoch (lockfiles, patch files by content, package.json), the config graph, every tsconfig at the root, the PostCSS config and browserslist, the resolver settings, the root's place in its workspace, and the manifests and entry files of packages linked into `node_modules` from outside it (a workspace plugin). A stylesheet's `@import`ed files are verified like a plugin's side reads. +- A key covers the tool build (version plus a digest of its sources), the dependency epoch (lockfiles, patch files by content, package.json), the config graph, every tsconfig at the root, the PostCSS config and browserslist, the resolver settings, the root's place in its workspace, and the manifests and entry files of packages linked into `node_modules` from outside it (a workspace plugin). A stylesheet's `@import`ed files, the paths an import was looked for at first, and what its PostCSS plugins read or list are verified like a plugin's side reads. - An entry is named by content, never by path: the module's source and every input that shapes its output (the compile mode and import stamps, the lockfiles, every `tsconfig*.json`, the config file and the files it imports, the PostCSS config, the env it inlines) hashed under a worktree-independent key. Paths inside an artifact are root-relative (`/src/App.tsx`) or workspace-relative (`/@fs/@mono/`), so two checkouts compute the same name and serve the same bytes, sourcemaps included. An artifact that still names a checkout (an import from outside the workspace) stays in that app's own cache. - A warm hit is verified before it is served: the side files a plugin read while transforming (recorded through `node:fs` and the engine's file system) and the files an `import.meta.glob` expanded to are digested again, and a mismatch, a file that appeared or one that moved is a miss, never a stale serve. Plugins that collect state from every transform (UnoCSS's shape) keep app modules out of the store for the session. - It holds the compiled module cache, the V8 bytecode cache of the plugin host, the TanStack Start client bundle (a cold worktree restores the generation its sources hash to) and the dependency URL ledger, so two checkouts bundling the same dependency bytes mint the same `/@oj-deps/...?v=` URLs. - Writes are atomic and write-once: two servers on one store, or two pushers of one key, leave one whole entry and never a torn one. Temp files are created exclusively (never through a planted symlink). A store that cannot be written costs sharing, not correctness. A corrupt or foreign entry is dropped on read. - The store directory is a trust boundary: it is created with mode 0700, and one owned by another user or writable by group or others is refused with one line on stderr (the server runs with its own cache instead). Entries are not signed; whoever can write the directory, or holds the wire's write token, decides what every reader serves. -- It is a cache with a budget: the modules directory is kept under 2 GiB (oldest entries first, once per boot, off the boot path) and temp files of killed processes are swept after an hour; the plugin host's bytecode directory has a 1 GiB budget when shared; the Start bundle store keeps a window of generations per app and config, protected by per-process pins. -- `oj store serve` publishes a store over HTTP with read and write bearer tokens (`OJ_STORE_READ_TOKEN`, `OJ_STORE_WRITE_TOKEN`; a dev server sends `OJ_STORE_TOKEN`), under a byte quota (`--max-bytes`, 10 GiB by default; a write past it is a 507). It stores only entries it could serve (relocatable module JSON; anything else is a 422), and `DELETE` under the write token purges a key. A dev server asks it only on a local miss of an unstamped key, with a 2 s connect and 5 s fetch timeout; an answer slower than 500 ms counts as a failure, three in a row stop the asking, and after 30 s one probe decides whether to resume. Pushes are queued (256 entries or 64 MiB; a full queue drops) and carry the module's source map with `sourcesContent`, so push only to a substituter as private as the checkout. +- It is a cache with a budget: the modules directory is kept under 2 GiB (oldest entries first, once per boot, off the boot path) and temp files of killed processes are swept after an hour; the plugin host's bytecode directory has a 1 GiB budget when shared; the Start bundle store keeps a window of generations per app and config, protected by per-process pins that a running server refreshes every ten minutes and that lapse an hour after the process is gone. +- `oj store serve` publishes a store over HTTP with read and write bearer tokens (`OJ_STORE_READ_TOKEN`, `OJ_STORE_WRITE_TOKEN`; a dev server sends `OJ_STORE_TOKEN`), under a byte quota (`--max-bytes`, 10 GiB by default; a write past it is a 507). It stores only entries it could serve (relocatable module JSON; anything else is a 422), and `DELETE` under the write token purges a key. A dev server asks it only on a local miss of an unstamped key, at most 16 requests at a time, with a 2 s connect and 5 s fetch timeout; an answer slower than 500 ms counts as a failure, three in a row stop the asking, and after 30 s one probe decides whether to resume. With the store, a dependency bundle's committed URL version is derived from its bytes, so two machines that bundled the same bytes mint the same URLs and share the modules compiled against them. Pushes are queued (256 entries or 64 MiB; a full queue drops) and carry the module's source map with `sourcesContent`, so push only to a substituter as private as the checkout. ## Quickstart diff --git a/crates/oj/src/main.rs b/crates/oj/src/main.rs index d7fff5204..062befe37 100644 --- a/crates/oj/src/main.rs +++ b/crates/oj/src/main.rs @@ -527,6 +527,20 @@ fn sniffed_manager_version(path: &std::path::Path, manager: &str, default_versio /// The store `--store` turns on: its DIR when given, else the `OJ_STORE_DIR` /// already in the environment (a CI job, a test harness pointing every oj at /// one store), else the user's cache dir. +/// The commands a user runs that have no `--store`: a dev server without +/// the flag and the one-shot commands (`oj store serve` keeps its own dir). The commands a server spawns for +/// itself (engine jobs, scripts, the type checker) inherit its choice. +fn clears_store_dir(command: &Command) -> bool { + matches!( + command, + Command::Dev { store: None, .. } + | Command::Build { .. } + | Command::Preview { .. } + | Command::Lint { .. } + | Command::Typecheck { .. } + ) +} + fn store_dir_for( flag: Option<&std::path::Path>, env: Option, @@ -652,7 +666,8 @@ fn main() -> anyhow::Result<()> { // Without the flag the store is off, wherever `OJ_STORE_DIR` points: the // variable is cleared for this process and its children (the engine, // the plugin host, the builders), so nothing of theirs is shared either. - if let Command::Dev { store: None, .. } = &cli.command { + // The commands a server spawns keep what it exported. + if clears_store_dir(&cli.command) { std::env::remove_var("OJ_STORE_DIR"); } if let Command::Dev { @@ -1078,6 +1093,20 @@ mod store_flag_tests { } } + #[test] + fn user_commands_without_the_flag_clear_the_store_dir_and_children_keep_it() { + let parse = |args: &[&str]| Cli::try_parse_from(args).expect("parse").command; + assert!(clears_store_dir(&parse(&["oj", "dev", "app"]))); + assert!(!clears_store_dir(&parse(&["oj", "dev", "--store", "app"]))); + assert!(clears_store_dir(&parse(&["oj", "build", "app"]))); + assert!(!clears_store_dir(&parse(&["oj", "store", "serve"]))); + assert!(!clears_store_dir(&parse(&[ + "oj", + "typecheck-worker", + "app" + ]))); + } + #[test] fn bare_store_enables_without_eating_the_root() { let (store, root) = parse_dev(&["oj", "dev", "--store", "app"]); diff --git a/crates/oj/src/start_dev.rs b/crates/oj/src/start_dev.rs index e4ab33f33..3c9d790e5 100644 --- a/crates/oj/src/start_dev.rs +++ b/crates/oj/src/start_dev.rs @@ -933,6 +933,25 @@ pub async fn start_dev( .prune(oj_cache::start_bundle::DEFAULT_PRUNE_BUDGET_BYTES); }); } + // The pin that keeps this server's generation (and its blobs) from + // eviction ages out after an hour unless refreshed: a long-lived server + // re-stamps it on a timer, and a dead one stops protecting within the + // hour. + { + let (root, mode) = (root.clone(), mode.clone()); + tokio::spawn(async move { + let mut every = tokio::time::interval(oj_cache::start_bundle::PIN_REFRESH_EVERY); + every.tick().await; + loop { + every.tick().await; + let (root, mode) = (root.clone(), mode.clone()); + let _ = tokio::task::spawn_blocking(move || { + start_bundle_store(&root, &mode).refresh_pin() + }) + .await; + } + }); + } // This server's routes run inside the dev server's cors and host gates, // as Vite's corsMiddleware and hostValidationMiddleware come before every @@ -3033,7 +3052,7 @@ fn codegen_store( oj_cache::start_codegen::StartCodegenStore::new( root, kind, - env!("CARGO_PKG_VERSION"), + oj_server::tool_version(), &extra, marker, ) @@ -3948,7 +3967,7 @@ fn hot_styles_added(cache: &Path) -> Vec { fn start_bundle_store(root: &Path, mode: &str) -> oj_cache::start_bundle::StartBundleStore { oj_cache::start_bundle::StartBundleStore::for_mode( root, - env!("CARGO_PKG_VERSION"), + oj_server::tool_version(), oj_cache::integrity::VerifyMode::Standard, mode, ) diff --git a/crates/oj_cache/src/integrity.rs b/crates/oj_cache/src/integrity.rs index d8335535c..736ce9e93 100644 --- a/crates/oj_cache/src/integrity.rs +++ b/crates/oj_cache/src/integrity.rs @@ -88,7 +88,7 @@ pub(crate) fn write_via_tmp(tmp: &Path, path: &Path, bytes: &[u8]) -> io::Result /// something else planted there first (a symlink into another directory, /// in a shared store) is refused instead of followed, which plain /// `fs::write` would do. -pub(crate) fn write_new(tmp: &Path, bytes: &[u8]) -> io::Result<()> { +pub fn write_new(tmp: &Path, bytes: &[u8]) -> io::Result<()> { let mut file = open_new(tmp)?; file.write_all(bytes) } @@ -102,7 +102,7 @@ pub(crate) fn open_new(tmp: &Path) -> io::Result { /// part. The counter keeps threads of one process apart, the random part /// keeps the name from being predicted (and so pre-planted) by anything /// else that can write the directory. -pub(crate) fn temp_tag() -> String { +pub fn temp_tag() -> String { static SEQ: AtomicU64 = AtomicU64::new(0); let seq = SEQ.fetch_add(1, Ordering::Relaxed); format!("{}-{seq}-{}", std::process::id(), random_tag()) diff --git a/crates/oj_cache/src/start_bundle/mod.rs b/crates/oj_cache/src/start_bundle/mod.rs index e1d86f4d1..adf0b0bff 100644 --- a/crates/oj_cache/src/start_bundle/mod.rs +++ b/crates/oj_cache/src/start_bundle/mod.rs @@ -8,8 +8,9 @@ //! Generations and blobs live in the shared oj store when there is one, so //! worktree B restores the bundle worktree A built: closure keys and stored //! closures are root-relative (`ws:`), and so are the stored globs. -//! `current` and the memo stay per-root; each root mirrors its `current` -//! into `pins/`, which every store's eviction honors. +//! `current` and the memo stay per-root; each process mirrors its root's +//! `current` into `pins/`, which every store's eviction honors while the +//! process lives and keeps refreshing it. use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, HashMap, HashSet}; @@ -60,14 +61,20 @@ const CLOSURE_FILE: &str = "closure.json"; const MEMO_FILE: &str = "memo.json"; const MANIFEST_FILE: &str = "manifest.json"; const CURRENT_FILE: &str = "current"; -/// Pin files inside the shared dir: `pins/-` names the -/// generation a running process at that root serves, so one worktree's -/// eviction can never delete blobs another running server reads live. +/// Pin files inside the shared dir: `pins/---` +/// names the generation a running process at that root serves, so one +/// worktree's eviction can never delete blobs another running server reads +/// live (see [`pin_id_for`]). const PINS_DIR: &str = "pins"; /// A pin whose file has not been refreshed for this long belongs to a -/// worktree that is gone (deleted checkout, abandoned sandbox): eviction may -/// ignore it, and the next prune removes the pin file itself. -const PIN_MAX_AGE: Duration = Duration::from_secs(7 * 24 * 60 * 60); +/// process that is gone (deleted checkout, abandoned sandbox, a crash on a +/// machine that has since rebooted): eviction may ignore it, and the next +/// scan removes the pin file itself. A running server refreshes its pin +/// well inside this ([`StartBundleStore::refresh_pin`], every ten minutes), +/// and a pin of a process this boot knows to be dead is dropped sooner. +pub const PIN_MAX_AGE: Duration = Duration::from_secs(60 * 60); +/// How often a long-lived server should call [`StartBundleStore::refresh_pin`]. +pub const PIN_REFRESH_EVERY: Duration = Duration::from_secs(10 * 60); /// What an in-root glob pattern's root prefix is stored as. const GLOB_ROOT_TOKEN: &str = "\0ws/"; const LEGACY_POINTER_FILE: &str = "latest"; @@ -351,14 +358,23 @@ impl StartBundleStore { /// Rewrites this process's pin for the generation it serves (the root's /// `current`), so a server that has not persisted or restored for a - /// while still holds its blobs past [`PIN_MAX_AGE`]. Cheap; a caller - /// with a long-lived server calls it on a timer. + /// while still holds its blobs past [`PIN_MAX_AGE`]. Two small file + /// writes, nothing read but `current`; a long-lived server calls it + /// every [`PIN_REFRESH_EVERY`]. pub fn refresh_pin(&self) { if let Some(key) = read_current(&self.local) { self.write_current(&key); } } + /// Removes this process's pin: on a clean shutdown the generation it + /// served is a plain generation again, evictable at once rather than + /// after [`PIN_MAX_AGE`]. The root's `current` stays, so the next boot + /// at this root restores it when it still holds. + pub fn release_pin(&self) { + let _ = fs::remove_file(self.dir.join(PINS_DIR).join(&self.pin_id)); + } + /// This store with the contents of `files` in its key: inputs of the /// bundle that no closure lists (a missing one keys as missing). A /// generation built from other contents is then no restore's match. The @@ -682,44 +698,50 @@ impl StartBundleStore { } /// Generation keys eviction must not remove: this root's `current` plus - /// every fresh pin. A pin older than [`PIN_MAX_AGE`] belongs to a dead - /// worktree and is deleted instead of honored. + /// every pin still held (see [`Self::held_pins`]). fn protected_keys(&self) -> HashSet { let mut keys: HashSet = read_current(&self.local).into_iter().collect(); + keys.extend(self.held_pins().into_iter().map(|pin| pin.key)); + keys + } + + /// Whether a held pin of another process names `key`: that process + /// serves the generation from its blobs right now. + fn pinned_by_another_root(&self, key: &str) -> bool { + self.held_pins() + .iter() + .any(|pin| pin.name != self.pin_id && pin.key == key) + } + + /// One pass over the pins dir: the pins still held, each with the key it + /// names. A pin older than [`PIN_MAX_AGE`], or whose name says its + /// process is gone ([`pin_holder_is_dead`]), is deleted instead of + /// honored, so a fleet of short-lived processes leaves no pile behind + /// and the budget stays enforceable. Only this process's own pin is + /// never deleted here. + fn held_pins(&self) -> Vec { + let mut pins = Vec::new(); let Ok(entries) = fs::read_dir(self.dir.join(PINS_DIR)) else { - return keys; + return pins; }; for e in entries.flatten() { + let name = e.file_name().to_string_lossy().into_owned(); let stale = e .metadata() .and_then(|m| m.modified()) .ok() .and_then(|m| m.elapsed().ok()) .is_some_and(|age| age > PIN_MAX_AGE); - if stale { + if name != self.pin_id && (stale || pin_holder_is_dead(&name)) { let _ = fs::remove_file(e.path()); } else if let Ok(key) = fs::read_to_string(e.path()) { - keys.insert(key.trim().to_string()); + pins.push(HeldPin { + name, + key: key.trim().to_string(), + }); } } - keys - } - - /// Whether a fresh pin of another root names `key`: that root serves the - /// generation from its blobs right now. - fn pinned_by_another_root(&self, key: &str) -> bool { - let Ok(entries) = fs::read_dir(self.dir.join(PINS_DIR)) else { - return false; - }; - entries.flatten().any(|e| { - e.file_name().to_string_lossy() != self.pin_id - && e.metadata() - .and_then(|m| m.modified()) - .ok() - .and_then(|m| m.elapsed().ok()) - .is_some_and(|age| age <= PIN_MAX_AGE) - && fs::read_to_string(e.path()).is_ok_and(|k| k.trim() == key) - }) + pins } /// A short digest of this store's salt, what every key of this store @@ -757,20 +779,78 @@ impl StartBundleStore { } } -/// The pin file name of `root` under `session`: the root's hash, so pins of -/// one checkout sort together, and the session, so two processes at the -/// same path (sandboxes run their app at one path over one store) never -/// share a pin. Sharing one, the second process's pin named only its own -/// generation and the first's lost its protection, and eviction swept the -/// blobs from under a running server. +/// A pin as a scan found it: its file name and the generation it names. +struct HeldPin { + name: String, + key: String, +} + +/// The pin file name of `root` under `session`: +/// `---`. The root's hash, so pins of one +/// checkout sort together; the boot and the pid, so a scan can tell a pin +/// whose process is gone (see [`pin_holder_is_dead`]) without waiting for +/// it to age out; and the session, so two processes at the same path +/// (sandboxes run their app at one path over one store) never share a pin. +/// Sharing one, the second process's pin named only its own generation and +/// the first's lost its protection, and eviction swept the blobs from under +/// a running server. fn pin_id_for(root: &Path, session: &str) -> String { let root = &blake3::hash(root.as_os_str().as_encoded_bytes()).to_hex()[..16]; - format!("{root}-{session}") + format!("{root}-{}-{}-{session}", boot_token(), std::process::id()) +} + +/// What a pid means on this machine right now: the kernel's boot id and +/// this process's pid namespace (Linux), joined without hyphens. A pid is +/// only comparable to the pids a scan can see when both match; across a +/// reboot or a container boundary the same number is another process. "0" +/// where neither is readable, which no real token equals. +fn boot_token() -> &'static str { + static TOKEN: std::sync::OnceLock = std::sync::OnceLock::new(); + TOKEN.get_or_init(|| { + let boot = fs::read_to_string("/proc/sys/kernel/random/boot_id") + .map(|s| s.trim().replace('-', "")) + .unwrap_or_default(); + let pid_ns = fs::read_link("/proc/self/ns/pid") + .map(|l| { + l.to_string_lossy() + .chars() + .filter(char::is_ascii_digit) + .collect::() + }) + .unwrap_or_default(); + if boot.is_empty() || pid_ns.is_empty() { + "0".to_string() + } else { + format!("{boot}{pid_ns}") + } + }) +} + +/// Whether a pin's name says its process is gone: the pin is from this +/// boot and pid namespace, so its pid is one of ours to look up, and +/// `/proc/` is not there. A pin from another boot or namespace, of an +/// older layout, or on a platform without `/proc` cannot be told, and is +/// honored until it ages out. +fn pin_holder_is_dead(name: &str) -> bool { + let mut parts = name.splitn(4, '-'); + let (Some(_root), Some(boot), Some(pid), Some(_session)) = + (parts.next(), parts.next(), parts.next(), parts.next()) + else { + return false; + }; + if boot == "0" || boot != boot_token() { + return false; + } + let Ok(pid) = pid.parse::() else { + return false; + }; + pid != std::process::id() && !Path::new("/proc").join(pid.to_string()).exists() } /// This process's pin session: random, made once. Every store of this /// process (one per persist) rewrites the same pin file, so a process leaves -/// one pin behind, which ages out after [`PIN_MAX_AGE`]. +/// one pin behind, which the next scan drops once the process is gone (or +/// after [`PIN_MAX_AGE`] when that cannot be told). fn process_pin_session() -> &'static str { static SESSION: std::sync::OnceLock = std::sync::OnceLock::new(); SESSION.get_or_init(integrity::random_tag) @@ -959,8 +1039,11 @@ fn par_map(items: &[I], f: impl Fn(&I) -> Option + Sync) -> out } +/// Stamps the entry as used now. Written aside and renamed over, never +/// opened in place: in a shared store a symlink planted at the touch file +/// would otherwise be followed and its target truncated. fn touch(entry: &Path) { - let _ = fs::write(entry.join(TOUCH_FILE), b""); + let _ = integrity::atomic_write(&entry.join(TOUCH_FILE), b""); } fn entry_size(dir: &Path) -> u64 { diff --git a/crates/oj_cache/src/start_bundle/tests.rs b/crates/oj_cache/src/start_bundle/tests.rs index 157aeecb4..1ec58a098 100644 --- a/crates/oj_cache/src/start_bundle/tests.rs +++ b/crates/oj_cache/src/start_bundle/tests.rs @@ -1654,3 +1654,194 @@ fn the_generation_window_is_per_salt() { store_b_dev.join_eviction(); assert!(!shared.join("start-bundle").join(&key_a).is_dir()); } + +/// Three generations of one root, persisted in turn: the keys oldest first, +/// `current` naming the last. +fn three_generations(fx: &Fixture, store: &StartBundleStore) -> Vec { + let mut keys = Vec::new(); + for i in 0..3 { + fx.write_module("a.tsx", &format!("export const a = {i} + 7000;")); + fx.write_build(&format!("bundle-{i}")); + keys.push(store.persist(&fx.start).unwrap().0); + std::thread::sleep(Duration::from_millis(20)); + } + store.join_eviction(); + keys +} + +fn plant_pin(shared: &Path, name: &str, key: &str, age: Duration) -> PathBuf { + let pins = shared.join("start-bundle").join(PINS_DIR); + fs::create_dir_all(&pins).unwrap(); + let pin = pins.join(name); + fs::write(&pin, key).unwrap(); + set_mtime(&pin, SystemTime::now() - age); + pin +} + +fn generation_dirs(shared: &Path) -> Vec { + fs::read_dir(shared.join("start-bundle")) + .unwrap() + .flatten() + .filter(is_generation_dir) + .map(|e| e.file_name().to_string_lossy().into_owned()) + .collect() +} + +// A fleet of short-lived processes leaves a pin per boot behind. Aged past +// PIN_MAX_AGE they protect nothing: the budget prune evicts what they named +// and sweeps the pile, one scan. +#[test] +fn a_pile_of_aged_pins_holds_nothing_over_the_budget() { + let shared = shared_base("pin-pile"); + let fx = Fixture::new("pin-pile"); + let store = split_store_at(&fx.root, &shared, SHARED_KEEP_GENERATIONS); + let keys = three_generations(&fx, &store); + for i in 0..1000 { + plant_pin( + &shared, + &format!("{i:016x}-0-1-gone"), + &keys[i % 2], + Duration::from_secs(2 * 60 * 60), + ); + } + let started = Instant::now(); + store.prune(1); + assert!( + started.elapsed() < Duration::from_secs(5), + "a thousand pins scanned in {:?}", + started.elapsed() + ); + assert_eq!( + generation_dirs(&shared), + vec![keys[2].clone()], + "only current survives a budget of one byte" + ); + let pins = fs::read_dir(shared.join("start-bundle").join(PINS_DIR)) + .unwrap() + .count(); + assert_eq!(pins, 1, "the aged pins are gone, this process's stays"); +} + +// A pin names its process: one of this boot that is no longer running is +// ignored and removed at once, one still running is honored however the +// store was opened. +#[test] +fn a_pin_of_a_dead_process_is_ignored_and_a_live_one_honored() { + if boot_token() == "0" { + return; + } + let shared = shared_base("pin-pids"); + let fx = Fixture::new("pin-pids"); + let store = split_store_at(&fx.root, &shared, SHARED_KEEP_GENERATIONS); + let keys = three_generations(&fx, &store); + let root = store.pin_id.split('-').next().unwrap().to_string(); + let dead = plant_pin( + &shared, + &format!("{root}-{}-2147483646-dead", boot_token()), + &keys[0], + Duration::ZERO, + ); + let live = plant_pin( + &shared, + &format!("{root}-{}-{}-live", boot_token(), std::process::id()), + &keys[1], + Duration::ZERO, + ); + store.prune(1); + let mut left = generation_dirs(&shared); + left.sort(); + let mut expected = vec![keys[1].clone(), keys[2].clone()]; + expected.sort(); + assert_eq!( + left, expected, + "the dead pin's generation went, the live one stayed" + ); + assert!(!dead.is_file(), "the dead pin is removed"); + assert!(live.is_file(), "the live pin is kept"); +} + +// A pin from another boot (or another pid namespace) names a pid this +// machine cannot look up: it is honored until it ages out, then dropped. +#[test] +fn a_pin_from_another_boot_is_honored_until_it_ages() { + let shared = shared_base("pin-boot"); + let fx = Fixture::new("pin-boot"); + let store = split_store_at(&fx.root, &shared, SHARED_KEEP_GENERATIONS); + let keys = three_generations(&fx, &store); + let root = store.pin_id.split('-').next().unwrap().to_string(); + let name = format!("{root}-deadbeef0000-2147483646-elsewhere"); + let pin = plant_pin(&shared, &name, &keys[0], Duration::ZERO); + store.prune(1); + assert!( + shared.join("start-bundle").join(&keys[0]).is_dir(), + "a fresh pin of another boot protects" + ); + assert!(pin.is_file()); + set_mtime(&pin, SystemTime::now() - Duration::from_secs(2 * 60 * 60)); + store.prune(1); + assert!( + !shared.join("start-bundle").join(&keys[0]).is_dir(), + "aged past PIN_MAX_AGE it protects nothing" + ); + assert!(!pin.is_file()); +} + +// refresh_pin re-stamps the pin on the hour scale PIN_MAX_AGE now runs at, +// and release_pin takes it away on a clean shutdown, leaving `current`. +#[test] +fn a_pin_is_refreshed_on_a_timer_and_released_on_shutdown() { + let shared = shared_base("pin-refresh"); + let fx = Fixture::new("pin-refresh"); + let store = split_store_at(&fx.root, &shared, SHARED_KEEP_GENERATIONS); + let (key, _) = store.persist(&fx.start).unwrap(); + let pin = shared + .join("start-bundle") + .join(PINS_DIR) + .join(&store.pin_id); + assert!(PIN_MAX_AGE <= Duration::from_secs(60 * 60)); + assert!( + PIN_REFRESH_EVERY * 3 <= PIN_MAX_AGE, + "a missed refresh or two is survivable" + ); + set_mtime( + &pin, + SystemTime::now() - PIN_MAX_AGE - Duration::from_secs(60), + ); + store.refresh_pin(); + let age = fs::metadata(&pin) + .unwrap() + .modified() + .unwrap() + .elapsed() + .unwrap(); + assert!(age < Duration::from_secs(60), "re-stamped: {age:?}"); + assert_eq!(fs::read_to_string(&pin).unwrap().trim(), key); + store.release_pin(); + assert!(!pin.is_file(), "released"); + assert_eq!(read_current(&store.local).as_deref(), Some(key.as_str())); + assert!( + split_store_at(&fx.root, &shared, SHARED_KEEP_GENERATIONS) + .restore(&fx.start, no_globs) + .is_ok(), + "the next boot still restores" + ); +} + +// The touch file is rewritten in a shared directory: a symlink planted +// there is replaced, never followed to its target. +#[test] +fn touching_an_entry_never_follows_a_symlink() { + let shared = shared_base("touch-link"); + let fx = Fixture::new("touch-link"); + let store = split_store_at(&fx.root, &shared, SHARED_KEEP_GENERATIONS); + let (key, _) = store.persist(&fx.start).unwrap(); + let entry = shared.join("start-bundle").join(&key); + let victim = fx.root.join("victim"); + fs::write(&victim, b"precious").unwrap(); + fs::remove_file(entry.join(TOUCH_FILE)).unwrap(); + std::os::unix::fs::symlink(&victim, entry.join(TOUCH_FILE)).unwrap(); + touch(&entry); + assert_eq!(fs::read(&victim).unwrap(), b"precious"); + let meta = fs::symlink_metadata(entry.join(TOUCH_FILE)).unwrap(); + assert!(meta.is_file(), "the link was replaced by a plain file"); +} diff --git a/crates/oj_cache/src/start_codegen.rs b/crates/oj_cache/src/start_codegen.rs index 9d8fbf21c..69a960bf2 100644 --- a/crates/oj_cache/src/start_codegen.rs +++ b/crates/oj_cache/src/start_codegen.rs @@ -483,8 +483,11 @@ fn par_map(files: &[PathBuf], f: impl Fn(&Path) -> Option + Sync) -> out } +/// Stamps the entry as used now. Written aside and renamed over, never +/// opened in place: in a shared store a symlink planted at the touch file +/// would otherwise be followed and its target truncated. fn touch(entry: &Path) { - let _ = fs::write(entry.join(TOUCH_FILE), b""); + let _ = integrity::atomic_write(&entry.join(TOUCH_FILE), b""); } #[cfg(test)] @@ -1033,4 +1036,23 @@ mod tests { "within budget, nothing is evicted" ); } + + // The touch file is rewritten in a directory other worktrees share: a + // symlink planted there is replaced, never followed to its target. + #[test] + fn touching_an_entry_never_follows_a_symlink() { + let fx = Fixture::new("touch-link"); + let (out, _) = tree_outputs(&fx); + let outputs = [("routeTree.gen.ts", out.as_path())]; + let key = fx.store().persist(&fx.inputs(), &outputs).unwrap(); + let entry = fx.entry_dir("route-tree", &key); + let victim = fx.path("victim"); + fs::write(&victim, b"precious").unwrap(); + fs::remove_file(entry.join(TOUCH_FILE)).unwrap(); + std::os::unix::fs::symlink(&victim, entry.join(TOUCH_FILE)).unwrap(); + touch(&entry); + assert_eq!(fs::read(&victim).unwrap(), b"precious"); + let meta = fs::symlink_metadata(entry.join(TOUCH_FILE)).unwrap(); + assert!(meta.is_file(), "the link was replaced by a plain file"); + } } diff --git a/crates/oj_css/src/imports.rs b/crates/oj_css/src/imports.rs index 80f187231..7d1f5b43f 100644 --- a/crates/oj_css/src/imports.rs +++ b/crates/oj_css/src/imports.rs @@ -11,8 +11,8 @@ use crate::path::{ is_external, node_modules_load_paths, normalize, read_package_json, strip_query, with_ext, }; use crate::rebase::DirRebase; -use crate::resolve::CssResolve; -use crate::sass::{compile_sass_collecting, is_sass, SassOptions}; +use crate::resolve::{CssResolve, Missing}; +use crate::sass::{compile_sass_tracing, is_sass, SassOptions}; const IMPORT: &str = "@import"; @@ -53,6 +53,22 @@ pub fn inline_imports_collecting<'s>( inline_imports_preprocessing(source, file, resolve, None, &[], deps) } +/// `inline_imports_collecting`, also appending to `missing` every path an +/// `@import` was looked for at and not found before it resolved (the +/// candidates ahead of the hit: `./x` and `./x.css` beside the importer +/// before a package `x`, a load path's package directory that is not +/// there), from the imported Sass files' own lookups too. A file created +/// at one of them later changes what the sheet inlines. +pub fn inline_imports_tracing<'s>( + source: &'s str, + file: &Path, + resolve: &CssResolve<'_>, + deps: &mut Vec, + missing: &mut Missing, +) -> Result, String> { + inline_imports_full(source, file, resolve, None, &[], deps, missing) +} + /// [`inline_imports_collecting`] with the environment's Sass options for an /// imported preprocessor file. Vite's postcss-import `load` compiles an /// imported `.scss` / `.sass` (`compileCSSPreprocessors`, with the @@ -67,6 +83,26 @@ pub fn inline_imports_preprocessing<'s>( sass_additional_data: Option<&str>, sass_load_paths: &[PathBuf], deps: &mut Vec, +) -> Result, String> { + inline_imports_full( + source, + file, + resolve, + sass_additional_data, + sass_load_paths, + deps, + &mut Missing::default(), + ) +} + +fn inline_imports_full<'s>( + source: &'s str, + file: &Path, + resolve: &CssResolve<'_>, + sass_additional_data: Option<&str>, + sass_load_paths: &[PathBuf], + deps: &mut Vec, + missing: &mut Missing, ) -> Result, String> { if !source.contains(IMPORT) { return Ok(Cow::Borrowed(source)); @@ -78,6 +114,7 @@ pub fn inline_imports_preprocessing<'s>( stack: Vec::new(), resolve, deps, + missing, inline: true, imported: HashMap::from([(normalize(file), HashSet::new())]), hashed: HashMap::new(), @@ -96,6 +133,8 @@ struct Inliner<'a, 'r> { stack: Vec, resolve: &'a CssResolve<'r>, deps: &'a mut Vec, + /// Where an import was looked for and not found before it resolved. + missing: &'a mut Missing, /// Whether imports are inlined at all (`hoist_imports` only orders). inline: bool, /// postcss-import's `skipDuplicates` (its default): the files inlined @@ -592,8 +631,13 @@ impl Inliner<'_, '_> { { // Normalized, like the absolute path Vite's // resolver hands postcss-import. - resolve_css_import_with(&import.spec, dir, self.resolve)? - .map(|target| normalize(&target)) + resolve_css_import_tracing( + &import.spec, + dir, + self.resolve, + self.missing, + )? + .map(|target| normalize(&target)) } _ => None, }; @@ -662,7 +706,7 @@ impl Inliner<'_, '_> { // postcss-import's `load` (Vite's) compiles a // preprocessor file and inlines its CSS. if is_sass(&target.to_string_lossy()) { - child = compile_sass_collecting( + child = compile_sass_tracing( &child, &SassOptions { load_dir: target.parent(), @@ -671,6 +715,7 @@ impl Inliner<'_, '_> { resolve: *self.resolve, }, self.deps, + self.missing, ) .map_err(|e| format!("@import {}: {e}", import.spec))?; } @@ -1231,6 +1276,7 @@ fn hoist_imports(css: &str) -> String { stack: Vec::new(), resolve: &CssResolve::default(), deps: &mut Vec::new(), + missing: &mut Missing::default(), inline: false, imported: HashMap::new(), hashed: HashMap::new(), @@ -1402,17 +1448,39 @@ pub fn resolve_css_import_with( spec: &str, dir: &Path, resolve: &CssResolve<'_>, +) -> Result, String> { + resolve_css_import_tracing(spec, dir, resolve, &mut Missing::default()) +} + +/// `resolve_css_import_with`, appending to `missing` each path tried and +/// not found before the answer, in the order Vite's resolver tries them: +/// the public file, the file beside the importer (`x`, then `x.css`), +/// then the packages. A package resolved through its `exports` map probes +/// nothing of its own here (the resolver's lookups stay inside it). +pub fn resolve_css_import_tracing( + spec: &str, + dir: &Path, + resolve: &CssResolve<'_>, + missing: &mut Missing, ) -> Result, String> { let spec = strip_query(spec); let aliased = resolve.alias_spec(spec); let spec = match &aliased { - Some(a) if Path::new(a).is_absolute() => return Ok(first_css_file(Path::new(a))), + Some(a) if Path::new(a).is_absolute() => { + return Ok(first_css_file_probing(Path::new(a), missing)); + } Some(a) => a.as_str(), None if spec.starts_with('/') => { + if let Some(public) = resolve.public_file(spec) { + return Ok(Some(public)); + } + if let Some(public) = resolve.public_path(spec) { + missing.files.push(public); + } return Ok(resolve - .public_file(spec) - .or_else(|| resolve.root_path(spec).and_then(|p| first_css_file(&p))) - .or_else(|| first_css_file(Path::new(spec)))); + .root_path(spec) + .and_then(|p| first_css_file_probing(&p, missing)) + .or_else(|| first_css_file_probing(Path::new(spec), missing))); } None => spec, }; @@ -1428,7 +1496,7 @@ pub fn resolve_css_import_with( if spec.starts_with('#') { return exports_css_entry(spec, dir, resolve.production); } - if let Some(local) = first_css_file(&dir.join(spec)) { + if let Some(local) = first_css_file_probing(&dir.join(spec), missing) { return Ok(Some(local)); } if spec.starts_with("./") || spec.starts_with("../") { @@ -1440,7 +1508,7 @@ pub fn resolve_css_import_with( // there goes on to the lookup from the importer (rolldown's // vite_resolve_plugin.rs: resolve_bare_import, then resolve_raw). if let Some(root) = resolve.dedupe_root(spec) { - let from_root = package_css_file(spec, root, resolve.production).map_err(|e| { + let from_root = package_css_file(spec, root, resolve.production, missing).map_err(|e| { format!( "cannot resolve @import \"{spec}\" from the root's copy of \"{}\" (resolve.dedupe): {e}", oj_resolver::package_name(spec) @@ -1450,27 +1518,34 @@ pub fn resolve_css_import_with( return Ok(from_root); } } - Ok(package_css_file(spec, dir, resolve.production).unwrap_or(None)) + Ok(package_css_file(spec, dir, resolve.production, missing).unwrap_or(None)) } /// A bare `spec` from the `node_modules` above `dir`; an error where the -/// package's `exports` reject it. -fn package_css_file(spec: &str, dir: &Path, production: bool) -> Result, String> { +/// package's `exports` reject it. A `node_modules` level without the +/// package is a missing directory: one installed there later wins. +fn package_css_file( + spec: &str, + dir: &Path, + production: bool, + missing: &mut Missing, +) -> Result, String> { let Some((pkg, rest)) = split_package_specifier(spec) else { return Ok(None); }; for nm in node_modules_load_paths(dir) { let pkg_dir = nm.join(pkg); if !pkg_dir.is_dir() { + missing.dirs.push(pkg_dir); continue; } if read_package_json(&pkg_dir).is_some_and(|json| json.get("exports").is_some()) { return exports_css_entry(spec, dir, production); } if rest.is_empty() { - return Ok(package_css_entry(&pkg_dir)); + return Ok(package_css_entry(&pkg_dir, missing)); } - if let Some(file) = first_css_file(&pkg_dir.join(rest)) { + if let Some(file) = first_css_file_probing(&pkg_dir.join(rest), missing) { return Ok(Some(file)); } } @@ -1549,22 +1624,36 @@ fn exports_entry( /// A bare package import: the `style` / `main` entry when it is CSS, else /// `index.css`. -fn package_css_entry(pkg_dir: &Path) -> Option { - let from_fields = read_package_json(pkg_dir).and_then(|json| { - ["style", "main"] - .iter() - .filter_map(|field| json.get(field)?.as_str()) - .flat_map(|entry| css_file_candidates(&pkg_dir.join(entry))) - .find(|c| c.is_file() && c.extension().is_some_and(|e| e == "css")) - }); - from_fields.or_else(|| { - let idx = pkg_dir.join("index.css"); - idx.is_file().then_some(idx) - }) +fn package_css_entry(pkg_dir: &Path, missing: &mut Missing) -> Option { + let fields = read_package_json(pkg_dir) + .map(|json| { + ["style", "main"] + .iter() + .filter_map(|field| json.get(field)?.as_str()) + .flat_map(|entry| css_file_candidates(&pkg_dir.join(entry))) + .filter(|c| c.extension().is_some_and(|e| e == "css")) + .collect::>() + }) + .unwrap_or_default(); + for candidate in fields.into_iter().chain([pkg_dir.join("index.css")]) { + if candidate.is_file() { + return Some(candidate); + } + missing.files.push(candidate); + } + None } -fn first_css_file(base: &Path) -> Option { - css_file_candidates(base).into_iter().find(|c| c.is_file()) +/// The first of `base`'s candidates that is a file, recording the ones +/// ahead of it. +fn first_css_file_probing(base: &Path, missing: &mut Missing) -> Option { + for candidate in css_file_candidates(base) { + if candidate.is_file() { + return Some(candidate); + } + missing.files.push(candidate); + } + None } /// `base`, then `base.css` when extensionless. Not `base/index.css`: @@ -1711,6 +1800,79 @@ mod tests { let _ = std::fs::remove_dir_all(&base); } + // `@import "x"` answered by a package was looked for beside the importer + // first (`x`, `x.css`): those are the misses, in order, and so is a + // `node_modules` level without the package. A sheet created at one of + // them shadows the package; the misses of the found file's own imports + // are collected along, a Sass import's included. + #[test] + fn tracing_variants_report_the_candidates_ahead_of_each_hit() { + let base = std::env::temp_dir().join(format!("oj-css-misses-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let src = base.join("app/src"); + let pkg = base.join("app/node_modules/x"); + // A nearer node_modules level without the package: probed first. + std::fs::create_dir_all(src.join("node_modules")).unwrap(); + std::fs::create_dir_all(&pkg).unwrap(); + std::fs::write(pkg.join("package.json"), r#"{"name":"x","style":"x.css"}"#).unwrap(); + std::fs::write(pkg.join("x.css"), ".pkg {}").unwrap(); + std::fs::write(src.join("part.scss"), "@use \"vars\";\n.p { c: vars.$c; }").unwrap(); + std::fs::write(src.join("_vars.scss"), "$c: 1;").unwrap(); + let run = |spec: &str| { + let mut deps = Vec::new(); + let mut missing = Missing::default(); + let out = inline_imports_tracing( + &format!("@import \"{spec}\";\n@import \"./part.scss\";\n.a {{}}"), + &src.join("a.css"), + &CssResolve::default(), + &mut deps, + &mut missing, + ) + .unwrap() + .into_owned(); + (out, deps, missing) + }; + let (out, deps, missing) = run("x"); + assert!(out.contains(".pkg"), "{out}"); + assert!(deps.contains(&pkg.join("x.css")), "{deps:?}"); + let files = &missing.files; + let at = |p: PathBuf| { + files + .iter() + .position(|m| *m == p) + .unwrap_or_else(|| panic!("{} not in {files:?}", p.display())) + }; + assert!(at(src.join("x")) < at(src.join("x.css"))); + assert!( + missing.dirs.contains(&src.join("node_modules/x")), + "{:?}", + missing.dirs + ); + assert!( + !files.contains(&pkg.join("x.css")) && !files.contains(&pkg.join("index.css")), + "the hit and what follows it are no misses: {files:?}" + ); + // The Sass import's own lookup: `vars.scss` before the partial. + assert!( + files.contains(&src.join("vars.scss")) && !files.contains(&src.join("_vars.scss")), + "{files:?}" + ); + // `./x` has no package fallback: the same two misses and no dirs. + let (_, _, relative) = run("./x"); + assert_eq!(&relative.files[..2], &[src.join("x"), src.join("x.css")]); + assert!(relative.dirs.is_empty(), "{:?}", relative.dirs); + // Shadowed: the sheet beside the importer answers and the package is + // never looked at. + std::fs::write(src.join("x.css"), ".local {}").unwrap(); + let (out, deps, missing) = run("x"); + assert!(out.contains(".local") && !out.contains(".pkg"), "{out}"); + assert!(deps.contains(&src.join("x.css")), "{deps:?}"); + assert_eq!(missing.files.first(), Some(&src.join("x"))); + assert!(!missing.files.iter().any(|p| p.starts_with(&pkg))); + assert!(missing.dirs.is_empty(), "{:?}", missing.dirs); + let _ = std::fs::remove_dir_all(&base); + } + // postcss-import's layout (the copy Vite bundles, under `cssMinify: // false`): the inlined rules replace the statement in place, what follows // starts on one new line, the first `@charset` leads and the others go, diff --git a/crates/oj_css/src/lib.rs b/crates/oj_css/src/lib.rs index a3b4c180d..4acd9b399 100644 --- a/crates/oj_css/src/lib.rs +++ b/crates/oj_css/src/lib.rs @@ -26,17 +26,18 @@ pub use compile::{ scope_css_module, scope_css_module_opts, CssOutput, }; pub use imports::{ - inline_imports, inline_imports_collecting, inline_imports_preprocessing, inline_imports_with, - resolve_css_import, resolve_css_import_with, + inline_imports, inline_imports_collecting, inline_imports_preprocessing, + inline_imports_tracing, inline_imports_with, resolve_css_import, resolve_css_import_tracing, + resolve_css_import_with, }; pub use lightning::LightningOptions; pub use modules::{css_modules_esm, is_css_module}; pub use path::{node_modules_load_paths, normalize}; pub use rebase::{rewrite_css_asset_urls, rewrite_css_image_set, rewrite_style_attribute_dev}; -pub use resolve::{CssModulesOptions, CssResolve, CssResolveConfig}; +pub use resolve::{CssModulesOptions, CssResolve, CssResolveConfig, Missing}; pub use sass::{ - compile_sass, compile_sass_collecting, compile_sass_opts, compile_sass_with, is_sass, - SassOptions, + compile_sass, compile_sass_collecting, compile_sass_opts, compile_sass_tracing, + compile_sass_with, is_sass, SassOptions, }; pub use targets::browser_targets; #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/oj_css/src/resolve.rs b/crates/oj_css/src/resolve.rs index 4367ceb57..288f3ac04 100644 --- a/crates/oj_css/src/resolve.rs +++ b/crates/oj_css/src/resolve.rs @@ -27,6 +27,24 @@ pub struct CssResolve<'a> { pub lightning: &'a LightningOptions, } +/// The paths a resolution looked for and did not find before it found its +/// answer (or gave up), in probe order: a Sass `@use` through the load +/// paths, a CSS `@import` through its candidates. Each is as much an input +/// of the compile as the file it found, since a file created at one of +/// them later shadows that answer. Directory probes are kept apart: their +/// absence is checked by listing, not by reading. +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub struct Missing { + pub files: Vec, + pub dirs: Vec, +} + +impl Missing { + pub fn is_empty(&self) -> bool { + self.files.is_empty() && self.dirs.is_empty() + } +} + static DEFAULT_LIGHTNING: LightningOptions = LightningOptions { include: 0, exclude: 0, @@ -165,10 +183,16 @@ impl CssResolve<'_> { /// The public-directory file a root-absolute `/x` names, if it exists. pub fn public_file(&self, spec: &str) -> Option { - let p = self.public_dir?.join(root_absolute_rel(spec)?); + let p = self.public_path(spec)?; p.is_file().then_some(p) } + /// The public-directory path a root-absolute `/x` names, whether or not + /// a file is there. + pub fn public_path(&self, spec: &str) -> Option { + Some(self.public_dir?.join(root_absolute_rel(spec)?)) + } + /// The path under the root a root-absolute `/x` names, not checked for /// existence so callers can probe extensions. pub fn root_path(&self, spec: &str) -> Option { diff --git a/crates/oj_css/src/sass.rs b/crates/oj_css/src/sass.rs index 0655058f4..1a58fcefa 100644 --- a/crates/oj_css/src/sass.rs +++ b/crates/oj_css/src/sass.rs @@ -8,7 +8,7 @@ use std::path::{Component, Path, PathBuf}; use crate::imports::{exports_sass_entry, split_package_specifier}; use crate::path::{node_modules_load_paths, read_package_json, with_ext}; -use crate::resolve::{CssResolve, CssResolveConfig}; +use crate::resolve::{CssResolve, CssResolveConfig, Missing}; pub fn is_sass(url: &str) -> bool { let f = url.split('?').next().unwrap_or(url); @@ -55,11 +55,26 @@ pub fn compile_sass_collecting( source: &str, opts: &SassOptions<'_>, deps: &mut Vec, +) -> Result { + compile_sass_tracing(source, opts, deps, &mut Missing::default()) +} + +/// `compile_sass_collecting`, also appending to `missing` every path Sass +/// probed and found nothing at before it found each stylesheet (the +/// candidates ahead of the hit in its search order: a `_partial` beside +/// the importer, a load path's copy, an index directory). A file created +/// at one of them later changes what the same source compiles to. +pub fn compile_sass_tracing( + source: &str, + opts: &SassOptions<'_>, + deps: &mut Vec, + missing: &mut Missing, ) -> Result { let fs = SassFs { resolve: opts.resolve.into(), seen: RefCell::default(), probes: RefCell::default(), + missing: RefCell::default(), failed: RefCell::default(), }; let mut options = grass::Options::default().fs(&fs); @@ -96,6 +111,9 @@ pub fn compile_sass_collecting( }) .map_err(|e| format!("sass error: {e}")); deps.append(&mut fs.seen.borrow_mut()); + let mut probed = fs.missing.take(); + missing.files.append(&mut probed.files); + missing.dirs.append(&mut probed.dirs); match fs.failed.take() { Some(e) => Err(format!("sass error: {e}")), None => out, @@ -314,6 +332,12 @@ struct SassFs { /// `(is_dir, is_file)` answers: grass re-probes the same candidates from /// every partial, and files do not change within a compile. probes: RefCell>, + /// The probes answered "no", in order. grass stops at the first + /// candidate it finds, so every one of these came before a hit or a + /// failure, never after. Relative probes (grass tries the entry's + /// specifier against its own empty path first) name nothing on disk + /// and are left out. + missing: RefCell, } impl SassFs { @@ -323,6 +347,14 @@ impl SassFs { return hit; } let v = answer(); + if !v && p.is_absolute() { + let mut missing = self.missing.borrow_mut(); + if dir { + missing.dirs.push(p.to_path_buf()); + } else { + missing.files.push(p.to_path_buf()); + } + } self.probes.borrow_mut().insert(key, v); v } @@ -862,4 +894,75 @@ mod tests { assert!(compile_sass(src, Some(&base.join("src/comp"))).is_err()); let _ = std::fs::remove_dir_all(&base); } + + // A `@use "theme"` answered by a package under node_modules was looked + // for beside the importer first: those candidates are reported as + // missing, in search order, and nothing probed after the hit is. A + // partial created at one of them then shadows the package. + #[test] + fn missing_probes_are_the_candidates_ahead_of_the_hit() { + let base = std::env::temp_dir().join(format!("oj-css-missing-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let styles = base.join("src/styles"); + let pkg = base.join("node_modules/theme"); + std::fs::create_dir_all(&styles).unwrap(); + std::fs::create_dir_all(&pkg).unwrap(); + std::fs::write(pkg.join("_index.scss"), "$c: red;\n").unwrap(); + let compile = || { + let mut deps = Vec::new(); + let mut missing = Missing::default(); + let css = compile_sass_tracing( + "@use \"theme\";\n.a { color: theme.$c; }", + &SassOptions { + load_dir: Some(&styles), + ..SassOptions::default() + }, + &mut deps, + &mut missing, + ) + .unwrap(); + (css, deps, missing) + }; + let (css, deps, missing) = compile(); + assert!(css.contains("red"), "{css}"); + assert_eq!(deps, vec![pkg.join("_index.scss")]); + // The importer's directory comes before the package, the plain name + // before the partial, and the package's own index directory probe + // ends the search: nothing under it is tried once it is found. + let files = &missing.files; + let at = |p: PathBuf| { + files + .iter() + .position(|m| *m == p) + .unwrap_or_else(|| panic!("{} not in {files:?}", p.display())) + }; + assert!(at(styles.join("theme.scss")) < at(styles.join("_theme.scss"))); + assert!(at(styles.join("_theme.scss")) < at(base.join("node_modules/theme.scss"))); + assert!(at(base.join("node_modules/theme.scss")) < at(pkg.join("index.scss"))); + assert!(files.iter().all(|p| p.is_absolute()), "{files:?}"); + assert!( + !files.contains(&pkg.join("_index.scss")), + "the hit is a dep, not a miss: {files:?}" + ); + assert!( + !files.contains(&pkg.join("index.css")), + "nothing is probed after the hit: {files:?}" + ); + assert!( + missing.dirs.contains(&styles.join("theme")), + "{:?}", + missing.dirs + ); + // Shadowed: the partial beside the importer is the answer now, and + // the package is never reached. + std::fs::write(styles.join("_theme.scss"), "$c: blue;\n").unwrap(); + let (css, deps, missing) = compile(); + assert!(css.contains("blue"), "{css}"); + assert_eq!(deps, vec![styles.join("_theme.scss")]); + assert!( + !missing.files.iter().any(|p| p.starts_with(&pkg)), + "{missing:?}" + ); + let _ = std::fs::remove_dir_all(&base); + } } diff --git a/crates/oj_server/build.rs b/crates/oj_server/build.rs index 1aa8d62f0..56606d947 100644 --- a/crates/oj_server/build.rs +++ b/crates/oj_server/build.rs @@ -29,8 +29,10 @@ fn source_id() { "oj_config", "oj_css", "oj_env", + "oj_graph", "oj_js", "oj_resolver", + "oj_rolldown_dev", "oj_server", "oj_stylex", ] { @@ -53,6 +55,10 @@ fn source_id() { println!("cargo:rustc-env=OJ_SOURCE_ID={:016x}", hasher.finish()); } +/// Code and the assets embedded in it (`include_str!`ed scripts, templates +/// and stylesheets shape output as much as the Rust around them). +const SOURCE_EXTENSIONS: &[&str] = &["rs", "mjs", "js", "cjs", "ts", "tsx", "json", "css", "html"]; + fn walk(dir: &std::path::Path, out: &mut Vec) { for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() { let path = entry.path(); @@ -60,7 +66,8 @@ fn walk(dir: &std::path::Path, out: &mut Vec) { walk(&path, out); } else if path .extension() - .is_some_and(|e| e == "rs" || e == "mjs" || e == "js") + .and_then(|e| e.to_str()) + .is_some_and(|e| SOURCE_EXTENSIONS.contains(&e)) { out.push(path); } diff --git a/crates/oj_server/src/assets/plugin-host.mjs b/crates/oj_server/src/assets/plugin-host.mjs index 4929a120b..85746fa6e 100644 --- a/crates/oj_server/src/assets/plugin-host.mjs +++ b/crates/oj_server/src/assets/plugin-host.mjs @@ -2485,7 +2485,13 @@ const transformEmitStore = new AsyncLocalStorage(); const bucket = transformReadStore.getStore(); if (!bucket) return; const path = pathOf(p); - if (path != null) bucket[kind].add(pathResolve(path)); + if (path == null) return; + const abs = pathResolve(path); + bucket[kind].add(abs); + // Claimed: every hook in flight learns this read went through the + // patch, so the engine's shared window (which cannot tell hooks + // apart) is not charged with it on anyone else's behalf. + patchedReads.at.set(kind + "\0" + abs, ++patchedReads.seq); }; // open with a flag that writes makes bytes rather than depending on them // (a plugin's log line during its transform is not an input): only an @@ -2658,6 +2664,29 @@ const transformWatchStore = new AsyncLocalStorage(); // syncBuiltinESMExports is a no-op) and are covered by the Rust TracingFs // ops layer instead. const transformReadStore = new AsyncLocalStorage(); +// Reads made through the patched node:fs, each with the sequence number of +// its moment, so a transform's reply can list the reads any hook made that +// way while it ran ("claimed"): the server charges a transform the engine +// window's reads minus the claimed ones, which leaves only reads the patch +// cannot see (a named esm import bound before it). Trimmed to what the +// transforms still in flight can need. +const patchedReads = { seq: 0, at: new Map(), active: new Set() }; +function claimedSince(since) { + const files = []; + const dirs = []; + for (const [key, seq] of patchedReads.at) { + if (seq <= since) continue; + const i = key.indexOf("\0"); + (key.slice(0, i) === "dirs" ? dirs : files).push(key.slice(i + 1)); + } + return { files, dirs }; +} +function trimPatchedReads() { + if (patchedReads.at.size < 4096) return; + let oldest = patchedReads.seq; + for (const b of patchedReads.active) oldest = Math.min(oldest, b.since); + for (const [key, seq] of patchedReads.at) if (seq <= oldest) patchedReads.at.delete(key); +} // Per-transform map of oj-resolved imports (spec -> id) the Rust side computes and // passes in, so a plugin's `this.resolve` during transform is a local lookup rather // than a host round-trip. ctx.resolve consults it first. @@ -6507,18 +6536,22 @@ async function transform(c, code, id, resolvedJson, phase, priorJson) { } else if (r.code != null && r.map === undefined) mapBroken ??= p.name ?? "?"; updateModuleInfo(c, id, r); } - const result = () => - JSON.stringify({ + const result = () => { + const claimed = claimedSince(readBucket.since); + return JSON.stringify({ code: current, watchFiles: [...bucket], readFiles: [...readBucket.files], readDirs: [...readBucket.dirs], + claimedFiles: claimed.files, + claimedDirs: claimed.dirs, maps, mapPlugins, mapBroken, moduleType: lowered ? "js" : null, emittedChunks: chunkBucket, }); + }; if (phase && phase !== "post" && phase !== "after-compile" && phase !== "normal-post") return result(); const prior = c.moduleInfoCache.get(id); const info = makeModuleInfo( @@ -6539,12 +6572,18 @@ async function transform(c, code, id, resolvedJson, phase, priorJson) { for (const { p, fn } of pluginsWithHook(c, "moduleParsed")) await fn.call(ctxFor(c, p), info); return result(); }; - const readBucket = { files: new Set(), dirs: new Set() }; - return transformWatchStore.run(bucket, () => - transformEmitStore.run(chunkBucket, () => - transformResolveStore.run({ importer: id, map: resolveMap }, () => transformReadStore.run(readBucket, runLoop)), - ), - ); + const readBucket = { files: new Set(), dirs: new Set(), since: patchedReads.seq }; + patchedReads.active.add(readBucket); + try { + return await transformWatchStore.run(bucket, () => + transformEmitStore.run(chunkBucket, () => + transformResolveStore.run({ importer: id, map: resolveMap }, () => transformReadStore.run(readBucket, runLoop)), + ), + ); + } finally { + patchedReads.active.delete(readBucket); + trimPatchedReads(); + } } async function replayModuleParsed(c, id) { diff --git a/crates/oj_server/src/css_engine.rs b/crates/oj_server/src/css_engine.rs index c9ee1b23a..5723ba759 100644 --- a/crates/oj_server/src/css_engine.rs +++ b/crates/oj_server/src/css_engine.rs @@ -7,6 +7,7 @@ use std::path::{Path, PathBuf}; +use oj_js::tracing_fs::ReadLog; use oj_js::{EngineConfig, EngineError, JsEngine}; const TAILWIND_JS: &str = include_str!("assets/css-tailwind.mjs"); @@ -44,6 +45,12 @@ pub struct CssEngine { /// Rides into every spawned and revived engine, so the debug GC fan-out /// keeps reaching this slot across revives. registry: Option, + /// The TracingFs sink of the tailwind engine's isolates (the other kinds + /// run on the real fs): a tracked compile opens a window on it, so a + /// PostCSS plugin's own reads, declared or not, reach the sheet's trace. + /// Off until `set_trace_reads`: a window then never opens and a read in + /// the isolate costs one atomic load, as in the plugin host. + read_log: std::sync::Arc, } /// The live engine, generation-stamped so concurrent failures revive once. @@ -69,6 +76,13 @@ pub struct CssDeps { pub files: Vec, /// `(dir, glob)`: the files under `dir` matching `glob`. pub dirs: Vec<(PathBuf, String)>, + /// What the engine's TracingFs saw while the compile ran, when a + /// window was open (the server persists its output): files whose bytes + /// or existence a plugin looked at, and directories it listed. Inputs + /// of the sheet's trace, not of its graph (a plugin's own sources are + /// among them). + pub read_files: Vec, + pub read_dirs: Vec, } impl CssDeps { @@ -94,6 +108,7 @@ impl CssDeps { CssDeps { files: paths("deps"), dirs, + ..CssDeps::default() } } } @@ -175,7 +190,12 @@ impl CssEngine { } std::fs::write(&script, js)?; - let engine = Self::spawn_engine(root, memory_limit_bytes, registry.clone()) + let read_log = std::sync::Arc::new(ReadLog::default()); + // Only the tailwind engine runs the app's own code (its PostCSS + // plugins); the preprocessors and svelte read nothing a sheet's + // declared imports do not already name. + let trace_reads = (kind == "tailwind").then(|| std::sync::Arc::clone(&read_log)); + let engine = Self::spawn_engine(root, memory_limit_bytes, registry.clone(), trace_reads) .await .map_err(|e| anyhow::anyhow!("cannot start the {kind} engine: {e}"))?; Ok(std::sync::Arc::new(CssEngine { @@ -192,6 +212,7 @@ impl CssEngine { last_revive: std::sync::Mutex::new(None), postcss_config, registry, + read_log, })) } @@ -199,9 +220,10 @@ impl CssEngine { root: &Path, memory_limit_bytes: usize, registry: Option, + trace_reads: Option>, ) -> Result { let config = EngineConfig { - trace_reads: None, + trace_reads, root: root.to_path_buf(), memory_limit_bytes: Some(memory_limit_bytes), default_deadline: None, @@ -235,7 +257,15 @@ impl CssEngine { if let Ok(mut last) = self.last_revive.lock() { *last = Some(std::time::Instant::now()); } - match Self::spawn_engine(&self.root, self.memory_limit_bytes, self.registry.clone()).await { + let trace_reads = (self.kind == "tailwind").then(|| std::sync::Arc::clone(&self.read_log)); + match Self::spawn_engine( + &self.root, + self.memory_limit_bytes, + self.registry.clone(), + trace_reads, + ) + .await + { Ok(fresh) => { slot.generation += 1; slot.engine = fresh; @@ -275,14 +305,32 @@ impl CssEngine { Ok(self.request(css, from, options, true).await?.0) } - /// [`compile`](Self::compile) plus the files the compile read. + /// Whether tracked compiles open TracingFs windows (the constructive + /// trace a persisted entry is verified by). Only a server that persists + /// what it compiles has a use for the rows; off, nothing is recorded. + pub fn set_trace_reads(&self, on: bool) { + self.read_log.set_enabled(on); + } + + /// [`compile`](Self::compile) plus the files the compile read: the + /// ones PostCSS messages declare, and with tracing on, every one the + /// isolate looked at while this compile was in flight (a concurrent + /// compile's too: the window cannot tell them apart, and more rows + /// only cost a recompile, never a stale serve). pub async fn compile_tracked( &self, css: &str, from: &str, ) -> Result<(String, CssDeps), String> { let from = absolute_from(&self.base, from); - self.request(css, from, serde_json::Value::Null, true).await + let window = self.read_log.begin(); + let compiled = self.request(css, from, serde_json::Value::Null, true).await; + let reads = self.read_log.finish(window); + compiled.map(|(css, mut deps)| { + deps.read_files = reads.files; + deps.read_dirs = reads.dirs; + (css, deps) + }) } /// Compiles from an absolute file path (build and Start host know the file, @@ -572,4 +620,64 @@ mod tests { "one revive, stamped" ); } + + /// The start-app fixture's node_modules (postcss and its dependencies), + /// or None where the fixture is not installed: callers skip then. + fn fixture_node_modules() -> Option { + let dir = + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../e2e/fixtures/start-app/node_modules"); + dir.join("postcss") + .exists() + .then(|| dir.canonicalize().unwrap()) + } + + // A PostCSS plugin's own reads (a named `node:fs` import, which the + // plugin host's JS-side patch cannot see) reach a tracked compile through + // the engine's TracingFs, and only while tracing is on: a server without + // the store opens no window and gets no rows, at no cost to the compile. + #[tokio::test(flavor = "multi_thread")] + async fn a_tracked_compile_reports_a_plugins_own_reads_only_while_tracing() { + let Some(node_modules) = fixture_node_modules() else { + eprintln!("skipping: fixture postcss not installed"); + return; + }; + let root = app_root(); + std::os::unix::fs::symlink(node_modules, root.path().join("node_modules")).unwrap(); + std::fs::write(root.path().join("side.txt"), "dark\n").unwrap(); + std::fs::write( + root.path().join("postcss.config.mjs"), + "import { readFileSync } from \"node:fs\";\n\ + const here = new URL(\".\", import.meta.url).pathname;\n\ + export default { plugins: [{ postcssPlugin: \"side\", Once(root) {\n\ + \x20 root.append(`.${readFileSync(here + \"side.txt\", \"utf8\").trim()} {}`);\n\ + } }] };\n", + ) + .unwrap(); + let side = root.path().canonicalize().unwrap().join("side.txt"); + let engine = CssEngine::tailwind(root.path(), None).await.unwrap(); + let compile = || async { + let (css, deps) = engine + .compile_tracked(".a {}", "/src/index.css") + .await + .unwrap(); + assert!(css.contains(".dark"), "{css}"); + deps + }; + let off = compile().await; + assert!( + off.read_files.is_empty() && off.read_dirs.is_empty(), + "reads recorded with tracing off: {off:?}" + ); + engine.set_trace_reads(true); + let on = compile().await; + assert!(on.read_files.contains(&side), "{:?}", on.read_files); + assert!( + on.files.is_empty(), + "an undeclared read is no graph import: {:?}", + on.files + ); + engine.set_trace_reads(false); + let off = compile().await; + assert!(off.read_files.is_empty(), "{:?}", off.read_files); + } } diff --git a/crates/oj_server/src/css_serve.rs b/crates/oj_server/src/css_serve.rs index 737526c76..d1415a37c 100644 --- a/crates/oj_server/src/css_serve.rs +++ b/crates/oj_server/src/css_serve.rs @@ -472,8 +472,48 @@ fn outside_root_deps(root: &Path, deps: CssDeps) -> Vec { /// `glob` with no node_modules and no dotfiles. `prune` is a subtree left /// out (already watched). pub(crate) fn css_dep_files(deps: CssDeps, prune: Option<&Path>) -> Vec { - let mut out = deps.files; - for (dir, glob) in deps.dirs { + let mut files = deps.files; + expand_dir_deps(deps.dirs, prune, &mut files, &mut Vec::new()); + files +} + +/// A compile's deps as a persisted sheet's inputs. +pub(crate) struct CssDepTrace { + /// The declared files and the `dir-dependency` expansions: the sheet's + /// graph imports, digested in its trace. + pub files: Vec, + /// Every directory an expansion listed, the declared one and those + /// under it: a file added or removed there changes the expansion + /// without touching any file's bytes, so each is a listing row. + pub listed: Vec, + /// What the engine's TracingFs window saw (see [`CssDeps`]). + pub read_files: Vec, + pub read_dirs: Vec, +} + +/// [`css_dep_files`] keeping what the trace needs apart from the graph's +/// imports: the directories the expansion walked and the isolate's reads. +pub(crate) fn css_dep_trace(deps: CssDeps) -> CssDepTrace { + let mut files = deps.files; + let mut listed = Vec::new(); + expand_dir_deps(deps.dirs, None, &mut files, &mut listed); + CssDepTrace { + files, + listed, + read_files: deps.read_files, + read_dirs: deps.read_dirs, + } +} + +/// Appends the files each `(dir, glob)` matches to `out` and every +/// directory walked on the way to `listed`. +fn expand_dir_deps( + dirs: Vec<(PathBuf, String)>, + prune: Option<&Path>, + out: &mut Vec, + listed: &mut Vec, +) { + for (dir, glob) in dirs { if prune.is_some_and(|p| dir.starts_with(p)) { continue; } @@ -489,6 +529,7 @@ pub(crate) fn css_dep_files(deps: CssDeps, prune: Option<&Path>) -> Vec let Ok(entries) = std::fs::read_dir(&at) else { continue; }; + listed.push(at); for entry in entries.flatten() { let name = entry.file_name(); if name.to_string_lossy().starts_with('.') || name == "node_modules" { @@ -509,7 +550,6 @@ pub(crate) fn css_dep_files(deps: CssDeps, prune: Option<&Path>) -> Vec } } } - out } pub(crate) enum EngineKind { @@ -532,7 +572,11 @@ pub(crate) async fn lazy_engine( let root = &state.root; let registry = Some(state.engine_registry.clone()); match kind { - EngineKind::Tailwind => CssEngine::tailwind(root, registry).await, + EngineKind::Tailwind => CssEngine::tailwind(root, registry).await.inspect(|engine| { + // A persisted sheet's trace needs what its PostCSS plugins + // read; a server without the store opens no window. + engine.set_trace_reads(state.persistent_cache); + }), EngineKind::Preprocess => CssEngine::preprocess(root, registry).await, EngineKind::Svelte => CssEngine::svelte(root, registry).await, } @@ -595,6 +639,7 @@ mod tailwind_sheet_tests { (base.clone(), "app/**/*.tsx".into()), (root.join("src"), "**/*.tsx".into()), ], + ..CssDeps::default() }; let mut got = outside_root_deps(&root, deps); got.sort(); @@ -608,6 +653,55 @@ mod tailwind_sheet_tests { ); } + // The trace's view of the same deps: the expansion's files join the + // declared ones, every directory the expansion walked is listed (the + // declared one and those under it, never node_modules or a dotdir), and + // the isolate's reads stay apart from the graph's imports. + #[test] + fn css_dep_trace_keeps_the_listed_directories_and_the_reads_apart() { + let base = tempfile::tempdir().unwrap(); + let base = base.path().canonicalize().unwrap(); + let icons = base.join("icons"); + for dir in [ + icons.join("deep"), + icons.join("node_modules/x"), + icons.join(".cache"), + ] { + std::fs::create_dir_all(dir).unwrap(); + } + for file in [ + icons.join("a.svg"), + icons.join("deep/b.svg"), + icons.join("notes.md"), + icons.join("node_modules/x/c.svg"), + icons.join(".cache/d.svg"), + base.join("side.txt"), + ] { + std::fs::write(file, "").unwrap(); + } + let trace = css_dep_trace(CssDeps { + files: vec![base.join("theme.css")], + dirs: vec![(icons.clone(), "**/*.svg".into())], + read_files: vec![base.join("side.txt")], + read_dirs: vec![base.clone()], + }); + let mut files = trace.files; + files.sort(); + assert_eq!( + files, + vec![ + icons.join("a.svg"), + icons.join("deep/b.svg"), + base.join("theme.css") + ] + ); + let mut listed = trace.listed; + listed.sort(); + assert_eq!(listed, vec![icons.clone(), icons.join("deep")]); + assert_eq!(trace.read_files, vec![base.join("side.txt")]); + assert_eq!(trace.read_dirs, vec![base]); + } + #[test] fn a_change_during_the_compile_leaves_its_sheet_stale() { let sheets = TailwindSheets::default(); diff --git a/crates/oj_server/src/lib.rs b/crates/oj_server/src/lib.rs index fad57a7a0..a1d1ad309 100644 --- a/crates/oj_server/src/lib.rs +++ b/crates/oj_server/src/lib.rs @@ -1757,7 +1757,7 @@ fn module_cache_config_salt( /// of the sources it was built from (`OJ_SOURCE_ID`, from the build /// script), so two builds of one version never serve each other's compiler /// output through a shared store. -pub(crate) const fn tool_version() -> &'static str { +pub const fn tool_version() -> &'static str { concat!(env!("CARGO_PKG_VERSION"), "+", env!("OJ_SOURCE_ID")) } @@ -1770,25 +1770,33 @@ pub(crate) const fn tool_version() -> &'static str { /// plugin spread over many modules is served by the next release's /// manifest or version bump, as webpack's `buildDependencies` leaves it. fn hash_linked_packages(root: &Path, workspace: &Path, hasher: &mut blake3::Hasher) { - let modules = root.join("node_modules"); + // The root's own node_modules and the workspace's (npm and yarn + // workspaces hoist a linked package above the app). + let mut dirs = vec![root.join("node_modules")]; + if workspace != root { + dirs.push(workspace.join("node_modules")); + } let mut links: Vec = Vec::new(); - for entry in std::fs::read_dir(&modules).into_iter().flatten().flatten() { - let path = entry.path(); - let scoped = entry.file_name().to_string_lossy().starts_with('@'); - if scoped && !path.is_symlink() { - links.extend( - std::fs::read_dir(&path) - .into_iter() - .flatten() - .flatten() - .map(|e| e.path()), - ); - } else { - links.push(path); + for modules in dirs { + for entry in std::fs::read_dir(&modules).into_iter().flatten().flatten() { + let path = entry.path(); + let scoped = entry.file_name().to_string_lossy().starts_with('@'); + if scoped && !path.is_symlink() { + links.extend( + std::fs::read_dir(&path) + .into_iter() + .flatten() + .flatten() + .map(|e| e.path()), + ); + } else { + links.push(path); + } } } links.retain(|p| p.is_symlink()); links.sort(); + links.dedup(); for link in links { let Ok(target) = std::fs::canonicalize(&link) else { continue; @@ -1965,7 +1973,7 @@ fn optimized_deps( let (include, exclude, entries) = oj_config::optimize_deps_lists(config); optimize::OptimizedDeps::prepare( root, - env!("CARGO_PKG_VERSION"), + tool_version(), optimize::OptimizeInput { no_discovery: config.optimize_deps.as_ref().and_then(|o| o.no_discovery), hold_until_crawl_end: config diff --git a/crates/oj_server/src/module_pipeline.rs b/crates/oj_server/src/module_pipeline.rs index ac8e00a97..c348cd70a 100644 --- a/crates/oj_server/src/module_pipeline.rs +++ b/crates/oj_server/src/module_pipeline.rs @@ -144,6 +144,7 @@ pub(crate) async fn ensure_module_as( class_field_semantics, verbatim_module_syntax, importer_format, + invalidated, } = compile_key( state, file, @@ -174,7 +175,11 @@ pub(crate) async fn ensure_module_as( // without a compile when it passes the same checks a memory entry would. // Not an app module where a plugin collects state from transforms: the // transform a hit skips is state it never sees (see `collector_plugins`). - let session_only = |stamped: bool| stamped || (!is_dep && state.collector_plugins); + // Nor a module hard-invalidated by an edit this session: its key carries + // the process's invalidation counter, which no other session computes, + // so persisting it would only fill the store with entries nobody hits. + let session_only = + |stamped: bool| stamped || invalidated || (!is_dep && state.collector_plugins); let mut verify_against: Option> = None; if state.persistent_cache && !session_only(false) { let disk_key = state.cache.disk_key(&key); @@ -433,10 +438,18 @@ pub(crate) async fn ensure_module_as( // A sheet's rows (the files it inlined) were digested by the // compile: one saved while it ran is this session's alone too. if module.kind == "css" { - trace_unsettled |= module - .trace - .iter() - .any(|row| modified_since(Path::new(&row.id), compile_started)); + trace_unsettled |= module.trace.iter().any(|row| { + let path = row.id.strip_prefix("dir:").unwrap_or(&row.id); + modified_since(Path::new(path), compile_started) + }); + } + // A transform that read or listed hundreds of files (a scanner + // over the whole tree, or a bystander charged with a concurrent + // scanner's reads, which the engine's window cannot tell apart) + // would cost a warm hit as much as the compile and swell the + // store: such an entry stays in memory. + if module.trace.len() > TRACE_ROWS_MAX { + trace_unsettled = true; } Arc::new(module) } @@ -478,6 +491,7 @@ pub(crate) async fn ensure_module_as( class_field_semantics, verbatim_module_syntax, importer_format, + invalidated, }), ) .key; @@ -660,7 +674,10 @@ fn modified_since(file: &Path, since: std::time::SystemTime) -> bool { let Ok(mtime) = std::fs::metadata(file).and_then(|m| m.modified()) else { return false; }; - if mtime >= since { + // The kernel stamps files from a coarser clock than the one `since` was + // read from (a jiffy behind at most): a write just after the compile + // started can carry a stamp just before it. + if mtime + RACY_MTIME_MARGIN >= since { return true; } let whole_second = mtime @@ -690,27 +707,79 @@ fn dir_listing_digest(dir: &Path) -> String { /// virtiofs mounts round to 1 s or 2 s). const RACY_MTIME_WINDOW: std::time::Duration = std::time::Duration::from_secs(2); -/// The files a sheet pulled in (`@import`s inlined into its output, Sass -/// partials, PostCSS dependencies) as constructive-trace rows: inputs of the -/// entry that change without the sheet's own bytes, so a warm hit re-digests -/// them. The sheet itself is in the key already. -fn css_trace_rows(sheet: &Path, deps: &[PathBuf]) -> Vec { - let mut files: Vec = deps - .iter() - .map(|p| normalize(p)) - .filter(|p| p != sheet) - .collect(); - files.sort(); - files.dedup(); - files - .into_iter() - .map(|file| oj_cache::TraceRow { - digest: std::fs::read(&file) - .map(|bytes| blake3::hash(&bytes).to_hex().to_string()) - .unwrap_or_default(), - id: file.to_string_lossy().into_owned(), - }) - .collect() +/// How far the file-time clock may lag the wall clock `since` is read from +/// (Linux stamps from the coarse clock, up to one tick, 10 ms at HZ=100). +const RACY_MTIME_MARGIN: std::time::Duration = std::time::Duration::from_millis(20); + +/// More rows than this and an entry stays in memory: see `ensure_module_as`. +const TRACE_ROWS_MAX: usize = 256; + +/// A sheet's inputs beyond its own bytes (those are in the key) as +/// constructive-trace rows, so a warm hit re-checks each: +/// - the files it pulled in (`@import`s inlined into its output, Sass +/// partials, PostCSS dependencies) and the files its PostCSS plugins read +/// on their own, each with its digest (empty where the plugin looked and +/// found nothing); +/// - the paths its imports were looked for at before they resolved, as +/// digest-less rows: a file created there later shadows the hit; +/// - the directories a `dir-dependency` expansion walked and the ones a +/// plugin listed, as listing rows (`dir:`): a file added under one +/// is a miss. A directory an import probed and found missing is one too, +/// with the empty listing. +/// +/// A path both read and probed missing (changed under the compile) keeps +/// the read's digest; the mtime check sees to the rest. Host scratch is +/// oj's own machinery, not an input. +fn css_trace_rows(root: &Path, sheet: &Path, css: &CssState) -> Vec { + let scratch = oj_cache::cache_base(root); + let sheet = normalize(sheet); + let mut rows: Vec = Vec::new(); + let digested = |file: &Path| oj_cache::TraceRow { + digest: std::fs::read(file) + .map(|bytes| blake3::hash(&bytes).to_hex().to_string()) + .unwrap_or_default(), + id: file.to_string_lossy().into_owned(), + }; + let listed = |dir: &Path| oj_cache::TraceRow { + digest: dir_listing_digest(dir), + id: format!("dir:{}", dir.display()), + }; + let own = |p: &Path| *p == sheet || p.starts_with(&scratch); + for file in css.deps.iter().chain(&css.read_files) { + let file = normalize(file); + if !own(&file) { + rows.push(digested(&file)); + } + } + for file in &css.missing.files { + let file = normalize(file); + if !own(&file) { + rows.push(oj_cache::TraceRow { + id: file.to_string_lossy().into_owned(), + digest: String::new(), + }); + } + } + for dir in css.listed_dirs.iter().chain(&css.read_dirs) { + let dir = normalize(dir); + if !dir.starts_with(&scratch) { + rows.push(listed(&dir)); + } + } + for dir in &css.missing.dirs { + rows.push(oj_cache::TraceRow { + id: format!("dir:{}", normalize(dir).display()), + digest: String::new(), + }); + } + // One row per path: the read's digest ahead of a probe's absence, a + // listing's digest ahead of a missing directory's. + rows.sort_by(|a, b| { + a.id.cmp(&b.id) + .then(a.digest.is_empty().cmp(&b.digest.is_empty())) + }); + rows.dedup_by(|b, a| a.id == b.id); + rows } async fn file_stamp(file: &Path) -> Option { @@ -992,6 +1061,9 @@ struct CompileKey { verbatim_module_syntax: bool, /// How Node reads the file, decided from the real path too. importer_format: oj_compiler::interop::ImporterFormat, + /// The key carries this process's invalidation counter (an edit this + /// session hard-invalidated the module): a key of this session alone. + invalidated: bool, } /// The newest HMR stamp among a module's imports, by their served urls: what @@ -1117,6 +1189,7 @@ fn compile_key( class_field_semantics, verbatim_module_syntax, importer_format, + invalidated: invalidated > 0, } } @@ -1340,6 +1413,19 @@ async fn preprocess_less_stylus( struct CssState { /// Pulled-in files (@import targets, sass loads), collected for the module graph. deps: Vec, + /// Where its imports were looked for and not found before they resolved + /// (the candidates ahead of each hit): trace rows, so a file created at + /// one of them later is a miss. Empty without the store. + missing: oj_css::Missing, + /// The directories a PostCSS `dir-dependency` expansion walked: listing + /// rows, so a file added under one is a miss. Empty without the store. + listed_dirs: Vec, + /// What the PostCSS engine's TracingFs saw while the sheet compiled: the + /// files its plugins read or checked for and the directories they + /// listed. Rows of the trace, not imports of the graph. Empty without + /// the store (no window opens). + read_files: Vec, + read_dirs: Vec, /// A CSS module's class map, its classes scoped in the sheet already. exports: Option>, /// The text a module's default names hash, when it is not the sheet @@ -1363,35 +1449,52 @@ async fn css_prepass( let load_paths = sass_load_paths_for(state, url); let dir = file.parent().map(Path::to_path_buf); let css_resolve = state.css_resolve.clone(); - let (compiled, deps) = tokio::task::spawn_blocking(move || { + // The paths Sass probed before each hit are rows of the trace; a + // server without the store does not collect them. + let tracing = state.persistent_cache; + let (compiled, deps, missing) = tokio::task::spawn_blocking(move || { let mut deps = Vec::new(); - let out = oj_css::compile_sass_collecting( - &source, - &oj_css::SassOptions { - load_dir: dir.as_deref(), - additional_data: data.as_deref(), - load_paths: &load_paths, - resolve: css_resolve.as_ref(), - }, - &mut deps, - ); - out.map(|css| (css, deps)) + let mut missing = oj_css::Missing::default(); + let opts = oj_css::SassOptions { + load_dir: dir.as_deref(), + additional_data: data.as_deref(), + load_paths: &load_paths, + resolve: css_resolve.as_ref(), + }; + let out = if tracing { + oj_css::compile_sass_tracing(&source, &opts, &mut deps, &mut missing) + } else { + oj_css::compile_sass_collecting(&source, &opts, &mut deps) + }; + out.map(|css| (css, deps, missing)) }) .await .map_err(|e| format!("sass compile task failed for {url}: {e}"))??; css.deps.extend(deps); + css.missing = missing; compiled } else { source }; // What Vite hands PostCSS, whose CSS-module names hash it. let postcss_input = css.scope_source.take().unwrap_or_else(|| source.clone()); - let source = oj_css::inline_imports_collecting( - &source, - file, - &state.css_resolve.as_ref(), - &mut css.deps, - )?; + // The same for the paths its `@import`s were looked for at. + let source = if state.persistent_cache { + oj_css::inline_imports_tracing( + &source, + file, + &state.css_resolve.as_ref(), + &mut css.deps, + &mut css.missing, + )? + } else { + oj_css::inline_imports_collecting( + &source, + file, + &state.css_resolve.as_ref(), + &mut css.deps, + )? + }; let source = if state.has_postcss { let compiled = match lazy_engine(state, EngineKind::Tailwind).await { Ok(engine) => engine.compile_tracked(&source, url).await, @@ -1400,11 +1503,15 @@ async fn css_prepass( match compiled { Ok((out, deps)) => { // The PostCSS deps join the sheet's graph imports, as Vite's - // compileCSS adds them to the module's watch files. - let files = tokio::task::spawn_blocking(move || css_dep_files(deps, None)) - .await - .unwrap_or_default(); - css.deps.extend(files); + // compileCSS adds them to the module's watch files. What + // the expansion listed and the plugins read on their own + // (a window was open only with the store) go to the trace. + if let Ok(trace) = tokio::task::spawn_blocking(move || css_dep_trace(deps)).await { + css.deps.extend(trace.files); + css.listed_dirs = trace.listed; + css.read_files = trace.read_files; + css.read_dirs = trace.read_dirs; + } out } Err(e) => { @@ -1727,7 +1834,7 @@ impl CompileJob { }; let dep_imports = css_dep_imports(state, &self.file, &self.css.deps); let trace = if state.persistent_cache { - css_trace_rows(&self.file, &self.css.deps) + css_trace_rows(&state.root, &self.file, &self.css) } else { Vec::new() }; @@ -2904,6 +3011,13 @@ mod tests { !super::modified_since(&file, now), "nanoseconds compare exactly" ); + // A stamp the coarse file-time clock put just below the compile's + // start: racy. + at(now - std::time::Duration::from_micros(500)); + assert!( + super::modified_since(&file, now), + "within the clock's lag is racy" + ); at(whole(now - s(1))); assert!( super::modified_since(&file, now), diff --git a/crates/oj_server/src/optimize.rs b/crates/oj_server/src/optimize.rs index e53bfa12c..e288197c7 100644 --- a/crates/oj_server/src/optimize.rs +++ b/crates/oj_server/src/optimize.rs @@ -81,8 +81,8 @@ pub struct OptimizedDeps { rx: watch::Receiver>>, dir: PathBuf, /// The session's base version: the persisted one on a warm boot, else - /// the prebundle hash salted with the ledger's epoch (see [`DepLedger`]). - /// Empty when disabled. + /// the prebundle hash, salted per process when there is no ledger (see + /// [`DepLedger`]). Empty when disabled. version: String, rerun: Option>, link_memo: LinkMemo, @@ -101,10 +101,10 @@ type OnCommit = Box; struct RerunState { /// Base prebundle hash, the seed of every browser version. hash: String, - /// Salts every version this optimizer mints: the ledger's epoch, so every - /// worktree on one store mints the same URLs for the same bundle (and a - /// wiped store or cache moves them all), or a per-process timestamp, - /// Vite's sessionTimestamp, when there is no ledger. + /// Salts every version this optimizer mints: a per-process timestamp, + /// Vite's sessionTimestamp, when there is no ledger; empty with one, so + /// every store that bundled one plan mints the same URLs (the ledger + /// keeps a URL from naming two bundles, see [`DepLedger`]). epoch: String, /// What each URL already served; `None` leaves the epoch alone to keep /// URLs unique. @@ -147,8 +147,8 @@ pub enum DepServe { /// (sorted) discovered set, so chunks that change can never be served under a /// URL a page already holds (Vite's getDiscoveredBrowserHash). URLs are /// `immutable`, and a later session (a restart, a cleared cache) may bundle -/// other bytes under the same set: the epoch and the [`DepLedger`] keep any -/// URL from ever naming two bundles. +/// other bytes under the same set: the epoch, or with a ledger its records, +/// keep any URL from ever naming two bundles. fn browser_hash<'a>( hash: &str, epoch: &str, @@ -180,15 +180,16 @@ fn session_timestamp() -> String { /// ones. That also makes every worktree mint its own URLs, and the dep /// version salts every persistent module-cache key, so no two worktrees /// could ever share a compiled module. The ledger gives the same guarantee -/// without the per-process salt: versions come from the inputs and an epoch -/// that lives as long as the ledger, each URL is recorded write-once with -/// its file's content hash, and a commit whose bytes disagree with a -/// recorded URL re-mints a version from the bytes (and reloads, as a -/// contradicted plan does). Wiping the ledger's directory starts a new -/// epoch, which moves every URL. +/// without the per-process salt: versions come from the inputs alone (the +/// prebundle hash and the dependency names, as Vite's committed +/// browserHash), so every store that bundled one plan mints one URL and the +/// compiles keyed on it are one entry everywhere (a fresh sandbox's keys +/// agree with a substituter's); each URL is recorded write-once with its +/// file's content hash, and a commit whose bytes disagree with a recorded +/// URL re-mints a version from the bytes (and reloads, as a contradicted +/// plan does). struct DepLedger { dir: PathBuf, - epoch: String, /// The pre-bundle directory: the bytes a URL serves are its file's. deps: PathBuf, } @@ -198,13 +199,11 @@ impl DepLedger { /// URLs. `None` when it cannot be written. fn open(dir: PathBuf, deps: PathBuf) -> Option { std::fs::create_dir_all(&dir).ok()?; - let fresh = format!("{}-{}", session_timestamp(), std::process::id()); - if !write_once(&dir.join("epoch"), fresh.as_bytes()) { - return None; - } - let epoch = std::fs::read_to_string(dir.join("epoch")).ok()?; - let epoch = epoch.trim().to_string(); - (!epoch.is_empty()).then_some(Self { dir, epoch, deps }) + // Writable, or there is no ledger (a per-process epoch then). + let probe = dir.join(format!("probe-{}", oj_cache::integrity::temp_tag())); + std::fs::write(&probe, b"").ok()?; + let _ = std::fs::remove_file(&probe); + Some(Self { dir, deps }) } /// The store's ledger for an app's `deps` dir. Without the store there @@ -242,16 +241,16 @@ impl DepLedger { /// Creates `path` holding `bytes` unless it exists: written aside and hard /// linked into place, so a reader never sees a partial file and the first /// writer wins. False only when neither this write nor an earlier one landed. +/// The aside file is created new under a name with a per-process counter +/// and a random part (`integrity::temp_tag`): two threads of one process +/// never share it, and nothing else that can write the shared store can +/// plant a symlink at it to be written through. fn write_once(path: &Path, bytes: &[u8]) -> bool { if path.is_file() { return true; } - let tmp = path.with_extension(format!( - "tmp-{}-{}", - std::process::id(), - session_timestamp() - )); - let linked = std::fs::write(&tmp, bytes).is_ok() + let tmp = path.with_extension(format!("tmp-{}", oj_cache::integrity::temp_tag())); + let linked = oj_cache::integrity::write_new(&tmp, bytes).is_ok() && match std::fs::hard_link(&tmp, path) { Ok(()) => true, Err(e) => e.kind() == std::io::ErrorKind::AlreadyExists, @@ -879,9 +878,11 @@ impl OptimizedDeps { } else { None }; - let epoch = ledger - .as_ref() - .map_or_else(session_timestamp, |l| l.epoch.clone()); + let epoch = if ledger.is_some() { + String::new() + } else { + session_timestamp() + }; let (tx, rx) = watch::channel(None); // optimizeDeps.force: ignore any cached pre-bundle and always rebuild. @@ -898,9 +899,10 @@ impl OptimizedDeps { (seeded, m.browser_hash.clone()) } // Vite's initDepsOptimizerMetadata: a cold session's base - // version is salted too (with the epoch), since a source edit can - // change the dep set (and the bytes) without changing the hash; - // the commit's ledger check catches bytes that moved. + // version is salted too (with the epoch, when there is one), + // since a source edit can change the dep set (and the bytes) + // without changing the hash; the ledger's check catches bytes + // that moved. None => ( std::collections::BTreeMap::new(), browser_hash(&hash, &epoch, std::iter::empty()), @@ -1040,11 +1042,13 @@ impl OptimizedDeps { /// URL moves to a new version, so no compile key still matches a module /// compiled against the plan, and the page reloads, /// Vite's "optimized dependencies changed". Vite's committed browserHash is -/// unsalted; this one keeps the epoch salt, so a later epoch's contradicted -/// plan never lands on this URL either. Bytes the ledger has seen under -/// another URL's version re-mint and reload the same way. `persist` gets the bundled entries and -/// their version before the commit releases any held request, as Vite's -/// commit writes the metadata before resolving the processing promise. +/// unsalted, and so is this one with a ledger (every store commits one plan +/// under one URL); without one it keeps the session salt, so a later +/// session's contradicted plan never lands on this URL either. Bytes the +/// ledger has seen under another URL's version re-mint and reload the same +/// way. `persist` gets the bundled entries and their version before the +/// commit releases any held request, as Vite's commit writes the metadata +/// before resolving the processing promise. fn commit_initial( rerun: &RerunState, mut map: DepMap, @@ -1786,6 +1790,43 @@ mod tests { } } + // The dep ledger is written from more than one thread of a process (two + // optimizer runs committing at once): each gets its own aside file, one + // record lands, and no aside file is left behind. + #[test] + fn the_ledger_writes_a_record_once_from_many_threads_and_leaves_no_temp() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("record"); + let writers: Vec<_> = (0..16u8) + .map(|i| { + let path = path.clone(); + std::thread::spawn(move || write_once(&path, &[i; 64])) + }) + .collect(); + for w in writers { + assert!(w.join().unwrap(), "every writer sees a record landed"); + } + let bytes = std::fs::read(&path).unwrap(); + assert!( + bytes.len() == 64 && bytes.iter().all(|b| *b == bytes[0]), + "one writer's whole record, never a mix" + ); + let names: Vec = std::fs::read_dir(dir.path()) + .unwrap() + .flatten() + .map(|e| e.file_name().to_string_lossy().into_owned()) + .collect(); + assert_eq!(names, ["record"], "no aside file left: {names:?}"); + // The aside name is not a function of the pid and the clock alone. + let symlinked = dir.path().join("planted"); + std::os::unix::fs::symlink(dir.path().join("victim"), &symlinked).unwrap(); + assert!( + oj_cache::integrity::write_new(&symlinked, b"x").is_err(), + "a planted link is refused, not written through" + ); + assert!(!dir.path().join("victim").exists()); + } + // Vite's pkg.main fallback: "main" is appended last so a dep that resolves // in the dev server never fails the prebundle under a Vite-shaped list. #[test] @@ -2631,12 +2672,12 @@ mod tests { std::fs::write(deps.join(file), bytes).unwrap(); } - /// A test optimizer whose ledger (and so epoch) lives in `dir`. + /// A test optimizer whose ledger lives in `dir`. fn ledgered_deps(dir: &Path) -> OptimizedDeps { let mut deps = test_deps(true, vec![]); let r = Arc::get_mut(deps.rerun.as_mut().unwrap()).unwrap(); r.ledger = DepLedger::open(dir.to_path_buf(), dir.join("deps")); - r.epoch = r.ledger.as_ref().unwrap().epoch.clone(); + r.epoch = String::new(); deps } @@ -2693,13 +2734,10 @@ mod tests { assert!(ledger.agrees("v2", "react.mjs", "bbbb"), "per version"); assert!(ledger.agrees("v1", "zod.mjs", "bbbb"), "per file"); let again = DepLedger::open(dir.path().join("l"), dir.path().join("deps")).unwrap(); - assert_eq!( - again.epoch, ledger.epoch, - "the epoch lives as long as the ledger" + assert!( + !again.agrees("v1", "react.mjs", "bbbb"), + "a record lives as long as the ledger" ); - assert!(!again.agrees("v1", "react.mjs", "bbbb")); - let wiped = DepLedger::open(dir.path().join("other"), dir.path().join("deps")).unwrap(); - assert_ne!(wiped.epoch, ledger.epoch, "a new ledger is a new epoch"); } // Two sessions on one ledger (a restart, another worktree on the same @@ -2720,13 +2758,43 @@ mod tests { bundled.get_mut("react").unwrap().file_hash = "abc".into(); bundled_bytes(dir.path(), "react.mjs", "the same bytes"); commit_initial(r, bundled, Some(plan), |_, _| {}); - assert_eq!(deps.browser_version(), v, "agreeing bytes keep the URL"); + assert_eq!( + deps.browser_version(), + v, + "a plan the bundle confirms keeps its version" + ); deps.meta_now("react").unwrap().url }) .collect(); assert_eq!(versions[0], versions[1]); } + // Two stores (two ledgers: two machines, or a fresh sandbox and a + // substituter) that bundled one plan commit the same URLs, so the + // compiles keyed on them are one entry everywhere. Other bytes under a + // URL a ledger recorded are that ledger's re-mint (see below). + #[test] + fn two_ledgers_commit_one_url_for_one_plan() { + let commit = |dir: &Path, dep: &str| { + let deps = ledgered_deps(dir); + let r = deps.rerun.as_ref().unwrap(); + let v = browser_hash(&r.hash, &r.epoch, std::iter::empty()); + *r.browser_version.write().unwrap() = v.clone(); + let file = format!("{dep}.mjs"); + let mut plan: DepMap = [(dep.to_string(), meta(&file, true))].into(); + plan.get_mut(dep).unwrap().url = dep_url(&file, &v); + let mut bundled = plan.clone(); + bundled.get_mut(dep).unwrap().file_hash = "abc".into(); + bundled_bytes(dir, &file, "the same bytes"); + commit_initial(r, bundled, Some(plan), |_, _| {}); + deps.meta_now(dep).unwrap().url + }; + let (a, b) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap()); + let url_a = commit(a.path(), "react"); + let url_b = commit(b.path(), "react"); + assert_eq!(url_a, url_b, "one plan, one URL on every store"); + } + // Vite's sessionTimestamp guarantee, kept by the ledger: other bytes // under a URL an earlier session served (a cleared pre-bundle over an // edited node_modules) move every URL to a version of the new bytes, and @@ -2762,8 +2830,12 @@ mod tests { ) }; let (v, first, _, first_reloads) = commit("aaaa"); - assert_eq!(first, dep_url("react.mjs", &v)); - assert_eq!(first_reloads, 0); + assert_eq!( + first, + dep_url("react.mjs", &v), + "a confirmed plan keeps its version" + ); + assert_eq!(first_reloads, 0, "and nothing reloads"); let (_, second, persisted, reloads) = commit("bbbb"); assert_ne!(second, first, "a served URL never names other bytes"); assert_eq!( diff --git a/crates/oj_server/src/plugins/host.rs b/crates/oj_server/src/plugins/host.rs index 38b2e1124..8d90d4c74 100644 --- a/crates/oj_server/src/plugins/host.rs +++ b/crates/oj_server/src/plugins/host.rs @@ -1394,9 +1394,18 @@ impl PluginHost { } /// The host's reply with what the TracingFs window saw folded in, files - /// into `reads` and listings into `read_dirs`, each sorted and deduped - /// with the host's own buckets: one no plugin answered (no reply) read - /// nothing of its own. + /// into `reads` and listings into `read_dirs`, each sorted and deduped: + /// one no plugin answered (no reply) read nothing of its own. + /// + /// The host's own buckets are exact (AsyncLocalStorage follows the hook + /// that read); the engine's window is charged with every read of every + /// hook in flight, since the isolate interleaves them. A read some hook + /// made through the patched `node:fs` is that hook's (the host lists + /// them as claimed), so it is dropped from this transform's share of the + /// window: a bystander is never charged a concurrent scanner's thousand + /// files beside its own one read. What no hook claimed (a read through + /// a binding the patch cannot see, a named `node:fs` import bound before + /// it) stays charged to every transform in flight, the sound side. fn with_fs_reads( raw: Option, code: &str, @@ -1405,13 +1414,20 @@ impl PluginHost { let had_reply = raw.is_some(); let mut t = HostTransform::parse(raw, code); if had_reply { - let strings = |paths: Vec| { - paths.into_iter().map(|p| p.to_string_lossy().into_owned()) + let claimed: std::collections::HashSet<&str> = + t.claimed.iter().map(String::as_str).collect(); + let unclaimed = |paths: Vec| { + paths + .into_iter() + .map(|p| p.to_string_lossy().into_owned()) + .filter(|p| !claimed.contains(p.as_str())) + .collect::>() }; - t.reads.extend(strings(fs_reads.files)); + let (files, dirs) = (unclaimed(fs_reads.files), unclaimed(fs_reads.dirs)); + t.reads.extend(files); t.reads.sort(); t.reads.dedup(); - t.read_dirs.extend(strings(fs_reads.dirs)); + t.read_dirs.extend(dirs); t.read_dirs.sort(); t.read_dirs.dedup(); } @@ -3901,6 +3917,11 @@ pub struct HostTransform { /// Directories the transform hooks listed (`readDirs` plus the window's /// listings): an entry added or removed under one changes the output. pub read_dirs: Vec, + /// Paths any hook in flight read or listed through the host's patched + /// `node:fs` while this transform ran (`claimedFiles`, `claimedDirs`): + /// attributed exactly by the host, so the engine's shared window is not + /// charged with them here. + pub claimed: Vec, } impl HostTransform { @@ -3928,6 +3949,7 @@ impl HostTransform { } self.reads.extend(next.reads); self.read_dirs.extend(next.read_dirs); + self.claimed.extend(next.claimed); } /// A reply that is not the host's JSON is the code itself; none leaves @@ -3971,6 +3993,11 @@ impl HostTransform { chunks: emitted_chunks(&v), reads: str_array("readFiles"), read_dirs: str_array("readDirs"), + claimed: { + let mut c = str_array("claimedFiles"); + c.extend(str_array("claimedDirs")); + c + }, module_type: v .get("moduleType") .and_then(|n| n.as_str()) @@ -4129,3 +4156,71 @@ mod bare_import_tests { } } } + +#[cfg(test)] +mod fs_reads_attribution_tests { + use super::*; + use std::path::PathBuf; + + fn window(files: &[&str], dirs: &[&str]) -> oj_js::tracing_fs::Reads { + oj_js::tracing_fs::Reads { + files: files.iter().map(PathBuf::from).collect(), + dirs: dirs.iter().map(PathBuf::from).collect(), + } + } + + // Reads other hooks made through the patched `node:fs` while this one + // ran (claimed) are theirs: dropped from this transform's window share. + // A read nobody claimed (a named import's) stays, with its own. + #[test] + fn claimed_reads_leave_the_shared_window_and_unclaimed_ones_stay() { + let raw = r#"{"code":"x","readFiles":["/app/own.txt"],"readDirs":[], + "claimedFiles":["/app/own.txt","/app/scanner-1.txt","/app/scanner-2.txt"], + "claimedDirs":["/app/src"]}"# + .to_string(); + let t = PluginHost::with_fs_reads( + Some(raw), + "x", + window( + &[ + "/app/scanner-1.txt", + "/app/scanner-2.txt", + "/app/named-import.txt", + ], + &["/app/src"], + ), + ); + assert_eq!( + t.reads, + vec![ + "/app/named-import.txt".to_string(), + "/app/own.txt".to_string() + ] + ); + assert!(t.read_dirs.is_empty(), "{:?}", t.read_dirs); + } + + // Nothing claimed (reads through a binding the patch cannot see): the + // window is all there is, sorted and deduped. + #[test] + fn an_empty_bucket_takes_the_window() { + let raw = r#"{"code":"x","readFiles":[],"readDirs":[]}"#.to_string(); + let t = PluginHost::with_fs_reads( + Some(raw), + "x", + window(&["/app/b.txt", "/app/a.txt", "/app/a.txt"], &["/app/icons"]), + ); + assert_eq!( + t.reads, + vec!["/app/a.txt".to_string(), "/app/b.txt".to_string()] + ); + assert_eq!(t.read_dirs, vec!["/app/icons".to_string()]); + } + + // No reply at all (no plugin answered): nothing is charged. + #[test] + fn no_reply_reads_nothing() { + let t = PluginHost::with_fs_reads(None, "x", window(&["/app/a.txt"], &[])); + assert!(t.reads.is_empty() && t.read_dirs.is_empty()); + } +} diff --git a/crates/oj_server/src/preseed.rs b/crates/oj_server/src/preseed.rs index 8776ac4df..3e44c1cb4 100644 --- a/crates/oj_server/src/preseed.rs +++ b/crates/oj_server/src/preseed.rs @@ -17,7 +17,7 @@ const REPORT_FILE: &str = "optimize-env-report.json"; fn stamp_key() -> String { format!( "{}:{}", - env!("CARGO_PKG_VERSION"), + crate::tool_version(), blake3::hash(OPTIMIZE_ENV_JS.as_bytes()).to_hex() ) } diff --git a/crates/oj_server/src/store_remote.rs b/crates/oj_server/src/store_remote.rs index 8d51d77ce..e3b66195f 100644 --- a/crates/oj_server/src/store_remote.rs +++ b/crates/oj_server/src/store_remote.rs @@ -22,8 +22,13 @@ //! The remote is on the request path, so it is held to a budget: a fetch //! that fails OR takes longer than [`SLOW_FETCH`] is a strike, three strikes //! open the breaker, and an open breaker lets one probe through after -//! [`COOLDOWN`] to see whether the remote is back. Pushes queue behind a -//! bound and are dropped, not waited for, when the queue is full or the +//! [`COOLDOWN`] to see whether the remote is back. A fetch runs inside a +//! request handler, which hyper drops when the browser goes away, so the +//! probe is a lease: dropped without a verdict it is given back, and one +//! older than the fetch timeout is treated as given back. At most +//! [`MAX_IN_FLIGHT`] fetches are on the wire at once; an eager crawl waits +//! its turn rather than opening a thousand connections. Pushes queue behind +//! a bound and are dropped, not waited for, when the queue is full or the //! breaker is open. use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; @@ -46,6 +51,9 @@ pub(crate) const SLOW_FETCH: Duration = Duration::from_millis(500); pub(crate) const TRIPS_AFTER: usize = 3; /// How long an open breaker leaves the remote alone before one probe. pub(crate) const COOLDOWN: Duration = Duration::from_secs(30); +/// Fetches on the wire at once; the rest wait for a slot (or return at once +/// while the breaker is open). +pub(crate) const MAX_IN_FLIGHT: usize = 16; /// The push queue's bounds: entries waiting and the bytes they hold. pub(crate) const PUSH_QUEUE_ENTRIES: usize = 256; pub(crate) const PUSH_QUEUE_BYTES: usize = 64 * 1024 * 1024; @@ -57,6 +65,8 @@ pub(crate) const MAX_ENTRY_BYTES: usize = crate::store_server::MAX_AC_BYTES; pub(crate) struct Tuning { pub cooldown: Duration, pub slow_fetch: Duration, + /// A probe this old without a verdict no longer holds the slot. + pub probe_expiry: Duration, pub queue_entries: usize, pub queue_bytes: usize, } @@ -66,6 +76,7 @@ impl Default for Tuning { Tuning { cooldown: COOLDOWN, slow_fetch: SLOW_FETCH, + probe_expiry: FETCH_TIMEOUT, queue_entries: PUSH_QUEUE_ENTRIES, queue_bytes: PUSH_QUEUE_BYTES, } @@ -73,13 +84,58 @@ impl Default for Tuning { } /// The breaker: closed while the remote answers in budget, open after -/// [`TRIPS_AFTER`] strikes in a row, half-open (one probe in flight) once -/// the cooldown has passed. The probe's outcome closes or re-opens it. +/// [`TRIPS_AFTER`] strikes in a row, half-open (one probe in flight, started +/// at `probing`) once the cooldown has passed. The probe's outcome closes +/// or re-opens it; a probe dropped without one gives the slot back. #[derive(Default)] struct Breaker { strikes: usize, open_since: Option, - probing: bool, + probing: Option, +} + +impl Breaker { + /// Whether a probe holds the slot: one started, not concluded, and not + /// older than `expiry` (a handler dropped mid-await and never reporting + /// back must not hold the remote shut for the rest of the session). + fn probe_live(&self, expiry: Duration) -> bool { + self.probing.is_some_and(|since| since.elapsed() < expiry) + } +} + +/// A fetch's admission to the wire: whether it is the probe, and the +/// promise of a verdict. Dropped without one (hyper drops a handler's +/// future when the client disconnects), it gives the probe slot back. +struct Admission<'a> { + store: &'a RemoteStore, + probe: Option, + concluded: bool, +} + +impl Admission<'_> { + fn struck(mut self, why: &str) { + self.concluded = true; + self.store.struck(why, self.probe.is_some()); + } + + fn answered_in_budget(mut self) { + self.concluded = true; + self.store.answered_in_budget(); + } +} + +impl Drop for Admission<'_> { + fn drop(&mut self) { + if self.concluded { + return; + } + if let Some(probe) = self.probe { + let mut b = self.store.breaker.lock().unwrap_or_else(|e| e.into_inner()); + if b.probing == Some(probe) { + b.probing = None; + } + } + } } pub struct RemoteStore { @@ -89,6 +145,8 @@ pub struct RemoteStore { client: reqwest::Client, tuning: Tuning, breaker: Mutex, + /// The fetch slots: [`MAX_IN_FLIGHT`] at once. + in_flight: tokio::sync::Semaphore, /// Fire-and-forget pushes run on their own small thread to keep the /// cache writer thread off the network. The channel is bounded by /// entries; `queued_bytes` bounds it by size. @@ -141,6 +199,7 @@ impl RemoteStore { client, tuning, breaker: Mutex::new(Breaker::default()), + in_flight: tokio::sync::Semaphore::new(MAX_IN_FLIGHT), push_tx, queued_bytes: AtomicUsize::new(0), dropped: AtomicUsize::new(0), @@ -176,20 +235,39 @@ impl RemoteStore { Some(store) } - /// Whether the remote is left alone right now. An open breaker whose - /// cooldown has passed answers `false` exactly once: that caller is the - /// probe, and its result decides for everyone else. + /// Whether the remote is left alone right now: the breaker is open and + /// either the cooldown has not passed or a probe holds the slot. A look + /// only; [`Self::admit`] takes the slot. pub(crate) fn tripped(&self) -> bool { - let mut b = self.breaker.lock().unwrap_or_else(|e| e.into_inner()); + let b = self.breaker.lock().unwrap_or_else(|e| e.into_inner()); match b.open_since { None => false, - Some(_) if b.probing => true, + Some(_) if b.probe_live(self.tuning.probe_expiry) => true, + Some(since) => since.elapsed() < self.tuning.cooldown, + } + } + + /// A fetch's admission, or None while the remote is left alone. An + /// open breaker whose cooldown has passed admits exactly one caller as + /// the probe (until it concludes, is dropped, or expires), and its + /// verdict decides for everyone else. + fn admit(&self) -> Option> { + let mut b = self.breaker.lock().unwrap_or_else(|e| e.into_inner()); + let probe = match b.open_since { + None => None, + Some(_) if b.probe_live(self.tuning.probe_expiry) => return None, Some(since) if since.elapsed() >= self.tuning.cooldown => { - b.probing = true; - false + let now = Instant::now(); + b.probing = Some(now); + Some(now) } - Some(_) => true, - } + Some(_) => return None, + }; + Some(Admission { + store: self, + probe, + concluded: false, + }) } /// Whether the breaker is open, without touching the probe. @@ -201,14 +279,20 @@ impl RemoteStore { .is_some() } - fn struck(&self, why: &str) { + /// A strike against the remote, by the probe or by an ordinary fetch. + fn struck(&self, why: &str, probe: bool) { let mut b = self.breaker.lock().unwrap_or_else(|e| e.into_inner()); - if b.probing { + if probe { // The probe failed: another cooldown, quietly. - b.probing = false; + b.probing = None; b.open_since = Some(Instant::now()); return; } + if b.open_since.is_some() { + // Admitted before the breaker opened, back after: it has nothing + // to add, and must not take the probe's slot or its verdict. + return; + } b.strikes += 1; if b.strikes >= TRIPS_AFTER && b.open_since.is_none() { b.open_since = Some(Instant::now()); @@ -254,9 +338,14 @@ impl RemoteStore { /// Read-through for a module entry this client's key computation missed /// locally. Returns the STORED (ws:/mono:) form; the caller rehomes it. pub async fn fetch_module(&self, key: &str) -> Option { + // Looked at before waiting for a slot, so a tripped remote costs a + // caller nothing, and admitted after, since the breaker may have + // opened meanwhile. if self.tripped() { return None; } + let _slot = self.in_flight.acquire().await.ok()?; + let admission = self.admit()?; let url = format!("{}/v1/ac/modules/{key}", self.base); let started = Instant::now(); let answered = async { @@ -268,7 +357,7 @@ impl RemoteStore { } .await; let Some(resp) = answered else { - self.struck("did not answer"); + admission.struck("did not answer"); return None; }; let body = if resp.status() == reqwest::StatusCode::OK { @@ -279,9 +368,9 @@ impl RemoteStore { // The clock covers the body too: a hit that trickles in is as slow // as a miss that does. if started.elapsed() > self.tuning.slow_fetch { - self.struck("answered slowly"); + admission.struck("answered slowly"); } else { - self.answered_in_budget(); + admission.answered_in_budget(); } let module: CachedModule = serde_json::from_slice(&body?).ok()?; // The admission gate, applied to what the WIRE delivered: nothing @@ -480,16 +569,22 @@ mod breaker_tests { puts: AtomicUsize, put_delay_ms: AtomicU64, gets: AtomicUsize, + /// GETs being answered right now, and the most there ever were. + in_flight: AtomicUsize, + most_in_flight: AtomicUsize, } async fn stand_in() -> (String, Arc) { let stub = Arc::new(Stub::default()); async fn on_get(State(s): State>) -> axum::response::Response { s.gets.fetch_add(1, Ordering::Relaxed); + let now = s.in_flight.fetch_add(1, Ordering::Relaxed) + 1; + s.most_in_flight.fetch_max(now, Ordering::Relaxed); let delay = s.delay_ms.load(Ordering::Relaxed); if delay > 0 { tokio::time::sleep(Duration::from_millis(delay)).await; } + s.in_flight.fetch_sub(1, Ordering::Relaxed); match s.hit_bytes.load(Ordering::Relaxed) { 0 => StatusCode::NOT_FOUND.into_response(), n => { @@ -636,6 +731,7 @@ mod breaker_tests { slow_fetch: Duration::from_millis(20), queue_entries: 4, queue_bytes: body_len * 3, + ..Tuning::default() }; // The breaker is open (slow misses tripped it): the pusher takes @@ -714,4 +810,123 @@ mod breaker_tests { Some(1024) ); } + + // The probe runs inside a request handler, and hyper drops the handler + // when the browser gives up on the request. A probe dropped mid-await + // gives the slot back, so the remote is asked again after the cooldown + // instead of being held shut for the rest of the session. + #[tokio::test(flavor = "multi_thread")] + async fn a_probe_dropped_mid_flight_gives_the_slot_back() { + let (base, stub) = stand_in().await; + let tuning = Tuning { + cooldown: Duration::from_millis(200), + slow_fetch: Duration::from_millis(20), + ..Tuning::default() + }; + let remote = RemoteStore::connect_with(&base, None, false, tuning).unwrap(); + let key = "ab".repeat(32); + stub.delay_ms.store(60, Ordering::Relaxed); + for _ in 0..TRIPS_AFTER { + assert_eq!(remote.fetch_module(&key).await, None); + } + assert!(remote.tripped()); + tokio::time::sleep(Duration::from_millis(250)).await; + assert!(!remote.tripped(), "the cooldown has passed"); + + // The probe goes out and its handler is dropped before the remote + // answers. + stub.delay_ms.store(2000, Ordering::Relaxed); + let probe = remote.fetch_module(&key); + assert!( + tokio::time::timeout(Duration::from_millis(100), probe) + .await + .is_err(), + "the probe was still waiting on the remote" + ); + assert_eq!( + stub.gets.load(Ordering::Relaxed), + TRIPS_AFTER + 1, + "the probe was sent" + ); + assert!( + !remote.tripped(), + "a dropped probe does not hold the breaker shut" + ); + + // The remote is quick again: the next fetch is the probe, and it + // closes the breaker. + stub.delay_ms.store(0, Ordering::Relaxed); + stub.hit_bytes.store(4, Ordering::Relaxed); + assert_eq!( + remote.fetch_module(&key).await.map(|m| m.code), + Some("xxxx".into()) + ); + assert_eq!(stub.gets.load(Ordering::Relaxed), TRIPS_AFTER + 2); + assert!(!remote.tripped()); + } + + // A probe that is neither concluded nor dropped (its future parked + // somewhere for good) expires after the fetch timeout, and the slot is + // free again. + #[tokio::test(flavor = "multi_thread")] + async fn a_probe_without_a_verdict_expires() { + let (base, stub) = stand_in().await; + let tuning = Tuning { + cooldown: Duration::from_millis(100), + slow_fetch: Duration::from_millis(20), + probe_expiry: Duration::from_millis(150), + ..Tuning::default() + }; + let remote = RemoteStore::connect_with(&base, None, false, tuning).unwrap(); + let key = "ab".repeat(32); + stub.delay_ms.store(60, Ordering::Relaxed); + for _ in 0..TRIPS_AFTER { + assert_eq!(remote.fetch_module(&key).await, None); + } + tokio::time::sleep(Duration::from_millis(120)).await; + let held = remote.admit().expect("the cooldown has passed"); + assert!(held.probe.is_some(), "this admission is the probe"); + assert!( + remote.tripped(), + "while the probe is out, everyone else waits" + ); + assert!(remote.admit().is_none()); + tokio::time::sleep(Duration::from_millis(200)).await; + assert!(!remote.tripped(), "an expired probe holds nothing"); + stub.delay_ms.store(0, Ordering::Relaxed); + stub.hit_bytes.store(4, Ordering::Relaxed); + assert!(remote.fetch_module(&key).await.is_some()); + assert!(!remote.tripped()); + std::mem::forget(held); + } + + // An eager crawl asks for many modules at once; the wire sees at most + // MAX_IN_FLIGHT of them at a time, and every one is still answered. + #[tokio::test(flavor = "multi_thread")] + async fn fetches_in_flight_are_bounded() { + let (base, stub) = stand_in().await; + let tuning = Tuning { + slow_fetch: Duration::from_secs(30), + ..Tuning::default() + }; + let remote = RemoteStore::connect_with(&base, None, false, tuning).unwrap(); + stub.delay_ms.store(50, Ordering::Relaxed); + stub.hit_bytes.store(4, Ordering::Relaxed); + // Spawned all at once (collected, not awaited one by one). + let fetches: Vec<_> = (0..50u8) + .map(|i| { + let remote = Arc::clone(&remote); + tokio::spawn( + async move { remote.fetch_module(&format!("{i:02x}").repeat(32)).await }, + ) + }) + .collect(); + for fetch in fetches { + assert!(fetch.await.unwrap().is_some()); + } + assert_eq!(stub.gets.load(Ordering::Relaxed), 50); + let most = stub.most_in_flight.load(Ordering::Relaxed); + assert!(most <= MAX_IN_FLIGHT, "{most} fetches in flight at once"); + assert!(most > 1, "the fetches did run concurrently: {most}"); + } } diff --git a/crates/oj_server/src/store_server.rs b/crates/oj_server/src/store_server.rs index b1dbe30c2..9c40b8b68 100644 --- a/crates/oj_server/src/store_server.rs +++ b/crates/oj_server/src/store_server.rs @@ -12,7 +12,7 @@ //! HEAD /v1/cas/{blake3} //! PUT /v1/cas/{blake3} write-once; body must match its digest //! DELETE /v1/cas/{blake3} operator purge (write token): 204, or 404 -//! POST /v1/cas/missing {"digests":[..]} -> {"missing":[..]} +//! POST /v1/cas/missing {"digests":[..]} -> {"missing":[..]} (at most 4096) //! ``` //! //! Write-once entries and split read/write tokens are the CREEP lesson @@ -53,6 +53,14 @@ pub const MAX_AC_BYTES: usize = 16 * 1024 * 1024; pub const DEFAULT_MAX_BYTES: u64 = 10 * 1024 * 1024 * 1024; /// A file is served in reads of this size, never loaded whole. const STREAM_CHUNK: usize = 256 * 1024; +/// The most digests one `POST /v1/cas/missing` looks up: each is a stat, +/// and reads may be public, so the list is bounded like a body is. +pub const MAX_MISSING_DIGESTS: usize = 4096; +/// A `.tmp-` file under `ac/` or `cas/` older than this at boot is a PUT +/// that crashed mid-write: swept before the quota counts the directory. A +/// younger one may be a PUT of another server over the same directory and +/// is left alone (and counted, since it holds disk). +const TMP_SWEEP_MIN_AGE: std::time::Duration = std::time::Duration::from_secs(60 * 60); pub struct StoreServer { dir: PathBuf, @@ -65,14 +73,17 @@ pub struct StoreServer { } /// A server over `dir` with its tokens (`None` read token: public reads; -/// `None` write token: writes refused) and its byte quota. Counts what `dir` -/// already holds, so a quota holds across restarts. +/// `None` write token: writes refused) and its byte quota. Sweeps the stale +/// temp files of crashed PUTs, then counts what `dir` already holds, so a +/// quota holds across restarts and a crash costs no quota for good. pub(crate) fn state( dir: PathBuf, read_token: Option, write_token: Option, max_bytes: u64, ) -> Arc { + sweep_stale_temps(&dir.join("ac")); + sweep_stale_temps(&dir.join("cas")); let used = bytes_under(&dir.join("ac")) + bytes_under(&dir.join("cas")); Arc::new(StoreServer { dir, @@ -113,6 +124,34 @@ impl StoreServer { } } +/// Whether `name` is a write-once aside file (`.tmp-`). +fn is_temp_name(name: &str) -> bool { + name.contains(".tmp-") +} + +/// Removes every aside file under `dir` older than [`TMP_SWEEP_MIN_AGE`]. +fn sweep_stale_temps(dir: &Path) { + for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() { + let path = entry.path(); + if path.is_dir() { + sweep_stale_temps(&path); + continue; + } + if !is_temp_name(&entry.file_name().to_string_lossy()) { + continue; + } + let stale = entry + .metadata() + .and_then(|m| m.modified()) + .ok() + .and_then(|m| m.elapsed().ok()) + .is_none_or(|age| age >= TMP_SWEEP_MIN_AGE); + if stale { + let _ = std::fs::remove_file(&path); + } + } +} + /// The size of every regular file under `dir` (0 for a dir that is not there). fn bytes_under(dir: &Path) -> u64 { let mut total = 0; @@ -246,19 +285,25 @@ fn admissible_entry(body: &[u8]) -> bool { /// Write-once publish: the bytes go to a temp file of this request's own and /// are hard-linked into place, so a reader never sees a partial entry and /// two writers of one key cannot mix: the link either creates the name or -/// finds it taken (409), whatever the other writer is doing meanwhile. +/// finds it taken (409), whatever the other writer is doing meanwhile. The +/// temp name carries a random part (`integrity::temp_tag`), so nothing else +/// with write access to the directory can plant a link at it beforehand. fn write_once(path: &Path, bytes: &[u8]) -> Result<(), StatusCode> { + let tmp = path.with_extension(format!("tmp-{}", oj_cache::integrity::temp_tag())); + write_once_via(path, &tmp, bytes) +} + +/// [`write_once`] with the temp path chosen: the temp file is created new, +/// never opened through whatever is at that path already. +fn write_once_via(path: &Path, tmp: &Path, bytes: &[u8]) -> Result<(), StatusCode> { if path.exists() { return Err(StatusCode::CONFLICT); } let parent = path.parent().ok_or(StatusCode::INTERNAL_SERVER_ERROR)?; std::fs::create_dir_all(parent).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; - static SEQ: AtomicU64 = AtomicU64::new(0); - let seq = SEQ.fetch_add(1, Ordering::Relaxed); - let tmp = path.with_extension(format!("tmp-{}-{seq}", std::process::id())); - std::fs::write(&tmp, bytes).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; - let linked = std::fs::hard_link(&tmp, path); - let _ = std::fs::remove_file(&tmp); + oj_cache::integrity::write_new(tmp, bytes).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + let linked = std::fs::hard_link(tmp, path); + let _ = std::fs::remove_file(tmp); match linked { Ok(()) => Ok(()), Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Err(StatusCode::CONFLICT), @@ -482,6 +527,9 @@ async fn cas_missing( let Ok(req) = serde_json::from_slice::(&body) else { return StatusCode::BAD_REQUEST.into_response(); }; + if req.digests.len() > MAX_MISSING_DIGESTS { + return StatusCode::BAD_REQUEST.into_response(); + } let mut missing: Vec<&String> = Vec::new(); for digest in &req.digests { let present = match cas_path(&s, digest) { @@ -945,6 +993,118 @@ mod quota_tests { let (status, _) = call(&app, Method::HEAD, &blob_uri, Some("r"), Vec::new()).await; assert_eq!(status, StatusCode::NOT_FOUND); } + + fn set_mtime(path: &Path, t: std::time::SystemTime) { + let f = std::fs::OpenOptions::new().append(true).open(path).unwrap(); + f.set_times(std::fs::FileTimes::new().set_modified(t)) + .unwrap(); + } + + // A PUT that crashed mid-write leaves its temp file. At boot an old one + // is swept before the quota counts the directory; a fresh one may be + // another server's PUT in flight and is kept. + #[tokio::test] + async fn stale_temps_of_crashed_puts_are_swept_at_boot_and_not_counted() { + let dir = tempfile::tempdir().unwrap(); + let module = entry("export const x = 1;"); + { + let app = router(state( + dir.path().to_path_buf(), + None, + Some("w".into()), + u64::MAX, + )); + let uri = format!("/v1/ac/modules/{}", key(1)); + let (status, _) = call(&app, Method::PUT, &uri, Some("w"), module.clone()).await; + assert_eq!(status, StatusCode::CREATED); + } + let shard = dir.path().join("ac/modules/01"); + let old = shard.join(format!("{}.tmp-1-0-abc", key(2))); + std::fs::write(&old, vec![b'x'; 1000]).unwrap(); + set_mtime( + &old, + std::time::SystemTime::now() - std::time::Duration::from_secs(2 * 60 * 60), + ); + let cas = dir.path().join("cas/ab"); + std::fs::create_dir_all(&cas).unwrap(); + let old_blob = cas.join(format!("{}.tmp-1-1-abc", key(0xab))); + std::fs::write(&old_blob, vec![b'y'; 500]).unwrap(); + set_mtime( + &old_blob, + std::time::SystemTime::now() - std::time::Duration::from_secs(2 * 60 * 60), + ); + let fresh = shard.join(format!("{}.tmp-1-2-abc", key(3))); + std::fs::write(&fresh, vec![b'z'; 10]).unwrap(); + let s = state(dir.path().to_path_buf(), None, Some("w".into()), u64::MAX); + assert!(!old.exists(), "the old temp is swept"); + assert!(!old_blob.exists(), "under cas/ too"); + assert!(fresh.exists(), "a fresh temp is kept"); + assert_eq!(s.used_bytes(), module.len() as u64 + 10); + } + + // The temp file of a write is created new: a link planted at its name + // is refused, and its target is never written through. + #[test] + fn a_link_planted_at_the_temp_name_is_not_followed() { + let dir = tempfile::tempdir().unwrap(); + let victim = dir.path().join("victim"); + std::fs::write(&victim, b"precious").unwrap(); + let path = dir + .path() + .join("ac/modules/01") + .join(format!("{}.json", key(1))); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + let tmp = path.with_extension("tmp-planted"); + std::os::unix::fs::symlink(&victim, &tmp).unwrap(); + assert_eq!( + write_once_via(&path, &tmp, b"poison"), + Err(StatusCode::INTERNAL_SERVER_ERROR) + ); + assert_eq!(std::fs::read(&victim).unwrap(), b"precious"); + assert!(!path.exists(), "nothing was linked into place"); + // The production name has a random part: pid, counter and tag. + let tag = oj_cache::integrity::temp_tag(); + assert_eq!(tag.split('-').count(), 3, "{tag}"); + assert!(write_once(&path, b"honest").is_ok()); + assert_eq!(std::fs::read(&path).unwrap(), b"honest"); + } + + // The digest list of a missing query is bounded: one over the cap is a + // bad request, the cap itself is answered. + #[tokio::test] + async fn the_missing_query_takes_at_most_the_cap() { + let dir = tempfile::tempdir().unwrap(); + let app = router(state(dir.path().to_path_buf(), None, None, u64::MAX)); + let digests = |n: usize| -> Vec { + let list: Vec = (0..n).map(|i| format!("{i:064x}")).collect(); + serde_json::json!({ "digests": list }) + .to_string() + .into_bytes() + }; + let (status, body) = call( + &app, + Method::POST, + "/v1/cas/missing", + None, + digests(MAX_MISSING_DIGESTS), + ) + .await; + assert_eq!(status, StatusCode::OK); + let answer: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert_eq!( + answer["missing"].as_array().unwrap().len(), + MAX_MISSING_DIGESTS + ); + let (status, _) = call( + &app, + Method::POST, + "/v1/cas/missing", + None, + digests(MAX_MISSING_DIGESTS + 1), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST); + } } #[cfg(test)] diff --git a/crates/oj_server/src/tests.rs b/crates/oj_server/src/tests.rs index 9bd299ae2..3cdecbadc 100644 --- a/crates/oj_server/src/tests.rs +++ b/crates/oj_server/src/tests.rs @@ -3496,6 +3496,47 @@ fn module_cache_salt_covers_the_roots_place_in_its_workspace() { // manifest and entry files are in the salt by content. A registry install // reached through a link (pnpm's `.pnpm`) is the lockfile's. #[cfg(unix)] +// A package linked into the WORKSPACE's node_modules (npm and yarn +// workspaces hoist it above the app) is salted like one linked into the +// app's own. +#[cfg(unix)] +#[test] +fn module_cache_salt_covers_packages_linked_above_the_app() { + let mono = std::env::temp_dir().join(format!("oj-salt-hoisted-link-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&mono); + let app = mono.join("app"); + std::fs::create_dir_all(mono.join("node_modules")).unwrap(); + std::fs::create_dir_all(mono.join("packages/plugin")).unwrap(); + std::fs::create_dir_all(&app).unwrap(); + std::fs::write(app.join("package.json"), br#"{"name":"app"}"#).unwrap(); + std::fs::write(app.join("package-lock.json"), br#"{"lockfileVersion":3}"#).unwrap(); + std::fs::write( + mono.join("packages/plugin/package.json"), + br#"{"name":"plugin","main":"index.js"}"#, + ) + .unwrap(); + std::fs::write(mono.join("packages/plugin/index.js"), b"1").unwrap(); + let settings = oj_resolver::ResolveSettings { + alias: vec![], + ..salt_settings(&app) + }; + let base = module_cache_config_salt(&app, &settings, None); + std::os::unix::fs::symlink( + mono.join("packages/plugin"), + mono.join("node_modules/plugin"), + ) + .unwrap(); + let linked = module_cache_config_salt(&app, &settings, None); + assert_ne!(base, linked, "a hoisted link joins the salt"); + std::fs::write(mono.join("packages/plugin/index.js"), b"2").unwrap(); + assert_ne!( + linked, + module_cache_config_salt(&app, &settings, None), + "its entry file by content" + ); + let _ = std::fs::remove_dir_all(&mono); +} + #[test] fn module_cache_salt_covers_linked_packages_by_content() { let root = salt_fixture("linked"); diff --git a/crates/oj_server/tests/dev/store.rs b/crates/oj_server/tests/dev/store.rs index 7ea44fe31..11943b8b1 100644 --- a/crates/oj_server/tests/dev/store.rs +++ b/crates/oj_server/tests/dev/store.rs @@ -10,6 +10,7 @@ use std::path::PathBuf; use std::time::Duration; +use crate::listen::{close, frame_matching, is_reload}; use crate::App; /// An app whose entry carries `marker`, so its store entries are this @@ -812,6 +813,104 @@ export default { }; "#; +// A module hard-invalidated by an edit this session compiles under a key +// that carries the process's invalidation counter: no other session +// computes it, so the entry stays in memory. The next session compiles the +// edited file cold and persists it under the key everyone computes. The +// socket's frame says the watcher has invalidated the module: a request +// ahead of the watcher reads the edited source and compiles it under the +// key every session computes, which is the cold case. +#[tokio::test(flavor = "multi_thread")] +async fn an_in_session_edits_recompile_is_not_persisted_but_the_next_sessions_is() { + let before = "inv-before-store"; + let after = "inv-after-store"; + let app = App::new(&[ + ( + "index.html", + "", + ), + ( + "src/main.ts", + &format!("export const main = \"{before}\";\n"), + ), + ]); + { + let server = crate::serve(dev(&app)).await; + let listening = server.listen().await; + let (mut socket, _) = server.ws(listening.addr, "/__ws", None).await; + assert!(server.text("/src/main.ts").await.contains(before)); + wait_for_entries(before, 1).await; + app.write(&[( + "src/main.ts", + &format!("export const main = \"{after}\";\n"), + )]); + frame_matching(&mut socket, "the edit's reload frame", is_reload).await; + close(socket).await; + assert!( + server.text("/src/main.ts").await.contains(after), + "the edit serves once the watcher has it" + ); + tokio::time::sleep(Duration::from_millis(500)).await; + assert!( + shared_entries(after).is_empty(), + "an edit's recompile was persisted under this session's key" + ); + } + let server = crate::serve(dev(&app)).await; + assert!(server.text("/src/main.ts").await.contains(after)); + wait_for_entries(after, 1).await; +} + +// A transform that read hundreds of files (a scanner over the tree) makes +// an entry whose warm hit would cost as much as the compile: it stays in +// memory, served all the same. +#[tokio::test(flavor = "multi_thread")] +async fn an_entry_with_hundreds_of_trace_rows_stays_in_memory() { + let marker = "many-rows-store"; + let mut files: Vec<(String, String)> = (0..300) + .map(|i| (format!("side/f{i}.txt"), format!("{i}\n"))) + .collect(); + files.push(( + "vite.config.mjs".into(), + r#"import fs from "node:fs"; +const here = new URL(".", import.meta.url).pathname; +export default { + plugins: [{ + name: "scanner", + transform(code, id) { + if (!id.split("?")[0].endsWith("/src/main.ts")) return null; + let n = 0; + for (const f of fs.readdirSync(here + "side")) n += fs.readFileSync(here + "side/" + f, "utf8").length; + return { code: code.replace("__N__", String(n)), map: null }; + }, + }], +}; +"# + .into(), + )); + files.push(( + "index.html".into(), + "".into(), + )); + files.push(( + "src/main.ts".into(), + format!("export const n = __N__; export const m = \"{marker}\";\n"), + )); + let refs: Vec<(&str, &str)> = files + .iter() + .map(|(a, b)| (a.as_str(), b.as_str())) + .collect(); + let app = App::new(&refs); + let server = crate::serve(dev(&app)).await; + let body = server.text("/src/main.ts").await; + assert!(body.contains(marker) && !body.contains("__N__"), "{body}"); + tokio::time::sleep(Duration::from_millis(700)).await; + assert!( + shared_entries(marker).is_empty(), + "an entry with hundreds of rows was persisted" + ); +} + // A side file written while the transform that read it ran (here by the // transform itself; an editor's save in the same instant is the same race) // is digested as it is now, next to output built from what it was. Such an @@ -1052,3 +1151,200 @@ async fn a_side_file_read_by_url_and_edited_between_sessions_is_a_miss() { "the entry built from the old file was served:\n{second}" ); } + +// CSS tracing + +/// `rel`, requested as the page's stylesheet: the served module carries +/// the sheet's text. +fn sheet_app(marker: &str, rel: &str, body: &str, files: &[(&str, &str)]) -> App { + let app = App::new(&[ + ( + "index.html", + &format!(""), + ), + (rel, &format!("{body}\n.{marker} {{ margin: 0; }}\n")), + ]); + app.write(files); + app +} + +// A Sass `@use "theme"` answered by a package was looked for beside the +// importer first; those candidates are inputs of the entry (digest-less +// rows). A partial created at one of them between sessions shadows the +// package, so the next session is a miss and serves the partial, as a +// server without the store does. +#[tokio::test(flavor = "multi_thread")] +async fn a_sass_partial_added_that_shadows_a_module_is_a_miss() { + let marker = "sass-shadow-store"; + let app = sheet_app( + marker, + "src/styles/main.scss", + "@use \"theme\";\n.t { color: theme.$c; }", + &[("node_modules/theme/_index.scss", "$c: red;\n")], + ); + settle(&app, "node_modules/theme/_index.scss"); + let session = || async { + let server = crate::serve(dev(&app)).await; + server.text("/src/styles/main.scss").await + }; + let first = session().await; + assert!(first.contains("red"), "{first}"); + wait_for_entries(marker, 1).await; + assert!(session().await.contains("red"), "unchanged inputs hit"); + app.write(&[("src/styles/_theme.scss", "$c: blue;\n")]); + let second = session().await; + // The dev compile prints the color as `#00f`. + assert!( + (second.contains("#00f") || second.contains("blue")) && !second.contains("red"), + "the entry built before the partial shadowed the package was served:\n{second}" + ); +} + +// The same for a CSS `@import "x"`: `x` and `x.css` beside the importer +// are tried before the package, so a sheet created there between sessions +// is a miss that serves the local sheet. +#[tokio::test(flavor = "multi_thread")] +async fn a_css_sheet_added_that_shadows_a_package_import_is_a_miss() { + let marker = "css-shadow-store"; + let app = sheet_app( + marker, + "src/index.css", + "@import \"x\";", + &[ + ( + "node_modules/x/package.json", + r#"{"name":"x","style":"x.css"}"#, + ), + ("node_modules/x/x.css", ".pkg { color: red; }\n"), + ], + ); + settle(&app, "node_modules/x/x.css"); + let session = || async { + let server = crate::serve(dev(&app)).await; + server.text("/src/index.css").await + }; + let first = session().await; + assert!(first.contains(".pkg"), "{first}"); + wait_for_entries(marker, 1).await; + assert!(session().await.contains(".pkg"), "unchanged inputs hit"); + app.write(&[("src/x.css", ".local { color: blue; }\n")]); + let second = session().await; + assert!( + second.contains(".local") && !second.contains(".pkg"), + "the entry built before the local sheet shadowed the package was served:\n{second}" + ); +} + +/// A PostCSS config whose plugin injects a side file's text without +/// declaring it (postcss-url's inlining, a home-grown plugin): the read is +/// the engine's TracingFs to see. +const SIDE_FILE_POSTCSS: &str = r#"import { readFileSync } from "node:fs"; +const here = new URL(".", import.meta.url).pathname; +export default { + plugins: [{ + postcssPlugin: "side", + Once(root) { + root.append(`.${readFileSync(here + "side.txt", "utf8").trim()} { margin: 0; }`); + }, + }], +}; +"#; + +// A file a PostCSS plugin read on its own is an input of the sheet: edited +// between sessions, the entry is a miss and the new text is served. +#[tokio::test(flavor = "multi_thread")] +async fn a_file_a_postcss_plugin_read_and_edited_between_sessions_is_a_miss() { + crate::require_fixture!("postcss"); + let marker = "postcss-side-store"; + let app = sheet_app( + marker, + "src/index.css", + ".a { color: red; }", + &[ + ( + "package.json", + r#"{"name":"postcss-side","version":"1.0.0"}"#, + ), + ("postcss.config.mjs", SIDE_FILE_POSTCSS), + ("side.txt", "dark\n"), + ], + ); + app.link_fixture("postcss"); + settle(&app, "side.txt"); + let session = || async { + let server = crate::serve(dev(&app)).await; + server.text("/src/index.css").await + }; + let first = session().await; + assert!(first.contains(".dark"), "{first}"); + wait_for_entries(marker, 1).await; + assert!(session().await.contains(".dark"), "unchanged inputs hit"); + app.write(&[("side.txt", "light\n")]); + let second = session().await; + assert!( + second.contains(".light") && !second.contains(".dark"), + "the entry built from the old side file was served:\n{second}" + ); +} + +/// A PostCSS config whose plugin declares a `dir-dependency` and bakes the +/// count of the files under it in, as an icon-sprite plugin does. +const DIR_DEPENDENCY_POSTCSS: &str = r#"import { readdirSync } from "node:fs"; +const here = new URL(".", import.meta.url).pathname; +export default { + plugins: [{ + postcssPlugin: "icons", + Once(root, { result }) { + const count = readdirSync(here + "icons").filter((n) => n.endsWith(".svg")).length; + root.append(`.icons-${count} { margin: 0; }`); + result.messages.push({ type: "dir-dependency", plugin: "icons", dir: here + "icons", glob: "*.svg", parent: result.opts.from }); + }, + }], +}; +"#; + +// A declared `dir-dependency` is a listing row for its directory, not the +// files matched at compile time: a file added under it between sessions is +// a miss, and the next session counts it. +#[tokio::test(flavor = "multi_thread")] +async fn a_file_added_under_a_postcss_dir_dependency_between_sessions_is_a_miss() { + crate::require_fixture!("postcss"); + let marker = "postcss-dir-dep-store"; + let app = sheet_app( + marker, + "src/index.css", + ".a { color: red; }", + &[ + ( + "package.json", + r#"{"name":"postcss-dir-dep","version":"1.0.0"}"#, + ), + ("postcss.config.mjs", DIR_DEPENDENCY_POSTCSS), + ("icons/a.svg", ""), + ], + ); + app.link_fixture("postcss"); + settle(&app, "icons"); + settle(&app, "icons/a.svg"); + let session = || async { + let server = crate::serve(dev(&app)).await; + server.text("/src/index.css").await + }; + let first = session().await; + assert!(first.contains(".icons-1"), "{first}"); + let entries = wait_for_entries(marker, 1).await; + // The row is the directory's listing (stored workspace-relative), with + // the matched file's row beside it. + let entry = std::fs::read_to_string(&entries[0]).unwrap(); + assert!( + entry.contains("\"dir:ws:icons\"") && entry.contains("\"ws:icons/a.svg\""), + "no listing row for the declared directory:\n{entry}" + ); + assert!(session().await.contains(".icons-1"), "unchanged inputs hit"); + app.write(&[("icons/b.svg", "")]); + let second = session().await; + assert!( + second.contains(".icons-2"), + "the entry with the old listing was served:\n{second}" + ); +} diff --git a/e2e/unit/plugin-host-read-trace.test.mjs b/e2e/unit/plugin-host-read-trace.test.mjs index 474ff7193..fabd77dae 100644 --- a/e2e/unit/plugin-host-read-trace.test.mjs +++ b/e2e/unit/plugin-host-read-trace.test.mjs @@ -64,6 +64,9 @@ test("plugin-host reports the files a transform read or checked and the director }; for (const [what, p] of Object.entries(expected)) assert.ok(files.includes(p), `${what}: ${p} in ${files}`); assert.ok(!files.includes(path.join(fx.root, "transforms.log")), `a write-only open is not an input: ${files}`); + // Every read through the patch is claimed for the engine window's sake. + for (const p of files) assert.ok(out.claimedFiles.includes(p), `claimed: ${p} in ${out.claimedFiles}`); + for (const d of out.readDirs) assert.ok(out.claimedDirs.includes(d), `claimed dir: ${d}`); for (const p of [...files, ...out.readDirs]) assert.ok(path.isAbsolute(p), `absolute: ${p}`); } finally { host.close();