Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(cli): share injected source pairs between process inject and upload (#91427)

Catalin13dc107a02b4
diff --git a/cli/.sampo/changesets/sourcemap-process-shared-pairs.md b/cli/.sampo/changesets/sourcemap-process-shared-pairs.md
new file mode 100644
index 000000000000..b7a10085b42d
--- /dev/null
+++ b/cli/.sampo/changesets/sourcemap-process-shared-pairs.md
@@ -0,0 +1,5 @@
+---
+cargo/posthog-cli: patch
+---
+
+Fix a race in `sourcemap process`: the source pairs are now read from disk once, injected, and the same in-memory pairs are uploaded. Previously inject and upload each re-walked the directory roots, so a bundler writing into the scanned directory mid-run (e.g. Turbopack's background filesystem-cache flush on Next.js 16.3+) could hand the upload pass chunks the inject pass never stamped, aborting the whole run with "Chunk ID not found". That error now names the offending file and says how to recover. `--delete-after` cleanup no longer fails the build when a file vanished or was replaced after upload: such pairs are skipped with a warning, and a replaced file's artifacts are left untouched instead of being stripped or deleted. Overlapping selection roots now process each file once instead of stamping it repeatedly. The "injecting selection" log line is bounded instead of printing every selected path, since a large stdin-provided selection used to produce a log line big enough to kill the CLI when stderr was a non-blocking pipe (e.g. spawned from Node.js).
diff --git a/cli/src/commands.rs b/cli/src/commands.rs
index 92f7e39ebd55..2ba89434d28a 100644
--- a/cli/src/commands.rs
+++ b/cli/src/commands.rs
@@ -421,8 +421,20 @@ impl Cli {
inject_args.release.clone(),
std::iter::empty(),
)?;
- crate::sourcemaps::plain::inject::inject(&inject_args, release.as_ref())?;
- crate::sourcemaps::plain::upload::upload(&upload_args, release.as_ref())?;
+ // Hand the pairs inject wrote straight to upload, instead of letting
+ // upload re-walk the directory: a bundler writing into it mid-run
+ // (e.g. Turbopack's background filesystem-cache flush on Next.js
+ // 16.3+) would otherwise give upload files inject never stamped,
+ // aborting the build with "Chunk ID not found" (posthog-js#4667).
+ let pairs =
+ crate::sourcemaps::plain::inject::inject(&inject_args, release.as_ref())?;
+ let file_selection = upload_args.file_selection.clone();
+ crate::sourcemaps::plain::upload::upload_pairs(
+ &upload_args,
+ pairs,
+ release.as_ref(),
+ file_selection,
+ )?;
}
},
Commands::Dsym { cmd } => match cmd {
diff --git a/cli/src/sourcemaps/args.rs b/cli/src/sourcemaps/args.rs
index c2708fcf4450..f6682e71177e 100644
--- a/cli/src/sourcemaps/args.rs
+++ b/cli/src/sourcemaps/args.rs
@@ -54,9 +54,47 @@ impl TryFrom<FileSelectionArgs> for FileSelection {
}
}
+/// Caps on the selection roots Display renders. A stdin-provided selection can hold
+/// thousands of paths, and printing them all produces a log line larger than the pipe
+/// buffer (16-64 KiB depending on the platform), which kills the process with EAGAIN
+/// when stderr is a non-blocking pipe (e.g. inherited from a Node.js parent, as the
+/// PostHog bundler plugins do). The count cap keeps the line readable; the byte budget
+/// bounds it even when the individual paths are long.
+const MAX_DISPLAYED_ROOTS: usize = 8;
+const MAX_DISPLAY_BYTES: usize = 1024;
+
impl Display for FileSelectionArgs {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(f, "{:?}", self.directory)
+ let mut rendered = String::from("[");
+ let mut shown = 0usize;
+ for path in self.directory.iter().take(MAX_DISPLAYED_ROOTS) {
+ let mut formatted = format!("{path:?}");
+ // Truncate rather than skip, so even a single pathological path stays inside
+ // the budget: Debug escaping can inflate a path well past PATH_MAX.
+ if formatted.len() > MAX_DISPLAY_BYTES {
+ let mut cut = MAX_DISPLAY_BYTES;
+ while !formatted.is_char_boundary(cut) {
+ cut -= 1;
+ }
+ formatted.truncate(cut);
+ formatted.push_str("...");
+ }
+ if shown > 0 && rendered.len() + formatted.len() + 2 > MAX_DISPLAY_BYTES {
+ break;
+ }
+ if shown > 0 {
+ rendered.push_str(", ");
+ }
+ rendered.push_str(&formatted);
+ shown += 1;
+ }
+ rendered.push(']');
+ let omitted = self.directory.len() - shown;
+ if omitted > 0 {
+ write!(f, "{rendered} and {omitted} more")
+ } else {
+ write!(f, "{rendered}")
+ }
}
}
@@ -262,6 +300,58 @@ mod tests {
parsed
}
+ #[test]
+ fn display_is_bounded_for_large_selections() {
+ let args = FileSelectionArgs {
+ directory: (0..10_000)
+ .map(|i| PathBuf::from(format!("static/chunks/chunk-{i}.js")))
+ .collect(),
+ stdin: false,
+ include: Vec::new(),
+ exclude: Vec::new(),
+ };
+
+ let rendered = args.to_string();
+
+ // Keep the rendered selection far under the smallest pipe buffer (16 KiB): a
+ // single oversized log line kills the CLI when stderr is a non-blocking pipe.
+ assert!(rendered.len() < 2048, "rendered {} bytes", rendered.len());
+ assert!(rendered.ends_with("and 9992 more"), "rendered: {rendered}");
+ }
+
+ #[test]
+ fn display_truncates_a_single_oversized_path() {
+ let args = FileSelectionArgs {
+ directory: vec![PathBuf::from("a".repeat(50_000))],
+ stdin: false,
+ include: Vec::new(),
+ exclude: Vec::new(),
+ };
+
+ let rendered = args.to_string();
+
+ assert!(rendered.len() < 2048, "rendered {} bytes", rendered.len());
+ assert!(rendered.contains("..."), "rendered: {rendered}");
+ }
+
+ #[test]
+ fn display_is_bounded_for_long_paths() {
+ let long_segment = "a".repeat(300);
+ let args = FileSelectionArgs {
+ directory: (0..10_000)
+ .map(|i| PathBuf::from(format!("{long_segment}/chunk-{i}.js")))
+ .collect(),
+ stdin: false,
+ include: Vec::new(),
+ exclude: Vec::new(),
+ };
+
+ let rendered = args.to_string();
+
+ assert!(rendered.len() < 2048, "rendered {} bytes", rendered.len());
+ assert!(rendered.ends_with("more"), "rendered: {rendered}");
+ }
+
fn make_args(name: Option<&str>, version: Option<&str>, build: Option<&str>) -> ReleaseArgs {
ReleaseArgs {
name: name.map(String::from),
diff --git a/cli/src/sourcemaps/hermes/inject.rs b/cli/src/sourcemaps/hermes/inject.rs
index 71e876b1405a..71bb2eed5485 100644
--- a/cli/src/sourcemaps/hermes/inject.rs
+++ b/cli/src/sourcemaps/hermes/inject.rs
@@ -16,7 +16,8 @@ pub fn inject(args: &InjectArgs) -> Result<()> {
// A React Native app reports its release from the app metadata it already sends. Event mode
// therefore injects chunk ids and nothing else here. A release id in the chunk would do
// nothing, because the bundle compiles to Hermes bytecode and no SDK reads the global.
- inject_impl(args, is_metro_bundle, None, EventReleaseSource::AppMetadata)
+ inject_impl(args, is_metro_bundle, None, EventReleaseSource::AppMetadata)?;
+ Ok(())
}
pub fn is_metro_bundle(entry: &DirEntry) -> bool {
diff --git a/cli/src/sourcemaps/inject.rs b/cli/src/sourcemaps/inject.rs
index 286f41217958..e0857eb75532 100644
--- a/cli/src/sourcemaps/inject.rs
+++ b/cli/src/sourcemaps/inject.rs
@@ -67,7 +67,7 @@ pub fn inject_impl(
matcher: impl Fn(&DirEntry) -> bool + 'static,
existing_release: Option<&Release>,
event_release_source: EventReleaseSource,
-) -> Result<()> {
+) -> Result<Vec<SourcePair>> {
let InjectArgs {
file_selection,
public_path_prefix,
@@ -127,7 +127,7 @@ pub fn inject_impl(
pair.save()?;
}
info!("injecting done");
- Ok(())
+ Ok(pairs)
}
/// Event-mode injection (`--release-mode=event`): content-addressed chunk ids plus an optional
@@ -544,4 +544,56 @@ mod tests {
assert!(format!("{error:#}").contains("Release fields are incomplete"));
}
+
+ #[test]
+ fn inject_impl_returns_the_injected_pairs() {
+ let dir = tempfile::tempdir().unwrap();
+ let js_path = dir.path().join("chunk.js");
+ fs::write(
+ &js_path,
+ "console.log(1);\n//# sourceMappingURL=chunk.js.map\n",
+ )
+ .unwrap();
+ fs::write(
+ dir.path().join("chunk.js.map"),
+ r#"{"version":3,"sources":[],"names":[],"mappings":""}"#,
+ )
+ .unwrap();
+
+ let args = InjectArgs {
+ file_selection: FileSelectionArgs {
+ directory: vec![dir.path().to_path_buf()],
+ stdin: false,
+ include: Vec::new(),
+ exclude: Vec::new(),
+ },
+ public_path_prefix: None,
+ release: ReleaseArgs {
+ name: None,
+ version: None,
+ build: None,
+ info_plist: None,
+ skip_release_on_fail: true,
+ },
+ release_mode: ReleaseMode::Event,
+ };
+
+ // AppMetadata skips release resolution, so nothing here touches the network.
+ let pairs = inject_impl(
+ &args,
+ is_javascript_file,
+ None,
+ EventReleaseSource::AppMetadata,
+ )
+ .unwrap();
+
+ assert_eq!(pairs.len(), 1);
+ assert!(pairs[0].get_chunk_id().is_some());
+ // The returned in-memory pair matches what reached disk, so a consumer (the
+ // process command's upload) can act on it without re-reading the directory.
+ assert_eq!(
+ fs::read_to_string(&js_path).unwrap(),
+ pairs[0].source.inner.content
+ );
+ }
}
diff --git a/cli/src/sourcemaps/plain/inject.rs b/cli/src/sourcemaps/plain/inject.rs
index 4ad32ba7f9d1..7ea300f5b828 100644
--- a/cli/src/sourcemaps/plain/inject.rs
+++ b/cli/src/sourcemaps/plain/inject.rs
@@ -5,10 +5,13 @@ use walkdir::DirEntry;
use crate::{
api::releases::Release,
invocation_context::context,
- sourcemaps::inject::{inject_impl, EventReleaseSource, InjectArgs},
+ sourcemaps::{
+ inject::{inject_impl, EventReleaseSource, InjectArgs},
+ source_pairs::SourcePair,
+ },
};
-pub fn inject(args: &InjectArgs, existing_release: Option<&Release>) -> Result<()> {
+pub fn inject(args: &InjectArgs, existing_release: Option<&Release>) -> Result<Vec<SourcePair>> {
context().capture_command_invoked("sourcemap_inject");
args.validate()?;
inject_impl(
diff --git a/cli/src/sourcemaps/plain/upload.rs b/cli/src/sourcemaps/plain/upload.rs
index ea63895dfe9c..83e63587cccc 100644
--- a/cli/src/sourcemaps/plain/upload.rs
+++ b/cli/src/sourcemaps/plain/upload.rs
@@ -1,4 +1,7 @@
use std::{
+ collections::{HashMap, HashSet},
+ fs::OpenOptions,
+ io::{Read, Seek, SeekFrom, Write},
path::{Path, PathBuf},
time::Instant,
};
@@ -25,12 +28,12 @@ use crate::{
args::{
FileSelectionArgs, ReleaseArgs, ReleaseMode, UploadConcurrencyArgs, UploadConflictArgs,
},
- content::MinifiedSourceFile,
+ content::{MinifiedSourceFile, SourceMapFile},
inject::get_release_for_maps,
plain::inject::{is_javascript_file, is_stylesheet_file},
source_pairs::{read_pairs, SourcePair},
},
- utils::files::{delete_files, FileSelection},
+ utils::files::{content_hash, FileSelection, SourceFile},
};
#[derive(clap::Args, Clone)]
@@ -87,29 +90,44 @@ pub fn upload_cmd(args: &Args) -> Result<()> {
}
pub fn upload(args: &Args, existing_release: Option<&Release>) -> Result<()> {
- if args.conflict.skip_on_conflict_ignored(args.release_mode) {
- warn!(
- "--skip-on-conflict is ignored with --release-mode=event. Every chunk's content changes with each release, so skipping conflicts would leave the previous release id in place. Overwriting instead."
- );
- }
-
// Resolve stdin once so the JavaScript upload and CSS cleanup scan the same paths.
let file_selection = args.file_selection.clone().resolve_stdin()?;
let selection = FileSelection::try_from(file_selection.clone())?;
- let mut pairs = read_pairs(
+ let pairs = read_pairs(
selection.into_iter().filter(is_javascript_file),
&args.public_path_prefix,
);
+ upload_pairs(args, pairs, existing_release, file_selection)
+}
- let sourcemap_paths = pairs
- .iter()
- .map(|pair| pair.sourcemap.inner.path.clone())
- .collect::<Vec<_>>();
- let source_paths = pairs
- .iter()
- .map(|pair| pair.source.inner.path.clone())
- .collect::<Vec<_>>();
+/// Upload `pairs`, then run the `--delete-after` cleanup scoped to `file_selection`
+/// (already stdin-resolved). `process` calls this directly with the pairs inject just
+/// wrote, so upload acts on the exact files inject stamped - in the state it left them
+/// in - even when a bundler keeps writing into the scanned directory in the background
+/// (e.g. Turbopack's filesystem-cache flush on Next.js 16.3+, posthog-js#4667).
+pub fn upload_pairs(
+ args: &Args,
+ mut pairs: Vec<SourcePair>,
+ existing_release: Option<&Release>,
+ file_selection: FileSelectionArgs,
+) -> Result<()> {
+ if args.conflict.skip_on_conflict_ignored(args.release_mode) {
+ warn!(
+ "--skip-on-conflict is ignored with --release-mode=event. Every chunk's content changes with each release, so skipping conflicts would leave the previous release id in place. Overwriting instead."
+ );
+ }
+
+ // Fingerprinting re-serializes and hashes every pair, which is not free for large
+ // maps - skip it when nothing gets cleaned up.
+ let cleanup_targets = if args.delete_after {
+ pairs
+ .iter()
+ .map(cleanup_target)
+ .collect::<Result<Vec<_>>>()?
+ } else {
+ Vec::new()
+ };
info!("Found {} chunks to upload", pairs.len());
// Reuse the pre-resolved release if available, otherwise fetch or create one. Skipped entirely
@@ -220,29 +238,17 @@ pub fn upload(args: &Args, existing_release: Option<&Release>) -> Result<()> {
pair.sourcemap.inner.path.display()
);
}
- let stylesheet_source_paths = stylesheet_pairs
- .iter()
- .map(|pair| pair.source.inner.path.clone())
- .collect::<Vec<_>>();
- let stylesheet_sourcemap_paths = stylesheet_pairs
+ let stylesheet_targets = stylesheet_pairs
.iter()
- .map(|pair| pair.sourcemap.inner.path.clone())
- .collect::<Vec<_>>();
-
- remove_sourcemap_references(
- source_paths
+ .map(cleanup_target)
+ .collect::<Result<Vec<_>>>()?;
+ cleanup_pairs(
+ cleanup_targets
.into_iter()
- .chain(stylesheet_source_paths)
+ .chain(stylesheet_targets)
.collect(),
)
- .context("While stripping sourcemap references")?;
- delete_files(
- sourcemap_paths
- .into_iter()
- .chain(stylesheet_sourcemap_paths)
- .collect(),
- )
- .context("While deleting sourcemaps")?;
+ .context("While cleaning up uploaded sourcemaps")?;
}
Ok(())
@@ -284,24 +290,402 @@ fn path_is_within_roots(path: &Path, roots: &[PathBuf]) -> bool {
.is_ok_and(|path| roots.iter().any(|root| path.starts_with(root)))
}
-fn remove_sourcemap_references(paths: Vec<PathBuf>) -> Result<()> {
- for path in paths {
- let mut source = MinifiedSourceFile::load(&path)
- .with_context(|| format!("Failed to read source file: {}", path.display()))?;
- if source.remove_sourcemap_reference() {
- source
- .save()
- .with_context(|| format!("Failed to save source file: {}", path.display()))?;
+/// One processed pair's on-disk artifacts, fingerprinted at the moment the pair was
+/// read for upload. Maps are hashed over their canonical JSON serialization, so the
+/// comparison is stable across whitespace and key order.
+struct CleanupTarget {
+ source_path: PathBuf,
+ sourcemap_path: PathBuf,
+ source_hash: String,
+ sourcemap_hash: String,
+}
+
+fn cleanup_target(pair: &SourcePair) -> Result<CleanupTarget> {
+ let canonical_map = serde_json::to_string(&pair.sourcemap.inner.content)?;
+ Ok(CleanupTarget {
+ source_path: pair.source.inner.path.clone(),
+ sourcemap_path: pair.sourcemap.inner.path.clone(),
+ source_hash: content_hash([pair.source.inner.content.as_bytes()]),
+ sourcemap_hash: content_hash([canonical_map.as_bytes()]),
+ })
+}
+
+/// Strip the sourceMappingURL reference from each verified source, then delete the
+/// maps that are safe to delete. A map can be shared by several chunks, so deletion
+/// needs the outcome of every source first: a skipped source is (or was replaced by)
+/// an artifact that may still reference the map. Skips warn instead of failing the
+/// build - the upload already succeeded, and a bundler that keeps writing into the
+/// directory (posthog-js#4667) may have removed or replaced files since they were read.
+fn cleanup_pairs(targets: Vec<CleanupTarget>) -> Result<()> {
+ // Maps are grouped by canonical path: distinct lexical paths or symlink aliases can
+ // name the same file (deletion then operates on the first selected alias; further
+ // aliases of an already-deleted map are left in place). A map shared by several chunks may only be deleted once every
+ // source referencing it was verified - a skipped source is (or was replaced by) an
+ // artifact that may still point at the map. Each sharing pair holds its own
+ // in-memory copy of the map (default-mode injection stamps a different chunk id
+ // into each copy, and the last save wins on disk), so the fingerprint of any of
+ // them identifies the map as ours.
+ let map_key = |path: &Path| path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
+ let mut maps: HashMap<PathBuf, MapCleanup> = HashMap::new();
+ for target in &targets {
+ let verified = strip_verified_source(target)?;
+ let entry = maps
+ .entry(map_key(&target.sourcemap_path))
+ .or_insert_with(|| MapCleanup {
+ path: target.sourcemap_path.clone(),
+ allowed_hashes: HashSet::new(),
+ blocked: false,
+ });
+ entry.allowed_hashes.insert(target.sourcemap_hash.clone());
+ entry.blocked |= !verified;
+ }
+ for map in maps.values() {
+ if map.blocked {
+ warn!(
+ "Skipping sourcemap deletion for {}: a source referencing it was skipped",
+ map.path.display()
+ );
+ continue;
}
+ delete_verified_map(&map.path, &map.allowed_hashes)?;
}
Ok(())
}
+struct MapCleanup {
+ path: PathBuf,
+ allowed_hashes: HashSet<String>,
+ blocked: bool,
+}
+
+/// Verify the source against its fingerprint and strip its sourceMappingURL reference.
+/// Returns whether the source was verified. Verification reads through a read-only
+/// handle, so a source that needs no stripping (e.g. one discovered through a sibling
+/// map, with no sourceMappingURL comment) never requires write access. When a
+/// reference does need stripping, the file is reopened writable and re-verified
+/// through that handle before writing: a bundler replacing the file in between (write
+/// new, then rename over the path) leaves the handle pointing at the old inode, so the
+/// replacement is never overwritten with stale bytes.
+fn strip_verified_source(target: &CleanupTarget) -> Result<bool> {
+ let bytes = match std::fs::read(&target.source_path) {
+ Ok(bytes) => bytes,
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
+ warn!(
+ "Skipping cleanup for {}: the file no longer exists",
+ target.source_path.display()
+ );
+ return Ok(false);
+ }
+ Err(e) => {
+ return Err(e).context(format!(
+ "Failed to read source file: {}",
+ target.source_path.display()
+ ))
+ }
+ };
+ if content_hash([&bytes]) != target.source_hash {
+ warn!(
+ "Skipping cleanup for {}: the file changed since it was uploaded",
+ target.source_path.display()
+ );
+ return Ok(false);
+ }
+ // The fingerprint matched the uploaded content, so the bytes are valid UTF-8.
+ let content = String::from_utf8(bytes).with_context(|| {
+ format!(
+ "Source file is not valid UTF-8: {}",
+ target.source_path.display()
+ )
+ })?;
+ let mut source = MinifiedSourceFile {
+ inner: SourceFile::new(target.source_path.clone(), content),
+ };
+ if !source.remove_sourcemap_reference() {
+ return Ok(true);
+ }
+
+ let mut file = match OpenOptions::new()
+ .read(true)
+ .write(true)
+ .open(&target.source_path)
+ {
+ Ok(file) => file,
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
+ warn!(
+ "Skipping cleanup for {}: the file no longer exists",
+ target.source_path.display()
+ );
+ return Ok(false);
+ }
+ Err(e) => {
+ return Err(e).context(format!(
+ "Failed to open source file for writing: {}",
+ target.source_path.display()
+ ))
+ }
+ };
+ let mut current = Vec::new();
+ file.read_to_end(&mut current).with_context(|| {
+ format!(
+ "Failed to read source file: {}",
+ target.source_path.display()
+ )
+ })?;
+ if content_hash([&current]) != target.source_hash {
+ warn!(
+ "Skipping cleanup for {}: the file changed since it was uploaded",
+ target.source_path.display()
+ );
+ return Ok(false);
+ }
+ let mut write = || -> std::io::Result<()> {
+ file.set_len(0)?;
+ file.seek(SeekFrom::Start(0))?;
+ file.write_all(source.inner.content.as_bytes())
+ };
+ write().with_context(|| {
+ format!(
+ "Failed to save source file: {}",
+ target.source_path.display()
+ )
+ })?;
+ Ok(true)
+}
+
+/// Delete the map only if it is still one of the copies that was uploaded. The file is
+/// renamed aside first: rename is atomic, so the verification and the final removal
+/// operate on the exact same object, and a replacement the bundler drops at the
+/// original path afterwards is never touched. A staged file that fails verification is
+/// renamed back.
+fn delete_verified_map(path: &Path, allowed_hashes: &HashSet<String>) -> Result<()> {
+ let Some(file_name) = path.file_name().and_then(|name| name.to_str()) else {
+ return Ok(());
+ };
+ let staged = path.with_file_name(format!(
+ "{}.{}.posthog-delete",
+ file_name,
+ std::process::id()
+ ));
+ match std::fs::rename(path, &staged) {
+ Ok(()) => {}
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
+ Err(e) => return Err(e).context(format!("Failed to delete sourcemap: {}", path.display())),
+ }
+ let matches = SourceMapFile::load(&staged)
+ .ok()
+ .and_then(|map| serde_json::to_string(&map.inner.content).ok())
+ .is_some_and(|canonical| allowed_hashes.contains(&content_hash([canonical.as_bytes()])));
+ if matches {
+ std::fs::remove_file(&staged)
+ .with_context(|| format!("Failed to delete sourcemap: {}", path.display()))?;
+ } else {
+ warn!(
+ "Skipping sourcemap deletion for {}: the map changed since it was uploaded",
+ path.display()
+ );
+ restore_staged(&staged, path)?;
+ }
+ Ok(())
+}
+
+/// Put a staged file back at its original path without clobbering anything that
+/// appeared there in the meantime: `hard_link` fails atomically when the destination
+/// exists, in which case the displaced copy is dropped - its consumers already
+/// reference the newer file at the original path.
+fn restore_staged(staged: &Path, path: &Path) -> Result<()> {
+ match std::fs::hard_link(staged, path) {
+ Ok(()) => {}
+ Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
+ warn!(
+ "A newer sourcemap appeared at {}; discarding the displaced copy",
+ path.display()
+ );
+ }
+ // Filesystems without hard links: fall back to a plain rename.
+ Err(_) => {
+ return std::fs::rename(staged, path).with_context(|| {
+ format!(
+ "Failed to restore sourcemap after skipped deletion: {}",
+ path.display()
+ )
+ });
+ }
+ }
+ std::fs::remove_file(staged).with_context(|| {
+ format!(
+ "Failed to remove staged sourcemap copy: {}",
+ staged.display()
+ )
+ })
+}
+
#[cfg(test)]
mod tests {
use super::*;
use crate::{sourcemaps::inject::inject_pairs, utils::files::FileSelection};
+ const MAP_JSON: &str = r#"{"version":3,"sources":["a.ts"],"names":[],"mappings":""}"#;
+
+ fn read_dir_pairs(dir: &Path) -> Vec<SourcePair> {
+ let selection = FileSelection::from_roots(vec![dir.to_path_buf()]);
+ read_pairs(selection.into_iter().filter(is_javascript_file), &None)
+ }
+
+ fn write_pair(dir: &Path, name: &str) -> (PathBuf, PathBuf) {
+ let source_path = dir.join(format!("{name}.js"));
+ let map_path = dir.join(format!("{name}.js.map"));
+ std::fs::write(
+ &source_path,
+ format!("console.log(1);\n//# sourceMappingURL={name}.js.map\n"),
+ )
+ .unwrap();
+ std::fs::write(&map_path, MAP_JSON).unwrap();
+ (source_path, map_path)
+ }
+
+ #[test]
+ fn cleanup_strips_references_and_deletes_maps() {
+ let dir = tempfile::tempdir().unwrap();
+ let (source_path, map_path) = write_pair(dir.path(), "chunk");
+ let pairs = read_dir_pairs(dir.path());
+ let target = cleanup_target(&pairs[0]).unwrap();
+
+ cleanup_pairs(vec![target]).unwrap();
+
+ let stripped = std::fs::read_to_string(&source_path).unwrap();
+ assert!(!stripped.contains("sourceMappingURL"), "{stripped}");
+ assert!(!map_path.exists());
+ }
+
+ #[test]
+ fn cleanup_skips_missing_and_replaced_sources() {
+ let dir = tempfile::tempdir().unwrap();
+
+ // The source vanished after upload: cleanup must not fail the build, and must
+ // leave the map alone.
+ let (missing_source, orphan_map) = write_pair(dir.path(), "gone");
+ // The source was replaced after upload: the replacement and its map are someone
+ // else's artifacts and must stay untouched.
+ let (replaced_source, replaced_map) = write_pair(dir.path(), "replaced");
+
+ let targets = read_dir_pairs(dir.path())
+ .iter()
+ .map(|pair| cleanup_target(pair).unwrap())
+ .collect::<Vec<_>>();
+
+ std::fs::remove_file(&missing_source).unwrap();
+ let replacement = "console.log(2);\n//# sourceMappingURL=replaced.js.map\n";
+ std::fs::write(&replaced_source, replacement).unwrap();
+
+ cleanup_pairs(targets).unwrap();
+
+ assert!(orphan_map.exists());
+ assert_eq!(
+ std::fs::read_to_string(&replaced_source).unwrap(),
+ replacement
+ );
+ assert!(replaced_map.exists());
+ }
+
+ #[test]
+ fn cleanup_keeps_a_replaced_map_but_strips_the_unchanged_source() {
+ let dir = tempfile::tempdir().unwrap();
+ let (source_path, map_path) = write_pair(dir.path(), "chunk");
+ let pairs = read_dir_pairs(dir.path());
+ let target = cleanup_target(&pairs[0]).unwrap();
+
+ let replacement_map = r#"{"version":3,"sources":["b.ts"],"names":[],"mappings":""}"#;
+ std::fs::write(&map_path, replacement_map).unwrap();
+
+ cleanup_pairs(vec![target]).unwrap();
+
+ // Our source is unchanged, so its reference is stripped; the map was replaced
+ // after upload, so the replacement stays in place.
+ let stripped = std::fs::read_to_string(&source_path).unwrap();
+ assert!(!stripped.contains("sourceMappingURL"), "{stripped}");
+ assert_eq!(std::fs::read_to_string(&map_path).unwrap(), replacement_map);
+ }
+
+ #[test]
+ fn overlapping_roots_yield_each_pair_once() {
+ let dir = tempfile::tempdir().unwrap();
+ write_pair(dir.path(), "chunk");
+
+ let selection =
+ FileSelection::from_roots(vec![dir.path().to_path_buf(), dir.path().to_path_buf()]);
+ let pairs = read_pairs(selection.into_iter().filter(is_javascript_file), &None);
+
+ assert_eq!(pairs.len(), 1);
+ }
+
+ #[test]
+ fn cleanup_deletes_a_shared_map_matching_any_uploaded_copy() {
+ let dir = tempfile::tempdir().unwrap();
+ let shared_map = dir.path().join("shared.js.map");
+ std::fs::write(&shared_map, MAP_JSON).unwrap();
+ std::fs::write(
+ dir.path().join("a.js"),
+ "console.log(1);\n//# sourceMappingURL=shared.js.map\n",
+ )
+ .unwrap();
+ std::fs::write(
+ dir.path().join("b.js"),
+ "console.log(2);\n//# sourceMappingURL=shared.js.map\n",
+ )
+ .unwrap();
+
+ let mut targets = read_dir_pairs(dir.path())
+ .iter()
+ .map(|pair| cleanup_target(pair).unwrap())
+ .collect::<Vec<_>>();
+ assert_eq!(targets.len(), 2);
+ // Sharing pairs hold separately injected copies of the map, so their
+ // fingerprints differ and only one matches the disk. Deletion must accept any
+ // of them.
+ targets[0].sourcemap_hash = "fingerprint-of-an-overwritten-copy".to_string();
+
+ cleanup_pairs(targets).unwrap();
+
+ assert!(!shared_map.exists());
+ }
+
+ #[test]
+ fn cleanup_keeps_a_shared_map_while_any_source_was_skipped() {
+ let dir = tempfile::tempdir().unwrap();
+ let shared_map = dir.path().join("shared.js.map");
+ std::fs::write(&shared_map, MAP_JSON).unwrap();
+ let kept = dir.path().join("a.js");
+ let replaced = dir.path().join("b.js");
+ std::fs::write(
+ &kept,
+ "console.log(1);\n//# sourceMappingURL=shared.js.map\n",
+ )
+ .unwrap();
+ std::fs::write(
+ &replaced,
+ "console.log(2);\n//# sourceMappingURL=shared.js.map\n",
+ )
+ .unwrap();
+
+ let targets = read_dir_pairs(dir.path())
+ .iter()
+ .map(|pair| cleanup_target(pair).unwrap())
+ .collect::<Vec<_>>();
+ assert_eq!(targets.len(), 2);
+
+ let replacement = "console.log(3);\n//# sourceMappingURL=shared.js.map\n";
+ std::fs::write(&replaced, replacement).unwrap();
+
+ cleanup_pairs(targets).unwrap();
+
+ // The unchanged source is stripped, but the map survives: the replacement
+ // still references it.
+ let stripped = std::fs::read_to_string(&kept).unwrap();
+ assert!(!stripped.contains("sourceMappingURL"), "{stripped}");
+ assert_eq!(std::fs::read_to_string(&replaced).unwrap(), replacement);
+ assert!(shared_map.exists());
+ }
+
#[test]
fn stylesheet_cleanup_only_accepts_maps_inside_selected_roots() {
let dir = tempfile::tempdir().expect("Failed to create temp dir");
diff --git a/cli/src/sourcemaps/source_pairs.rs b/cli/src/sourcemaps/source_pairs.rs
index 03c05df6caed..7d55c5aa0531 100644
--- a/cli/src/sourcemaps/source_pairs.rs
+++ b/cli/src/sourcemaps/source_pairs.rs
@@ -113,6 +113,7 @@ pub fn read_pairs(
selection: impl Iterator<Item = DirEntry>,
prefix: &Option<String>,
) -> Vec<SourcePair> {
+ let mut seen_paths = std::collections::HashSet::new();
let pairs = selection
.filter_map(|entry| {
let path = entry.path();
@@ -121,6 +122,11 @@ pub fn read_pairs(
.context("failed to canonicalize path")
.map_err(|e| warn!("skip: {e:?}"))
.ok()?;
+ // Overlapping selection roots yield the same file more than once; a second
+ // pass would stamp a fresh chunk id over the first and upload a stale copy.
+ if !seen_paths.insert(entry_path.clone()) {
+ return None;
+ }
let source = MinifiedSourceFile::load(&entry_path)
.context("failed to read source")
.map_err(|e| warn!("skip: {e:?}"))
@@ -162,9 +168,12 @@ impl SourcePair {
/// In symbol-set mode no hash is set and the upload layer hashes the raw payload, matching
/// the hashes the server already stores for previous uploads.
pub fn into_upload(mut self, release_mode: ReleaseMode) -> Result<SymbolSetUpload> {
- let chunk_id = self
- .get_chunk_id()
- .ok_or_else(|| anyhow!("Chunk ID not found"))?;
+ let chunk_id = self.get_chunk_id().ok_or_else(|| {
+ anyhow!(
+ "Chunk ID not found in {}. Run 'sourcemap inject' before 'sourcemap upload', or use 'sourcemap process' to do both.",
+ self.source.inner.path.display()
+ )
+ })?;
let release_id = self.sourcemap.get_release_id();
let source_content = self.source.inner.content.clone();
let sourcemap_content = serde_json::to_string(&self.sourcemap.inner.content)?;