Unverified Commit 7984e4ab authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

turbopack-cli: add --persistent-caching flag for filesystem-backed cache (#91657)

### What?

Adds `--persistent-caching` and `--cache-dir` CLI flags to `turbopack
dev` and `turbopack build` in the standalone `turbopack-cli` crate.

### Why?

The standalone `turbopack-cli` binary (used independently of `next`) had
no way to opt into the filesystem-backed persistent cache that the
`next-napi-bindings` integration already supports. Without this,
repeated builds always start cold — every incremental run re-computes
the full task graph from scratch.

### How?

**`build.rs` (new):** A Cargo build script that uses `vergen-gitcl` to
emit `VERGEN_GIT_DESCRIBE` and `VERGEN_GIT_DIRTY` as compile-time env
vars. These are used to key the cache by git version, matching the same
approach as `next-napi-bindings`. The build script embeds the dirty
state at compile time rather than runtime to avoid a git subprocess on
every startup.

The dirty-state caching tradeoff (explained in the build script
comment): there's a narrow edge case where the tree becomes newly dirty
without triggering a Cargo rebuild, but in practice this is safe — if
nothing in the crate changed, the binary is semantically equivalent to a
clean build, so using the HEAD hash as the cache key is correct.

**`arguments.rs`:** Two new flags on `CommonArguments` (shared by both
`dev` and `build` subcommands):
- `--persistent-caching` — opt-in flag to enable the filesystem cache
- `--cache-dir <PATH>` — override the cache directory (defaults to
`.turbopack/cache` in the project root)

**`dev/mod.rs` and `build/mod.rs`:**
- The `Backend` type alias changes from
`TurboTasksBackend<NoopBackingStorage>` to
`TurboTasksBackend<Either<TurboBackingStorage, NoopBackingStorage>>` to
unify the type without dynamic dispatch.
- When `--persistent-caching` is set: initializes `TurboBackingStorage`
via `turbo_backing_storage()`, selects
`StorageMode::ReadWriteOnShutdown` for CI/short sessions and
`StorageMode::ReadWrite` for interactive dev, and prints a warning if
the cache was invalidated on startup.
- When not set: falls back to `noop_backing_storage()` — identical
behavior to before.
- Respects the `TURBO_ENGINE_READ_ONLY` env var to force read-only mode.

---------
Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
Co-authored-by: 's avatarClaude <noreply@anthropic.com>
parent 7d451fe0
...@@ -9896,6 +9896,7 @@ dependencies = [ ...@@ -9896,6 +9896,7 @@ dependencies = [
"codspeed-criterion-compat", "codspeed-criterion-compat",
"console-subscriber", "console-subscriber",
"dunce", "dunce",
"either",
"futures", "futures",
"owo-colors", "owo-colors",
"regex", "regex",
...@@ -9927,6 +9928,7 @@ dependencies = [ ...@@ -9927,6 +9928,7 @@ dependencies = [
"turbopack-nodejs", "turbopack-nodejs",
"turbopack-resolve", "turbopack-resolve",
"turbopack-trace-utils", "turbopack-trace-utils",
"vergen-gitcl",
"webbrowser", "webbrowser",
] ]
......
...@@ -42,6 +42,7 @@ bincode = { workspace = true } ...@@ -42,6 +42,7 @@ bincode = { workspace = true }
clap = { workspace = true, features = ["derive", "env"] } clap = { workspace = true, features = ["derive", "env"] }
console-subscriber = { workspace = true, optional = true } console-subscriber = { workspace = true, optional = true }
dunce = { workspace = true } dunce = { workspace = true }
either = { workspace = true }
futures = { workspace = true } futures = { workspace = true }
owo-colors = { workspace = true } owo-colors = { workspace = true }
rustc-hash = { workspace = true } rustc-hash = { workspace = true }
...@@ -75,6 +76,10 @@ turbopack-resolve = { workspace = true } ...@@ -75,6 +76,10 @@ turbopack-resolve = { workspace = true }
turbopack-trace-utils = { workspace = true } turbopack-trace-utils = { workspace = true }
webbrowser = { workspace = true } webbrowser = { workspace = true }
[build-dependencies]
anyhow = { workspace = true }
vergen-gitcl = { workspace = true }
[dev-dependencies] [dev-dependencies]
criterion = { workspace = true, features = ["async_tokio"] } criterion = { workspace = true, features = ["async_tokio"] }
regex = { workspace = true } regex = { workspace = true }
......
...@@ -72,6 +72,8 @@ fn bench_small_apps(c: &mut Criterion) { ...@@ -72,6 +72,8 @@ fn bench_small_apps(c: &mut Criterion) {
full_stats: false, full_stats: false,
target: None, target: None,
worker_threads: None, worker_threads: None,
persistent_caching: false,
cache_dir: None,
}, },
no_sourcemap: false, no_sourcemap: false,
no_minify: false, no_minify: false,
......
use std::env;
fn main() -> anyhow::Result<()> {
println!("cargo:rerun-if-env-changed=CI");
let is_ci = env::var("CI").is_ok_and(|value| !value.is_empty());
// We use the git dirty state to disable filesystem cache (filesystem cache relies on a
// commit hash to be safe). One tradeoff of this is that we must invalidate the rust build more
// often.
//
// This invalidates the build if any untracked files change. That's sufficient for the case
// where we transition from dirty to clean.
//
// There's an edge-case here where the repository could be newly dirty, but we can't know
// because our build hasn't been invalidated, since the untracked files weren't untracked last
// time we ran. That will cause us to incorrectly report ourselves as clean.
//
// However, in practice that shouldn't be much of an issue: If no other dependency of this
// top-level crate has changed (which would've triggered our rebuild), then the resulting binary
// must be equivalent to a clean build anyways. Therefore, filesystem cache using the HEAD
// commit hash as a version is okay.
let git = vergen_gitcl::GitclBuilder::default()
.dirty(/* include_untracked */ true)
.describe(
/* tags */ true,
/* dirty */ !is_ci, // suppress the dirty suffix in CI
/* matches */ Some("v[0-9]*"), // find the last version tag
)
.build()?;
vergen_gitcl::Emitter::default()
.add_instructions(&git)?
.fail_on_error()
.emit()?;
Ok(())
}
...@@ -95,6 +95,16 @@ pub struct CommonArguments { ...@@ -95,6 +95,16 @@ pub struct CommonArguments {
/// Number of worker threads to use for parallel processing /// Number of worker threads to use for parallel processing
#[clap(long)] #[clap(long)]
pub worker_threads: Option<usize>, pub worker_threads: Option<usize>,
/// Enable filesystem-backed persistent caching.
/// Cache is stored at `<cache-dir>/<git-version>`.
#[clap(long)]
pub persistent_caching: bool,
/// Directory to store the persistent cache.
/// Defaults to `.turbopack/cache` relative to the project directory.
#[clap(long)]
pub cache_dir: Option<PathBuf>,
// Enable experimental garbage collection with the provided memory limit in // Enable experimental garbage collection with the provided memory limit in
// MB. // MB.
// #[clap(long)] // #[clap(long)]
......
...@@ -6,12 +6,14 @@ use std::{ ...@@ -6,12 +6,14 @@ use std::{
}; };
use anyhow::{Context, Result, bail}; use anyhow::{Context, Result, bail};
use either::Either;
use rustc_hash::FxHashSet; use rustc_hash::FxHashSet;
use tracing::Instrument; use tracing::Instrument;
use turbo_rcstr::RcStr; use turbo_rcstr::RcStr;
use turbo_tasks::{ResolvedVc, TransientInstance, TryJoinIterExt, TurboTasks, Vc, apply_effects}; use turbo_tasks::{ResolvedVc, TransientInstance, TryJoinIterExt, TurboTasks, Vc, apply_effects};
use turbo_tasks_backend::{ use turbo_tasks_backend::{
BackendOptions, NoopBackingStorage, TurboTasksBackend, noop_backing_storage, BackendOptions, GitVersionInfo, NoopBackingStorage, StartupCacheState, StorageMode,
TurboBackingStorage, TurboTasksBackend, noop_backing_storage, turbo_backing_storage,
}; };
use turbo_tasks_fs::FileSystem; use turbo_tasks_fs::FileSystem;
use turbo_unix_path::join_path; use turbo_unix_path::join_path;
...@@ -55,7 +57,7 @@ use crate::{ ...@@ -55,7 +57,7 @@ use crate::{
}, },
}; };
type Backend = TurboTasksBackend<NoopBackingStorage>; type Backend = TurboTasksBackend<Either<TurboBackingStorage, NoopBackingStorage>>;
pub struct TurbopackBuildBuilder { pub struct TurbopackBuildBuilder {
turbo_tasks: Arc<TurboTasks<Backend>>, turbo_tasks: Arc<TurboTasks<Backend>>,
...@@ -523,14 +525,57 @@ pub async fn build(args: &BuildArguments) -> Result<()> { ...@@ -523,14 +525,57 @@ pub async fn build(args: &BuildArguments) -> Result<()> {
root_dir, root_dir,
} = normalize_dirs(&args.common.dir, &args.common.root)?; } = normalize_dirs(&args.common.dir, &args.common.root)?;
let tt = TurboTasks::new(TurboTasksBackend::new( let is_ci = std::env::var("CI").is_ok_and(|v| !v.is_empty());
BackendOptions { let is_short_session = true; // build sessions are always short
dependency_tracking: false,
storage_mode: None, let tt = if args.common.persistent_caching {
..Default::default() let version_info = GitVersionInfo {
}, describe: env!("VERGEN_GIT_DESCRIBE"),
noop_backing_storage(), dirty: option_env!("CI").is_none_or(|v| v.is_empty())
)); && env!("VERGEN_GIT_DIRTY") == "true",
};
let cache_dir = args
.common
.cache_dir
.clone()
.unwrap_or_else(|| PathBuf::from(&*project_dir).join(".turbopack/cache"));
let (backing_storage, cache_state) =
turbo_backing_storage(&cache_dir, &version_info, is_ci, is_short_session)?;
let storage_mode = if std::env::var("TURBO_ENGINE_READ_ONLY").is_ok() {
StorageMode::ReadOnly
} else if is_ci || is_short_session {
StorageMode::ReadWriteOnShutdown
} else {
StorageMode::ReadWrite
};
let tt = TurboTasks::new(TurboTasksBackend::new(
BackendOptions {
dependency_tracking: false,
storage_mode: Some(storage_mode),
..Default::default()
},
Either::Left(backing_storage),
));
if let StartupCacheState::Invalidated { reason_code } = cache_state {
eprintln!(
"warn - Turbopack cache was invalidated{}",
reason_code
.as_deref()
.map(|r| format!(": {r}"))
.unwrap_or_default()
);
}
tt
} else {
TurboTasks::new(TurboTasksBackend::new(
BackendOptions {
dependency_tracking: false,
storage_mode: None,
..Default::default()
},
Either::Right(noop_backing_storage()),
))
};
let mut builder = TurbopackBuildBuilder::new(tt.clone(), project_dir, root_dir) let mut builder = TurbopackBuildBuilder::new(tt.clone(), project_dir, root_dir)
.log_detail(args.common.log_detail) .log_detail(args.common.log_detail)
......
...@@ -9,6 +9,7 @@ use std::{ ...@@ -9,6 +9,7 @@ use std::{
}; };
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use either::Either;
use owo_colors::OwoColorize; use owo_colors::OwoColorize;
use rustc_hash::FxHashSet; use rustc_hash::FxHashSet;
use turbo_rcstr::{RcStr, rcstr}; use turbo_rcstr::{RcStr, rcstr};
...@@ -18,7 +19,8 @@ use turbo_tasks::{ ...@@ -18,7 +19,8 @@ use turbo_tasks::{
util::{FormatBytes, FormatDuration}, util::{FormatBytes, FormatDuration},
}; };
use turbo_tasks_backend::{ use turbo_tasks_backend::{
BackendOptions, NoopBackingStorage, TurboTasksBackend, noop_backing_storage, BackendOptions, GitVersionInfo, NoopBackingStorage, StartupCacheState, StorageMode,
TurboBackingStorage, TurboTasksBackend, noop_backing_storage, turbo_backing_storage,
}; };
use turbo_tasks_fs::FileSystem; use turbo_tasks_fs::FileSystem;
use turbo_tasks_malloc::TurboMalloc; use turbo_tasks_malloc::TurboMalloc;
...@@ -54,7 +56,7 @@ use crate::{ ...@@ -54,7 +56,7 @@ use crate::{
pub(crate) mod web_entry_source; pub(crate) mod web_entry_source;
type Backend = TurboTasksBackend<NoopBackingStorage>; type Backend = TurboTasksBackend<Either<TurboBackingStorage, NoopBackingStorage>>;
pub struct TurbopackDevServerBuilder { pub struct TurbopackDevServerBuilder {
turbo_tasks: Arc<TurboTasks<Backend>>, turbo_tasks: Arc<TurboTasks<Backend>>,
...@@ -374,13 +376,56 @@ pub async fn start_server(args: &DevArguments) -> Result<()> { ...@@ -374,13 +376,56 @@ pub async fn start_server(args: &DevArguments) -> Result<()> {
root_dir, root_dir,
} = normalize_dirs(&args.common.dir, &args.common.root)?; } = normalize_dirs(&args.common.dir, &args.common.root)?;
let tt = TurboTasks::new(TurboTasksBackend::new( let is_ci = std::env::var("CI").is_ok_and(|v| !v.is_empty());
BackendOptions { let is_short_session = is_ci;
storage_mode: None,
..Default::default() let tt = if args.common.persistent_caching {
}, let version_info = GitVersionInfo {
noop_backing_storage(), describe: env!("VERGEN_GIT_DESCRIBE"),
)); dirty: option_env!("CI").is_none_or(|v| v.is_empty())
&& env!("VERGEN_GIT_DIRTY") == "true",
};
let cache_dir = args
.common
.cache_dir
.clone()
.unwrap_or_else(|| PathBuf::from(&*project_dir).join(".turbopack/cache"));
let (backing_storage, cache_state) =
turbo_backing_storage(&cache_dir, &version_info, is_ci, is_short_session)?;
let storage_mode = if std::env::var("TURBO_ENGINE_READ_ONLY").is_ok() {
StorageMode::ReadOnly
} else if is_ci || is_short_session {
StorageMode::ReadWriteOnShutdown
} else {
StorageMode::ReadWrite
};
let tt = TurboTasks::new(TurboTasksBackend::new(
BackendOptions {
storage_mode: Some(storage_mode),
..Default::default()
},
Either::Left(backing_storage),
));
if let StartupCacheState::Invalidated { reason_code } = cache_state {
eprintln!(
"{} - Turbopack cache was invalidated{}",
"warn ".yellow(),
reason_code
.as_deref()
.map(|r| format!(": {r}"))
.unwrap_or_default()
);
}
tt
} else {
TurboTasks::new(TurboTasksBackend::new(
BackendOptions {
storage_mode: None,
..Default::default()
},
Either::Right(noop_backing_storage()),
))
};
let tt_clone = tt.clone(); let tt_clone = tt.clone();
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment