Unverified Commit 66211372 authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

turbopack: skip strict directives of referenced chunk item cells

Strict factories inside a strict chunk wrapper reference their code cell together with a factory-owned cell holding the directive's byte range. The CellRope applies it with Rope::skip when read, so chunk compositions stay independent of the directive's position.
Co-authored-by: 's avatarLuke Sandberg <210140+lukesandberg@users.noreply.github.com>
parent 4bd51aff
......@@ -2,7 +2,7 @@
use std::{future::Future, io::Write, pin::Pin};
use anyhow::Result;
use anyhow::{Result, ensure};
use bincode::{
Decode, Encode,
de::{Decoder, read::Reader as _},
......@@ -26,6 +26,10 @@ use crate::rope::{InnerRope, Rope, RopeBuilder};
/// computed by whoever reads the rope's bytes. A `CellRope` describes whatever the cells currently
/// hold; consumers that need its bytes to match a value they computed earlier compare a content
/// hash (writing a [`crate::File::from_cell_rope`] file does).
///
/// A referenced cell's bytes can be patched when the rope is read: see
/// [`CellRopeBuilder::push_cell_skipping`]. The patch is itself a reference to a cell, so it stays
/// as independent of the cells' contents as the rest of the rope.
#[turbo_tasks::value(shared)]
#[derive(Clone, Debug, Default)]
pub struct CellRope {
......@@ -38,11 +42,50 @@ enum CellRopeSegment {
Inline(InlineRope),
/// Bytes owned (and persisted) by another cell.
Cell(ResolvedVc<Rope>),
/// Bytes owned by another cell, without the range held by `skip` (if any), see
/// [`CellRopeBuilder::push_cell_skipping`].
SkippedCell {
cell: ResolvedVc<Rope>,
skip: ResolvedVc<OptionByteRange>,
},
/// All of another `CellRope`'s bytes. Lets a rope extend another one (e.g. append a footer)
/// without copying its segments.
Nested(ResolvedVc<CellRope>),
}
/// An optional range of bytes, as `(start, end)` offsets. Left out of a cell's bytes by
/// [`CellRopeBuilder::push_cell_skipping`].
#[turbo_tasks::value(shared)]
#[derive(Clone, Copy, Debug)]
pub struct OptionByteRange {
range: Option<(usize, usize)>,
}
impl OptionByteRange {
pub fn new(range: Option<std::ops::Range<usize>>) -> Self {
OptionByteRange {
range: range.map(|range| (range.start, range.end)),
}
}
pub fn range(&self) -> Option<std::ops::Range<usize>> {
self.range.map(|(start, end)| start..end)
}
}
/// `rope` without the bytes in `skip`. Errors if `skip` doesn't lie within `rope`.
fn skip_range(rope: Rope, skip: &OptionByteRange) -> Result<Rope> {
let Some(range) = skip.range() else {
return Ok(rope);
};
ensure!(
range.start <= range.end && range.end <= rope.len(),
"skipped range {range:?} is out of bounds for a cell of {} bytes",
rope.len()
);
Ok(rope.skip(range))
}
/// The contents of an inline segment. Stored without its length, which is recomputed when the
/// rope is read.
#[derive(Clone, Debug, NonLocalValue)]
......@@ -84,8 +127,9 @@ impl CellRope {
/// Reads every referenced cell (and nested rope) and concatenates the segments into a flat
/// [`Rope`].
///
/// This doesn't copy any bytes: the result shares the cells' buffers. If any cell fails to
/// read, this fails too; a partial rope is never returned.
/// This doesn't copy any bytes: the result shares the cells' buffers, and skipped ranges are
/// left out with [`Rope::skip`]. If any cell fails to read (or a skipped range doesn't fit its
/// cell), this fails too; a partial rope is never returned.
pub async fn read(&self) -> Result<Rope> {
self.read_segments(true).await
}
......@@ -113,6 +157,14 @@ impl CellRope {
(*cell.untracked().await?).clone()
}
}
CellRopeSegment::SkippedCell { cell, skip } => {
let (rope, skip) = if tracked {
((*cell.await?).clone(), *skip.await?)
} else {
((*cell.untracked().await?).clone(), *skip.untracked().await?)
};
skip_range(rope, &skip)?
}
CellRopeSegment::Nested(rope) => {
let rope = if tracked {
rope.await?
......@@ -137,7 +189,12 @@ impl CellRope {
pub fn cell_count(&self) -> usize {
self.segments
.iter()
.filter(|segment| matches!(segment, CellRopeSegment::Cell(_)))
.filter(|segment| {
matches!(
segment,
CellRopeSegment::Cell(_) | CellRopeSegment::SkippedCell { .. }
)
})
.count()
}
......@@ -147,7 +204,14 @@ impl CellRope {
CellRopeSegment::Inline(inline) => {
CellRopePart::Inline(Rope::from_inner(inline.0.clone()))
}
CellRopeSegment::Cell(cell) => CellRopePart::Cell(*cell),
CellRopeSegment::Cell(cell) => CellRopePart::Cell {
cell: *cell,
skip: None,
},
CellRopeSegment::SkippedCell { cell, skip } => CellRopePart::Cell {
cell: *cell,
skip: Some(*skip),
},
CellRopeSegment::Nested(rope) => CellRopePart::Nested(*rope),
})
}
......@@ -157,8 +221,12 @@ impl CellRope {
pub enum CellRopePart {
/// Bytes owned by the rope itself.
Inline(Rope),
/// A reference to a cell owned by another task.
Cell(ResolvedVc<Rope>),
/// A reference to a cell owned by another task, and to the range of its bytes to leave out
/// (see [`CellRopeBuilder::push_cell_skipping`]).
Cell {
cell: ResolvedVc<Rope>,
skip: Option<ResolvedVc<OptionByteRange>>,
},
/// A reference to all of another `CellRope`'s bytes.
Nested(ResolvedVc<CellRope>),
}
......@@ -189,6 +257,22 @@ impl CellRopeBuilder {
self.segments.push(CellRopeSegment::Cell(cell));
}
/// Appends a reference to a cell owned by another task, leaving out the range of its bytes
/// that `skip` holds (nothing if it holds `None`).
///
/// Both are only read when the rope is read, so the range can follow the cell's contents:
/// e.g. a cell and a range computed from it by the same task. Reading fails if the range
/// doesn't lie within the cell's bytes.
pub fn push_cell_skipping(
&mut self,
cell: ResolvedVc<Rope>,
skip: ResolvedVc<OptionByteRange>,
) {
self.flush_inline();
self.segments
.push(CellRopeSegment::SkippedCell { cell, skip });
}
/// Appends a reference to all of another `CellRope`'s bytes, without copying its segments.
pub fn push_rope(&mut self, rope: ResolvedVc<CellRope>) {
self.flush_inline();
......@@ -203,6 +287,9 @@ impl CellRopeBuilder {
self.inline.concat(&Rope::from_inner(inline.0.clone()));
}
CellRopeSegment::Cell(cell) => self.push_cell(*cell),
CellRopeSegment::SkippedCell { cell, skip } => {
self.push_cell_skipping(*cell, *skip)
}
CellRopeSegment::Nested(nested) => self.push_rope(*nested),
}
}
......@@ -424,6 +511,105 @@ mod tests {
};
}
/// A range owned by its own task, like the range a code cell's producer computes.
#[turbo_tasks::function(operation, root)]
fn range_operation(range: Option<(usize, usize)>) -> Vc<OptionByteRange> {
OptionByteRange::new(range.map(|(start, end)| start..end)).cell()
}
/// `a<cell without skip>d`, referencing both without reading them.
#[turbo_tasks::function(operation, root)]
fn compose_skipping_operation(
cell: ResolvedVc<Rope>,
skip: ResolvedVc<OptionByteRange>,
) -> Vc<CellRope> {
let mut builder = CellRopeBuilder::default();
builder += "a";
builder.push_cell_skipping(cell, skip);
builder += "d";
builder.build().cell()
}
/// Reads `a<"bcxyef" without range>d`, tracked and untracked, checking they agree.
async fn read_skipping(range: Option<(usize, usize)>) -> Result<(CellRope, RcStr)> {
let switch = switch_operation().resolve().strongly_consistent().await?;
let cell = item_operation(switch, "bcxyef".into())
.resolve()
.strongly_consistent()
.await?;
let skip = range_operation(range)
.resolve()
.strongly_consistent()
.await?;
let rope = compose_skipping_operation(cell, skip)
.resolve()
.strongly_consistent()
.await?;
let tracked = read_operation(rope).read_strongly_consistent().await?;
let untracked = read_untracked_operation(rope)
.read_strongly_consistent()
.await?;
assert_eq!(tracked, untracked);
Ok(((*rope.await?).clone(), (*tracked).clone()))
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn skipped_cells_leave_out_their_range_when_read() {
turbo_tasks!()
.run_once(async {
let (rope, text) = read_skipping(Some((2, 4))).await?;
assert_eq!(text.as_str(), "abcefd");
assert_eq!(rope.cell_count(), 1);
assert!(
rope.parts()
.any(|part| matches!(part, CellRopePart::Cell { skip: Some(_), .. }))
);
let (_, text) = read_skipping(None).await?;
assert_eq!(text.as_str(), "abcxyefd");
let (_, text) = read_skipping(Some((0, 6))).await?;
assert_eq!(text.as_str(), "ad");
anyhow::Ok(())
})
.await
.unwrap();
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn skipped_ranges_out_of_bounds_fail_the_read() {
turbo_tasks!()
.run_once(async {
let err = read_skipping(Some((4, 7)))
.await
.expect_err("a range past the cell's end must fail the read");
assert!(
format!("{err:?}").contains("out of bounds"),
"unexpected error: {err:?}"
);
anyhow::Ok(())
})
.await
.unwrap();
}
/// The skip is stored as a reference too, and survives encoding.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn skipped_cells_round_trip_through_encoding() {
turbo_tasks!()
.run_once(async {
let (rope, _) = read_skipping(Some((2, 4))).await?;
let config = bincode::config::standard();
let encoded = bincode::encode_to_vec(&rope, config)?;
assert!(encoded.len() < 32, "encoded to {} bytes", encoded.len());
let (decoded, _): (CellRope, _) = bincode::decode_from_slice(&encoded, config)?;
assert_eq!(decoded, rope);
assert_eq!(decoded.read().await?.to_str()?, "abcefd");
anyhow::Ok(())
})
.await
.unwrap();
}
#[test]
fn builder_merges_adjacent_inline_parts() {
let mut builder = CellRopeBuilder::default();
......
......@@ -50,7 +50,7 @@ use turbo_rcstr::RcStr;
use turbo_tasks::{NonLocalValue, ResolvedVc, ValueToString, Vc, turbobail, turbofmt};
pub use crate::{
cell_rope::{CellRope, CellRopeBuilder, CellRopePart},
cell_rope::{CellRope, CellRopeBuilder, CellRopePart, OptionByteRange},
content::{
File, FileContent, FileJsonContent, FileLine, FileLinesContent, FileMeta, LinkContent,
LinkTarget, Permissions, PersistedFileContent, WriteLinkContent, WriteLinkTargetType,
......
......@@ -5,14 +5,14 @@ use std::{
sync::Arc,
};
use anyhow::{Context, Result, bail};
use anyhow::{Context, Result, bail, ensure};
use bincode::{Decode, Encode};
use rustc_hash::FxHashMap;
use tracing::instrument;
use turbo_rcstr::RcStr;
use turbo_tasks::{NonLocalValue, ResolvedVc, TryJoinIterExt, Vc};
use turbo_tasks_fs::{
CellRope, CellRopeBuilder, CellRopePart, File, FileContent,
CellRope, CellRopeBuilder, CellRopePart, File, FileContent, OptionByteRange,
rope::{Rope, RopeBuilder},
};
use turbo_tasks_hash::{DeterministicHash, DeterministicHasher, hash_xxh3_hash128};
......@@ -103,6 +103,10 @@ pub struct CodeCells {
should_generate_debug_id: bool,
/// Same as [`Code`]'s strict directive offset.
strict_directive: Option<usize>,
/// [`Code::strict_directive`] as a cell, so that a composition can leave the directive out of
/// `code` without reading either (see
/// [`CodeCompositionBuilder::push_code_cells_without_strict_directive`]).
strict_directive_range: ResolvedVc<OptionByteRange>,
}
#[turbo_tasks::value_impl]
......@@ -140,6 +144,11 @@ impl CodeCells {
pub fn code(&self) -> ResolvedVc<Rope> {
self.code
}
/// The cell holding the byte range of the code's strict directive, if it has one.
pub fn strict_directive_range(&self) -> ResolvedVc<OptionByteRange> {
self.strict_directive_range
}
}
impl Code {
......@@ -181,11 +190,13 @@ impl Code {
)
})
.collect();
let strict_directive_range = OptionByteRange::new(self.strict_directive()).resolved_cell();
CodeCells {
code: self.code.resolved_cell(),
mappings,
should_generate_debug_id: self.should_generate_debug_id,
strict_directive: self.strict_directive,
strict_directive_range,
}
.resolved_cell()
}
......@@ -526,6 +537,21 @@ impl CodeCompositionBuilder {
self.items.push(cells);
}
/// Like [`CodeCompositionBuilder::push_code_cells`], but leaves out the code's strict
/// directive, like [`CodeBuilder::push_code_without_strict_directive`]. `strict_directive` is
/// [`CodeCells::strict_directive_range`]; it's applied when the composition is read, so this
/// reads none of the cells either, and the composition doesn't depend on where the directive
/// is.
pub fn push_code_cells_without_strict_directive(
&mut self,
cells: ResolvedVc<CodeCells>,
code: ResolvedVc<Rope>,
strict_directive: ResolvedVc<OptionByteRange>,
) {
self.body.push_cell_skipping(code, strict_directive);
self.items.push(cells);
}
pub fn build(self) -> CodeComposition {
CodeComposition {
body: self.body.build().resolved_cell(),
......@@ -712,11 +738,23 @@ impl CodeComposition {
for part in body.parts() {
match part {
CellRopePart::Inline(bytes) => code.push_source(&bytes, None::<SectionMap>),
CellRopePart::Cell(_) => code.push_code(
pieces
CellRopePart::Cell { skip, .. } => {
let piece = pieces
.next()
.context("a composition has one piece per cell segment")?,
),
.context("a composition has one piece per cell segment")?;
match skip {
None => code.push_code(piece),
Some(skip) => {
// The body leaves out the range the cell holds; it's the piece's
// directive by construction, which this removes from the mappings.
ensure!(
skip.await?.range() == piece.strict_directive(),
"a skipped range must be the piece's strict directive"
);
code.push_code_without_strict_directive(piece)
}
}
}
CellRopePart::Nested(_) => bail!("a composition body doesn't nest ropes"),
}
}
......@@ -790,16 +828,29 @@ impl CodeComposition {
for part in body.parts() {
match part {
CellRopePart::Inline(bytes) => offset += bytes.len(),
CellRopePart::Cell(_) => {
CellRopePart::Cell { skip, .. } => {
let (cells, len) = pieces
.next()
.context("a composition has one piece per cell segment")?;
// Mirrors `CodeBuilder::push_code_without_strict_directive`.
let directive = if skip.is_some() {
cells
.strict_directive
.map(|start| start..start + STRICT_DIRECTIVE.len())
} else {
None
};
for (index, map) in &cells.mappings {
let index = match &directive {
Some(directive) if directive.contains(index) => continue,
Some(directive) if *index >= directive.end => index - directive.len(),
_ => *index,
};
if let Some(map) = map {
map_cells.insert(offset + index, *map);
}
}
offset += len;
offset += len - directive.map_or(0, |directive| directive.len());
}
CellRopePart::Nested(_) => bail!("a composition body doesn't nest ropes"),
}
......@@ -966,6 +1017,8 @@ mod tests {
struct Output {
code: RcStr,
map: RcStr,
/// How many section maps the source map references as cells instead of copying them.
map_cells: usize,
body: ReadRef<CellRope>,
}
......@@ -975,11 +1028,9 @@ mod tests {
async fn output_operation(text: ResolvedVc<Text>) -> Result<Vc<Output>> {
let composition = composition(*text).await?;
let code = composition.build_code().await?;
let map = composition
.generate_source_map(&code, None)
.await?
.read()
.await?;
let map_rope = composition.generate_source_map(&code, None).await?;
let map_cells = map_rope.cell_count();
let map = map_rope.read().await?;
let mut flat = CodeBuilder::new(true, false);
flat += "[";
......@@ -1000,6 +1051,7 @@ mod tests {
Ok(Output {
code: code.source_code().to_str()?.into(),
map: map.to_str()?.into(),
map_cells,
body: composition.body().await?,
}
.cell())
......@@ -1043,6 +1095,160 @@ mod tests {
.await
.unwrap();
}
/// A strict piece: its directive's offset depends on `text`, like a factory's parameter list
/// before its directive.
fn strict_piece_code(text: &str) -> Code {
let mut code = CodeBuilder::new(true, false);
code.push_source(&Rope::from(format!("(({text})=>{{")), None::<SectionMap>);
code.push_strict_directive();
let map = r#"{"version":3,"sources":["body.js"],"names":[],"mappings":"AAAA,EAAE"}"#;
code.push_source(&Rope::from("x();y()".to_string()), Some(Rope::from(map)));
code += "})";
code.build()
}
#[turbo_tasks::function]
async fn edited_strict_piece(text: ResolvedVc<Text>) -> Result<Vc<CodeCells>> {
let text = text.await?.text.get().clone();
Ok(*strict_piece_code(&text).resolved_code_cells())
}
#[turbo_tasks::function]
fn fixed_strict_piece() -> Vc<CodeCells> {
*strict_piece_code("fixed").resolved_code_cells()
}
/// What a chunk item's entry exposes for a strict factory: references only.
#[turbo_tasks::value(shared)]
struct StrictPieceRef {
cells: ResolvedVc<CodeCells>,
code: ResolvedVc<Rope>,
strict_directive: ResolvedVc<OptionByteRange>,
}
#[turbo_tasks::function]
async fn strict_piece_ref(cells: ResolvedVc<CodeCells>) -> Result<Vc<StrictPieceRef>> {
let value = cells.await?;
Ok(StrictPieceRef {
cells,
code: value.code(),
strict_directive: value.strict_directive_range(),
}
.cell())
}
static STRICT_COMPOSITION_EXECUTIONS: AtomicUsize = AtomicUsize::new(0);
/// `[<edited without directive>,<fixed with directive>,<fixed without directive>]`.
#[turbo_tasks::function]
async fn strict_composition(text: ResolvedVc<Text>) -> Result<Vc<CodeComposition>> {
STRICT_COMPOSITION_EXECUTIONS.fetch_add(1, Ordering::SeqCst);
let mut builder = CodeCompositionBuilder::new(true, false);
builder += "[";
let edited = strict_piece_ref(edited_strict_piece(*text)).await?;
builder.push_code_cells_without_strict_directive(
edited.cells,
edited.code,
edited.strict_directive,
);
builder += ",";
let fixed = strict_piece_ref(fixed_strict_piece()).await?;
builder.push_code_cells(fixed.cells, fixed.code);
builder += ",";
builder.push_code_cells_without_strict_directive(
fixed.cells,
fixed.code,
fixed.strict_directive,
);
builder += "]";
Ok(builder.build().cell())
}
/// Like `output_operation`, for the strict composition: checks it against building the same
/// pieces with a `CodeBuilder`, which removes the directives itself.
#[turbo_tasks::function(operation, root)]
async fn strict_output_operation(text: ResolvedVc<Text>) -> Result<Vc<Output>> {
let composition = strict_composition(*text).await?;
let code = composition.build_code().await?;
let map_rope = composition.generate_source_map(&code, None).await?;
let map_cells = map_rope.cell_count();
let map = map_rope.read().await?;
let edited = edited_strict_piece(*text).to_code().await?;
let fixed = fixed_strict_piece().to_code().await?;
let mut flat = CodeBuilder::new(true, false);
flat += "[";
flat.push_code_without_strict_directive(&edited);
flat += ",";
flat.push_code(&fixed);
flat += ",";
flat.push_code_without_strict_directive(&fixed);
flat += "]";
let flat = flat.build();
ensure!(code.source_code() == flat.source_code(), "code differs");
ensure!(code.mappings == flat.mappings, "mappings differ");
ensure!(
map == flat.generate_source_map_ref(None),
"source map differs"
);
ensure!(
composition.body().await?.read().await? == *code.source_code(),
"body differs from the built code"
);
Ok(Output {
code: code.source_code().to_str()?.into(),
map: map.to_str()?.into(),
map_cells,
body: composition.body().await?,
}
.cell())
}
/// Strict directives are left out when the composition is read, so moving a piece's
/// directive (by editing the code before it) doesn't re-execute the composition either.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn skipped_directives_follow_piece_edits_without_recomposing() {
turbo_tasks::TurboTasks::new(TurboTasksBackend::new(
BackendOptions::default(),
noop_backing_storage(),
))
.run_once(async {
let text_op = text_operation();
let text = text_op.resolve().strongly_consistent().await?;
let output = strict_output_operation(text);
let before = output.read_strongly_consistent().await?;
assert_eq!(
before.code.as_str(),
r#"[((one)=>{x();y()}),((fixed)=>{"use strict";x();y()}),((fixed)=>{x();y()})]"#
);
assert!(before.map.contains("body.js"));
// Every piece's map is referenced, at its offset after the skipped directives.
assert_eq!(before.map_cells, 3);
let executions = STRICT_COMPOSITION_EXECUTIONS.load(Ordering::SeqCst);
text_op
.read_strongly_consistent()
.await?
.text
.set("a, longer, list".into());
let after = output.read_strongly_consistent().await?;
assert_eq!(
after.code.as_str(),
r#"[((a, longer, list)=>{x();y()}),((fixed)=>{"use strict";x();y()}),((fixed)=>{x();y()})]"#
);
assert_eq!(
STRICT_COMPOSITION_EXECUTIONS.load(Ordering::SeqCst),
executions,
"the composition must not re-execute"
);
assert_eq!(before.body, after.body);
anyhow::Ok(())
})
.await
.unwrap();
}
}
#[cfg(test)]
......
......@@ -5,7 +5,7 @@ use turbo_rcstr::RcStr;
use turbo_tasks::{
NonLocalValue, ReadRef, ResolvedVc, TryJoinIterExt, ValueToString, Vc, debug::ValueDebugFormat,
};
use turbo_tasks_fs::rope::Rope;
use turbo_tasks_fs::{OptionByteRange, rope::Rope};
use turbopack_core::{
chunk::{ChunkItem, ChunkItemExt, MangleType, MinifyType, ModuleId},
code_builder::CodeCells,
......@@ -50,9 +50,11 @@ async fn code_module_id_and_path(
}
MinifyType::NoMinify => factory.code,
};
let cells_value = cells.await?;
Ok(CodeModuleIdAndPath {
id: item.chunk_item.id().await?,
code: cells.await?.code(),
code: cells_value.code(),
strict_directive: cells_value.strict_directive_range(),
cells,
path: item.chunk_item.asset_ident().to_string().owned().await?,
strict: factory.strict,
......@@ -86,6 +88,9 @@ pub struct CodeModuleIdAndPath {
pub cells: ResolvedVc<CodeCells>,
/// The cell holding the factory's bytes ([`CodeCells::code`]).
pub code: ResolvedVc<Rope>,
/// The cell holding the byte range of the factory's strict directive
/// ([`CodeCells::strict_directive_range`]).
pub strict_directive: ResolvedVc<OptionByteRange>,
pub path: RcStr,
pub strict: bool,
}
......
......@@ -32,8 +32,16 @@ pub trait ModuleFactorySink<F>: Write + AddAssign<&'static str> {
/// References each factory's cells, so that the chunk's persisted representation doesn't copy
/// them, and doesn't depend on their bytes.
impl ModuleFactorySink<CodeModuleIdAndPath> for CodeCompositionBuilder {
fn push_factory(&mut self, factory: &CodeModuleIdAndPath, _without_strict_directive: bool) {
self.push_code_cells(factory.cells, factory.code);
fn push_factory(&mut self, factory: &CodeModuleIdAndPath, without_strict_directive: bool) {
if without_strict_directive {
self.push_code_cells_without_strict_directive(
factory.cells,
factory.code,
factory.strict_directive,
);
} else {
self.push_code_cells(factory.cells, factory.code);
}
}
}
......
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