diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index c7a35f11..1eaca3c4 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -396,6 +396,9 @@ jobs: npx napi build --no-const-enum --platform --release --target aarch64-pc-windows-msvc -o dist if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } npm run build:entrypoints --silent + - name: Check production native imports + working-directory: bindings/js + run: npm run test:imports - uses: actions/upload-artifact@v4 with: name: dynwinrt diff --git a/bindings/js/README.md b/bindings/js/README.md index 05a3e734..884ed899 100644 --- a/bindings/js/README.md +++ b/bindings/js/README.md @@ -21,6 +21,19 @@ metadata revisions without rebuilding a native addon. The runtime primarily targets **data-style WinRT APIs** (AI, storage, notifications, networking, globalization, …). It also supports WinUI `Application + Window` hosting through the generated `Application.create()` helper when the caller supplies an STA UI thread, an initialized Windows App SDK runtime, and application lifecycle. Unpackaged callers can initialize the runtime with `initWinappsdk()`; the helper resolves the framework resources from that package graph. It also enables Per-Monitor V2 DPI awareness on the UI thread. +### System DispatcherQueue loading + +The system DispatcherQueue helper resolves +`CoreMessaging.dll!CreateDispatcherQueueController` only when it needs to create +a current-thread queue, loading the DLL from the Windows system directory. +Capturing an existing queue skips that resolution. A successful resolution +retains the module for the process lifetime so controllers and callbacks remain +valid; DLL or export failures are reported at queue creation and can be retried. +Importing the root or `/com` entrypoint does not load CoreMessaging for this +helper. Apartment, message-pumping, and shutdown requirements are unchanged. +This is not a general older-Windows compatibility or addon feature-isolation +guarantee. + ## Quick start `@microsoft/dynwinrt` is the **runtime**. You generate the typed bindings ahead of time with [`@microsoft/dynwinrt-codegen`](https://www.npmjs.com/package/@microsoft/dynwinrt-codegen), then import them at runtime: diff --git a/bindings/js/__test__/native-imports.spec.ts b/bindings/js/__test__/native-imports.spec.ts new file mode 100644 index 00000000..d74111f7 --- /dev/null +++ b/bindings/js/__test__/native-imports.spec.ts @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import test from 'ava' +import { spawnSync } from 'node:child_process' +import { existsSync, readdirSync } from 'node:fs' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' + +const packageDir = fileURLToPath(new URL('..', import.meta.url)) +const distDir = join(packageDir, 'dist') + +function findDumpbin(): string { + const vswhere = join( + process.env['ProgramFiles(x86)'] ?? 'C:\\Program Files (x86)', + 'Microsoft Visual Studio', + 'Installer', + 'vswhere.exe', + ) + const installation = spawnSync(vswhere, ['-latest', '-products', '*', '-property', 'installationPath'], { + encoding: 'utf8', + timeout: 10_000, + windowsHide: true, + }) + if (installation.status !== 0 || !installation.stdout.trim()) { + throw new Error(`MSVC dumpbin is required to check native imports: ${installation.error ?? installation.stderr}`) + } + const toolsDir = join(installation.stdout.trim(), 'VC', 'Tools', 'MSVC') + const versions = readdirSync(toolsDir).sort((a, b) => b.localeCompare(a, undefined, { numeric: true })) + const hosts = process.arch === 'arm64' ? ['Hostarm64\\arm64', 'Hostx64\\x64'] : ['Hostx64\\x64'] + for (const version of versions) { + for (const host of hosts) { + const candidate = join(toolsDir, version, 'bin', host, 'dumpbin.exe') + if (existsSync(candidate)) return candidate + } + } + throw new Error(`MSVC dumpbin was not found under ${toolsDir}`) +} + +test('native addons do not statically import CoreMessaging or CreateDispatcherQueueController', (t) => { + const artifacts = readdirSync(distDir).filter((name) => /^dynwinrt\.win32-.*\.node$/.test(name)) + t.true(artifacts.length > 0, 'Build the production JS addon before checking imports') + const dumpbin = findDumpbin() + for (const artifact of artifacts) { + const imports = spawnSync(dumpbin, ['/nologo', '/imports', join(distDir, artifact)], { + encoding: 'utf8', + timeout: 30_000, + windowsHide: true, + }) + t.is(imports.status, 0, `${artifact}: ${imports.error ?? imports.stderr}`) + t.notRegex(imports.stdout, /coremessaging\.dll|CreateDispatcherQueueController/i, artifact) + } +}) + +for (const entrypoint of ['@microsoft/dynwinrt', '@microsoft/dynwinrt/com']) { + test(`fresh ${entrypoint} import does not load CoreMessaging for DispatcherQueue`, (t) => { + const child = spawnSync( + process.execPath, + [ + '--eval', + ` + const assert = require('node:assert/strict'); + const { basename } = require('node:path'); + const modules = () => process.report.getReport().sharedObjects.map(p => basename(p).toLowerCase()); + const before = modules(); + const runtime = require(${JSON.stringify(entrypoint)}); + assert.equal(typeof runtime.DynWinRtValue, 'function'); + const after = modules(); + assert(after.some(p => /^dynwinrt\\.win32-.*\\.node$/.test(p)), 'native addon was not loaded'); + assert( + before.includes('coremessaging.dll') || !after.includes('coremessaging.dll'), + 'ordinary import introduced CoreMessaging.dll' + ); + console.log('lazy-coremessaging-import-ok'); + `, + ], + { cwd: packageDir, encoding: 'utf8', timeout: 10_000, windowsHide: true }, + ) + t.is(child.status, 0, `${child.error ?? child.stderr}`) + t.regex(child.stdout, /lazy-coremessaging-import-ok/) + }) +} diff --git a/bindings/js/package.json b/bindings/js/package.json index 8ea84a24..daa7f034 100644 --- a/bindings/js/package.json +++ b/bindings/js/package.json @@ -91,12 +91,13 @@ "format:rs": "cargo fmt", "lint": "oxlint", "test": "npm run test:types && ava", + "test:imports": "ava __test__/native-imports.spec.ts", "test:generated-unsafe": "npm run build:test-hooks && npm run build:entrypoints && ava __test__/generated-unsafe-companion.e2e.ts", "test:winrt-implementation": "npm run build:test-hooks && npm run build:entrypoints && ava __test__/winrt-implementation.spec.ts", "test:native-completion": "npm run build:test-hooks && npm run build:entrypoints && ava __test__/native-completion.e2e.ts", "test:borrowed-copy": "npm run build:test-hooks && npm run build:entrypoints && ava __test__/borrowed-copy.e2e.ts", "test:types": "npm run test:types:index && npm run test:types:raw", - "test:types:index": "tsc --noEmit --strict --target ESNext --module NodeNext --moduleResolution NodeNext __test__/index.spec.ts __test__/winrt-marshalling.spec.ts __test__/winrt-implementation.spec.ts", + "test:types:index": "tsc --noEmit --strict --target ESNext --module NodeNext --moduleResolution NodeNext __test__/index.spec.ts __test__/winrt-marshalling.spec.ts __test__/winrt-implementation.spec.ts __test__/native-imports.spec.ts", "test:types:raw": "tsc --noEmit --project __test__/types/tsconfig.json", "test:tsfn": "npm run build:test-hooks && ava __test__/tsfn.spec.ts", "version": "napi version" diff --git a/crates/dynwinrt/src/dispatcher_queue.rs b/crates/dynwinrt/src/dispatcher_queue.rs index 255163f0..a3dd6dc1 100644 --- a/crates/dynwinrt/src/dispatcher_queue.rs +++ b/crates/dynwinrt/src/dispatcher_queue.rs @@ -6,9 +6,12 @@ use windows::System::{ DispatcherQueue, DispatcherQueueController, DispatcherQueueHandler, DispatcherQueueShutdownStartingEventArgs, }; -use windows::Win32::System::WinRT::{ - CreateDispatcherQueueController, DQTAT_COM_STA, DQTYPE_THREAD_CURRENT, DispatcherQueueOptions, -}; +use windows::Win32::System::WinRT::{DQTAT_COM_STA, DQTYPE_THREAD_CURRENT, DispatcherQueueOptions}; + +mod core_messaging; + +#[cfg(test)] +mod tests; /// A cloneable handle that can enqueue work from any thread onto a captured /// Windows system dispatcher queue. @@ -39,7 +42,19 @@ pub struct SystemDispatcherQueue { impl SystemDispatcherQueue { pub fn ensure_for_current_thread() -> windows_core::Result { - match DispatcherQueue::GetForCurrentThread() { + Self::ensure_for_current_thread_with( + DispatcherQueue::GetForCurrentThread, + core_messaging::create_controller, + ) + } + + fn ensure_for_current_thread_with( + get_queue: impl FnOnce() -> windows_core::Result, + create_controller: impl FnOnce( + DispatcherQueueOptions, + ) -> windows_core::Result, + ) -> windows_core::Result { + match get_queue() { Ok(queue) => return Ok(Self::new(queue, None)), // A successful ABI call with a null queue becomes Error::empty(). Err(error) if error.code().is_ok() => {} @@ -51,7 +66,7 @@ impl SystemDispatcherQueue { threadType: DQTYPE_THREAD_CURRENT, apartmentType: DQTAT_COM_STA, }; - let controller = unsafe { CreateDispatcherQueueController(options)? }; + let controller = create_controller(options)?; let queue = controller.DispatcherQueue()?; Ok(Self::new(queue, Some(controller))) } diff --git a/crates/dynwinrt/src/dispatcher_queue/core_messaging.rs b/crates/dynwinrt/src/dispatcher_queue/core_messaging.rs new file mode 100644 index 00000000..f1e17136 --- /dev/null +++ b/crates/dynwinrt/src/dispatcher_queue/core_messaging.rs @@ -0,0 +1,303 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use std::{ffi::c_void, sync::OnceLock}; + +use windows::{ + System::DispatcherQueueController, + Win32::{ + Foundation::{FreeLibrary, HMODULE}, + System::{ + LibraryLoader::{GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW}, + WinRT::DispatcherQueueOptions, + }, + }, +}; +use windows_core::{Error, HRESULT, Result, s, w}; + +type CreateDispatcherQueueControllerFn = + unsafe extern "system" fn(DispatcherQueueOptions, *mut *mut c_void) -> HRESULT; + +static CREATE_CONTROLLER: OnceLock = OnceLock::new(); + +struct Module(HMODULE); + +impl Drop for Module { + fn drop(&mut self) { + let _ = unsafe { FreeLibrary(self.0) }; + } +} + +pub(super) fn create_controller( + options: DispatcherQueueOptions, +) -> Result { + let create = resolve(&CREATE_CONTROLLER, load_module, find_create_controller)?; + invoke(*create, options) +} + +fn load_module() -> Result { + unsafe { LoadLibraryExW(w!("CoreMessaging.dll"), None, LOAD_LIBRARY_SEARCH_SYSTEM32) } + .map(Module) +} + +fn find_create_controller(module: &Module) -> Result { + let address = unsafe { GetProcAddress(module.0, s!("CreateDispatcherQueueController")) } + .ok_or_else(Error::from_thread)?; + // dispatcherqueue.h and windows-rs declare HRESULT WINAPI with options by + // value and an IDispatcherQueueController** output. The module is retained + // before this pointer is published. + Ok(unsafe { + std::mem::transmute:: isize, CreateDispatcherQueueControllerFn>( + address, + ) + }) +} + +fn resolve( + cache: &OnceLock, + load: impl FnOnce() -> Result, + find: impl FnOnce(&M) -> Result, +) -> Result<&CreateDispatcherQueueControllerFn> { + if let Some(create) = cache.get() { + return Ok(create); + } + + // Native loading stays outside the publication lock; failures leave the + // cache empty so a later explicit request can retry. + let module = load().map_err(|error| { + Error::new( + error.code(), + format!("Failed to load CoreMessaging.dll for DispatcherQueue creation: {error}"), + ) + })?; + let create = find(&module).map_err(|error| { + Error::new( + error.code(), + format!("Failed to resolve CoreMessaging.dll!CreateDispatcherQueueController: {error}"), + ) + })?; + + Ok(cache.get_or_init(|| { + // Only the winner retains a loader reference for the process lifetime, + // keeping controller/callback code valid too. Losing closures drop + // their temporary modules, as does failed export resolution above. + std::mem::forget(module); + create + })) +} + +fn invoke( + create: CreateDispatcherQueueControllerFn, + options: DispatcherQueueOptions, +) -> Result { + let mut controller = std::ptr::null_mut(); + // Match windows-rs: adopt the owned output only on a successful HRESULT. + // A successful null becomes Error::empty(); failed outputs are undefined. + unsafe { + create(options, &mut controller).and_then(|| windows_core::Type::from_abi(controller)) + } +} + +#[cfg(test)] +mod tests { + use std::sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + mpsc, + }; + use std::time::Duration; + use windows::Win32::Foundation::{E_ACCESSDENIED, ERROR_MOD_NOT_FOUND, ERROR_PROC_NOT_FOUND}; + + use super::*; + + unsafe extern "system" fn successful_null( + _: DispatcherQueueOptions, + _: *mut *mut c_void, + ) -> HRESULT { + HRESULT(0) + } + + unsafe extern "system" fn successful_status_with_null( + _: DispatcherQueueOptions, + _: *mut *mut c_void, + ) -> HRESULT { + HRESULT(1) + } + + unsafe extern "system" fn failed_creation( + _: DispatcherQueueOptions, + _: *mut *mut c_void, + ) -> HRESULT { + E_ACCESSDENIED + } + + struct ModuleProbe(Arc); + + impl Drop for ModuleProbe { + fn drop(&mut self) { + self.0.fetch_add(1, Ordering::SeqCst); + } + } + + #[test] + fn native_result_preserves_failure_and_successful_null() { + for create in [ + successful_null as CreateDispatcherQueueControllerFn, + successful_status_with_null, + ] { + let error = invoke(create, DispatcherQueueOptions::default()).unwrap_err(); + assert_eq!(error.code(), Error::empty().code()); + } + let error = invoke(failed_creation, DispatcherQueueOptions::default()).unwrap_err(); + assert_eq!(error.code(), E_ACCESSDENIED); + } + + #[test] + fn missing_system_module_reports_deferred_load_error() { + let cache = OnceLock::new(); + let error = resolve( + &cache, + || { + unsafe { + LoadLibraryExW( + w!("dynwinrt-test-missing-coremessaging.dll"), + None, + LOAD_LIBRARY_SEARCH_SYSTEM32, + ) + } + .map(Module) + }, + find_create_controller, + ) + .unwrap_err(); + assert_eq!(error.code(), HRESULT::from_win32(ERROR_MOD_NOT_FOUND.0)); + assert!(error.message().contains("CoreMessaging.dll")); + assert!(error.message().contains("DispatcherQueue creation")); + assert!(cache.get().is_none()); + } + + #[test] + fn missing_native_export_reports_deferred_resolution_error() { + let cache = OnceLock::new(); + let error = resolve(&cache, load_module, |module| { + let address = unsafe { + GetProcAddress( + module.0, + s!("DynwinrtTestMissingCreateDispatcherQueueController"), + ) + }; + assert!(address.is_none()); + Err(Error::from_thread()) + }) + .unwrap_err(); + assert_eq!(error.code(), HRESULT::from_win32(ERROR_PROC_NOT_FOUND.0)); + assert!( + error + .message() + .contains("CoreMessaging.dll!CreateDispatcherQueueController") + ); + assert!(cache.get().is_none()); + } + + #[test] + fn failed_resolution_releases_module_and_can_retry() { + let cache = OnceLock::new(); + let dropped = Arc::new(AtomicUsize::new(0)); + let error = resolve( + &cache, + || Ok(ModuleProbe(dropped.clone())), + |_| { + Err(Error::from_hresult(HRESULT::from_win32( + ERROR_PROC_NOT_FOUND.0, + ))) + }, + ) + .unwrap_err(); + assert_eq!(error.code(), HRESULT::from_win32(ERROR_PROC_NOT_FOUND.0)); + assert_eq!(dropped.load(Ordering::SeqCst), 1); + assert!(cache.get().is_none()); + + let first = resolve( + &cache, + || Ok(ModuleProbe(dropped.clone())), + |_| Ok(successful_null), + ) + .unwrap(); + let second = resolve( + &cache, + || -> Result { panic!("cached module must not be loaded again") }, + |_| panic!("cached export must not be resolved again"), + ) + .unwrap(); + assert!(std::ptr::eq(first, second)); + assert_eq!(dropped.load(Ordering::SeqCst), 1); + } + + #[test] + fn failed_load_leaves_cache_retryable() { + let cache = OnceLock::new(); + let error = resolve( + &cache, + || -> Result { + Err(Error::from_hresult(HRESULT::from_win32( + ERROR_MOD_NOT_FOUND.0, + ))) + }, + |_| panic!("a failed load must not resolve an export"), + ) + .unwrap_err(); + assert_eq!(error.code(), HRESULT::from_win32(ERROR_MOD_NOT_FOUND.0)); + assert!(cache.get().is_none()); + + let dropped = Arc::new(AtomicUsize::new(0)); + resolve( + &cache, + || Ok(ModuleProbe(dropped.clone())), + |_| Ok(successful_null), + ) + .unwrap(); + assert!(cache.get().is_some()); + assert_eq!(dropped.load(Ordering::SeqCst), 0); + } + + #[test] + fn concurrent_resolution_retains_only_the_winning_module() { + const THREADS: usize = 8; + let cache = OnceLock::new(); + let dropped = Arc::new(AtomicUsize::new(0)); + let (ready_tx, ready_rx) = mpsc::channel(); + std::thread::scope(|scope| { + let threads = (0..THREADS) + .map(|_| { + scope.spawn(|| { + let create = resolve( + &cache, + || Ok(ModuleProbe(dropped.clone())), + |_| { + let (release_tx, release_rx) = mpsc::channel(); + ready_tx.send(release_tx).unwrap(); + release_rx.recv_timeout(Duration::from_secs(10)).unwrap(); + Ok(successful_null) + }, + ) + .unwrap(); + create as *const _ as usize + }) + }) + .collect::>(); + let releases = (0..THREADS) + .map(|_| ready_rx.recv_timeout(Duration::from_secs(10)).unwrap()) + .collect::>(); + for release in releases { + release.send(()).unwrap(); + } + let published = threads + .into_iter() + .map(|thread| thread.join().unwrap()) + .collect::>(); + assert!(published.iter().all(|address| *address == published[0])); + }); + assert_eq!(dropped.load(Ordering::SeqCst), THREADS - 1); + assert!(cache.get().is_some()); + } +} diff --git a/crates/dynwinrt/src/dispatcher_queue/tests.rs b/crates/dynwinrt/src/dispatcher_queue/tests.rs new file mode 100644 index 00000000..3bd70c55 --- /dev/null +++ b/crates/dynwinrt/src/dispatcher_queue/tests.rs @@ -0,0 +1,188 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use std::{ + sync::{ + Arc, Mutex, + atomic::{AtomicBool, AtomicUsize, Ordering}, + }, + thread, + time::{Duration, Instant}, +}; + +use windows::Win32::{ + Foundation::{E_ABORT, E_ACCESSDENIED}, + System::WinRT::{RO_INIT_SINGLETHREADED, RoInitialize, RoUninitialize}, + UI::WindowsAndMessaging::{DispatchMessageW, MSG, PM_REMOVE, PeekMessageW, TranslateMessage}, +}; +use windows_core::{Error, Result}; +use windows_future::AsyncStatus; + +use super::*; + +struct Apartment; + +impl Drop for Apartment { + fn drop(&mut self) { + unsafe { RoUninitialize() }; + } +} + +fn on_sta(test: impl FnOnce() -> Result<()> + Send + 'static) -> Result<()> { + thread::spawn(move || { + unsafe { RoInitialize(RO_INIT_SINGLETHREADED)? }; + let _apartment = Apartment; + test() + }) + .join() + .expect("DispatcherQueue test thread panicked") +} + +fn pump_until(mut done: impl FnMut() -> Result) -> Result<()> { + let deadline = Instant::now() + Duration::from_secs(10); + while !done()? { + if Instant::now() >= deadline { + return Err(Error::new(E_ABORT, "DispatcherQueue test pump timed out")); + } + let mut message = MSG::default(); + for _ in 0..64 { + if !unsafe { PeekMessageW(&mut message, None, 0, 0, PM_REMOVE) }.as_bool() { + break; + } + unsafe { + let _ = TranslateMessage(&message); + DispatchMessageW(&message); + } + } + thread::sleep(Duration::from_millis(1)); + } + Ok(()) +} + +struct TestQueue(SystemDispatcherQueue); + +impl TestQueue { + fn shutdown(&mut self) -> Result<()> { + self.0.request_shutdown()?; + if let Some(action) = self.0.shutdown_action.as_ref() { + pump_until(|| Ok(action.Status()? != AsyncStatus::Started))?; + action.GetResults()?; + } + Ok(()) + } +} + +impl Drop for TestQueue { + fn drop(&mut self) { + if let Err(error) = self.shutdown() { + if thread::panicking() { + eprintln!("DispatcherQueue test cleanup failed: {error}"); + } else { + panic!("DispatcherQueue test cleanup failed: {error}"); + } + } + } +} + +#[test] +fn queue_query_failure_does_not_resolve_coremessaging() { + let result = SystemDispatcherQueue::ensure_for_current_thread_with( + || Err(Error::from_hresult(E_ACCESSDENIED)), + |_| panic!("a native queue query failure must propagate without loading"), + ); + assert_eq!(result.err().unwrap().code(), E_ACCESSDENIED); +} + +#[test] +fn successful_null_queue_attempts_creation_with_unchanged_options() { + let result = SystemDispatcherQueue::ensure_for_current_thread_with( + || Err(Error::empty()), + |options| { + assert_eq!(options.dwSize as usize, size_of::()); + assert_eq!(options.threadType, DQTYPE_THREAD_CURRENT); + assert_eq!(options.apartmentType, DQTAT_COM_STA); + Err(Error::new(E_ABORT, "injected controller creation failure")) + }, + ); + let error = result.err().unwrap(); + assert_eq!(error.code(), E_ABORT); + assert!( + error + .message() + .contains("injected controller creation failure") + ); +} + +#[test] +fn current_thread_creation_reuse_callbacks_and_shutdown() -> Result<()> { + on_sta(|| { + let mut owner = TestQueue(SystemDispatcherQueue::ensure_for_current_thread()?); + assert!(owner.0.was_created()); + assert!(owner.0.has_thread_access()?); + + let removed_observers = Arc::new(AtomicUsize::new(0)); + let removed_starting = removed_observers.clone(); + let removed_completed = removed_observers.clone(); + owner.0.observe_shutdown( + move || { + removed_starting.fetch_add(1, Ordering::SeqCst); + }, + move || { + removed_completed.fetch_add(1, Ordering::SeqCst); + }, + )?; + let events = Arc::new(Mutex::new(Vec::new())); + let starting_events = events.clone(); + let completed_events = events.clone(); + owner.0.observe_shutdown( + move || starting_events.lock().unwrap().push("starting"), + move || completed_events.lock().unwrap().push("completed"), + )?; + + let mut reused = SystemDispatcherQueue::ensure_for_current_thread_with( + DispatcherQueue::GetForCurrentThread, + |_| panic!("an existing queue must not resolve CoreMessaging"), + )?; + assert!(!reused.was_created()); + assert!(reused.has_thread_access()?); + assert_eq!(reused.queue, owner.0.queue); + assert!(!reused.request_shutdown()?); + let removed_starting = removed_observers.clone(); + let removed_completed = removed_observers.clone(); + reused.observe_shutdown( + move || { + removed_starting.fetch_add(1, Ordering::SeqCst); + }, + move || { + removed_completed.fetch_add(1, Ordering::SeqCst); + }, + )?; + drop(reused); + + let owner_thread = thread::current().id(); + let callback_on_owner = Arc::new(AtomicBool::new(false)); + let callback_thread = callback_on_owner.clone(); + let work_events = events.clone(); + let handle = owner.0.handle(); + assert!( + thread::spawn(move || { + handle.try_enqueue(move || { + callback_thread.store(thread::current().id() == owner_thread, Ordering::SeqCst); + work_events.lock().unwrap().push("work"); + Ok(()) + }) + }) + .join() + .unwrap()? + ); + pump_until(|| Ok(!events.lock().unwrap().is_empty()))?; + assert!(callback_on_owner.load(Ordering::SeqCst)); + assert!(owner.0.request_shutdown()?); + assert!(!owner.0.request_shutdown()?); + owner.shutdown()?; + assert_eq!(*events.lock().unwrap(), ["work", "starting", "completed"]); + assert_eq!(removed_observers.load(Ordering::SeqCst), 0); + assert!(!owner.0.handle().try_enqueue(|| Ok(()))?); + Ok(()) + }) +}