Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .changepacks/changepack_log_css_serialization_cache.json
Original file line number Diff line number Diff line change
@@ -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"
}
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions libs/binding/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
113 changes: 113 additions & 0 deletions libs/binding/src/css_cache.rs
Original file line number Diff line number Diff line change
@@ -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<String>, bool, bool);

static CSS_CACHE: LazyLock<Mutex<HashMap<Key, String>>> = LazyLock::new(Mutex::default);

fn cache() -> MutexGuard<'static, HashMap<Key, String>> {
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<StyleSheet>);

/// 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<SheetGuard<'_>> {
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);
}
}
44 changes: 36 additions & 8 deletions libs/binding/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,28 +1,29 @@
//! 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};
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<Mutex<StyleSheet>> =
LazyLock::new(|| Mutex::new(StyleSheet::default()));
/// Every mutable borrow of it forgets the serializations of the sheet before.
pub static GLOBAL_STYLE_SHEET: LazyLock<SheetCell> = LazyLock::new(SheetCell::default);

/// Borrow the live stylesheet, recovering its contents after an unwind.
pub fn with_style_sheet<F, R>(f: F) -> R
Expand All @@ -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, R>(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<usize>) {
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<String, HashSet<u32>>) {
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()
Expand Down Expand Up @@ -96,6 +121,7 @@ pub fn export_file_map_internal() -> Result<String, String> {
/// Restore canonical bucket identities decoded by a host adapter.
pub fn import_canonical_map_internal(map: HashMap<String, String>) {
set_canonical_map(map);
invalidate_css();
}

/// Export canonical bucket identities in path order.
Expand Down Expand Up @@ -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.
Expand All @@ -149,13 +176,14 @@ pub fn get_css(file_num: Option<usize>, 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)
}
})
}
Expand Down
20 changes: 17 additions & 3 deletions libs/binding/src/output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -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,
Expand All @@ -78,7 +91,8 @@ impl Output {
if !collected && !default_collected {
None
} else {
Some(sheet.create_css(
Some(cached_css(
sheet,
if global {
None
} else {
Expand Down
Loading
Loading