diff --git a/.changepacks/changepack_log_engine_sessions_bindings.json b/.changepacks/changepack_log_engine_sessions_bindings.json new file mode 100644 index 000000000..f43836947 --- /dev/null +++ b/.changepacks/changepack_log_engine_sessions_bindings.json @@ -0,0 +1,8 @@ +{ + "changes": { + "bindings/devup-ui-wasm/package.json": "Patch", + "bindings/devup-ui-binding/package.json": "Patch" + }, + "note": "New `createSession()`, `selectSession(id)` and `dropSession(id)` exports on the WASM and native engines: a session is an engine state of its own (numbering, sheet, theme, settings and module resolver), and every call works on the selected one. Session 0 is selected from the start. `selectSession` and `dropSession` throw a `TypeError` for an id that is not an unsigned 32-bit integer, and an `Error` for an unknown session or for dropping session 0", + "date": "2026-11-15T00:00:00.000Z" +} diff --git a/.changepacks/changepack_log_engine_sessions_state.json b/.changepacks/changepack_log_engine_sessions_state.json new file mode 100644 index 000000000..1ffc362ab --- /dev/null +++ b/.changepacks/changepack_log_engine_sessions_state.json @@ -0,0 +1,8 @@ +{ + "changes": { + "bindings/devup-ui-wasm/package.json": "Patch", + "bindings/devup-ui-binding/package.json": "Patch" + }, + "note": "The engine keeps its state per engine session: class and file numbering, routes, prefix, debug, atom hoisting, slot reservation, shorthands, theme tokens, Tailwind definitions, the stylesheet, the stylesheet caches and the module resolver move together when a session is switched. Session 0 is the only one until a host creates another, so a single app sees no change", + "date": "2026-11-15T00:00:00.000Z" +} diff --git a/bindings/argument-validation.cjs b/bindings/argument-validation.cjs index a0e3edb41..1488e41ba 100644 --- a/bindings/argument-validation.cjs +++ b/bindings/argument-validation.cjs @@ -5,6 +5,7 @@ module.exports = function createBoundary() { const descriptors = { codeExtract: extraction, codeExtractWithoutSourceMap: extraction, + dropSession: 'id:u', getCss: 'file_num:n import_main_css:b', getThemeInterface: 'package_name:s color_interface_name:s typography_interface_name:s length_interface_name:s shadows_interface_name:s theme_interface_name:s', @@ -20,6 +21,7 @@ module.exports = function createBoundary() { reserveClassSlots: 'rows:rows _package:s single_css:b import_main_css_in_code:b _import_main_css_in_css:b import_aliases:aliases', seedFileMap: 'files:a', + selectSession: 'id:u', setAtomHoist: 'threshold:n', setDebug: 'debug:b', setModuleResolver: 'resolver:f', @@ -32,6 +34,7 @@ module.exports = function createBoundary() { p: 'a string, null or undefined', f: 'a function, null or undefined', a: 'an array of strings', + u: 'a session id', aliases: 'an alias mapping', canonical: 'a canonical mapping', class: 'a nested class-index mapping', @@ -51,6 +54,7 @@ module.exports = function createBoundary() { p: (value) => value == null || typeof value === 'string', f: (value) => value == null || typeof value === 'function', a: Array.isArray, + u: (value) => Number.isInteger(value) && value >= 0 && value <= 0xffffffff, } let frame const fail = (slot) => { diff --git a/bindings/devup-ui-binding/README.md b/bindings/devup-ui-binding/README.md index 71afa1212..6014328dc 100644 --- a/bindings/devup-ui-binding/README.md +++ b/bindings/devup-ui-binding/README.md @@ -2,7 +2,7 @@ Synchronous native build-time compiler for Node.js and Bun. Both `require('@devup-ui/binding')` and named ESM imports expose exactly the existing -30 compiler names, with identical function/class identities and no default init. +33 compiler names, with identical function/class identities and no default init. Authored CommonJS/ESM declarations are included; no WASM dependency is required. The private loader selects one optional platform sibling: Windows MSVC, macOS, @@ -96,4 +96,4 @@ The decoder is private and target-bounded: unused Serde hints use trait forwardi Malformed-enum error paths follow shipped serde-wasm-bindgen 0.6.5: Object.entries result length is read and coerced once for the check, then read and coerced again for the invalid-length diagnostic when the first length is not one, before any index read. The second value supplies the diagnostic; errors thrown by its getter or coercion propagate unchanged. Valid enums retain one length read. -The shared native/WASM boundary validates ordinary calls at 46 argument positions in 19 functions: malformed inputs throw a genuine `TypeError` naming the function, parameter and required type before state mutation. Preflight defaults the entire alias map on schema failure (after diagnostics) or a caught iterator-import failure whose `new Error(String(error))` conversion succeeds. Raw access failures and conversion faults escape unchanged before resolver selection; conversion runs once with the pending failure cleared, so reentry is isolated and resolver changes take effect before the outer core starts. Extraction and reservation remain strict. For example, `setPrefix(false)` throws `setPrefix(): argument prefix must be a string, null or undefined`; string/nullish prefixes remain supported. Extraction wrappers retain the measured metadata, receiver, extra-argument and apply/construct policy; `seedFileMap` validates and copies the caller's array before engine entry without rereading its indices. Same-revision Node/Bun identity, 272-case invalid-input, 73-exception preservation and seed-safety gates cover these contracts, not optimized shipping-native performance or real Node-host Linux Rust/authored-JS 100% coverage, which remain public-delivery gates. +The shared native/WASM boundary validates ordinary calls at 48 argument positions in 21 functions: malformed inputs throw a genuine `TypeError` naming the function, parameter and required type before state mutation. Preflight defaults the entire alias map on schema failure (after diagnostics) or a caught iterator-import failure whose `new Error(String(error))` conversion succeeds. Raw access failures and conversion faults escape unchanged before resolver selection; conversion runs once with the pending failure cleared, so reentry is isolated and resolver changes take effect before the outer core starts. Extraction and reservation remain strict. For example, `setPrefix(false)` throws `setPrefix(): argument prefix must be a string, null or undefined`; string/nullish prefixes remain supported. Extraction wrappers retain the measured metadata, receiver, extra-argument and apply/construct policy; `seedFileMap` validates and copies the caller's array before engine entry without rereading its indices. Same-revision Node/Bun identity, 288-case invalid-input, 73-exception preservation and seed-safety gates cover these contracts, not optimized shipping-native performance or real Node-host Linux Rust/authored-JS 100% coverage, which remain public-delivery gates. diff --git a/bindings/devup-ui-binding/adapter.cjs b/bindings/devup-ui-binding/adapter.cjs index a34c93cac..0c3e24546 100644 --- a/bindings/devup-ui-binding/adapter.cjs +++ b/bindings/devup-ui-binding/adapter.cjs @@ -82,6 +82,8 @@ exports.createBinding = function createBinding(raw) { Output: raw.Output, codeExtract, codeExtractWithoutSourceMap, + createSession: () => raw.createSession(), + dropSession: (id) => raw.dropSession(id), exportCanonicalMap: raw.exportCanonicalMap, exportClassMap: raw.exportClassMap, exportFileMap: raw.exportFileMap, @@ -108,6 +110,7 @@ exports.createBinding = function createBinding(raw) { resetBuildState: () => raw.reset(false), resetStateForTesting: () => raw.reset(true), seedFileMap, + selectSession: (id) => raw.selectSession(id), setAtomHoist: (value) => raw.setAtomHoist(index(value)), setDebug: (value) => raw.setDebug(value), setModuleResolver, diff --git a/bindings/devup-ui-binding/index.d.cts b/bindings/devup-ui-binding/index.d.cts index eae4ba96a..153dfeb41 100644 --- a/bindings/devup-ui-binding/index.d.cts +++ b/bindings/devup-ui-binding/index.d.cts @@ -11,7 +11,7 @@ export class Output { readonly updatedBaseStyle: boolean } -// Positional signatures intentionally match the existing 30-name compiler ABI. +// Positional signatures intentionally match the existing 33-name compiler ABI. export function codeExtract( filename: string, code: string, @@ -32,6 +32,10 @@ export function codeExtractWithoutSourceMap( importMainCssInCss: boolean, importAliases: unknown, ): Output +/** Create an engine session with a clean state; select it before each call. */ +export function createSession(): number +/** Drop a session and its state; dropping the live one makes session 0 live. */ +export function dropSession(id: number): boolean export function exportCanonicalMap(): string export function exportClassMap(): string export function exportFileMap(): string @@ -78,6 +82,8 @@ export function reserveClassSlots( export function resetBuildState(): void export function resetStateForTesting(): void export function seedFileMap(files: string[]): void +/** Make a session live: later calls work on its state until another is selected. */ +export function selectSession(id: number): void export function setAtomHoist(threshold?: number | null): void export function setDebug(debug: boolean): void export function setModuleResolver( diff --git a/bindings/devup-ui-binding/index.mjs b/bindings/devup-ui-binding/index.mjs index 015b58724..9e71069c4 100644 --- a/bindings/devup-ui-binding/index.mjs +++ b/bindings/devup-ui-binding/index.mjs @@ -4,6 +4,8 @@ export const { Output, codeExtract, codeExtractWithoutSourceMap, + createSession, + dropSession, exportCanonicalMap, exportClassMap, exportFileMap, @@ -27,6 +29,7 @@ export const { resetBuildState, resetStateForTesting, seedFileMap, + selectSession, setAtomHoist, setDebug, setModuleResolver, diff --git a/bindings/devup-ui-binding/src/host.rs b/bindings/devup-ui-binding/src/host.rs index 394ae0d40..50a782fed 100644 --- a/bindings/devup-ui-binding/src/host.rs +++ b/bindings/devup-ui-binding/src/host.rs @@ -16,20 +16,23 @@ pub struct Resolved { pub code: String, } type Resolver = FunctionRef, Option>>; -struct State(Option>); +/// The resolver each engine session set in this environment +struct State(core::PerSession>); /// Initialize environment-local ownership without overwriting existing state. #[napi] pub fn init(env: Env) -> Result<()> { if env.get_instance_data::()?.is_none() { - env.set_instance_data(State(None), (), |context| drop(context.value))?; + env.set_instance_data(State(core::PerSession::new()), (), |context| { + drop(context.value); + })?; } Ok(()) } /// Replace the owned synchronous resolver in the current environment only. #[napi] pub fn set_resolver(env: Env, resolver: Option) -> Result<()> { - state(&env)?.0 = resolver.map(Rc::new); + state(&env)?.0.set_live(resolver.map(Rc::new)); Ok(()) } fn state(env: &Env) -> Result<&'static mut State> { @@ -41,13 +44,32 @@ fn state(env: &Env) -> Result<&'static mut State> { pub fn reset(env: Env, full: bool) -> Result<()> { let state = state(&env)?; if full { - core::reset_state_internal(|| state.0 = None); + core::reset_state_internal(|| state.0 = core::PerSession::new()); } else { core::reset_build_state_internal(); - state.0 = None; + state.0.set_live(None); } Ok(()) } +/// Create an engine session with a clean state and return its id. +#[napi] +pub fn create_session() -> u32 { + core::create_session() +} +/// Make session `id` live until another is selected. +#[napi] +pub fn select_session(env: Env, id: u32) -> Result<()> { + core::select_session(id) + .map(drop) + .map_err(|error| binding_error(env, error)) +} +/// Drop session `id` with its state and this environment's resolver for it. +#[napi] +pub fn drop_session(env: Env, id: u32) -> Result { + let dropped = core::drop_session(id).map_err(|error| binding_error(env, error))?; + state(&env)?.0.remove(id); + Ok(dropped) +} fn with_resolver( env: Env, diagnostics: core::ResolverState, @@ -56,7 +78,7 @@ fn with_resolver( &dyn Fn() -> std::result::Result<(), String>, ) -> Result, ) -> Result { - let current = state(&env)?.0.clone(); + let current = state(&env)?.0.live(); let diagnostics = Rc::new(RefCell::new(diagnostics)); let failure = Rc::new(RefCell::new(None)); let resolver = current.map(|current| { diff --git a/bindings/devup-ui-binding/src/lib.rs b/bindings/devup-ui-binding/src/lib.rs index 7211b6d16..cc0eec980 100644 --- a/bindings/devup-ui-binding/src/lib.rs +++ b/bindings/devup-ui-binding/src/lib.rs @@ -5,7 +5,10 @@ mod host; mod output; mod value; -pub use host::{Resolved, extract, has_devup_ui, init, reserve, reset, set_resolver}; +pub use host::{ + Resolved, create_session, drop_session, extract, has_devup_ui, init, reserve, reset, + select_session, set_resolver, +}; pub use output::NativeOutput; use de::Wasm32Index; diff --git a/bindings/devup-ui-wasm/README.md b/bindings/devup-ui-wasm/README.md index 066708bcf..507b238b7 100644 --- a/bindings/devup-ui-wasm/README.md +++ b/bindings/devup-ui-wasm/README.md @@ -67,6 +67,16 @@ unwind. Binding tests compose these with sheet/resolver snapshots. Keep a named guard on its creating thread and retain `#[serial]`: guards clean up but do not serialize concurrent tests. Cleanup does not run for panic=abort. +## Sessions + +`createSession()` returns the id of a new engine session with a clean state, and +`selectSession(id)` makes it live: every later call reads and changes that +session's state, resolver included, until another is selected. Session 0 is +live from the start, so a single app needs neither. Two apps in one process +each select their own session before each call. `dropSession(id)` forgets a +session (dropping the live one makes session 0 live), and the full test reset +forgets every session but 0. + ## Errors A source the build cannot compile makes `codeExtract` throw an `Error`. Its diff --git a/bindings/devup-ui-wasm/script.js b/bindings/devup-ui-wasm/script.js index 7bc343dff..754f3bb39 100644 --- a/bindings/devup-ui-wasm/script.js +++ b/bindings/devup-ui-wasm/script.js @@ -50,9 +50,9 @@ types = types.replace(hookType, '') assert.equal(types.includes('install_panic_hook'), false) writeFileSync('pkg/index.d.ts', types, 'utf8') const names = [...source.matchAll(/^exports\.(\w+) = \1;/gm)] -assert.equal(names.length, 30) -assert.equal(new Set(names.map((match) => match[1])).size, 30) -assert.equal([...source.matchAll(/^exports\./gm)].length, 30) +assert.equal(names.length, 33) +assert.equal(new Set(names.map((match) => match[1])).size, 33) +assert.equal([...source.matchAll(/^exports\./gm)].length, 33) assert.equal(source.includes('module.exports'), false) for (const name of ['codeExtract', 'codeExtractWithoutSourceMap']) { const signatures = [ diff --git a/bindings/devup-ui-wasm/src/lib.rs b/bindings/devup-ui-wasm/src/lib.rs index 067b5abb6..516044ce8 100644 --- a/bindings/devup-ui-wasm/src/lib.rs +++ b/bindings/devup-ui-wasm/src/lib.rs @@ -40,7 +40,9 @@ mod css_output_edge_tests; mod dynamic_as_sibling_props_tests; thread_local! { - static MODULE_RESOLVER: RefCell> = const { RefCell::new(None) }; + /// The resolver `setModuleResolver` set in each engine session + static MODULE_RESOLVER: RefCell> = + const { RefCell::new(binding_core::PerSession::new()) }; } #[cfg(not(tarpaulin_include))] @@ -297,6 +299,40 @@ pub fn seed_file_map(files: Vec) { binding_core::seed_file_map(&files); } +/// Create an engine session with a clean state and return its id. +/// +/// Two apps in one process each keep their own session: select it before +/// every call so the call reads and changes only that app's state. Session 0 +/// is live until another is selected. +#[wasm_bindgen(js_name = "createSession")] +#[must_use] +pub fn create_session() -> u32 { + binding_core::create_session() +} + +/// Make session `id` live: every later call works on its state until +/// another session is selected. +#[wasm_bindgen(js_name = "selectSession")] +#[cfg(not(tarpaulin_include))] +pub fn select_session(id: u32) -> Result<(), JsValue> { + binding_core::select_session(id).map(drop).map_err(js_error) +} + +/// Drop session `id` with its state and resolver (testable without `JsValue`) +pub fn drop_session_internal(id: u32) -> Result { + let dropped = binding_core::drop_session(id)?; + MODULE_RESOLVER.with_borrow_mut(|resolvers| resolvers.remove(id)); + Ok(dropped) +} + +/// Drop session `id` with its state and module resolver, returning whether +/// it existed. Dropping the live session makes session 0 live. +#[wasm_bindgen(js_name = "dropSession")] +#[cfg(not(tarpaulin_include))] +pub fn drop_session(id: u32) -> Result { + drop_session_internal(id).map_err(js_error) +} + /// Forget a source file that was deleted or renamed away. /// /// Its global CSS, its own bucket and the class names handed out in it go, @@ -314,7 +350,7 @@ pub fn remove_file(filename: &str) -> bool { /// alone. Theme, shorthands and debug mode are set by every build, and stay. pub fn reset_build_state_internal() { binding_core::reset_build_state_internal(); - MODULE_RESOLVER.with_borrow_mut(|current| *current = None); + MODULE_RESOLVER.with_borrow_mut(|current| current.set_live(None)); } #[wasm_bindgen(js_name = "resetBuildState")] @@ -476,7 +512,7 @@ fn code_extract_internal_impl( #[wasm_bindgen(js_name = "setModuleResolver")] #[cfg(not(tarpaulin_include))] pub fn set_module_resolver(resolver: Option) { - MODULE_RESOLVER.with_borrow_mut(|current| *current = resolver); + MODULE_RESOLVER.with_borrow_mut(|current| current.set_live(resolver)); } #[cfg(not(tarpaulin_include))] @@ -537,7 +573,7 @@ fn call_module_resolver( /// The resolver set by `setModuleResolver`, if any #[cfg(not(tarpaulin_include))] fn resolver_from_js(state: std::rc::Rc>) -> Option> { - let resolver = MODULE_RESOLVER.with_borrow(Clone::clone)?; + let resolver = MODULE_RESOLVER.with_borrow(binding_core::PerSession::live)?; Some(Box::new(move |specifier: &str, importer: &str| { let request = state.borrow().request(specifier, importer)?; call_module_resolver(&resolver, request, &state) @@ -1727,6 +1763,25 @@ mod tests { assert!(json_str.starts_with('{') || json_str.starts_with("[]")); } + #[test] + #[serial] + fn sessions_keep_their_own_prefix_until_dropped() { + let _state = TestStateGuard::new(); + // Given: a second session with its own prefix + let session = create_session(); + assert_eq!(binding_core::select_session(session), Ok(0)); + set_prefix(Some("app-".into())); + // When / Then: session 0 keeps its own, and the dropped session goes + assert_eq!(binding_core::select_session(0), Ok(session)); + assert_eq!(get_prefix(), None); + assert_eq!( + drop_session_internal(0), + Err("engine session 0 cannot be dropped".to_string()) + ); + assert_eq!(drop_session_internal(session), Ok(true)); + assert_eq!(drop_session_internal(session), Ok(false)); + } + #[test] #[serial] fn remove_file_reports_whether_the_sheet_changed() { diff --git a/bindings/devup-ui-wasm/src/reservation.rs b/bindings/devup-ui-wasm/src/reservation.rs index f3c692439..baf3cb9b4 100644 --- a/bindings/devup-ui-wasm/src/reservation.rs +++ b/bindings/devup-ui-wasm/src/reservation.rs @@ -37,16 +37,18 @@ pub fn reserve_class_slots( import_aliases: import_aliases_from_js(import_aliases, 5)?, ..ExtractOption::default() }; - let resolver = MODULE_RESOLVER.with_borrow(Clone::clone).map(|resolver| { - let state = Rc::new(RefCell::new(ResolverState::default())); - for input in &inputs { - state.borrow_mut().add_source(&input.filename, &input.code); - } - move |specifier: &str, importer: &str| { - let request = state.borrow().request(specifier, importer)?; - call_module_resolver(&resolver, request, &state) - } - }); + let resolver = MODULE_RESOLVER + .with_borrow(devup_ui_binding_core::PerSession::live) + .map(|resolver| { + let state = Rc::new(RefCell::new(ResolverState::default())); + for input in &inputs { + state.borrow_mut().add_source(&input.filename, &input.code); + } + move |specifier: &str, importer: &str| { + let request = state.borrow().request(specifier, importer)?; + call_module_resolver(&resolver, request, &state) + } + }); reserve_class_slots_internal( &inputs, option, diff --git a/bindings/devup-ui-wasm/src/state.rs b/bindings/devup-ui-wasm/src/state.rs index d503fad73..9b42bc82a 100644 --- a/bindings/devup-ui-wasm/src/state.rs +++ b/bindings/devup-ui-wasm/src/state.rs @@ -4,7 +4,7 @@ use wasm_bindgen::prelude::*; /// Never call during extraction or a resolver callback, or between build environments. pub fn reset_state_internal() { devup_ui_binding_core::reset_state_internal(|| { - super::MODULE_RESOLVER.with_borrow_mut(|resolver| *resolver = None); + super::MODULE_RESOLVER.with_borrow_mut(|resolver| *resolver = Default::default()); }); } @@ -17,7 +17,7 @@ pub fn reset_state_for_testing() { #[cfg(test)] pub(crate) struct TestStateGuard { sheet: sheet::StyleSheet, - resolver: Option, + resolver: devup_ui_binding_core::PerSession, _engine: extractor::test_state::TestStateGuard, } @@ -26,7 +26,7 @@ impl TestStateGuard { pub(crate) fn new() -> Self { Self { sheet: super::with_style_sheet_mut(std::mem::take), - resolver: super::MODULE_RESOLVER.with_borrow_mut(Option::take), + resolver: super::MODULE_RESOLVER.with_borrow_mut(std::mem::take), _engine: extractor::test_state::TestStateGuard::new(), } } @@ -36,6 +36,7 @@ impl TestStateGuard { impl Drop for TestStateGuard { fn drop(&mut self) { super::with_style_sheet_mut(|sheet| *sheet = std::mem::take(&mut self.sheet)); - super::MODULE_RESOLVER.with_borrow_mut(|resolver| *resolver = self.resolver.take()); + super::MODULE_RESOLVER + .with_borrow_mut(|resolver| *resolver = std::mem::take(&mut self.resolver)); } } diff --git a/bindings/devup-ui-wasm/src/state/tests.rs b/bindings/devup-ui-wasm/src/state/tests.rs index d9b2bb1d9..20c08efcb 100644 --- a/bindings/devup-ui-wasm/src/state/tests.rs +++ b/bindings/devup-ui-wasm/src/state/tests.rs @@ -52,7 +52,7 @@ fn reset_returns_fresh_extraction_when_engine_is_dirty() { reset_state_for_testing(); assert_eq!(export_sheet_internal().unwrap(), empty_sheet); assert_eq!(get_default_theme().unwrap(), None); - assert!(MODULE_RESOLVER.with_borrow(Option::is_none)); + assert!(MODULE_RESOLVER.with_borrow(|resolver| resolver.live().is_none())); assert_eq!(get_prefix(), None); assert!(!is_debug()); assert_eq!(css::atom_hoist::atom_hoist_threshold(), None); diff --git a/e2e/binding/corpus/state.mjs b/e2e/binding/corpus/state.mjs index 85f5e8b64..9a56e169f 100644 --- a/e2e/binding/corpus/state.mjs +++ b/e2e/binding/corpus/state.mjs @@ -42,6 +42,33 @@ add('reservation-malformed-second-row-arity-nonmutation', (h) => { h.call('reserveClassSlots', value, pkg, false, false, false, {}) h.call('reserveClassSlots', rows, pkg, false, false, false, { bad: 7 }) }) +add('sessions-keep-apart-until-dropped', (h) => { + h.call('setPrefix', 'zero-') + h.extract(source) + const session = h.call('createSession').value.value + h.call('selectSession', session) + h.call('registerTheme', theme) + h.extract(box('color="blue"'), { filename: 'src/second.tsx' }) + h.call('selectSession', 0) + h.extract(source) + h.call('selectSession', 7) + h.call('dropSession', 0) + h.call('selectSession', session) + h.call('dropSession', session) + h.call('dropSession', session) +}) +add('remove-file-stays-in-its-session', (h) => { + h.extract(source, { single: false }) + const session = h.call('createSession').value.value + h.call('selectSession', session) + h.extract(box('color="blue"'), { single: false }) + h.call('selectSession', 0) + h.call('removeFile', file) + h.call('removeFile', file) + h.call('selectSession', session) + h.call('removeFile', file) + h.call('dropSession', session) +}) add('remove-file-drops-its-own-styles', (h) => { h.call('importCanonicalMap', { 'src/child.tsx': 'src/root.tsx' }) h.extract(source, { single: false }) diff --git a/e2e/binding/host.mjs b/e2e/binding/host.mjs index a86141ce5..861eed8ba 100644 --- a/e2e/binding/host.mjs +++ b/e2e/binding/host.mjs @@ -68,7 +68,7 @@ save('provenance.json', { scenarios: corpus.map((c) => c.name), }) const names = - 'Output codeExtract codeExtractWithoutSourceMap exportCanonicalMap exportClassMap exportFileMap exportSheet getCss getDefaultTheme getPrefix getThemeInterface getUnreservedClassSlotCount hasDevupUI importCanonicalMap importClassMap importFileMap importFileRoutes importSheet isDebug registerShorthands registerTheme removeFile reserveClassSlots resetBuildState resetStateForTesting seedFileMap setAtomHoist setDebug setModuleResolver setPrefix'.split( + 'Output codeExtract codeExtractWithoutSourceMap createSession dropSession exportCanonicalMap exportClassMap exportFileMap exportSheet getCss getDefaultTheme getPrefix getThemeInterface getUnreservedClassSlotCount hasDevupUI importCanonicalMap importClassMap importFileMap importFileRoutes importSheet isDebug registerShorthands registerTheme removeFile reserveClassSlots resetBuildState resetStateForTesting seedFileMap selectSession setAtomHoist setDebug setModuleResolver setPrefix'.split( ' ', ) const abi = { @@ -199,8 +199,8 @@ const h = { ) }, } -assert.equal(corpus.length, 26) -assert.equal(new Set(corpus.map((c) => c.name)).size, 26) +assert.equal(corpus.length, 28) +assert.equal(new Set(corpus.map((c) => c.name)).size, 28) h.note('public-error-inventory', runDiagnostics(w)) for (const test of corpus) { scenario = test.name diff --git a/e2e/binding/package/consumer.mjs b/e2e/binding/package/consumer.mjs index 3940b9cca..c3bb6d17f 100644 --- a/e2e/binding/package/consumer.mjs +++ b/e2e/binding/package/consumer.mjs @@ -136,7 +136,7 @@ export async function consume(options) { ] .map((match) => match[1]) .sort() - assert.equal(names.length, 30) + assert.equal(names.length, 33) for (const manager of ['npm', 'bun']) { for (const omit of [false, true]) { const startRequest = server.requests.length diff --git a/e2e/binding/validation-cases.mjs b/e2e/binding/validation-cases.mjs index f69d04387..715538bdd 100644 --- a/e2e/binding/validation-cases.mjs +++ b/e2e/binding/validation-cases.mjs @@ -20,6 +20,7 @@ const extractSlots = export const positions = [ ['codeExtract', extractSlots, extraction], ['codeExtractWithoutSourceMap', extractSlots, extraction], + ['dropSession', 'id:session', () => [1]], ['getCss', 'file_num:n import_main_css:b', () => [null, false]], [ 'getThemeInterface', @@ -45,6 +46,7 @@ export const positions = [ () => [[row], pkg, false, false, false, {}], ], ['seedFileMap', 'files:seed', () => [['src/new.tsx']]], + ['selectSession', 'id:session', () => [0]], ['setAtomHoist', 'threshold:n', () => [2]], ['setDebug', 'debug:b', () => [true]], ['setModuleResolver', 'resolver:resolver', () => [null]], @@ -62,6 +64,7 @@ const labels = { prefix: 'a string, null or undefined', resolver: 'a function, null or undefined', seed: 'an array of strings', + session: 'a session id', aliases: 'an alias mapping', canonical: 'a canonical mapping', class: 'a nested class-index mapping', @@ -81,6 +84,7 @@ const invalid = { b: [7, 'false', null, undefined], n: ['2', false, 1n, Symbol('number'), {}], prefix: [false, true, 7, {}], + session: ['1', false, -1, 1.5, 2 ** 32, null, undefined, {}], resolver: [false, true, 7, 'callback', {}], seed: [ ...roots, @@ -154,6 +158,6 @@ export const cases = positions.flatMap((position) => .map((good, index) => (index === position.index ? value : good)), })), ) -assert.equal(positions.length, 46) -assert.equal(new Set(positions.map((p) => p.fn)).size, 19) +assert.equal(positions.length, 48) +assert.equal(new Set(positions.map((p) => p.fn)).size, 21) assert.equal(new Set(cases.map((c) => c.id)).size, cases.length) diff --git a/e2e/binding/validation.mjs b/e2e/binding/validation.mjs index 499bb1b34..d1ee1fe06 100644 --- a/e2e/binding/validation.mjs +++ b/e2e/binding/validation.mjs @@ -114,7 +114,7 @@ for (const [engine, entry] of [ const summary = { cases: cases.length, positions: positions.length, - functions: 18, + functions: 21, engines: 2, runs: runs.length, failed: runs.filter((run) => run.failed).length, diff --git a/libs/binding/src/lib.rs b/libs/binding/src/lib.rs index a7d7a4c23..cf38d16c4 100644 --- a/libs/binding/src/lib.rs +++ b/libs/binding/src/lib.rs @@ -4,6 +4,7 @@ mod css_cache; mod output; mod reservation; mod resolver_state; +pub mod session; pub use css::debug::{is_debug, set_debug}; pub use css::slot_reservation::unreserved_slot_count as get_unreserved_class_slot_count; @@ -13,6 +14,9 @@ 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, check_resolved_path, resolved_module}; +pub use session::{ + PerSession, create_session, drop_session, live_session, select_session, with_session, +}; 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}; @@ -166,7 +170,10 @@ pub fn reset_build_state_internal() { } /// Clear test state at a quiescent boundary, clearing the host resolver before registries. +/// +/// Every engine session but 0 goes, and session 0 starts clean. pub fn reset_state_internal(clear_resolver: impl FnOnce()) { + session::reset_sessions(); with_style_sheet_mut(|sheet| *sheet = StyleSheet::default()); clear_resolver(); css::test_state::reset_state_for_testing(); diff --git a/libs/binding/src/session.rs b/libs/binding/src/session.rs new file mode 100644 index 000000000..f060cbe73 --- /dev/null +++ b/libs/binding/src/session.rs @@ -0,0 +1,240 @@ +//! Engine sessions: independent engine states in one process. +//! +//! The engine's globals always hold one session's state, the live session. +//! Every other session's state is parked here. Switching to a session +//! exchanges its parked state with the live globals, so the code that reads +//! them does not know about sessions. Session 0 exists from the start; until a +//! host creates another, the engine behaves as a single process-wide engine. +//! +//! The parked CSS numbering and stylesheet may cross threads. The extractor's +//! stylesheet caches stay on the thread that filled them, so each thread keeps +//! its own per-session caches and aligns them on every switch. + +use std::cell::{Cell, RefCell}; +use std::collections::BTreeMap; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::{Mutex, MutexGuard, PoisonError}; + +use css::engine_state::CssState; +use extractor::ExtractorCaches; +use sheet::StyleSheet; + +use crate::with_style_sheet_mut; + +/// Everything one session keeps between calls, apart from thread-bound caches: +/// the CSS crate's numbering, registries and settings, and the stylesheet. +#[derive(Default)] +pub struct EngineState { + css: CssState, + sheet: StyleSheet, +} + +impl EngineState { + /// Exchange this state with the live one. + pub fn swap_live(&mut self) { + self.css.swap_live(); + with_style_sheet_mut(|live| std::mem::swap(live, &mut self.sheet)); + } +} + +struct Sessions { + next: u32, + parked: BTreeMap, +} + +#[derive(Default)] +struct ThreadCaches { + live: u32, + parked: BTreeMap, +} + +/// The session whose state the globals hold. +static LIVE: AtomicU32 = AtomicU32::new(0); + +static SESSIONS: Mutex = Mutex::new(Sessions { + next: 1, + parked: BTreeMap::new(), +}); + +/// Held while [`with_session`] runs, so no other thread switches under it. +static RUNNING: Mutex<()> = Mutex::new(()); + +thread_local! { + static CACHES: RefCell = RefCell::default(); + /// Whether this thread is inside [`with_session`] + static INSIDE: Cell = const { Cell::new(false) }; +} + +fn sessions() -> MutexGuard<'static, Sessions> { + SESSIONS.lock().unwrap_or_else(PoisonError::into_inner) +} + +fn running() -> MutexGuard<'static, ()> { + RUNNING.lock().unwrap_or_else(PoisonError::into_inner) +} + +fn unknown(id: u32) -> String { + format!("engine session {id} does not exist: create it with createSession() first") +} + +fn busy(live: u32) -> String { + format!("engine session {live} is running a call: switch sessions only after that call returns") +} + +/// The session whose state is live. +pub fn live_session() -> u32 { + LIVE.load(Ordering::Acquire) +} + +/// Park the live state and make session `id` live, returning the session +/// that was live. +fn switch(id: u32) -> Result { + let live = live_session(); + if id != live { + // Callers hold the session lock, so the state can be swapped unlocked + let mut state = sessions().parked.remove(&id).ok_or_else(|| unknown(id))?; + state.swap_live(); + sessions().parked.insert(live, state); + LIVE.store(id, Ordering::Release); + } + align_caches(id); + Ok(live) +} + +/// Make this thread's live caches those of session `id`. +fn align_caches(id: u32) { + CACHES.with_borrow_mut(|caches| { + if caches.live != id { + let mut next = caches.parked.remove(&id).unwrap_or_default(); + next.swap_live(); + caches.parked.insert(caches.live, next); + caches.live = id; + } + }); +} + +/// Create a session with a clean engine state, returning its id. +/// +/// Ids are never handed out twice, even after the session is dropped. +pub fn create_session() -> u32 { + let mut sessions = sessions(); + let id = sessions.next; + sessions.next = id.saturating_add(1); + sessions.parked.insert(id, EngineState::default()); + id +} + +/// Make session `id` live until another is selected, returning the session +/// that was live. +/// +/// # Errors +/// When the session does not exist, or a [`with_session`] call is running on +/// this thread with another session live. +pub fn select_session(id: u32) -> Result { + if INSIDE.get() { + let live = live_session(); + return if id == live { + Ok(live) + } else { + Err(busy(live)) + }; + } + let _running = running(); + switch(id) +} + +/// Drop session `id` and its state, returning whether it existed. Dropping +/// the live session makes session 0 live first. +/// +/// Caches the session left on other threads go when those threads end. +/// +/// # Errors +/// For session 0, and when the session is live inside a running +/// [`with_session`] call. +pub fn drop_session(id: u32) -> Result { + if id == 0 { + return Err("engine session 0 cannot be dropped".to_string()); + } + if live_session() == id { + select_session(0)?; + } + CACHES.with_borrow_mut(|caches| caches.parked.remove(&id)); + Ok(sessions().parked.remove(&id).is_some()) +} + +/// Switches back to the session that was live, also on unwind. +struct Restore(u32); + +impl Drop for Restore { + fn drop(&mut self) { + INSIDE.set(false); + switch(self.0).ok(); + } +} + +/// Run `f` with session `id` live, then make the previous session live +/// again, holding the session lock throughout. +/// +/// A nested call on the same thread runs directly when `id` is already live. +/// +/// # Errors +/// When the session does not exist, or a nested call names another session. +pub fn with_session(id: u32, f: impl FnOnce() -> R) -> Result { + if INSIDE.get() { + let live = live_session(); + return if id == live { Ok(f()) } else { Err(busy(live)) }; + } + let _running = running(); + let _restore = Restore(switch(id)?); + INSIDE.set(true); + Ok(f()) +} + +/// Forget every session but 0 and make it live, for the full test reset that +/// then clears the live state. +pub fn reset_sessions() { + sessions().parked.clear(); + LIVE.store(0, Ordering::Release); + CACHES.with_borrow_mut(|caches| *caches = ThreadCaches::default()); +} + +/// A value a host adapter keeps for each session itself, such as the module +/// resolver it calls back into: the live session's value is the one in use. +#[derive(Debug)] +pub struct PerSession(BTreeMap); + +impl Default for PerSession { + fn default() -> Self { + Self::new() + } +} + +impl PerSession { + pub const fn new() -> Self { + Self(BTreeMap::new()) + } +} + +impl PerSession { + /// The live session's value. + pub fn live(&self) -> Option { + self.0.get(&live_session()).cloned() + } + + /// Set or clear the live session's value. + pub fn set_live(&mut self, value: Option) { + let live = live_session(); + match value { + Some(value) => self.0.insert(live, value), + None => self.0.remove(&live), + }; + } + + /// Forget a dropped session's value. + pub fn remove(&mut self, id: u32) { + self.0.remove(&id); + } +} + +#[cfg(test)] +mod tests; diff --git a/libs/binding/src/session/tests.rs b/libs/binding/src/session/tests.rs new file mode 100644 index 000000000..173d20e88 --- /dev/null +++ b/libs/binding/src/session/tests.rs @@ -0,0 +1,272 @@ +use super::*; +use crate::{ + ExtractionMode, SourceMapMode, code_extract, get_css, register_theme_internal, + remove_file_internal, with_style_sheet, +}; +use extractor::ExtractOption; +use serial_test::serial; + +/// Clean engine state for the test, and only session 0 afterwards. +struct Clean { + _sheet: SheetGuard, + _engine: extractor::test_state::TestStateGuard, +} + +struct SheetGuard(StyleSheet); + +impl Drop for SheetGuard { + fn drop(&mut self) { + reset_sessions(); + with_style_sheet_mut(|sheet| std::mem::swap(sheet, &mut self.0)); + } +} + +fn clean() -> Clean { + reset_sessions(); + Clean { + _sheet: SheetGuard(with_style_sheet_mut(std::mem::take)), + _engine: extractor::test_state::TestStateGuard::new(), + } +} + +fn extract(filename: &str, color: &str) -> String { + extract_source( + filename, + &format!("import {{Box}} from '@devup-ui/react'; ;"), + ) +} + +fn extract_global(filename: &str, color: &str) -> String { + extract_source( + filename, + &format!( + "import {{globalCss}} from '@devup-ui/react'; globalCss({{ body: {{ color: \"{color}\" }} }});" + ), + ) +} + +fn extract_source(filename: &str, source: &str) -> String { + code_extract( + (filename, source), + ExtractOption { + single_css: true, + ..ExtractOption::default() + }, + ExtractionMode { + source_map: SourceMapMode::Skip, + resolver: None, + resolver_check: None, + import_main_css_in_css: false, + }, + ) + .map_or_else(|error| panic!("{error}"), |output| output.code) +} + +#[test] +#[serial] +fn sessions_keep_their_own_numbering_settings_and_sheet() { + let _clean = clean(); + // Given: session 0 extracted one file under a prefix + css::set_prefix(Some("zero-".into())); + extract("zero.tsx", "red"); + let session = create_session(); + // When: another session extracts the same file differently + let code = with_session(session, || { + assert_eq!(live_session(), session); + assert_eq!(css::get_prefix(), None); + assert_eq!(css::file_map::get_file_map().len(), 0); + register_theme_internal( + serde_json::from_str(r##"{"colors":{"default":{"brand":"#fff"}}}"##) + .unwrap_or_else(|error| panic!("{error}")), + ); + extract("other.tsx", "blue") + }); + // Then: each session reads only its own state + assert_eq!(live_session(), 0); + assert_eq!(css::get_prefix().as_deref(), Some("zero-")); + assert!(get_css(None, false).contains("color:red")); + assert!(!get_css(None, false).contains("color:blue")); + assert!(with_style_sheet(|sheet| sheet.theme.colors.is_empty())); + assert!(code.is_ok_and(|code| code.contains("className=\"a\""))); + let css = with_session(session, || { + assert!( + css::file_map::get_file_map() + .get_by_left("zero.tsx") + .is_none() + ); + get_css(None, false) + }); + assert!(css.is_ok_and(|css| css.contains("color:blue") && css.contains("--brand"))); +} + +#[test] +#[serial] +fn removing_a_file_forgets_it_only_in_the_live_session() { + let _clean = clean(); + // Given: two sessions each extracted global CSS from the same filename + extract_global("shared.tsx", "red"); + let session = create_session(); + assert!(with_session(session, || extract_global("shared.tsx", "blue")).is_ok()); + // When: the live session 0 forgets the file + assert!(remove_file_internal("shared.tsx")); + // Then: session 0 lost its styles while the other session kept its own + assert!(!get_css(None, false).contains("color:red")); + let css = with_session(session, || get_css(None, false)); + assert!(css.is_ok_and(|css| css.contains("color:blue"))); + assert_eq!( + with_session(session, || remove_file_internal("shared.tsx")), + Ok(true) + ); +} + +#[test] +#[serial] +fn selecting_a_session_keeps_it_live_until_another_is_selected() { + let _clean = clean(); + let first = create_session(); + let second = create_session(); + assert_ne!(first, second); + assert_eq!(select_session(first), Ok(0)); + css::set_prefix(Some("first-".into())); + assert_eq!(select_session(first), Ok(first)); + assert_eq!(select_session(second), Ok(first)); + assert_eq!(css::get_prefix(), None); + assert_eq!(select_session(first), Ok(second)); + assert_eq!(css::get_prefix().as_deref(), Some("first-")); + assert_eq!(select_session(0), Ok(first)); + assert_eq!(css::get_prefix(), None); +} + +#[test] +#[serial] +fn unknown_sessions_are_refused() { + let _clean = clean(); + let message = unknown(42); + assert_eq!(select_session(42), Err(message.clone())); + assert_eq!(with_session(42, || ()), Err(message)); + assert_eq!(live_session(), 0); +} + +#[test] +#[serial] +fn nested_calls_may_not_switch_sessions() { + let _clean = clean(); + let session = create_session(); + let nested = with_session(session, || { + ( + with_session(session, live_session), + with_session(0, live_session), + select_session(session), + select_session(0), + drop_session(session), + ) + }); + assert_eq!( + nested, + Ok(( + Ok(session), + Err(busy(session)), + Ok(session), + Err(busy(session)), + Err(busy(session)), + )) + ); + assert_eq!(live_session(), 0); +} + +#[test] +#[serial] +fn a_panicking_call_still_switches_back() { + let _clean = clean(); + let session = create_session(); + let result = std::panic::catch_unwind(|| { + with_session(session, || { + css::set_prefix(Some("lost-".into())); + panic!("call failed"); + }) + }); + assert!(result.is_err()); + assert_eq!(live_session(), 0); + assert_eq!(css::get_prefix(), None); + assert_eq!( + with_session(session, css::get_prefix), + Ok(Some("lost-".into())) + ); +} + +#[test] +#[serial] +fn dropping_sessions() { + let _clean = clean(); + assert_eq!( + drop_session(0), + Err("engine session 0 cannot be dropped".to_string()) + ); + let parked = create_session(); + let live = create_session(); + assert_eq!(drop_session(parked), Ok(true)); + assert_eq!(drop_session(parked), Ok(false)); + assert_eq!(select_session(parked), Err(unknown(parked))); + css::set_prefix(Some("zero-".into())); + assert_eq!(select_session(live), Ok(0)); + // Dropping the live session makes session 0 live again + assert_eq!(drop_session(live), Ok(true)); + assert_eq!(live_session(), 0); + assert_eq!(css::get_prefix().as_deref(), Some("zero-")); + // Ids are not handed out twice + assert!(create_session() > live); +} + +#[test] +#[serial] +fn caches_follow_the_session_on_each_thread() { + let _clean = clean(); + let session = create_session(); + assert_eq!(select_session(session), Ok(0)); + // Another thread aligns its own caches when it switches + let other = std::thread::spawn(move || { + let selected = (select_session(session), select_session(0)); + CACHES.with_borrow(|caches| (selected, caches.live, caches.parked.len())) + }) + .join(); + assert!(other.is_ok_and(|other| other == ((Ok(session), Ok(session)), 0, 1))); + assert_eq!(live_session(), 0); + CACHES.with_borrow(|caches| assert_eq!((caches.live, caches.parked.len()), (session, 1))); + assert_eq!(select_session(0), Ok(0)); + CACHES.with_borrow(|caches| assert_eq!((caches.live, caches.parked.len()), (0, 1))); +} + +#[test] +#[serial] +fn per_session_values_follow_the_live_session() { + let _clean = clean(); + let mut values = PerSession::::default(); + values.set_live(Some(1)); + let session = create_session(); + assert_eq!( + with_session(session, || { + let before = values.live(); + values.set_live(Some(2)); + (before, values.live()) + }), + Ok((None, Some(2))) + ); + assert_eq!(values.live(), Some(1)); + values.remove(0); + assert_eq!(values.live(), None); + values.set_live(Some(3)); + values.set_live(None); + assert_eq!(values.live(), None); + assert!(format!("{values:?}").contains('2')); +} + +#[test] +#[serial] +fn full_reset_forgets_every_session() { + let _clean = clean(); + let session = create_session(); + assert_eq!(select_session(session), Ok(0)); + crate::reset_state_internal(|| {}); + assert_eq!(live_session(), 0); + assert_eq!(select_session(session), Err(unknown(session))); +} diff --git a/libs/css/src/engine_state.rs b/libs/css/src/engine_state.rs new file mode 100644 index 000000000..b4752fc82 --- /dev/null +++ b/libs/css/src/engine_state.rs @@ -0,0 +1,69 @@ +//! Everything the CSS crate keeps between calls, held as one value so an +//! engine session can own it while another session's state is live. + +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; +use std::sync::atomic::Ordering; + +use crate::{ + atom_hoist, class_map, debug, file_map, file_routes, slot_reservation, tailwind_definitions, + theme_tokens, +}; + +/// The prefix, debug flag, atom hoisting, class and file numbering, routes, +/// shorthands, theme tokens and Tailwind definitions of one engine session. +/// +/// The default value is a clean engine, as after a full reset. +#[derive(Default)] +pub struct CssState { + prefix: Option, + debug: bool, + hoist: Option, + plan: Option>, + reservation: slot_reservation::State, + classes: HashMap>, + files: bimap::BiHashMap, + canonical: HashMap, + routes: HashMap>, + shorthands: (BTreeMap>, bool), + tokens: theme_tokens::ThemeTokenRegistry, + tailwind: tailwind_definitions::Definitions, +} + +impl CssState { + /// Exchange this state with the live one: afterwards the live engine runs + /// on what this value held, and this value holds what was live. + pub fn swap_live(&mut self) { + let prefix = crate::get_prefix(); + crate::set_prefix(std::mem::replace(&mut self.prefix, prefix)); + let debug = debug::is_debug(); + debug::set_debug(std::mem::replace(&mut self.debug, debug)); + let hoist = atom_hoist::atom_hoist_threshold(); + atom_hoist::set_atom_hoist(std::mem::replace(&mut self.hoist, hoist)); + let plan = atom_hoist::atom_plan(); + atom_hoist::restore_atom_plan(std::mem::replace(&mut self.plan, plan)); + self.reservation = slot_reservation::replace_state(self.reservation); + class_map::with_class_map_mut(|live| std::mem::swap(live, &mut self.classes)); + file_map::with_file_map_mut(|live| std::mem::swap(live, &mut self.files)); + file_map::with_canonical_map_mut(|live| std::mem::swap(live, &mut self.canonical)); + file_routes::with_file_routes_mut(|live| std::mem::swap(live, &mut self.routes)); + self.shorthands = replace_shorthands(std::mem::take(&mut self.shorthands)); + self.tokens = theme_tokens::replace_registry(std::mem::take(&mut self.tokens)); + self.tailwind = + tailwind_definitions::replace_definitions(std::mem::take(&mut self.tailwind)); + } +} + +/// Install `state` as the live custom shorthands, returning the previous ones +/// and clearing a poisoned lock. +pub(crate) fn replace_shorthands( + state: (BTreeMap>, bool), +) -> (BTreeMap>, bool) { + let mut registry = crate::CUSTOM_SHORTHANDS + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let old = std::mem::replace(&mut *registry, state.0); + let present = crate::HAS_CUSTOM_SHORTHANDS.swap(state.1, Ordering::Relaxed); + drop(registry); + crate::CUSTOM_SHORTHANDS.clear_poison(); + (old, present) +} diff --git a/libs/css/src/file_map.rs b/libs/css/src/file_map.rs index 0c12d8723..b425725ab 100644 --- a/libs/css/src/file_map.rs +++ b/libs/css/src/file_map.rs @@ -38,7 +38,7 @@ where } #[inline] -fn with_file_map_mut(f: F) -> R +pub(crate) fn with_file_map_mut(f: F) -> R where F: FnOnce(&mut BiHashMap) -> R, { @@ -150,7 +150,7 @@ where } #[inline] -fn with_canonical_map_mut(f: F) -> R +pub(crate) fn with_canonical_map_mut(f: F) -> R where F: FnOnce(&mut std::collections::HashMap) -> R, { diff --git a/libs/css/src/file_routes.rs b/libs/css/src/file_routes.rs index bb16a8154..367407bde 100644 --- a/libs/css/src/file_routes.rs +++ b/libs/css/src/file_routes.rs @@ -42,7 +42,7 @@ where } #[inline] -fn with_file_routes_mut(f: F) -> R +pub(crate) fn with_file_routes_mut(f: F) -> R where F: FnOnce(&mut HashMap>) -> R, { diff --git a/libs/css/src/lib.rs b/libs/css/src/lib.rs index 43e2509a6..1e8ff692b 100644 --- a/libs/css/src/lib.rs +++ b/libs/css/src/lib.rs @@ -6,6 +6,7 @@ pub mod atom_name; pub mod class_map; mod constant; pub mod debug; +pub mod engine_state; pub mod file_map; pub mod file_routes; pub mod is_special_property; @@ -268,7 +269,7 @@ static HAS_CUSTOM_SHORTHANDS: AtomicBool = AtomicBool::new(false); /// Clear custom aliases at a quiescent test boundary, including the fast-path flag. pub fn reset_custom_shorthands() { - test_state::replace_shorthands((BTreeMap::new(), false)); + engine_state::replace_shorthands((BTreeMap::new(), false)); } /// Replace the custom shorthand registry used by style extraction. diff --git a/libs/css/src/test_state.rs b/libs/css/src/test_state.rs index 4a0929e5c..597b2850b 100644 --- a/libs/css/src/test_state.rs +++ b/libs/css/src/test_state.rs @@ -2,29 +2,14 @@ //! they provide cleanup, not mutual exclusion. Keep scopes on their creating thread //! and use them only when extraction and callbacks are quiescent. -use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::marker::PhantomData; use std::rc::Rc; -use std::sync::atomic::Ordering; use crate::{ - atom_hoist, class_map, debug, file_map, file_routes, slot_reservation, tailwind_definitions, - theme_tokens, + atom_hoist, class_map, debug, engine_state::CssState, file_map, file_routes, slot_reservation, + tailwind_definitions, theme_tokens, }; -pub(crate) fn replace_shorthands( - state: (BTreeMap>, bool), -) -> (BTreeMap>, bool) { - let mut registry = crate::CUSTOM_SHORTHANDS - .write() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let old = std::mem::replace(&mut *registry, state.0); - let present = crate::HAS_CUSTOM_SHORTHANDS.swap(state.1, Ordering::Relaxed); - drop(registry); - crate::CUSTOM_SHORTHANDS.clear_poison(); - (old, present) -} - /// Reset CSS-owned persistent state without retaining a snapshot. pub fn reset_state_for_testing() { crate::set_prefix(None); @@ -45,41 +30,19 @@ pub fn reset_state_for_testing() { /// including unwind and nested scopes. Hold a named binding and the serial lock. #[must_use] pub struct TestStateGuard { - prefix: Option, - debug: bool, - hoist: Option, - plan: Option>, - reservation: slot_reservation::State, - classes: HashMap>, - files: bimap::BiHashMap, - canonical: HashMap, - routes: HashMap>, - shorthands: (BTreeMap>, bool), - tokens: theme_tokens::ThemeTokenRegistry, - tailwind: tailwind_definitions::Definitions, + outer: CssState, same_thread: PhantomData>, } impl TestStateGuard { - /// Snapshot owned values; no state lock is held during the test body. + /// Move the live state into the guard; no state lock is held during the test body. pub fn new() -> Self { - let guard = Self { - prefix: crate::get_prefix(), - debug: debug::is_debug(), - hoist: atom_hoist::atom_hoist_threshold(), - plan: atom_hoist::atom_plan(), - reservation: slot_reservation::replace_state(Default::default()), - classes: class_map::get_class_map(), - files: file_map::get_file_map(), - canonical: file_map::get_canonical_map(), - routes: file_routes::get_file_routes(), - shorthands: replace_shorthands((BTreeMap::new(), false)), - tokens: theme_tokens::replace_registry(Default::default()), - tailwind: tailwind_definitions::replace_definitions(Default::default()), + let mut outer = CssState::default(); + outer.swap_live(); + Self { + outer, same_thread: PhantomData, - }; - reset_state_for_testing(); - guard + } } } @@ -91,18 +54,7 @@ impl Default for TestStateGuard { impl Drop for TestStateGuard { fn drop(&mut self) { - crate::set_prefix(self.prefix.take()); - debug::set_debug(self.debug); - atom_hoist::set_atom_hoist(self.hoist); - atom_hoist::restore_atom_plan(self.plan.take()); - slot_reservation::replace_state(std::mem::take(&mut self.reservation)); - class_map::set_class_map(std::mem::take(&mut self.classes)); - file_map::set_file_map(std::mem::take(&mut self.files)); - file_map::set_canonical_map(std::mem::take(&mut self.canonical)); - file_routes::set_file_routes(std::mem::take(&mut self.routes)); - replace_shorthands(std::mem::take(&mut self.shorthands)); - theme_tokens::replace_registry(std::mem::take(&mut self.tokens)); - tailwind_definitions::replace_definitions(std::mem::take(&mut self.tailwind)); + self.outer.swap_live(); } } diff --git a/libs/css/src/test_state/tests.rs b/libs/css/src/test_state/tests.rs index 82057e0f9..57805e6a8 100644 --- a/libs/css/src/test_state/tests.rs +++ b/libs/css/src/test_state/tests.rs @@ -1,5 +1,7 @@ use super::*; use serial_test::serial; +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; +use std::sync::atomic::Ordering; fn seed() { crate::set_prefix(Some("outer".into())); diff --git a/libs/extractor/src/lib.rs b/libs/extractor/src/lib.rs index 72999ac29..03d978156 100644 --- a/libs/extractor/src/lib.rs +++ b/libs/extractor/src/lib.rs @@ -157,6 +157,7 @@ mod utf16_boundary_tests; mod util_type; mod utils; mod vanilla_extract; +pub use vanilla_extract::ExtractorCaches; #[cfg(test)] mod vanilla_extract_theme_import_tests; mod visit; diff --git a/libs/extractor/src/vanilla_extract.rs b/libs/extractor/src/vanilla_extract.rs index f780f7846..7357fb9c0 100644 --- a/libs/extractor/src/vanilla_extract.rs +++ b/libs/extractor/src/vanilla_extract.rs @@ -514,27 +514,38 @@ fn sandbox_error( type ImportedRuns = FxHashMap; -#[derive(Debug)] -pub(crate) struct CacheGuard { +/// The stylesheet runs and stripped TypeScript one engine session cached on +/// the calling thread: the runs carry that session's file numbers, so two +/// sessions never share them. +#[derive(Debug, Default)] +pub struct ExtractorCaches { imported: ImportedRuns, stripped: FxHashMap)>, - same_thread: std::marker::PhantomData>, } +impl ExtractorCaches { + /// Exchange these caches with the calling thread's live ones. + pub fn swap_live(&mut self) { + IMPORTED_RUNS.with_borrow_mut(|runs| std::mem::swap(runs, &mut self.imported)); + STRIPPED.with_borrow_mut(|stripped| std::mem::swap(stripped, &mut self.stripped)); + } +} + +/// Empty caches until dropped, when the outer ones return. +#[derive(Debug)] +pub(crate) struct CacheGuard(ExtractorCaches); + impl Default for CacheGuard { fn default() -> Self { - Self { - imported: IMPORTED_RUNS.with_borrow_mut(std::mem::take), - stripped: STRIPPED.with_borrow_mut(std::mem::take), - same_thread: std::marker::PhantomData, - } + let mut outer = ExtractorCaches::default(); + outer.swap_live(); + Self(outer) } } impl Drop for CacheGuard { fn drop(&mut self) { - IMPORTED_RUNS.with_borrow_mut(|runs| *runs = std::mem::take(&mut self.imported)); - STRIPPED.with_borrow_mut(|stripped| *stripped = std::mem::take(&mut self.stripped)); + self.0.swap_live(); } } diff --git a/packages/plugin-utils/src/__tests__/compiler-types.test.ts b/packages/plugin-utils/src/__tests__/compiler-types.test.ts index c6b757714..adf52c2ff 100644 --- a/packages/plugin-utils/src/__tests__/compiler-types.test.ts +++ b/packages/plugin-utils/src/__tests__/compiler-types.test.ts @@ -78,7 +78,7 @@ describe('compiler structural types', () => { Object.keys(compiler).filter( (key) => key !== 'Output' && key !== 'default', ), - ).toHaveLength(29) + ).toHaveLength(32) } finally { compiler.resetStateForTesting() } diff --git a/packages/plugin-utils/src/__tests__/wasm-abi.test.ts b/packages/plugin-utils/src/__tests__/wasm-abi.test.ts index 45390ebfc..156cf48be 100644 --- a/packages/plugin-utils/src/__tests__/wasm-abi.test.ts +++ b/packages/plugin-utils/src/__tests__/wasm-abi.test.ts @@ -44,6 +44,8 @@ describe('@devup-ui/wasm exports', () => { 'Output', 'codeExtract', 'codeExtractWithoutSourceMap', + 'createSession', + 'dropSession', 'exportCanonicalMap', 'exportClassMap', 'exportFileMap', @@ -67,6 +69,7 @@ describe('@devup-ui/wasm exports', () => { 'resetBuildState', 'resetStateForTesting', 'seedFileMap', + 'selectSession', 'setAtomHoist', 'setDebug', 'setModuleResolver', @@ -394,3 +397,29 @@ describe('@devup-ui/wasm reservation', () => { expect(wasm.getUnreservedClassSlotCount()).toBe(0) }) }) + +describe('@devup-ui/wasm sessions', () => { + it('keeps each session apart until it is dropped', () => { + const prefix = wasm.getPrefix() + const session = wasm.createSession() + wasm.selectSession(session) + expect(wasm.getPrefix()).toBeUndefined() + wasm.setPrefix('app-') + wasm.selectSession(0) + expect(wasm.getPrefix()).toBe(prefix) + expect(() => wasm.selectSession(session + 1)).toThrow( + `engine session ${session + 1} does not exist`, + ) + expect(() => wasm.selectSession(-1)).toThrow( + 'selectSession(): argument id must be a session id', + ) + wasm.selectSession(session) + expect(wasm.getPrefix()).toBe('app-') + expect(wasm.dropSession(session)).toBe(true) + expect(wasm.getPrefix()).toBe(prefix) + expect(wasm.dropSession(session)).toBe(false) + expect(() => wasm.dropSession(0)).toThrow( + 'engine session 0 cannot be dropped', + ) + }) +})