diff --git a/.changepacks/changepack_log_css_serialization_cache.json b/.changepacks/changepack_log_css_serialization_cache.json new file mode 100644 index 000000000..ec393a34b --- /dev/null +++ b/.changepacks/changepack_log_css_serialization_cache.json @@ -0,0 +1,8 @@ +{ + "changes": { + "bindings/devup-ui-binding/package.json": "Patch", + "bindings/devup-ui-wasm/package.json": "Patch" + }, + "note": "Reuse a serialized stylesheet until the sheet or the atom-hoisting settings it reads change: getCss and the CSS a transform returns no longer serialize the same unchanged sheet again. The output is byte-identical.", + "date": "2026-11-15T00:00:00.000Z" +} diff --git a/Cargo.lock b/Cargo.lock index fc7ea0d27..e36f2f33a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -598,6 +598,7 @@ dependencies = [ "css", "extractor", "serde_json", + "serial_test", "sheet", ] diff --git a/libs/binding/Cargo.toml b/libs/binding/Cargo.toml index aa50e11f4..bf580965a 100644 --- a/libs/binding/Cargo.toml +++ b/libs/binding/Cargo.toml @@ -18,3 +18,6 @@ sheet = { path = "../sheet" } css = { path = "../css" } serde_json = "1.0.154" bimap = { version = "0.6.3", features = ["serde"] } + +[dev-dependencies] +serial_test = "4.0.1" diff --git a/libs/binding/src/css_cache.rs b/libs/binding/src/css_cache.rs new file mode 100644 index 000000000..61e005049 --- /dev/null +++ b/libs/binding/src/css_cache.rs @@ -0,0 +1,113 @@ +//! Serialized stylesheets, reused until the sheet or a setting they read changes. +//! +//! A build serializes the same sheet many times between two extractions: the +//! transform that changed it, the shared base the host writes next, and every +//! stylesheet module the bundler loads. Each entry is exactly what +//! `StyleSheet::create_css` returned for its key, so a hit is byte-identical. + +use sheet::StyleSheet; +use std::collections::HashMap; +use std::ops::{Deref, DerefMut}; +use std::sync::{LazyLock, LockResult, Mutex, MutexGuard, PoisonError}; + +/// What a serialization reads besides the sheet: the bucket, whether a file +/// stylesheet imports the shared base, and whether atom hoisting is in effect. +type Key = (Option, bool, bool); + +static CSS_CACHE: LazyLock>> = LazyLock::new(Mutex::default); + +fn cache() -> MutexGuard<'static, HashMap> { + CSS_CACHE.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// The key of a serialization; only a file stylesheet imports the shared base. +fn key(bucket: Option<&str>, import_main_css: bool) -> Key { + ( + bucket.map(str::to_string), + bucket.is_some() && import_main_css, + css::atom_hoist::is_atom_hoist(), + ) +} + +/// Serialize `bucket` (the shared base when `None`), reusing an unchanged result. +pub(crate) fn cached_css( + sheet: &StyleSheet, + bucket: Option<&str>, + import_main_css: bool, +) -> String { + cache() + .entry(key(bucket, import_main_css)) + .or_insert_with(|| sheet.create_css(bucket, import_main_css)) + .clone() +} + +/// Forget every serialization; called whenever the sheet or a setting it reads changes. +pub(crate) fn invalidate_css() { + cache().clear(); +} + +/// A stylesheet behind a mutex whose every mutable borrow forgets its serializations. +#[derive(Default)] +pub struct SheetCell(Mutex); + +/// A locked stylesheet; borrowing it mutably forgets its serializations. +pub struct SheetGuard<'a>(MutexGuard<'a, StyleSheet>); + +impl SheetCell { + /// Lock the stylesheet as `Mutex::lock` does. + /// + /// # Errors + /// The stylesheet, still usable, when a holder of the lock panicked. + pub fn lock(&self) -> LockResult> { + self.0 + .lock() + .map(SheetGuard) + .map_err(|poisoned| PoisonError::new(SheetGuard(poisoned.into_inner()))) + } +} + +impl SheetGuard<'_> { + /// Borrow the sheet mutably, keeping its serializations for the caller to forget. + pub(crate) fn untracked(&mut self) -> &mut StyleSheet { + &mut self.0 + } +} + +impl Deref for SheetGuard<'_> { + type Target = StyleSheet; + + fn deref(&self) -> &StyleSheet { + &self.0 + } +} + +impl DerefMut for SheetGuard<'_> { + fn deref_mut(&mut self) -> &mut StyleSheet { + invalidate_css(); + &mut self.0 + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::*; + + #[test] + fn only_file_stylesheets_import_the_shared_base() { + assert_eq!(key(None, true), key(None, false)); + assert_ne!(key(Some("a.tsx"), true), key(Some("a.tsx"), false)); + } + + #[test] + fn a_poisoned_sheet_stays_usable() { + let cell = SheetCell::default(); + let _ = std::panic::catch_unwind(|| { + let _guard = cell.lock(); + panic!("poison the sheet"); + }); + let mut sheet = cell.lock().err().map(PoisonError::into_inner).unwrap(); + sheet.add_import("a.tsx", "b.css"); + assert_eq!(sheet.imports.len(), 1); + } +} diff --git a/libs/binding/src/lib.rs b/libs/binding/src/lib.rs index cc89b9a04..8d62f10d1 100644 --- a/libs/binding/src/lib.rs +++ b/libs/binding/src/lib.rs @@ -1,14 +1,14 @@ //! Host-neutral binding orchestration; JavaScript values belong to the host adapter. +mod css_cache; mod output; mod reservation; mod resolver_state; -pub use css::atom_hoist::set_atom_hoist; pub use css::debug::{is_debug, set_debug}; -pub use css::file_routes::set_file_routes as import_file_routes_internal; pub use css::slot_reservation::unreserved_slot_count as get_unreserved_class_slot_count; pub use css::{get_prefix, set_custom_shorthands as register_shorthands_internal, set_prefix}; +pub use css_cache::{SheetCell, SheetGuard}; pub use extractor::{has_devup_ui, has_devup_ui_with}; pub use output::{CssOptions, ExtractionMode, Output, SourceMapMode, code_extract}; pub use reservation::{ReservationInput, reserve_class_slots_internal}; @@ -16,13 +16,14 @@ pub use resolver_state::{ResolverRequest, ResolverState}; use css::class_map::{set_class_map, with_class_map}; use css::file_map::{set_canonical_map, set_file_map, with_canonical_map, with_file_map}; +use css_cache::{cached_css, invalidate_css}; use sheet::StyleSheet; -use std::collections::{BTreeMap, HashMap}; -use std::sync::{LazyLock, Mutex}; +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::sync::LazyLock; /// The single stylesheet shared by extraction, reservation and host test seams. -pub static GLOBAL_STYLE_SHEET: LazyLock> = - LazyLock::new(|| Mutex::new(StyleSheet::default())); +/// Every mutable borrow of it forgets the serializations of the sheet before. +pub static GLOBAL_STYLE_SHEET: LazyLock = LazyLock::new(SheetCell::default); /// Borrow the live stylesheet, recovering its contents after an unwind. pub fn with_style_sheet(f: F) -> R @@ -46,6 +47,30 @@ where f(&mut guard) } +/// Mutably borrow the live stylesheet for a change that forgets the +/// serializations itself, and only when it changed the sheet. +fn with_style_sheet_untracked(f: F) -> R +where + F: FnOnce(&mut StyleSheet) -> R, +{ + let mut guard = GLOBAL_STYLE_SHEET + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + f(guard.untracked()) +} + +/// Hoist atoms shared by `threshold` routes, or stop hoisting with `None`. +pub fn set_atom_hoist(threshold: Option) { + css::atom_hoist::set_atom_hoist(threshold); + invalidate_css(); +} + +/// Restore the routes each file reaches, which plan atom hoisting. +pub fn import_file_routes_internal(map: HashMap>) { + css::file_routes::set_file_routes(map); + invalidate_css(); +} + /// The text of an error the internal exports return fn error_text(error: impl std::fmt::Display) -> String { error.to_string() @@ -96,6 +121,7 @@ pub fn export_file_map_internal() -> Result { /// Restore canonical bucket identities decoded by a host adapter. pub fn import_canonical_map_internal(map: HashMap) { set_canonical_map(map); + invalidate_css(); } /// Export canonical bucket identities in path order. @@ -132,6 +158,7 @@ pub fn reset_state_internal(clear_resolver: impl FnOnce()) { clear_resolver(); css::test_state::reset_state_for_testing(); extractor::test_state::reset_caches_for_testing(); + invalidate_css(); } /// Register a decoded theme in the live stylesheet. @@ -149,13 +176,14 @@ pub fn get_css(file_num: Option, import_main_css: bool) -> String { with_style_sheet(|sheet| { if let Some(file_num) = file_num { with_file_map(|map| { - sheet.create_css( + cached_css( + sheet, map.get_by_right(&file_num).map(String::as_str), import_main_css, ) }) } else { - sheet.create_css(None, import_main_css) + cached_css(sheet, None, import_main_css) } }) } diff --git a/libs/binding/src/output.rs b/libs/binding/src/output.rs index 284113ca4..bdc3466da 100644 --- a/libs/binding/src/output.rs +++ b/libs/binding/src/output.rs @@ -4,7 +4,8 @@ use extractor::{ extract_without_source_map, }; -use crate::with_style_sheet_mut; +use crate::css_cache::{cached_css, invalidate_css}; +use crate::with_style_sheet_untracked; /// Whether extraction generates a source map. #[derive(Clone, Copy)] @@ -63,11 +64,23 @@ impl Output { let _atom_mode = css::atom_hoist::AtomModeGuard::new(options.single_css); let canonical_filename = canonical(&filename); let global = options.single_css || is_global(&filename); - with_style_sheet_mut(|sheet| { + with_style_sheet_untracked(|sheet| { + let planned = sheet.atom_plan.is_some(); // Global CSS belongs to the raw SOURCE file, never its collapsed bucket. let default_collected = sheet.rm_global_css(&filename, global); let (collected, updated_base_style) = sheet.update_styles_in_bucket(&output.styles, &canonical_filename, global); + // The commit reports every style, global rule, import and font face it + // added or removed, but not the atom plan its first commit freezes into + // the sheet. A source extracted again changes neither: what was + // serialized before still holds. + if collected + || updated_base_style + || default_collected + || planned != sheet.atom_plan.is_some() + { + invalidate_css(); + } Self { code: output.code, map: output.map, @@ -78,7 +91,8 @@ impl Output { if !collected && !default_collected { None } else { - Some(sheet.create_css( + Some(cached_css( + sheet, if global { None } else { diff --git a/libs/binding/tests/css_cache.rs b/libs/binding/tests/css_cache.rs new file mode 100644 index 000000000..71dff1ae7 --- /dev/null +++ b/libs/binding/tests/css_cache.rs @@ -0,0 +1,172 @@ +use std::collections::{HashMap, HashSet}; + +use devup_ui_binding_core::{ + ExtractionMode, GLOBAL_STYLE_SHEET, Output, SourceMapMode, code_extract, get_css, + import_canonical_map_internal, import_file_map_internal, import_file_routes_internal, + reset_state_internal, set_atom_hoist, with_style_sheet, +}; +use extractor::ExtractOption; +use serial_test::serial; + +fn extract(filename: &str, code: &str, single_css: bool) -> Result { + code_extract( + (filename, code), + ExtractOption { + package: "@devup-ui/react".to_string(), + css_dir: "df".to_string(), + single_css, + ..ExtractOption::default() + }, + ExtractionMode { + source_map: SourceMapMode::Skip, + resolver: None, + resolver_check: None, + import_main_css_in_css: false, + }, + ) +} + +#[test] +#[serial] +fn css_is_reused_until_an_extraction_changes_the_sheet() -> Result<(), String> { + // Given: a transform that added a style, and the base read once. + reset_state_internal(|| {}); + let red = extract( + "red.tsx", + "import { Box } from '@devup-ui/react'; export const view = ;", + true, + )?; + let first = get_css(None, false); + + // When: the base is read again, then another transform adds a style. + let again = get_css(None, true); + extract( + "blue.tsx", + "import { Box } from '@devup-ui/react'; export const view = ;", + true, + )?; + let changed = get_css(None, false); + + // Then: the unchanged sheet reads the same, the changed one holds both. + assert_eq!(red.css.as_deref(), Some(first.as_str())); + assert_eq!(again, first); + assert!(!first.contains("blue")); + assert!(changed.contains("red") && changed.contains("blue")); + Ok(()) +} + +#[test] +#[serial] +fn css_survives_a_source_extracted_again_unchanged() -> Result<(), String> { + // Given: a source extracted once, with a global rule, and its base read. + reset_state_internal(|| {}); + let source = "import { Box, globalCss } from '@devup-ui/react'; globalCss({ body: { m: 0 } }); export const view = ;"; + extract("page.tsx", source, true)?; + let first = get_css(None, false); + + // When: the same source is extracted again, as a prewarm and its transform do. + let again = extract("page.tsx", source, true)?; + + // Then: the base reads the same as from a fresh serialization. + assert_eq!(get_css(None, false), first); + assert!(again.updated_base_style); + assert!(first.contains("red")); + Ok(()) +} + +#[test] +#[serial] +fn css_is_forgotten_when_the_sheet_is_borrowed_mutably() { + // Given: the base of an empty sheet, read once. + reset_state_internal(|| {}); + let empty = get_css(None, false); + + // When: a host test seam edits the locked sheet directly. + GLOBAL_STYLE_SHEET + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .add_import("page.tsx", "theme.css"); + + // Then: the next read serializes the edited sheet. + let edited = get_css(None, false); + assert_ne!(edited, empty); + assert!(edited.contains("@import \"theme.css\";")); +} + +/// The file stylesheet and the base, as a fresh serialization writes them now. +fn fresh() -> (String, String) { + with_style_sheet(|sheet| { + ( + sheet.create_css(Some("shared.tsx"), false), + sheet.create_css(None, false), + ) + }) +} + +/// The file stylesheet and the base, as the cached reads return them now. +fn read() -> (String, String) { + (get_css(Some(0), false), get_css(None, false)) +} + +#[test] +#[serial] +fn css_follows_every_atom_hoisting_setting() -> Result<(), String> { + // Given: a source extracted before atom hoisting, read once. + reset_state_internal(|| {}); + import_file_map_internal(std::iter::once(("shared.tsx".to_string(), 0)).collect()); + extract( + "shared.tsx", + "import { Box } from '@devup-ui/react'; export const view = ;", + false, + )?; + assert_eq!(read(), fresh()); + + // When: each setting the serialization reads changes after a read. + import_file_routes_internal(HashMap::from([( + "shared.tsx".to_string(), + HashSet::from([0, 1]), + )])); + let routed = (read(), fresh()); + import_canonical_map_internal(HashMap::new()); + let canonical = (read(), fresh()); + set_atom_hoist(Some(2)); + let hoisted = (read(), fresh()); + set_atom_hoist(None); + let plain = (read(), fresh()); + + // Then: every read is what a fresh serialization writes at that point. + assert_eq!(routed.0, routed.1); + assert_eq!(canonical.0, canonical.1); + assert_eq!(hoisted.0, hoisted.1); + assert_eq!(plain.0, plain.1); + reset_state_internal(|| {}); + Ok(()) +} + +#[test] +#[serial] +fn css_is_forgotten_when_a_commit_freezes_the_atom_plan() -> Result<(), String> { + // Given: atom hoisting over two routes, the empty sheet read once. + reset_state_internal(|| {}); + import_file_map_internal(std::iter::once(("shared.tsx".to_string(), 0)).collect()); + import_file_routes_internal(HashMap::from([( + "shared.tsx".to_string(), + HashSet::from([0, 1]), + )])); + set_atom_hoist(Some(2)); + read(); + + // When: a source without styles commits, freezing the plan into the sheet. + let output = extract( + "shared.tsx", + "import { Box } from '@devup-ui/react'; export const view = 1;", + false, + )?; + + // Then: nothing was collected, yet the read follows the frozen plan. + assert!(output.css.is_none()); + assert!(with_style_sheet(|sheet| sheet.atom_plan.is_some())); + assert_eq!(read(), fresh()); + reset_state_internal(|| {}); + Ok(()) +}