mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-12-05 11:15:01 +03:00
perf(preview): keep PDF documents open in the worker by docId
The preview workers now use a linear-memory ABI with four exports: `memory`, `prepare(len)`, `invoke()` and `output_ptr()`. The host writes each request into worker memory in one copy and copies each response out in one copy. The old ABI called an export for every 4 bytes in each direction. Rust gives out only the addresses of its own buffers, so the crate keeps `forbid(unsafe_code)`. Buffers larger than 1 MiB go back to the allocator after each request. The PDF worker keeps each parsed document under a `docId` that the host assigns. The frames are `PDF_OPEN`, `PDF_RENDER` and `PDF_CLOSE`. The bytes of a document go to the worker once per open, not once per page. Page pixels come back as a compact RGBA buffer that the worker transfers. The playground bridge has one session table in `wasm_pdf_state.rs`. It opens at most 8 documents or 256 MiB of source bytes. To make room, the table closes least recently used idle documents, but only when that makes the new document fit. Empty documents and documents larger than 256 MiB never go to the worker. The table closes a document when the view clears the last scope that used it, also when no page request claimed it yet. A reopen that fails after a worker restart keeps the known page count. The table restarts the worker before the IDs run out. The bridge no longer keeps 16 copies of PDF bytes. Each worker event listener ignores events from a replaced worker, so a late error of an old worker cannot stop the new one. A crash answers each sent request once, so the count of unanswered requests stays exact. `pdf-client.js` uses the same protocol and keeps its public methods. It keeps the same open budget and waits for room before it sends an open. New bytes for a known `docKey` now open a new document and drop the old page count and pages. Before, the client returned the old page count. Four snapshot IDs of the PDF viewer and the attachment toolbar use `format_args!`, so the production bundle has no copy of their prefixes. The prefix gate now checks 14 prefixes.
This commit is contained in:
1 parent
a8ff41ccdf
commit
2144304032
19 files changed
+2276
-918
No files matched your search
@@ -7,7 +7,7 @@ These crates belong to the client Cargo workspace rooted at `packages/frontend/C
|
||||
|
||||
### Workspace boundaries
|
||||
- `blocksuite/crates/doc` (`blocksuite-playground-doc`) & `bs-relay`: Pure CRDT document engine and binary room sync relay (`#![forbid(unsafe_code)]`, zero GUI/platform dependencies, `packages/frontend/scripts/check-invariants.sh` rejects `ui`, `wgpu`, `objc2`, and `web-sys` in `blocksuite/blocksuite/crates/doc/Cargo.toml`) built on `y-octo 0.4.0`. Preserves 53-bit `clientId` (`1..=2^53 - 1`), complete flavour schema defaults (`schema/`, including `affine:database` `sys:version = 3` typed authoring and cell updates with 0 JS writeback updates on initial load), top-level Awareness `color` alongside `user` and `selectionV2`, deterministic `now_ms`-driven undo/awareness clocks (`session/`), WebSocket-only `seed-claim` / `seed-claim-result` single-winner arbitration (keyed by `seed:<docId>`), awareness refcounting across connections that forwards a removal (including the equal-clock live-to-`null` form `y-protocols` uses to expire a peer) once the last owner releases a client, `?ws=` relay origin forwarding with permissive blob CORS headers, and `wasm32-unknown-unknown` compatibility under `--no-default-features`. `read/` (`PageDocSession::read_page_snapshot`) is the typed read side: an ordered `PageSnapshot` tree of `BlockNode`s whose `BlockContent` covers every supported block flavour (including `affine:database` columns, cells, views, and child rows), keeps the normalized JSON of every `prop:*`, numbers `numbered` list runs, reads `prop:textAlign` and the note display modes by their BlockSuite wire values (`both` / `doc` / `edgeless`), reports blocks outside the root tree as `detached`, and reads any other flavour as `Unknown` instead of dropping it.
|
||||
- `blocksuite/crates/preview` (`blocksuite-preview`): Pure-Rust offline preview kernel (`#![forbid(unsafe_code)]`, zero GUI/network/OS blocking I/O, zero host system font discovery or wall-clock calls). Provides `FontPool`, `SvgRasterizer`, `PinnedPixelCache`, `MermaidRenderer` (`merman` `resvg_safe`), pure in-memory RaTeX outline math rendering, `InMemoryTypstWorld`, `HayroPdfRenderer`, and `PreviewEngine`. All four worker features (`mermaid`, `math`, `typst`, `pdf`) compile independently on `wasm32-unknown-unknown` with `wasm-worker`, whose only exports are the four scalar `affine_worker_*` functions in `wasm_worker.rs` (`reset_input`, `push_input_u32`, `invoke`, `output_u32`) that `packages/frontend/hosts/web/src/wasm-scalar-rpc.js` calls through a raw `WebAssembly.instantiate`.
|
||||
- `blocksuite/crates/preview` (`blocksuite-preview`): Pure-Rust offline preview kernel (`#![forbid(unsafe_code)]`, zero GUI/network/OS blocking I/O, zero host system font discovery or wall-clock calls). Provides `FontPool`, `SvgRasterizer`, `PinnedPixelCache`, `MermaidRenderer` (`merman` `resvg_safe`), pure in-memory RaTeX outline math rendering, `InMemoryTypstWorld`, `HayroPdfRenderer`, and `PreviewEngine`. All four worker features (`mermaid`, `math`, `typst`, `pdf`) compile independently on `wasm32-unknown-unknown` with `wasm-worker`, whose only exports are the linear-memory ABI in `wasm_worker.rs` (`memory`, `prepare(len) -> ptr`, `invoke() -> len`, `output_ptr() -> ptr`, with zero `unsafe`: Rust only gives out the addresses of its own buffers) that `packages/frontend/hosts/web/src/wasm-scalar-rpc.js` calls through a raw `WebAssembly.instantiate`, reading `memory.buffer` again after every call and checking each address range before it makes a view. The PDF worker keeps parsed documents under host-assigned `docId`s (`pdf_open`, `pdf_render`, `pdf_close`); the playground bridge (`wasm_pdf_state.rs`) and `hosts/web/src/pdf-client.js` assign the IDs, send each document's bytes once per open, never keep more than 8 documents or 256 MiB of source bytes open (they close least recently used idle documents only when that makes room, and otherwise wait for an answer), and reject empty documents and documents over 256 MiB before they reach the worker.
|
||||
- `blocksuite/crates/editor` (`blocksuite-editor`): Reusable BlockSuite editor crate depending only on `blocksuite-playground-doc`, `blocksuite-preview`, `ui-kit`, `ui`, `ui-tokens`, and general utility crates (zero `affine-store` dependency and zero storage/network protocol leaks). Owns `theme` (backed by `ui-tokens` for colors, typography, icons, and `register_bundled_fonts`; on `wasm32` the fonts come from `register_web_font_bytes` instead, which rejects data with zero usable faces (`validate_font_bytes`), so the Wasm bundle embeds zero font bytes), `directory` (`WorkspaceDocDirectory` host port, `InMemoryDocDirectory`, and exact substring UTF-16 highlight matching), `block_flow/` (Page-mode renderer with LTR/RTL logical start/end placement), `database/` (`Table`/`Kanban`/`Calendar` views, `InlineAxis`, `BidiIsolation`, Filter/Sort/GroupBy with `@emotion/hash` text keys and NFD canonical diacritic-folding collation, and DST-aware calendar layout), `rich_text/` (rich paragraph engine), `editor_session/` (selection and preedit core), `clipboard/`, `overlays/` (generic over `OverlayHost`), `surface/`, and `edgeless/` (generic over `EdgelessToolbarHost`).
|
||||
- `blocksuite/crates/playground`: Standalone demonstration and verification host owning `PlaygroundView` (`lib.rs`, `chrome.rs`, `view_room.rs`), `room_client/` (live room sync), `showcase.rs` (deterministic `seed_showcase_doc` workspace), `PlaygroundView` glue for `editor_session/`, `overlays/`, and `edgeless/`, the native macOS desktop entry (`native-playground`), the WebAssembly canvas entry (`wasm_main`, which `web/index.html` calls after it fetched the seven `ui-tokens` fonts from `assets/fonts/` and passed each to `register_web_font`; both throw, and the page never reports ready, when a font has zero usable faces or the set misses one of `REQUIRED_FONT_FAMILIES`), and the deterministic headless verification CLI (`src/bin/bs_harness/`). It reuses the editor kernel and bundled fonts through `blocksuite-editor`, `ui-kit`, and `ui-tokens`.
|
||||
- `unexpected_cfgs = "deny"` is enforced workspace-wide in `Cargo.toml`; dead upstream feature gates are forbidden.
|
||||
|
||||
@@ -199,7 +199,7 @@ impl Overlays {
|
||||
})
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.snapshot(
|
||||
SharedString::from(format!("overlay.attachment_toolbar.{id_suffix}")),
|
||||
format_args!("overlay.attachment_toolbar.{id_suffix}"),
|
||||
Some("overlay.attachment_toolbar"),
|
||||
)
|
||||
.snapshot_text(label)
|
||||
@@ -241,7 +241,7 @@ impl Overlays {
|
||||
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
|
||||
.on_click(emit(cx, move |_: &ClickEvent| ev.clone()))
|
||||
.snapshot(
|
||||
SharedString::from(format!("overlay.attachment_toolbar.{id_suffix}")),
|
||||
format_args!("overlay.attachment_toolbar.{id_suffix}"),
|
||||
Some("overlay.attachment_toolbar"),
|
||||
)
|
||||
.snapshot_focused(active)
|
||||
|
||||
@@ -112,7 +112,7 @@ impl PlaygroundView {
|
||||
.overflow_hidden();
|
||||
if in_view {
|
||||
page_card = page_card.snapshot(
|
||||
SharedString::from(format!("overlay.pdf_viewer.page.{idx}")),
|
||||
format_args!("overlay.pdf_viewer.page.{idx}"),
|
||||
Some("overlay.pdf_viewer"),
|
||||
);
|
||||
}
|
||||
@@ -229,7 +229,7 @@ impl PlaygroundView {
|
||||
if thumb_in_view {
|
||||
item = item
|
||||
.snapshot(
|
||||
SharedString::from(format!("overlay.pdf_viewer.thumb.{idx}")),
|
||||
format_args!("overlay.pdf_viewer.thumb.{idx}"),
|
||||
Some("overlay.pdf_viewer.thumbnails"),
|
||||
)
|
||||
.snapshot_focused(is_active);
|
||||
|
||||
@@ -1,12 +1,24 @@
|
||||
//! Scoped state machine for WebAssembly (`wasm32`) worker-backed PDF page counts and page
|
||||
//! rasterization requests (`WasmPdfPageProvider`).
|
||||
//! Main-thread state of the WebAssembly (`wasm32`) PDF worker (`WasmPdfPageProvider`).
|
||||
//!
|
||||
//! Isolates per-view `scope_id` requests so:
|
||||
//! The PDF worker keeps each opened document parsed under a `doc_id` that this state assigns.
|
||||
//! This state is the only owner of what is open there:
|
||||
//! - A session opens a document version (`pdf_key`) once. Page requests name its `doc_id`, so
|
||||
//! the bytes cross to the worker once per open, not once per page.
|
||||
//! - At most `MAX_OPEN_PDF_DOCS` sessions and `MAX_OPEN_PDF_BYTES` source bytes are open. The
|
||||
//! least recently used sessions with no unanswered worker request close first, and only when
|
||||
//! closing them makes the new document fit. Otherwise the new document waits for the next
|
||||
//! delivery. An empty document or one larger than `MAX_OPEN_PDF_BYTES` is `Invalid` and never
|
||||
//! goes to the worker.
|
||||
//! - A session closes when the last view scope that requested its pages is cleared, or when a
|
||||
//! scope is cleared before any page request claimed the session.
|
||||
//! - `doc_id` values increase and are never reused while the worker runs. Before they run out,
|
||||
//! the state drops every session and the caller restarts the worker.
|
||||
//!
|
||||
//! Per-view `scope_id` requests stay isolated:
|
||||
//! - Closing view A (`clear_scope(scope_a)`) cancels A's pending entries without dropping B's;
|
||||
//! - A single-page worker error (`deliver_page_error`) affects only scopes still waiting on that
|
||||
//! exact `(pdf_key, page_index, scale_bits)` request and never invalidates a valid document
|
||||
//! `PdfPageCount::Ready` or clobbers another view's in-flight page request;
|
||||
//! - Document-level parse failures (`deliver_doc_error`) update `counts` independently.
|
||||
//! - A single-page worker error affects only scopes still waiting on that exact
|
||||
//! `(pdf_key, page_index, scale_bits)` request and never invalidates a valid document count;
|
||||
//! - An open failure marks the document `Invalid` independently of page requests.
|
||||
|
||||
use std::{
|
||||
collections::{HashMap, HashSet},
|
||||
@@ -20,9 +32,63 @@ use crate::block_flow::{
|
||||
|
||||
pub(crate) type PdfPageKey = (u64, String, usize, u32);
|
||||
|
||||
const MAX_OPEN_PDF_DOCS: usize = 8;
|
||||
const MAX_OPEN_PDF_BYTES: usize = 256 * 1024 * 1024;
|
||||
|
||||
/// What the caller sends to the worker bridge after a state change, outside the state lock.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub(crate) struct WorkerPlan {
|
||||
/// Terminate the worker first, because every `doc_id` was used.
|
||||
pub(crate) restart: bool,
|
||||
/// Sessions that this change closed.
|
||||
pub(crate) close: Vec<u32>,
|
||||
/// The session is new: open it with the request bytes.
|
||||
pub(crate) open: bool,
|
||||
}
|
||||
|
||||
/// Outcome of a page count query.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(crate) enum CountStep {
|
||||
Known(PdfPageCount),
|
||||
/// Send the plan, which opens the new session `doc_id`.
|
||||
Open {
|
||||
doc_id: u32,
|
||||
plan: WorkerPlan,
|
||||
},
|
||||
}
|
||||
|
||||
/// Outcome of a page request.
|
||||
pub(crate) enum PageStep {
|
||||
Staged(Result<PdfPreviewPage, ()>),
|
||||
/// An identical request is on its way, or the open budget waits for a delivery.
|
||||
Pending,
|
||||
/// Send the plan, open `doc_id` when the plan says so or the restarted worker lost it, then
|
||||
/// request the page.
|
||||
Render {
|
||||
doc_id: u32,
|
||||
plan: WorkerPlan,
|
||||
},
|
||||
}
|
||||
|
||||
struct PdfSession {
|
||||
doc_id: u32,
|
||||
source_bytes: usize,
|
||||
last_used: u64,
|
||||
scopes: HashSet<u64>,
|
||||
/// Worker requests (opens and renders) not answered yet.
|
||||
unanswered: u32,
|
||||
/// The last scope that could claim this session was cleared while its open was on the way.
|
||||
/// The session closes when the open is answered, unless a page request claims it first.
|
||||
close_if_unclaimed: bool,
|
||||
}
|
||||
|
||||
pub(crate) struct WasmPdfState {
|
||||
counts: HashMap<String, PdfPageCount>,
|
||||
count_in_flight: HashSet<String>,
|
||||
sessions: HashMap<String, PdfSession>,
|
||||
session_keys: HashMap<u32, String>,
|
||||
next_doc_id: u32,
|
||||
clock: u64,
|
||||
admission_waiting: bool,
|
||||
pages: PdfStagingMailbox<PdfPageKey>,
|
||||
in_flight: HashSet<PdfPageKey>,
|
||||
cap_bytes: usize,
|
||||
@@ -32,52 +98,94 @@ impl WasmPdfState {
|
||||
pub(crate) fn new(cap_bytes: usize) -> Self {
|
||||
Self {
|
||||
counts: HashMap::new(),
|
||||
count_in_flight: HashSet::new(),
|
||||
sessions: HashMap::new(),
|
||||
session_keys: HashMap::new(),
|
||||
next_doc_id: 1,
|
||||
clock: 0,
|
||||
admission_waiting: false,
|
||||
pages: PdfStagingMailbox::with_cap(cap_bytes),
|
||||
in_flight: HashSet::new(),
|
||||
cap_bytes,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `Ok(status)` when cached or already in-flight, or `Err(())` when the caller must
|
||||
/// dispatch a fresh `requestPdfPageCount` worker message.
|
||||
pub(crate) fn query_or_begin_count(&mut self, pdf_key: &str) -> Result<PdfPageCount, ()> {
|
||||
/// Returns the page count of `pdf_key`, or opens a session for it.
|
||||
pub(crate) fn query_or_open(&mut self, pdf_key: &str, source_bytes: usize) -> CountStep {
|
||||
if !Self::fits_worker(source_bytes) {
|
||||
self.counts
|
||||
.insert(pdf_key.to_string(), PdfPageCount::Invalid);
|
||||
return CountStep::Known(PdfPageCount::Invalid);
|
||||
}
|
||||
if let Some(&status) = self.counts.get(pdf_key) {
|
||||
return Ok(status);
|
||||
self.touch(pdf_key);
|
||||
return CountStep::Known(status);
|
||||
}
|
||||
if self.count_in_flight.insert(pdf_key.to_string()) {
|
||||
Err(())
|
||||
} else {
|
||||
Ok(PdfPageCount::Pending)
|
||||
if self.sessions.contains_key(pdf_key) {
|
||||
self.touch(pdf_key);
|
||||
return CountStep::Known(PdfPageCount::Pending);
|
||||
}
|
||||
match self.admit(pdf_key, source_bytes) {
|
||||
Some((doc_id, plan)) => CountStep::Open { doc_id, plan },
|
||||
None => CountStep::Known(PdfPageCount::Pending),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn cancel_count_request(&mut self, pdf_key: &str) {
|
||||
self.count_in_flight.remove(pdf_key);
|
||||
}
|
||||
|
||||
/// Consumes a staged page result if present; otherwise registers `(scope_id, pdf_key,
|
||||
/// page_index, scale_bits)` in `in_flight` and reports whether a worker request must be sent.
|
||||
/// Consumes a staged page result if present. Otherwise registers `(scope_id, pdf_key,
|
||||
/// page_index, scale_bits)` in `in_flight` and decides whether a worker request goes out.
|
||||
pub(crate) fn take_staged_or_begin_page(
|
||||
&mut self,
|
||||
scope_id: u64,
|
||||
pdf_key: &str,
|
||||
source_bytes: usize,
|
||||
page_index: usize,
|
||||
scale: f32,
|
||||
) -> (Option<Result<PdfPreviewPage, ()>>, bool) {
|
||||
) -> PageStep {
|
||||
let scale_bits = scale.to_bits();
|
||||
let key: PdfPageKey = (scope_id, pdf_key.to_string(), page_index, scale_bits);
|
||||
if let Some(staged) = self.pages.take(&key) {
|
||||
return (Some(staged), false);
|
||||
return PageStep::Staged(staged);
|
||||
}
|
||||
if !Self::fits_worker(source_bytes) {
|
||||
return PageStep::Staged(Err(()));
|
||||
}
|
||||
let already_in_flight = self
|
||||
.in_flight
|
||||
.iter()
|
||||
.any(|(_, k, p, s)| k == pdf_key && *p == page_index && *s == scale_bits);
|
||||
let step = if already_in_flight {
|
||||
PageStep::Pending
|
||||
} else if let Some(session) = self.sessions.get(pdf_key) {
|
||||
let doc_id = session.doc_id;
|
||||
self.touch(pdf_key);
|
||||
PageStep::Render {
|
||||
doc_id,
|
||||
plan: WorkerPlan::default(),
|
||||
}
|
||||
} else {
|
||||
match self.admit(pdf_key, source_bytes) {
|
||||
Some((doc_id, plan)) => PageStep::Render { doc_id, plan },
|
||||
None => return PageStep::Pending,
|
||||
}
|
||||
};
|
||||
self.in_flight.insert(key);
|
||||
(None, !already_in_flight)
|
||||
if let Some(session) = self.sessions.get_mut(pdf_key) {
|
||||
session.scopes.insert(scope_id);
|
||||
session.close_if_unclaimed = false;
|
||||
if matches!(step, PageStep::Render { .. }) {
|
||||
session.unanswered += 1;
|
||||
}
|
||||
}
|
||||
step
|
||||
}
|
||||
|
||||
/// Records an open that the caller sent for a session whose worker restarted.
|
||||
pub(crate) fn note_reopen(&mut self, doc_id: u32) {
|
||||
if let Some(session) = self.session_by_id(doc_id) {
|
||||
session.unanswered += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// Withdraws a request that the bridge could not send.
|
||||
pub(crate) fn cancel_page_request(
|
||||
&mut self,
|
||||
scope_id: u64,
|
||||
@@ -87,56 +195,73 @@ impl WasmPdfState {
|
||||
) {
|
||||
let key: PdfPageKey = (scope_id, pdf_key.to_string(), page_index, scale.to_bits());
|
||||
self.in_flight.remove(&key);
|
||||
if let Some(session) = self.sessions.get_mut(pdf_key) {
|
||||
session.unanswered = session.unanswered.saturating_sub(1);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn deliver_page_count(&mut self, pdf_key: String, page_count: usize) {
|
||||
self.count_in_flight.remove(&pdf_key);
|
||||
/// Withdraws a session whose open the bridge could not send.
|
||||
pub(crate) fn cancel_open(&mut self, doc_id: u32) {
|
||||
if let Some(pdf_key) = self.session_keys.remove(&doc_id) {
|
||||
self.sessions.remove(&pdf_key);
|
||||
}
|
||||
}
|
||||
|
||||
/// Stores the page count of an opened session. Returns whether a view should refresh.
|
||||
/// Also returns the session to close when no page request claimed it in time.
|
||||
pub(crate) fn deliver_open(&mut self, doc_id: u32, page_count: usize) -> (bool, Option<u32>) {
|
||||
self.admission_waiting = false;
|
||||
let Some(pdf_key) = self.answer(doc_id) else {
|
||||
return (true, None);
|
||||
};
|
||||
let status = if page_count > 0 {
|
||||
PdfPageCount::Ready(page_count)
|
||||
} else {
|
||||
PdfPageCount::Invalid
|
||||
};
|
||||
self.counts.insert(pdf_key, status);
|
||||
self.counts.insert(pdf_key.clone(), status);
|
||||
(true, self.close_unclaimed(&pdf_key))
|
||||
}
|
||||
|
||||
/// Marks document-level `page_count` parsing as `Invalid` without clobbering unrelated
|
||||
/// in-flight page requests.
|
||||
pub(crate) fn deliver_doc_error(&mut self, pdf_key: String) {
|
||||
self.count_in_flight.remove(&pdf_key);
|
||||
self.counts.insert(pdf_key, PdfPageCount::Invalid);
|
||||
/// Marks a document `Invalid` after the worker failed to open it. A document that opened
|
||||
/// before keeps its page count: then the failure comes from a worker that stopped, not from
|
||||
/// the document. Later unknown `doc_id` errors for its pages stay single-page failures.
|
||||
/// Also returns the session to close when no page request claimed it in time.
|
||||
pub(crate) fn deliver_open_error(&mut self, doc_id: u32) -> (bool, Option<u32>) {
|
||||
self.admission_waiting = false;
|
||||
let Some(pdf_key) = self.answer(doc_id) else {
|
||||
return (true, None);
|
||||
};
|
||||
self.counts
|
||||
.entry(pdf_key.clone())
|
||||
.or_insert(PdfPageCount::Invalid);
|
||||
(true, self.close_unclaimed(&pdf_key))
|
||||
}
|
||||
|
||||
/// Delivers a single-page render failure strictly to scopes still waiting on
|
||||
/// `(pdf_key, page_index, scale.to_bits())`, leaving document `counts` and other pages intact.
|
||||
pub(crate) fn deliver_page_error(
|
||||
&mut self,
|
||||
pdf_key: &str,
|
||||
doc_id: u32,
|
||||
page_index: usize,
|
||||
scale: f32,
|
||||
) -> bool {
|
||||
let s_bits = scale.to_bits();
|
||||
let mut scopes = Vec::new();
|
||||
self.in_flight.retain(|(sc, k, p, s)| {
|
||||
let hit = k == pdf_key && *p == page_index && *s == s_bits;
|
||||
if hit {
|
||||
scopes.push(*sc);
|
||||
}
|
||||
!hit
|
||||
});
|
||||
if scopes.is_empty() {
|
||||
return false;
|
||||
}
|
||||
for sc in scopes {
|
||||
let wake = std::mem::take(&mut self.admission_waiting);
|
||||
let Some(pdf_key) = self.answer(doc_id) else {
|
||||
return wake;
|
||||
};
|
||||
let scopes = self.take_waiting_scopes(&pdf_key, page_index, scale.to_bits());
|
||||
for sc in &scopes {
|
||||
self.pages
|
||||
.stage_failed((sc, pdf_key.to_string(), page_index, s_bits));
|
||||
.stage_failed((*sc, pdf_key.clone(), page_index, scale.to_bits()));
|
||||
}
|
||||
true
|
||||
wake || !scopes.is_empty()
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn deliver_page_ready(
|
||||
&mut self,
|
||||
pdf_key: String,
|
||||
doc_id: u32,
|
||||
page_index: usize,
|
||||
page_count: usize,
|
||||
scale: f32,
|
||||
@@ -144,17 +269,14 @@ impl WasmPdfState {
|
||||
height_px: u32,
|
||||
rgba: &[u8],
|
||||
) -> bool {
|
||||
let wake = std::mem::take(&mut self.admission_waiting);
|
||||
let Some(pdf_key) = self.answer(doc_id) else {
|
||||
return wake;
|
||||
};
|
||||
let s_bits = scale.to_bits();
|
||||
let mut scopes = Vec::new();
|
||||
self.in_flight.retain(|(sc, k, p, s)| {
|
||||
let hit = k == &pdf_key && *p == page_index && *s == s_bits;
|
||||
if hit {
|
||||
scopes.push(*sc);
|
||||
}
|
||||
!hit
|
||||
});
|
||||
let scopes = self.take_waiting_scopes(&pdf_key, page_index, s_bits);
|
||||
if scopes.is_empty() {
|
||||
return false;
|
||||
return wake;
|
||||
}
|
||||
let safe_scale = scale.max(f32::EPSILON);
|
||||
let orig_w_pt = ((width_px as f32) / safe_scale).max(1.0);
|
||||
@@ -203,9 +325,144 @@ impl WasmPdfState {
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn clear_scope(&mut self, scope_id: u64) -> Vec<Arc<ui::RenderImage>> {
|
||||
/// Drops the pending requests and staged pages of `scope_id`, and closes the sessions that
|
||||
/// no other scope requested pages from. Returns the retired images and the closed `doc_id`s.
|
||||
pub(crate) fn clear_scope(&mut self, scope_id: u64) -> (Vec<Arc<ui::RenderImage>>, Vec<u32>) {
|
||||
self.in_flight.retain(|(sc, _, _, _)| *sc != scope_id);
|
||||
self.pages.drain_matching(|(sc, _, _, _)| *sc == scope_id)
|
||||
let mut released = Vec::new();
|
||||
for (pdf_key, session) in &mut self.sessions {
|
||||
let was_claimed = session.scopes.remove(&scope_id);
|
||||
if !session.scopes.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if was_claimed || session.unanswered == 0 {
|
||||
released.push(pdf_key.clone());
|
||||
} else {
|
||||
session.close_if_unclaimed = true;
|
||||
}
|
||||
}
|
||||
let closed = released
|
||||
.into_iter()
|
||||
.filter_map(|pdf_key| self.close(&pdf_key))
|
||||
.collect();
|
||||
(
|
||||
self.pages.drain_matching(|(sc, _, _, _)| *sc == scope_id),
|
||||
closed,
|
||||
)
|
||||
}
|
||||
|
||||
/// Opens a session for `pdf_key`, closing least recently used idle sessions to fit the
|
||||
/// budget. Closes nothing and returns `None` when closing every idle session would still
|
||||
/// not make the new document fit.
|
||||
fn admit(&mut self, pdf_key: &str, source_bytes: usize) -> Option<(u32, WorkerPlan)> {
|
||||
let mut plan = WorkerPlan::default();
|
||||
if self.next_doc_id == u32::MAX {
|
||||
self.restart_worker();
|
||||
plan.restart = true;
|
||||
}
|
||||
let mut idle: Vec<(u64, &String, usize)> = self
|
||||
.sessions
|
||||
.iter()
|
||||
.filter(|(_, s)| s.unanswered == 0)
|
||||
.map(|(k, s)| (s.last_used, k, s.source_bytes))
|
||||
.collect();
|
||||
idle.sort_unstable_by_key(|(last_used, _, _)| *last_used);
|
||||
let mut open_docs = self.sessions.len();
|
||||
let mut open_bytes: usize = self.sessions.values().map(|s| s.source_bytes).sum();
|
||||
let mut victims = Vec::new();
|
||||
let mut idle = idle.into_iter();
|
||||
while open_docs >= MAX_OPEN_PDF_DOCS || open_bytes + source_bytes > MAX_OPEN_PDF_BYTES {
|
||||
let Some((_, key, bytes)) = idle.next() else {
|
||||
self.admission_waiting = true;
|
||||
return None;
|
||||
};
|
||||
open_docs -= 1;
|
||||
open_bytes -= bytes;
|
||||
victims.push(key.clone());
|
||||
}
|
||||
for key in victims {
|
||||
plan.close.extend(self.close(&key));
|
||||
}
|
||||
let doc_id = self.next_doc_id;
|
||||
self.next_doc_id += 1;
|
||||
self.clock += 1;
|
||||
self.sessions.insert(
|
||||
pdf_key.to_string(),
|
||||
PdfSession {
|
||||
doc_id,
|
||||
source_bytes,
|
||||
last_used: self.clock,
|
||||
scopes: HashSet::new(),
|
||||
unanswered: 1,
|
||||
close_if_unclaimed: false,
|
||||
},
|
||||
);
|
||||
self.session_keys.insert(doc_id, pdf_key.to_string());
|
||||
plan.open = true;
|
||||
Some((doc_id, plan))
|
||||
}
|
||||
|
||||
/// Forgets every session and `doc_id` and drops the pending page requests. The views send
|
||||
/// their requests again on the next refresh.
|
||||
fn restart_worker(&mut self) {
|
||||
self.sessions.clear();
|
||||
self.session_keys.clear();
|
||||
self.in_flight.clear();
|
||||
self.next_doc_id = 1;
|
||||
}
|
||||
|
||||
/// Only documents the worker accepts in one request go to it.
|
||||
fn fits_worker(source_bytes: usize) -> bool {
|
||||
(1..=MAX_OPEN_PDF_BYTES).contains(&source_bytes)
|
||||
}
|
||||
|
||||
fn close_unclaimed(&mut self, pdf_key: &str) -> Option<u32> {
|
||||
let session = self.sessions.get(pdf_key)?;
|
||||
if session.close_if_unclaimed && session.scopes.is_empty() && session.unanswered == 0 {
|
||||
self.close(pdf_key)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn close(&mut self, pdf_key: &str) -> Option<u32> {
|
||||
let session = self.sessions.remove(pdf_key)?;
|
||||
self.session_keys.remove(&session.doc_id);
|
||||
Some(session.doc_id)
|
||||
}
|
||||
|
||||
fn touch(&mut self, pdf_key: &str) {
|
||||
if let Some(session) = self.sessions.get_mut(pdf_key) {
|
||||
self.clock += 1;
|
||||
session.last_used = self.clock;
|
||||
}
|
||||
}
|
||||
|
||||
fn session_by_id(&mut self, doc_id: u32) -> Option<&mut PdfSession> {
|
||||
let pdf_key = self.session_keys.get(&doc_id)?;
|
||||
self.sessions.get_mut(pdf_key)
|
||||
}
|
||||
|
||||
/// Counts one answer for `doc_id` and returns its `pdf_key`, or `None` when the session is
|
||||
/// closed.
|
||||
fn answer(&mut self, doc_id: u32) -> Option<String> {
|
||||
let pdf_key = self.session_keys.get(&doc_id)?.clone();
|
||||
if let Some(session) = self.sessions.get_mut(&pdf_key) {
|
||||
session.unanswered = session.unanswered.saturating_sub(1);
|
||||
}
|
||||
Some(pdf_key)
|
||||
}
|
||||
|
||||
fn take_waiting_scopes(&mut self, pdf_key: &str, page_index: usize, s_bits: u32) -> Vec<u64> {
|
||||
let mut scopes = Vec::new();
|
||||
self.in_flight.retain(|(sc, k, p, s)| {
|
||||
let hit = k == pdf_key && *p == page_index && *s == s_bits;
|
||||
if hit {
|
||||
scopes.push(*sc);
|
||||
}
|
||||
!hit
|
||||
});
|
||||
scopes
|
||||
}
|
||||
}
|
||||
|
||||
@@ -213,77 +470,252 @@ impl WasmPdfState {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const RGBA_4X4: [u8; 64] = [255; 64];
|
||||
|
||||
fn render_doc(state: &mut WasmPdfState, scope: u64, key: &str, page: usize) -> u32 {
|
||||
match state.take_staged_or_begin_page(scope, key, 1024, page, 1.0) {
|
||||
PageStep::Render { doc_id, plan } => {
|
||||
assert!(
|
||||
plan.close.is_empty() && !plan.restart,
|
||||
"{key} closes nothing"
|
||||
);
|
||||
doc_id
|
||||
}
|
||||
_ => panic!("{key} page {page} must go to the worker"),
|
||||
}
|
||||
}
|
||||
|
||||
fn open_doc(state: &mut WasmPdfState, key: &str) -> (u32, WorkerPlan) {
|
||||
match state.query_or_open(key, 1024) {
|
||||
CountStep::Open { doc_id, plan } => (doc_id, plan),
|
||||
other => panic!("{key} must open, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn late_closed_scope_page_error_preserves_other_scope_pending_page_and_valid_count() {
|
||||
fn page_errors_stay_per_scope_and_open_errors_mark_only_their_document() {
|
||||
let mut state = WasmPdfState::new(32 * 1024 * 1024);
|
||||
assert_eq!(state.query_or_begin_count("doc"), Err(()));
|
||||
state.deliver_page_count("doc".into(), 5);
|
||||
let (doc, plan) = open_doc(&mut state, "doc");
|
||||
assert!(plan.open && plan.close.is_empty() && !plan.restart);
|
||||
assert!(state.deliver_open(doc, 5).0);
|
||||
assert_eq!(
|
||||
state.query_or_begin_count("doc"),
|
||||
Ok(PdfPageCount::Ready(5))
|
||||
state.query_or_open("doc", 1024),
|
||||
CountStep::Known(PdfPageCount::Ready(5))
|
||||
);
|
||||
|
||||
// View A (scope 1) requests page 0; View B (scope 2) requests page 1 of the same PDF.
|
||||
let (staged_a, send_a) = state.take_staged_or_begin_page(1, "doc", 0, 1.0);
|
||||
assert!(staged_a.is_none() && send_a);
|
||||
let (staged_b, send_b) = state.take_staged_or_begin_page(2, "doc", 1, 1.0);
|
||||
assert!(staged_b.is_none() && send_b);
|
||||
// View A (scope 1) requests page 0; view B (scope 2) requests page 1 of the same PDF.
|
||||
assert_eq!(render_doc(&mut state, 1, "doc", 0), doc);
|
||||
assert_eq!(render_doc(&mut state, 2, "doc", 1), doc);
|
||||
// A second scope on the same page waits for the request on its way.
|
||||
assert!(matches!(
|
||||
state.take_staged_or_begin_page(2, "doc", 1024, 0, 1.0),
|
||||
PageStep::Pending
|
||||
));
|
||||
|
||||
// View A closes before page 0 finishes; late error for page 0 arrives afterwards.
|
||||
let _ = state.clear_scope(1);
|
||||
// View A closes before page 0 finishes. The session stays open for view B.
|
||||
let (_, closed) = state.clear_scope(1);
|
||||
assert!(closed.is_empty());
|
||||
assert!(
|
||||
!state.deliver_page_error("doc", 0, 1.0),
|
||||
"late error for closed scope A must be ignored without staging or waking"
|
||||
state.deliver_page_error(doc, 0, 1.0),
|
||||
"scope 2 still waits on page 0"
|
||||
);
|
||||
assert_eq!(
|
||||
state.query_or_begin_count("doc"),
|
||||
Ok(PdfPageCount::Ready(5)),
|
||||
"single-page error must never downgrade known valid page count to Invalid"
|
||||
state.query_or_open("doc", 1024),
|
||||
CountStep::Known(PdfPageCount::Ready(5)),
|
||||
"a page error never downgrades a valid count"
|
||||
);
|
||||
assert!(matches!(
|
||||
state.take_staged_or_begin_page(2, "doc", 1024, 0, 1.0),
|
||||
PageStep::Staged(Err(()))
|
||||
));
|
||||
|
||||
assert!(state.deliver_page_ready(doc, 1, 5, 1.0, 4, 4, &RGBA_4X4));
|
||||
match state.take_staged_or_begin_page(2, "doc", 1024, 1, 1.0) {
|
||||
PageStep::Staged(Ok(page)) => assert_eq!((page.page_index, page.page_count), (1, 5)),
|
||||
_ => panic!("page 1 must be staged for scope 2"),
|
||||
}
|
||||
|
||||
// An open error marks its document invalid. Its pipelined page fails on its own.
|
||||
let (bad, _) = open_doc(&mut state, "corrupt");
|
||||
assert_eq!(render_doc(&mut state, 2, "corrupt", 0), bad);
|
||||
assert!(state.deliver_open_error(bad).0);
|
||||
assert!(state.deliver_page_error(bad, 0, 1.0));
|
||||
assert_eq!(
|
||||
state.in_flight.len(),
|
||||
state.query_or_open("corrupt", 1024),
|
||||
CountStep::Known(PdfPageCount::Invalid)
|
||||
);
|
||||
|
||||
// Clearing the last scope closes both sessions. Late results are ignored.
|
||||
let (_, mut closed) = state.clear_scope(2);
|
||||
closed.sort_unstable();
|
||||
assert_eq!(closed, vec![doc, bad]);
|
||||
assert!(!state.deliver_page_ready(doc, 3, 5, 1.0, 4, 4, &RGBA_4X4));
|
||||
assert!(state.in_flight.is_empty() && state.sessions.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_budget_closes_least_recently_used_idle_session_and_waits_when_all_are_busy() {
|
||||
let mut state = WasmPdfState::new(32 * 1024 * 1024);
|
||||
let ids: Vec<u32> = (0..MAX_OPEN_PDF_DOCS)
|
||||
.map(|i| open_doc(&mut state, &format!("doc{i}")).0)
|
||||
.collect();
|
||||
assert_eq!(ids, (1..=MAX_OPEN_PDF_DOCS as u32).collect::<Vec<_>>());
|
||||
|
||||
// Every session waits for its open answer, so a ninth document waits too.
|
||||
assert_eq!(
|
||||
state.query_or_open("doc8", 1024),
|
||||
CountStep::Known(PdfPageCount::Pending)
|
||||
);
|
||||
assert!(matches!(
|
||||
state.take_staged_or_begin_page(1, "doc8", 1024, 0, 1.0),
|
||||
PageStep::Pending
|
||||
));
|
||||
assert!(
|
||||
state.in_flight.is_empty(),
|
||||
"a waiting page holds no request"
|
||||
);
|
||||
|
||||
// Any answer wakes the views. `doc0` is answered but used most recently afterwards.
|
||||
for &id in &ids {
|
||||
assert!(state.deliver_open(id, 1).0);
|
||||
}
|
||||
assert!(matches!(
|
||||
state.query_or_open("doc0", 1024),
|
||||
CountStep::Known(PdfPageCount::Ready(1))
|
||||
));
|
||||
let (doc8, plan) = open_doc(&mut state, "doc8");
|
||||
assert_eq!(
|
||||
(doc8, plan.close),
|
||||
(MAX_OPEN_PDF_DOCS as u32 + 1, vec![ids[1]])
|
||||
);
|
||||
|
||||
// A large document closes idle sessions until the byte budget fits.
|
||||
let big = MAX_OPEN_PDF_BYTES - 1024 * 6;
|
||||
let (_, plan) = match state.query_or_open("big", big) {
|
||||
CountStep::Open { doc_id, plan } => (doc_id, plan),
|
||||
other => panic!("big must open, got {other:?}"),
|
||||
};
|
||||
assert_eq!(plan.close, vec![ids[2], ids[3]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn doc_ids_restart_with_the_worker_before_they_run_out() {
|
||||
let mut state = WasmPdfState::new(32 * 1024 * 1024);
|
||||
let old = render_doc(&mut state, 1, "doc", 0);
|
||||
state.next_doc_id = u32::MAX;
|
||||
let (doc_id, plan) = open_doc(&mut state, "other");
|
||||
assert!(plan.restart && plan.open);
|
||||
assert_eq!(doc_id, 1);
|
||||
assert!(state.in_flight.is_empty());
|
||||
assert!(!state.deliver_page_ready(old + 1000, 0, 1, 1.0, 4, 4, &RGBA_4X4));
|
||||
assert_eq!(
|
||||
render_doc(&mut state, 1, "doc", 0),
|
||||
2,
|
||||
"a dropped session opens again"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bridge_failures_withdraw_requests_and_reopens_count_as_unanswered() {
|
||||
let mut state = WasmPdfState::new(32 * 1024 * 1024);
|
||||
// The bridge could not send a new session's open: nothing stays behind.
|
||||
let doc = render_doc(&mut state, 1, "doc", 0);
|
||||
state.cancel_page_request(1, "doc", 0, 1.0);
|
||||
state.cancel_open(doc);
|
||||
assert!(state.sessions.is_empty() && state.in_flight.is_empty());
|
||||
|
||||
// A restarted worker lost the session: the reopen is one more unanswered request.
|
||||
let doc = render_doc(&mut state, 1, "doc", 0);
|
||||
state.note_reopen(doc);
|
||||
assert_eq!(state.sessions["doc"].unanswered, 3);
|
||||
assert!(state.deliver_open(doc, 2).0);
|
||||
assert!(state.deliver_open(doc, 2).0);
|
||||
assert!(state.deliver_page_ready(doc, 0, 2, 1.0, 4, 4, &RGBA_4X4));
|
||||
assert_eq!(state.sessions["doc"].unanswered, 0);
|
||||
|
||||
// Pruning a source keeps the kept pages and drops the others of that scope only.
|
||||
let keep: HashSet<(usize, u32)> = [(1, 1.0f32.to_bits())].into_iter().collect();
|
||||
render_doc(&mut state, 1, "doc", 1);
|
||||
render_doc(&mut state, 1, "doc", 2);
|
||||
assert!(matches!(
|
||||
state.take_staged_or_begin_page(2, "doc", 1024, 2, 1.0),
|
||||
PageStep::Pending
|
||||
));
|
||||
assert_eq!(
|
||||
state.prune_source(1, "doc", &keep).len(),
|
||||
1,
|
||||
"view B's pending request for page 1 must remain registered"
|
||||
"staged page 0 retires"
|
||||
);
|
||||
let mut left: Vec<(u64, usize)> = state.in_flight.iter().map(|k| (k.0, k.2)).collect();
|
||||
left.sort_unstable();
|
||||
assert_eq!(left, vec![(1, 1), (2, 2)]);
|
||||
}
|
||||
|
||||
// View B's page 1 succeeds and is consumed directly without re-sending!
|
||||
let rgba = vec![255u8; 4 * 4 * 4];
|
||||
assert!(state.deliver_page_ready("doc".into(), 1, 5, 1.0, 4, 4, &rgba));
|
||||
let (consumed_b, resend_b) = state.take_staged_or_begin_page(2, "doc", 1, 1.0);
|
||||
assert!(!resend_b);
|
||||
let page = consumed_b.expect("staged ready").expect("valid page");
|
||||
assert_eq!((page.page_index, page.page_count), (1, 5));
|
||||
|
||||
// Open-scope page error marks only the failing page as Failed while keeping count Ready(5).
|
||||
let (_, send_c) = state.take_staged_or_begin_page(2, "doc", 2, 1.0);
|
||||
assert!(send_c);
|
||||
assert!(state.deliver_page_error("doc", 2, 1.0));
|
||||
let (failed_c, resend_c) = state.take_staged_or_begin_page(2, "doc", 2, 1.0);
|
||||
assert!(!resend_c && matches!(failed_c, Some(Err(()))));
|
||||
#[test]
|
||||
fn admission_closes_idle_sessions_only_when_the_new_document_then_fits() {
|
||||
let mut state = WasmPdfState::new(32 * 1024 * 1024);
|
||||
// One idle 1 KiB session and seven busy ones.
|
||||
let (idle, _) = open_doc(&mut state, "idle");
|
||||
assert!(state.deliver_open(idle, 1).0);
|
||||
for i in 0..MAX_OPEN_PDF_DOCS - 1 {
|
||||
open_doc(&mut state, &format!("busy{i}"));
|
||||
}
|
||||
// Closing the idle session frees a slot but not enough bytes: nothing closes.
|
||||
let big = MAX_OPEN_PDF_BYTES - 1024 * 3;
|
||||
assert_eq!(
|
||||
state.query_or_begin_count("doc"),
|
||||
Ok(PdfPageCount::Ready(5))
|
||||
state.query_or_open("big", big),
|
||||
CountStep::Known(PdfPageCount::Pending)
|
||||
);
|
||||
assert!(
|
||||
state.sessions.contains_key("idle"),
|
||||
"the idle session stays open"
|
||||
);
|
||||
assert_eq!(state.sessions.len(), MAX_OPEN_PDF_DOCS);
|
||||
// A small document fits once the idle session closes.
|
||||
let (_, plan) = open_doc(&mut state, "small");
|
||||
assert_eq!(plan.close, vec![idle]);
|
||||
|
||||
// Document-level parse error independently marks invalid PDFs as Invalid.
|
||||
assert_eq!(state.query_or_begin_count("cancelled"), Err(()));
|
||||
state.cancel_count_request("cancelled");
|
||||
assert_eq!(state.query_or_begin_count("cancelled"), Err(()));
|
||||
state.cancel_count_request("cancelled");
|
||||
// Empty and oversized documents never go to the worker.
|
||||
for (key, bytes) in [("empty", 0), ("huge", MAX_OPEN_PDF_BYTES + 1)] {
|
||||
assert_eq!(
|
||||
state.query_or_open(key, bytes),
|
||||
CountStep::Known(PdfPageCount::Invalid)
|
||||
);
|
||||
assert!(matches!(
|
||||
state.take_staged_or_begin_page(1, key, bytes, 0, 1.0),
|
||||
PageStep::Staged(Err(()))
|
||||
));
|
||||
}
|
||||
assert!(matches!(
|
||||
state.query_or_open("limit", MAX_OPEN_PDF_BYTES),
|
||||
CountStep::Known(PdfPageCount::Pending)
|
||||
));
|
||||
}
|
||||
|
||||
let (_, send_cancel) = state.take_staged_or_begin_page(2, "doc:4:deadbeef", 3, 1.0);
|
||||
assert!(send_cancel);
|
||||
state.cancel_page_request(2, "doc:4:deadbeef", 3, 1.0);
|
||||
let (_, send_prune) = state.take_staged_or_begin_page(2, "doc:4:deadbeef", 4, 1.0);
|
||||
assert!(send_prune);
|
||||
let drained = state.prune_source(2, "doc", &HashSet::new());
|
||||
assert!(drained.is_empty() && state.in_flight.is_empty());
|
||||
#[test]
|
||||
fn unclaimed_sessions_close_with_their_scope_and_reopen_failures_keep_counts() {
|
||||
let mut state = WasmPdfState::new(32 * 1024 * 1024);
|
||||
// Answered and never claimed: clearing a scope closes it at once.
|
||||
let (answered, _) = open_doc(&mut state, "answered");
|
||||
assert_eq!(state.deliver_open(answered, 2), (true, None));
|
||||
// Still waiting for its open: it closes when the answer comes.
|
||||
let (waiting, _) = open_doc(&mut state, "waiting");
|
||||
// Claimed by a page request before the answer: it stays open.
|
||||
let (claimed, _) = open_doc(&mut state, "claimed");
|
||||
assert_eq!(render_doc(&mut state, 2, "claimed", 0), claimed);
|
||||
|
||||
assert_eq!(state.query_or_begin_count("corrupt"), Err(()));
|
||||
state.deliver_doc_error("corrupt".into());
|
||||
let (_, closed) = state.clear_scope(1);
|
||||
assert_eq!(closed, vec![answered]);
|
||||
assert_eq!(state.deliver_open(waiting, 3), (true, Some(waiting)));
|
||||
assert_eq!(state.deliver_open(claimed, 4), (true, None));
|
||||
assert!(state.sessions.contains_key("claimed"));
|
||||
|
||||
// A reopen that fails after a worker restart keeps the known page count.
|
||||
state.note_reopen(claimed);
|
||||
assert_eq!(state.deliver_open_error(claimed), (true, None));
|
||||
assert_eq!(
|
||||
state.query_or_begin_count("corrupt"),
|
||||
Ok(PdfPageCount::Invalid)
|
||||
state.query_or_open("claimed", 1024),
|
||||
CountStep::Known(PdfPageCount::Ready(4))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,7 @@ use crate::{
|
||||
rgba_pixels_to_render_image,
|
||||
},
|
||||
theme::PlaygroundTheme,
|
||||
wasm_pdf_state::WasmPdfState,
|
||||
wasm_pdf_state::{CountStep, PageStep, WasmPdfState, WorkerPlan},
|
||||
};
|
||||
|
||||
const MAX_MATH_CACHE_ENTRIES: usize = 1024;
|
||||
@@ -54,16 +54,20 @@ extern "C" {
|
||||
dpr: f32,
|
||||
) -> Result<(), JsValue>;
|
||||
|
||||
#[wasm_bindgen(js_namespace = ["window", "__playgroundPreview"], js_name = requestPdfPageCount, catch)]
|
||||
fn js_request_pdf_page_count(pdf_key: &str, bytes: &[u8]) -> Result<(), JsValue>;
|
||||
#[wasm_bindgen(js_namespace = ["window", "__playgroundPreview"], js_name = isPdfOpen)]
|
||||
fn js_is_pdf_open(doc_id: u32) -> bool;
|
||||
|
||||
#[wasm_bindgen(js_namespace = ["window", "__playgroundPreview"], js_name = openPdf, catch)]
|
||||
fn js_open_pdf(doc_id: u32, bytes: &[u8]) -> Result<(), JsValue>;
|
||||
|
||||
#[wasm_bindgen(js_namespace = ["window", "__playgroundPreview"], js_name = requestPdfPage, catch)]
|
||||
fn js_request_pdf_page(
|
||||
pdf_key: &str,
|
||||
bytes: &[u8],
|
||||
page_index: usize,
|
||||
scale: f32,
|
||||
) -> Result<(), JsValue>;
|
||||
fn js_request_pdf_page(doc_id: u32, page_index: usize, scale: f32) -> Result<(), JsValue>;
|
||||
|
||||
#[wasm_bindgen(js_namespace = ["window", "__playgroundPreview"], js_name = closePdf)]
|
||||
fn js_close_pdf(doc_id: u32);
|
||||
|
||||
#[wasm_bindgen(js_namespace = ["window", "__playgroundPreview"], js_name = restartPdfWorker)]
|
||||
fn js_restart_pdf_worker();
|
||||
|
||||
#[wasm_bindgen(js_namespace = ["window", "__playgroundPreview"], js_name = requestCodePreview, catch)]
|
||||
fn js_request_code_preview(
|
||||
@@ -235,23 +239,33 @@ impl MathPreviewProvider for WasmMathPreviewProvider {
|
||||
}
|
||||
}
|
||||
|
||||
fn lock_pdf_state() -> std::sync::MutexGuard<'static, WasmPdfState> {
|
||||
pdf_state().lock().unwrap_or_else(|p| p.into_inner())
|
||||
}
|
||||
|
||||
/// Sends the bridge calls of a state change. Runs without the state lock, because a bridge
|
||||
/// call can deliver a result synchronously.
|
||||
fn send_worker_plan(plan: &WorkerPlan) {
|
||||
if plan.restart {
|
||||
js_restart_pdf_worker();
|
||||
}
|
||||
for &doc_id in &plan.close {
|
||||
js_close_pdf(doc_id);
|
||||
}
|
||||
}
|
||||
|
||||
struct WasmPdfPageProvider;
|
||||
|
||||
impl PdfPageProvider for WasmPdfPageProvider {
|
||||
fn page_count(&self, cache_key: &str, bytes: &[u8]) -> PdfPageCount {
|
||||
let pdf_key = resolve_pdf_key(cache_key, bytes);
|
||||
let status = pdf_state()
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.query_or_begin_count(&pdf_key);
|
||||
match status {
|
||||
Ok(hit) => hit,
|
||||
Err(()) => {
|
||||
if js_request_pdf_page_count(&pdf_key, bytes).is_err() {
|
||||
pdf_state()
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.cancel_count_request(&pdf_key);
|
||||
let step = lock_pdf_state().query_or_open(&pdf_key, bytes.len());
|
||||
match step {
|
||||
CountStep::Known(status) => status,
|
||||
CountStep::Open { doc_id, plan } => {
|
||||
send_worker_plan(&plan);
|
||||
if js_open_pdf(doc_id, bytes).is_err() {
|
||||
lock_pdf_state().cancel_open(doc_id);
|
||||
return PdfPageCount::Invalid;
|
||||
}
|
||||
PdfPageCount::Pending
|
||||
@@ -291,21 +305,33 @@ impl PdfPageProvider for WasmPdfPageProvider {
|
||||
scale: f32,
|
||||
) -> PdfAsyncPageResult {
|
||||
let pdf_key = resolve_pdf_key(cache_key, bytes);
|
||||
let (staged, should_request) = pdf_state()
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.take_staged_or_begin_page(scope_id, &pdf_key, page_index, scale);
|
||||
if let Some(res) = staged {
|
||||
return match res {
|
||||
Ok(hit) => PdfAsyncPageResult::Ready(hit),
|
||||
Err(()) => PdfAsyncPageResult::Failed,
|
||||
};
|
||||
let step = lock_pdf_state().take_staged_or_begin_page(
|
||||
scope_id,
|
||||
&pdf_key,
|
||||
bytes.len(),
|
||||
page_index,
|
||||
scale,
|
||||
);
|
||||
let (doc_id, plan) = match step {
|
||||
PageStep::Staged(Ok(page)) => return PdfAsyncPageResult::Ready(page),
|
||||
PageStep::Staged(Err(())) => return PdfAsyncPageResult::Failed,
|
||||
PageStep::Pending => return PdfAsyncPageResult::Pending,
|
||||
PageStep::Render { doc_id, plan } => (doc_id, plan),
|
||||
};
|
||||
send_worker_plan(&plan);
|
||||
// The worker loses its documents when it restarts after an error.
|
||||
let reopen = !plan.open && !js_is_pdf_open(doc_id);
|
||||
let opened = !(plan.open || reopen) || js_open_pdf(doc_id, bytes).is_ok();
|
||||
let sent = opened && js_request_pdf_page(doc_id, page_index, scale).is_ok();
|
||||
let mut state = lock_pdf_state();
|
||||
if reopen && opened {
|
||||
state.note_reopen(doc_id);
|
||||
}
|
||||
if should_request && js_request_pdf_page(&pdf_key, bytes, page_index, scale).is_err() {
|
||||
pdf_state()
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.cancel_page_request(scope_id, &pdf_key, page_index, scale);
|
||||
if !sent {
|
||||
state.cancel_page_request(scope_id, &pdf_key, page_index, scale);
|
||||
if plan.open && !opened {
|
||||
state.cancel_open(doc_id);
|
||||
}
|
||||
return PdfAsyncPageResult::Failed;
|
||||
}
|
||||
PdfAsyncPageResult::Pending
|
||||
@@ -486,65 +512,66 @@ pub fn deliver_math_error(
|
||||
notify_active_view(false);
|
||||
}
|
||||
|
||||
/// Callback invoked by `preview-workers.js` when Hayro reports a PDF's page count.
|
||||
#[wasm_bindgen]
|
||||
pub fn deliver_pdf_page_count(pdf_key: String, page_count: usize) {
|
||||
pdf_state()
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.deliver_page_count(pdf_key, page_count);
|
||||
bump_preview_revision();
|
||||
notify_active_view(true);
|
||||
}
|
||||
|
||||
/// Callback invoked by `preview-workers.js` when Hayro fails to parse a PDF's document structure
|
||||
/// (`page_count` request).
|
||||
#[wasm_bindgen]
|
||||
pub fn deliver_pdf_error(pdf_key: String) {
|
||||
pdf_state()
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.deliver_doc_error(pdf_key);
|
||||
bump_preview_revision();
|
||||
notify_active_view(true);
|
||||
}
|
||||
|
||||
/// Callback invoked by `preview-workers.js` when a single PDF page rasterization fails,
|
||||
/// isolating failure to scopes waiting on that exact `(pdf_key, page_index, scale)` request.
|
||||
#[wasm_bindgen]
|
||||
pub fn deliver_pdf_page_error(pdf_key: String, page_index: usize, scale: f32) {
|
||||
let affected = pdf_state()
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.deliver_page_error(&pdf_key, page_index, scale);
|
||||
if affected {
|
||||
fn wake_after_pdf_delivery(wake: bool) {
|
||||
if wake {
|
||||
bump_preview_revision();
|
||||
notify_active_view(true);
|
||||
}
|
||||
}
|
||||
|
||||
/// Callback invoked by `preview-workers.js` when the worker opened the PDF session `doc_id`.
|
||||
#[wasm_bindgen]
|
||||
pub fn deliver_pdf_open(doc_id: u32, page_count: usize) {
|
||||
let (wake, close) = lock_pdf_state().deliver_open(doc_id, page_count);
|
||||
send_worker_plan(&WorkerPlan {
|
||||
close: close.into_iter().collect(),
|
||||
..WorkerPlan::default()
|
||||
});
|
||||
wake_after_pdf_delivery(wake);
|
||||
}
|
||||
|
||||
/// Callback invoked by `preview-workers.js` when the worker could not parse the PDF of session
|
||||
/// `doc_id`.
|
||||
#[wasm_bindgen]
|
||||
pub fn deliver_pdf_open_error(doc_id: u32) {
|
||||
let (wake, close) = lock_pdf_state().deliver_open_error(doc_id);
|
||||
send_worker_plan(&WorkerPlan {
|
||||
close: close.into_iter().collect(),
|
||||
..WorkerPlan::default()
|
||||
});
|
||||
wake_after_pdf_delivery(wake);
|
||||
}
|
||||
|
||||
/// Callback invoked by `preview-workers.js` when a single PDF page rasterization fails,
|
||||
/// isolating failure to scopes waiting on that exact `(doc_id, page_index, scale)` request.
|
||||
#[wasm_bindgen]
|
||||
pub fn deliver_pdf_page_error(doc_id: u32, page_index: usize, scale: f32) {
|
||||
let wake = lock_pdf_state().deliver_page_error(doc_id, page_index, scale);
|
||||
wake_after_pdf_delivery(wake);
|
||||
}
|
||||
|
||||
pub(crate) fn prune_wasm_pdf_jobs_for_source(
|
||||
scope_id: u64,
|
||||
source_id: &str,
|
||||
keep_keys: &HashSet<(usize, u32)>,
|
||||
) -> Vec<Arc<ui::RenderImage>> {
|
||||
pdf_state()
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.prune_source(scope_id, source_id, keep_keys)
|
||||
lock_pdf_state().prune_source(scope_id, source_id, keep_keys)
|
||||
}
|
||||
|
||||
pub(crate) fn clear_wasm_pdf_scope(scope_id: u64) -> Vec<Arc<ui::RenderImage>> {
|
||||
pdf_state()
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.clear_scope(scope_id)
|
||||
let (retired, closed) = lock_pdf_state().clear_scope(scope_id);
|
||||
send_worker_plan(&WorkerPlan {
|
||||
close: closed,
|
||||
..WorkerPlan::default()
|
||||
});
|
||||
retired
|
||||
}
|
||||
|
||||
/// Callback invoked by `preview-workers.js` with one rasterized page of session `doc_id`.
|
||||
#[wasm_bindgen]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn deliver_pdf_page(
|
||||
pdf_key: String,
|
||||
doc_id: u32,
|
||||
page_index: usize,
|
||||
page_count: usize,
|
||||
scale: f32,
|
||||
@@ -552,14 +579,8 @@ pub fn deliver_pdf_page(
|
||||
height_px: u32,
|
||||
rgba: &[u8],
|
||||
) {
|
||||
let delivered = pdf_state()
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.deliver_page_ready(
|
||||
pdf_key, page_index, page_count, scale, width_px, height_px, rgba,
|
||||
);
|
||||
if delivered {
|
||||
bump_preview_revision();
|
||||
notify_active_view(true);
|
||||
}
|
||||
let wake = lock_pdf_state().deliver_page_ready(
|
||||
doc_id, page_index, page_count, scale, width_px, height_px, rgba,
|
||||
);
|
||||
wake_after_pdf_delivery(wake);
|
||||
}
|
||||
@@ -9,7 +9,9 @@ export function installPlaygroundPreviewBridge(wasmExports, baseUrl = window.loc
|
||||
const pendingMath = new Map();
|
||||
const pendingPdf = new Map();
|
||||
const pendingCode = new Map();
|
||||
const cachedPdfBytes = new Map();
|
||||
// `docId`s open in the current PDF worker. The bytes stay with the Rust session.
|
||||
const openPdfDocs = new Set();
|
||||
let detachPdfWorker = null;
|
||||
const mountedHtmlEmbeds = new Map();
|
||||
const registeredFonts = [];
|
||||
let mermaidFontsSent = 0;
|
||||
@@ -155,22 +157,11 @@ export function installPlaygroundPreviewBridge(wasmExports, baseUrl = window.loc
|
||||
URL.revokeObjectURL(entry.blobUrl);
|
||||
}
|
||||
mountedHtmlEmbeds.clear();
|
||||
// Fails the PDF requests on their way and terminates the worker with its documents.
|
||||
failAllPendingPdf();
|
||||
};
|
||||
}
|
||||
|
||||
function rememberPdfBytes(pdfKey, bytes) {
|
||||
if (cachedPdfBytes.has(pdfKey)) {
|
||||
return cachedPdfBytes.get(pdfKey);
|
||||
}
|
||||
if (cachedPdfBytes.size >= 16) {
|
||||
const oldestKey = cachedPdfBytes.keys().next().value;
|
||||
if (oldestKey !== undefined) cachedPdfBytes.delete(oldestKey);
|
||||
}
|
||||
const copy = new Uint8Array(bytes);
|
||||
cachedPdfBytes.set(pdfKey, copy);
|
||||
return copy;
|
||||
}
|
||||
|
||||
function failAllPendingMath() {
|
||||
const entries = Array.from(pendingMath.values());
|
||||
pendingMath.clear();
|
||||
@@ -189,41 +180,28 @@ export function installPlaygroundPreviewBridge(wasmExports, baseUrl = window.loc
|
||||
}
|
||||
}
|
||||
|
||||
function deliverPdfCountError(pdfKey) {
|
||||
if (typeof wasmExports.deliver_pdf_error === 'function') {
|
||||
wasmExports.deliver_pdf_error(pdfKey);
|
||||
}
|
||||
}
|
||||
|
||||
function deliverPdfPageError(pdfKey, pageIndex, scale) {
|
||||
if (typeof wasmExports.deliver_pdf_page_error === 'function') {
|
||||
wasmExports.deliver_pdf_page_error(pdfKey, pageIndex, scale);
|
||||
} else if (typeof wasmExports.deliver_pdf_error === 'function') {
|
||||
wasmExports.deliver_pdf_error(pdfKey);
|
||||
}
|
||||
// Stops listening to the current PDF worker and terminates it. Its documents are gone, and
|
||||
// a late `error` or `messageerror` from it can no longer reach the next worker.
|
||||
function dropPdfWorker() {
|
||||
if (!pdfWorker) return;
|
||||
const deadWorker = pdfWorker;
|
||||
pdfWorker = null;
|
||||
detachPdfWorker?.();
|
||||
detachPdfWorker = null;
|
||||
openPdfDocs.clear();
|
||||
deadWorker.terminate?.();
|
||||
}
|
||||
|
||||
function failAllPendingPdf() {
|
||||
const entries = Array.from(pendingPdf.values());
|
||||
pendingPdf.clear();
|
||||
if (pdfWorker) {
|
||||
pdfWorker.terminate?.();
|
||||
pdfWorker = null;
|
||||
}
|
||||
const seenCountKeys = new Set();
|
||||
const seenPageKeys = new Set();
|
||||
dropPdfWorker();
|
||||
// One answer per request sent: the Rust state counts each unanswered request.
|
||||
for (const req of entries) {
|
||||
if (req.op === 'page_count') {
|
||||
if (!seenCountKeys.has(req.pdfKey)) {
|
||||
seenCountKeys.add(req.pdfKey);
|
||||
deliverPdfCountError(req.pdfKey);
|
||||
}
|
||||
} else {
|
||||
const pageKey = `${req.pdfKey}:${req.pageIndex}:${req.scale}`;
|
||||
if (!seenPageKeys.has(pageKey)) {
|
||||
seenPageKeys.add(pageKey);
|
||||
deliverPdfPageError(req.pdfKey, req.pageIndex, req.scale);
|
||||
}
|
||||
if (req.op === 'pdf_open') {
|
||||
wasmExports.deliver_pdf_open_error(req.docId);
|
||||
} else if (req.op === 'pdf_render') {
|
||||
wasmExports.deliver_pdf_page_error(req.docId, req.pageIndex, req.scale);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -293,41 +271,66 @@ export function installPlaygroundPreviewBridge(wasmExports, baseUrl = window.loc
|
||||
|
||||
function ensurePdfWorker() {
|
||||
if (!pdfWorker) {
|
||||
pdfWorker = spawnWorker(
|
||||
const ownWorker = spawnWorker(
|
||||
resolveWorkerAsset('pdfScript', './workers/pdf-worker.js'),
|
||||
resolveWorkerAsset('pdfWasm', './workers/pdf-worker.wasm')
|
||||
);
|
||||
pdfWorker.addEventListener('error', failAllPendingPdf);
|
||||
pdfWorker.addEventListener('messageerror', failAllPendingPdf);
|
||||
pdfWorker.addEventListener('message', event => {
|
||||
const onFailure = () => {
|
||||
if (ownWorker === pdfWorker) failAllPendingPdf();
|
||||
};
|
||||
const onMessage = event => {
|
||||
if (ownWorker !== pdfWorker) return;
|
||||
const msg = event?.data;
|
||||
if (!msg || !pendingPdf.has(msg.id)) return;
|
||||
const req = pendingPdf.get(msg.id);
|
||||
pendingPdf.delete(msg.id);
|
||||
if (req.op === 'page_count') {
|
||||
if (!msg.ok || !msg.result) {
|
||||
deliverPdfCountError(req.pdfKey);
|
||||
if (req.op === 'pdf_open') {
|
||||
if (msg.ok && msg.result) {
|
||||
wasmExports.deliver_pdf_open(req.docId, msg.result.pageCount ?? 0);
|
||||
} else {
|
||||
wasmExports.deliver_pdf_page_count(req.pdfKey, msg.result.pageCount ?? 0);
|
||||
wasmExports.deliver_pdf_open_error(req.docId);
|
||||
}
|
||||
} else if (req.op === 'pdf_render') {
|
||||
if (msg.ok && msg.result?.rgba) {
|
||||
wasmExports.deliver_pdf_page(
|
||||
req.docId,
|
||||
req.pageIndex,
|
||||
msg.result.pageCount ?? 1,
|
||||
req.scale,
|
||||
msg.result.widthPx,
|
||||
msg.result.heightPx,
|
||||
msg.result.rgba
|
||||
);
|
||||
} else {
|
||||
wasmExports.deliver_pdf_page_error(req.docId, req.pageIndex, req.scale);
|
||||
}
|
||||
} else if (msg.ok && msg.result?.rgba) {
|
||||
wasmExports.deliver_pdf_page(
|
||||
req.pdfKey,
|
||||
req.pageIndex,
|
||||
msg.result.pageCount ?? 1,
|
||||
req.scale,
|
||||
msg.result.widthPx,
|
||||
msg.result.heightPx,
|
||||
msg.result.rgba
|
||||
);
|
||||
} else {
|
||||
deliverPdfPageError(req.pdfKey, req.pageIndex, req.scale);
|
||||
}
|
||||
});
|
||||
};
|
||||
ownWorker.addEventListener('error', onFailure);
|
||||
ownWorker.addEventListener('messageerror', onFailure);
|
||||
ownWorker.addEventListener('message', onMessage);
|
||||
detachPdfWorker = () => {
|
||||
ownWorker.removeEventListener?.('error', onFailure);
|
||||
ownWorker.removeEventListener?.('messageerror', onFailure);
|
||||
ownWorker.removeEventListener?.('message', onMessage);
|
||||
};
|
||||
pdfWorker = ownWorker;
|
||||
}
|
||||
return pdfWorker;
|
||||
}
|
||||
|
||||
function postPdf(req, message, transfer = []) {
|
||||
const worker = ensurePdfWorker();
|
||||
const id = nextId++;
|
||||
pendingPdf.set(id, req);
|
||||
try {
|
||||
worker.postMessage({ ...message, id }, transfer);
|
||||
} catch (err) {
|
||||
pendingPdf.delete(id);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
function resolveSvgIntrinsicSize(svgText) {
|
||||
const openMatch = /<svg\b[^>]*>/i.exec(svgText);
|
||||
if (!openMatch) {
|
||||
@@ -561,32 +564,30 @@ export function installPlaygroundPreviewBridge(wasmExports, baseUrl = window.loc
|
||||
wasmExports.deliver_math_error(latex, display, fontSizePt, colorCss, dpr);
|
||||
}
|
||||
},
|
||||
requestPdfPageCount(pdfKey, bytes) {
|
||||
const id = nextId++;
|
||||
const payload = rememberPdfBytes(pdfKey, bytes);
|
||||
pendingPdf.set(id, { op: 'page_count', pdfKey });
|
||||
try {
|
||||
ensurePdfWorker().postMessage({ id, op: 'page_count', pdfBytes: payload });
|
||||
} catch {
|
||||
pendingPdf.delete(id);
|
||||
deliverPdfCountError(pdfKey);
|
||||
}
|
||||
isPdfOpen(docId) {
|
||||
return openPdfDocs.has(docId);
|
||||
},
|
||||
requestPdfPage(pdfKey, bytes, pageIndex, scale) {
|
||||
const id = nextId++;
|
||||
const payload = rememberPdfBytes(pdfKey, bytes);
|
||||
pendingPdf.set(id, { op: 'render_page', pdfKey, pageIndex, scale });
|
||||
try {
|
||||
ensurePdfWorker().postMessage({
|
||||
id,
|
||||
pdfBytes: payload,
|
||||
pageIndex,
|
||||
scale,
|
||||
});
|
||||
} catch {
|
||||
pendingPdf.delete(id);
|
||||
deliverPdfPageError(pdfKey, pageIndex, scale);
|
||||
}
|
||||
// `bytes` is a view of the main Wasm memory. Copy it into a buffer of its own and transfer
|
||||
// that buffer, so the bytes cross once and no copy stays here.
|
||||
openPdf(docId, bytes) {
|
||||
const pdfBytes = new Uint8Array(bytes);
|
||||
postPdf({ op: 'pdf_open', docId }, { op: 'pdf_open', docId, pdfBytes }, [pdfBytes.buffer]);
|
||||
openPdfDocs.add(docId);
|
||||
},
|
||||
requestPdfPage(docId, pageIndex, scale) {
|
||||
postPdf(
|
||||
{ op: 'pdf_render', docId, pageIndex, scale },
|
||||
{ op: 'pdf_render', docId, pageIndex, scale }
|
||||
);
|
||||
},
|
||||
closePdf(docId) {
|
||||
if (!openPdfDocs.delete(docId)) return;
|
||||
postPdf({ op: 'pdf_close', docId }, { op: 'pdf_close', docId });
|
||||
},
|
||||
// Restarts the PDF worker without answering its requests. The caller has dropped them.
|
||||
restartPdfWorker() {
|
||||
pendingPdf.clear();
|
||||
dropPdfWorker();
|
||||
},
|
||||
pickImages(requestId) {
|
||||
openFilePicker(requestId, 'image/*', 32 * 1024 * 1024, false, (_file, bytes) => {
|
||||
|
||||
@@ -69,10 +69,10 @@ The `mermaid` and `typst` workers omit `svg-text`, because the Web host renders
|
||||
|
||||
| Worker Feature | Profile | Stripped + `wasm-opt -Oz` Raw Size | `gzip -9` Size |
|
||||
| --- | --- | ---: | ---: |
|
||||
| `math,wasm-worker` (RaTeX + `svg-raster` outlines) | `wasm-worker-size` (`opt-level = "z"`, fat LTO) | 3,073,023 B (2.93 MiB) | 1,198,027 B (1.14 MiB) |
|
||||
| `pdf,wasm-worker` (`hayro 0.9.0`, zero `resvg`) | `wasm-worker-size` (`opt-level = "z"`, fat LTO) | 3,175,888 B (3.03 MiB) | 1,521,787 B (1.45 MiB) |
|
||||
| `mermaid,wasm-worker` (`merman 0.11.0`, zero `svg-text`, with ELK) | `wasm-worker-size` (`opt-level = "z"`, fat LTO) | 10,698,577 B (10.20 MiB) | 4,146,907 B (3.95 MiB) |
|
||||
| `typst,wasm-worker` (`typst 0.15.1`, zero `svg-text`) | `wasm-worker-size` (`opt-level = "z"`, fat LTO) | 19,354,592 B (18.46 MiB) | 8,141,108 B (7.76 MiB) |
|
||||
| `math,wasm-worker` (RaTeX + `svg-raster` outlines) | `wasm-worker-size` (`opt-level = "z"`, fat LTO) | 3,072,764 B (2.93 MiB) | 1,198,018 B (1.14 MiB) |
|
||||
| `pdf,wasm-worker` (`hayro 0.9.0`, zero `resvg`) | `wasm-worker-size` (`opt-level = "z"`, fat LTO) | 3,176,018 B (3.03 MiB) | 1,522,615 B (1.45 MiB) |
|
||||
| `mermaid,wasm-worker` (`merman 0.11.0`, zero `svg-text`, with ELK) | `wasm-worker-size` (`opt-level = "z"`, fat LTO) | 10,698,263 B (10.20 MiB) | 4,147,091 B (3.95 MiB) |
|
||||
| `typst,wasm-worker` (`typst 0.15.1`, zero `svg-text`) | `wasm-worker-size` (`opt-level = "z"`, fat LTO) | 19,354,421 B (18.46 MiB) | 8,141,725 B (7.76 MiB) |
|
||||
|
||||
Measured on Linux x86-64 with Rust `1.98.1` and Binaryen `version_123`, with the flags above.
|
||||
|
||||
@@ -81,7 +81,7 @@ Measured on Linux x86-64 with Rust `1.98.1` and Binaryen `version_123`, with the
|
||||
- `math`, `mermaid`, and `pdf` are pure safe Rust with zero `cc` build scripts and zero native C or C++ libraries.
|
||||
- `typst` depends on `stacker` -> `psm`, which compiles a small stack-probe assembly stub via `cc` on native targets (`wasm32-unknown-unknown` builds do not invoke `psm`).
|
||||
- `blocksuite-preview` itself enforces `#![forbid(unsafe_code)]`, zero wall-clock calls, zero host font discovery, strict CSS color validation with XML attribute escaping, and zero external SVG `<image href>` filesystem or network resolution.
|
||||
- The Wasm Worker boundary is four scalar exports (`affine_worker_reset_input`, `affine_worker_push_input_u32`, `affine_worker_invoke`, `affine_worker_output_u32`) that stream one binary request and response frame through 32-bit words. The workers export no `wasm-bindgen` classes, so `wasm-opt` removes every engine method that no opcode reaches.
|
||||
- The Wasm Worker boundary is four exports: `memory`, `prepare(len) -> ptr`, `invoke() -> len`, and `output_ptr() -> ptr`. The host writes one binary request frame into the buffer that `prepare` returns and copies the response frame out of linear memory once. Rust gives out the addresses of its own buffers only, so the crate keeps `#![forbid(unsafe_code)]`. The workers export no `wasm-bindgen` classes, so `wasm-opt` removes every engine method that no opcode reaches.
|
||||
|
||||
## 5. S1 Release Probe Measurements and Verification Boundaries
|
||||
|
||||
|
||||
@@ -338,6 +338,25 @@ impl PreviewEngine {
|
||||
Ok(handle)
|
||||
}
|
||||
|
||||
/// Parses and caches a PDF document under a handle that the caller chose.
|
||||
///
|
||||
/// Rejects a handle that is already loaded, so one handle never refers to two documents.
|
||||
#[cfg(feature = "pdf")]
|
||||
pub fn load_pdf_with_handle(
|
||||
&mut self,
|
||||
handle: u32,
|
||||
pdf_bytes: impl Into<Vec<u8>>,
|
||||
) -> Result<(), PreviewError> {
|
||||
if self.pdf_docs.contains_key(&handle) {
|
||||
return Err(PreviewError::Pdf(format!(
|
||||
"pdf handle {handle} is already loaded"
|
||||
)));
|
||||
}
|
||||
let renderer = HayroPdfRenderer::from_bytes(pdf_bytes)?;
|
||||
self.pdf_docs.insert(handle, renderer);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Removes a previously loaded PDF document handle from memory.
|
||||
#[cfg(feature = "pdf")]
|
||||
pub fn unload_pdf(&mut self, handle: u32) -> bool {
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
//! Linear-memory request ABI of the preview Web Workers.
|
||||
//!
|
||||
//! The host calls `prepare(len)` and writes one request frame `[opcode, ...payload]` into the
|
||||
//! returned buffer, then calls `invoke()` and reads `invoke()` bytes at `output_ptr()`. The frame
|
||||
//! starts with `0x01` and a binary payload on success, or `0x00` and UTF-8 error text on failure.
|
||||
//! Rust only gives out the addresses of its own buffers and never reads an address from the host.
|
||||
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
use crate::cache::CacheLimits;
|
||||
@@ -17,6 +24,15 @@ std::thread_local! {
|
||||
std::cell::RefCell::new(RawWorkerState::new());
|
||||
}
|
||||
|
||||
/// Largest request frame that `prepare` accepts: a 256 MiB PDF plus its request header.
|
||||
const MAX_REQUEST_BYTES: u32 = 256 * 1024 * 1024 + 64;
|
||||
/// Buffers larger than this go back to the allocator after each request.
|
||||
const RETAINED_BUFFER_BYTES: usize = 1024 * 1024;
|
||||
|
||||
const OPCODE_PDF_OPEN: u8 = 5;
|
||||
const OPCODE_PDF_RENDER: u8 = 6;
|
||||
const OPCODE_PDF_CLOSE: u8 = 7;
|
||||
|
||||
struct RawWorkerState {
|
||||
engine: PreviewEngine,
|
||||
input: Vec<u8>,
|
||||
@@ -140,59 +156,71 @@ impl RawWorkerState {
|
||||
Err("typst feature disabled in this worker".to_string())
|
||||
}
|
||||
}
|
||||
5 => {
|
||||
OPCODE_PDF_OPEN => {
|
||||
#[cfg(feature = "pdf")]
|
||||
{
|
||||
if payload.len() < 4 {
|
||||
return Err("missing pdf page_index header".to_string());
|
||||
}
|
||||
let page_index =
|
||||
u32::from_le_bytes([payload[0], payload[1], payload[2], payload[3]])
|
||||
as usize;
|
||||
Self::render_pdf_frame(&mut self.engine, page_index, 2.0, &payload[4..])
|
||||
let doc_id = read_doc_id(payload)?;
|
||||
// Reuses the request buffer: the PDF bytes move to its start in place, so no
|
||||
// second buffer is allocated.
|
||||
let mut pdf_bytes = std::mem::take(&mut self.input);
|
||||
pdf_bytes.drain(..5);
|
||||
self.engine
|
||||
.load_pdf_with_handle(doc_id, pdf_bytes)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let page_count = self
|
||||
.engine
|
||||
.pdf_page_count(doc_id)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let mut frame = Vec::with_capacity(5);
|
||||
frame.push(1);
|
||||
frame.extend_from_slice(&(page_count as u32).to_le_bytes());
|
||||
Ok(frame)
|
||||
}
|
||||
#[cfg(not(feature = "pdf"))]
|
||||
{
|
||||
Err("pdf feature disabled in this worker".to_string())
|
||||
}
|
||||
}
|
||||
6 => {
|
||||
OPCODE_PDF_RENDER => {
|
||||
#[cfg(feature = "pdf")]
|
||||
{
|
||||
if payload.len() < 8 {
|
||||
return Err("missing pdf page_index and scale header".to_string());
|
||||
if payload.len() != 12 {
|
||||
return Err("pdf render request needs doc_id, page_index and scale".into());
|
||||
}
|
||||
let doc_id = read_doc_id(payload)?;
|
||||
let page_index =
|
||||
u32::from_le_bytes([payload[0], payload[1], payload[2], payload[3]])
|
||||
u32::from_le_bytes([payload[4], payload[5], payload[6], payload[7]])
|
||||
as usize;
|
||||
let raw_scale =
|
||||
f32::from_le_bytes([payload[4], payload[5], payload[6], payload[7]]);
|
||||
f32::from_le_bytes([payload[8], payload[9], payload[10], payload[11]]);
|
||||
let scale = if raw_scale.is_finite() && raw_scale > 0.0 {
|
||||
raw_scale.clamp(0.25, 4.0)
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
Self::render_pdf_frame(&mut self.engine, page_index, scale, &payload[8..])
|
||||
let (page_count, buf) = self
|
||||
.engine
|
||||
.render_pdf_page(doc_id, PdfRenderRequest::for_page(page_index, scale))
|
||||
.map_err(|e| e.to_string())?;
|
||||
let mut frame = Vec::with_capacity(13 + buf.pixels.len());
|
||||
frame.push(1);
|
||||
frame.extend_from_slice(&(page_count as u32).to_le_bytes());
|
||||
frame.extend_from_slice(&buf.width_px.to_le_bytes());
|
||||
frame.extend_from_slice(&buf.height_px.to_le_bytes());
|
||||
frame.extend_from_slice(&buf.pixels);
|
||||
Ok(frame)
|
||||
}
|
||||
#[cfg(not(feature = "pdf"))]
|
||||
{
|
||||
Err("pdf feature disabled in this worker".to_string())
|
||||
}
|
||||
}
|
||||
7 => {
|
||||
OPCODE_PDF_CLOSE => {
|
||||
#[cfg(feature = "pdf")]
|
||||
{
|
||||
let handle = self
|
||||
.engine
|
||||
.load_pdf(payload.to_vec())
|
||||
.map_err(|e| e.to_string())?;
|
||||
let count = self.engine.pdf_page_count(handle);
|
||||
let _ = self.engine.unload_pdf(handle);
|
||||
let page_count = count.map_err(|e| e.to_string())?;
|
||||
let mut frame = Vec::with_capacity(5);
|
||||
frame.push(1);
|
||||
frame.extend_from_slice(&(page_count as u32).to_le_bytes());
|
||||
Ok(frame)
|
||||
let doc_id = read_doc_id(payload)?;
|
||||
self.engine.unload_pdf(doc_id);
|
||||
Ok(vec![1])
|
||||
}
|
||||
#[cfg(not(feature = "pdf"))]
|
||||
{
|
||||
@@ -268,53 +296,40 @@ impl RawWorkerState {
|
||||
other => Err(format!("unknown worker opcode {other}")),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "pdf")]
|
||||
fn render_pdf_frame(
|
||||
engine: &mut PreviewEngine,
|
||||
page_index: usize,
|
||||
scale: f32,
|
||||
pdf_bytes: &[u8],
|
||||
) -> Result<Vec<u8>, String> {
|
||||
let handle = engine
|
||||
.load_pdf(pdf_bytes.to_vec())
|
||||
.map_err(|e| e.to_string())?;
|
||||
let render = engine.render_pdf_page(handle, PdfRenderRequest::for_page(page_index, scale));
|
||||
let _ = engine.unload_pdf(handle);
|
||||
let (page_count, buf) = render.map_err(|e| e.to_string())?;
|
||||
let mut frame = Vec::with_capacity(13 + buf.pixels.len());
|
||||
frame.push(1);
|
||||
frame.extend_from_slice(&(page_count as u32).to_le_bytes());
|
||||
frame.extend_from_slice(&buf.width_px.to_le_bytes());
|
||||
frame.extend_from_slice(&buf.height_px.to_le_bytes());
|
||||
frame.extend_from_slice(&buf.pixels);
|
||||
Ok(frame)
|
||||
}
|
||||
}
|
||||
|
||||
/// Clears the worker's raw request buffer ahead of streaming a new request.
|
||||
#[wasm_bindgen]
|
||||
pub fn affine_worker_reset_input() {
|
||||
#[cfg(feature = "pdf")]
|
||||
fn read_doc_id(payload: &[u8]) -> Result<u32, String> {
|
||||
payload
|
||||
.first_chunk::<4>()
|
||||
.map(|bytes| u32::from_le_bytes(*bytes))
|
||||
.ok_or_else(|| "missing pdf doc_id header".to_string())
|
||||
}
|
||||
|
||||
/// Sizes the request buffer to `len` bytes and returns its address in linear memory.
|
||||
/// Returns `0` when `len` is larger than the request limit.
|
||||
#[wasm_bindgen(js_name = prepare)]
|
||||
pub fn affine_worker_prepare(len: u32) -> u32 {
|
||||
if len > MAX_REQUEST_BYTES {
|
||||
return 0;
|
||||
}
|
||||
WORKER_STATE.with(|cell| {
|
||||
let mut st = cell.borrow_mut();
|
||||
if st.output.capacity() > RETAINED_BUFFER_BYTES {
|
||||
st.output = Vec::new();
|
||||
} else {
|
||||
st.output.clear();
|
||||
}
|
||||
st.input.clear();
|
||||
st.output.clear();
|
||||
});
|
||||
st.input.resize(len as usize, 0);
|
||||
st.input.as_ptr() as usize as u32
|
||||
})
|
||||
}
|
||||
|
||||
/// Appends `valid_bytes` (1..=4) little-endian bytes of `word` to the raw request buffer.
|
||||
#[wasm_bindgen]
|
||||
pub fn affine_worker_push_input_u32(word: u32, valid_bytes: u32) {
|
||||
let count = (valid_bytes as usize).min(4);
|
||||
let bytes = word.to_le_bytes();
|
||||
WORKER_STATE.with(|cell| {
|
||||
cell.borrow_mut().input.extend_from_slice(&bytes[..count]);
|
||||
});
|
||||
}
|
||||
|
||||
/// Executes the buffered worker request and returns the binary response frame length.
|
||||
#[wasm_bindgen]
|
||||
pub fn affine_worker_invoke() -> usize {
|
||||
/// Executes the request frame that the host wrote after `prepare` and returns the response
|
||||
/// frame length.
|
||||
#[wasm_bindgen(js_name = invoke)]
|
||||
pub fn affine_worker_invoke() -> u32 {
|
||||
WORKER_STATE.with(|cell| {
|
||||
let mut st = cell.borrow_mut();
|
||||
let response = match st.dispatch() {
|
||||
@@ -326,25 +341,20 @@ pub fn affine_worker_invoke() -> usize {
|
||||
frame
|
||||
}
|
||||
};
|
||||
if st.input.capacity() > RETAINED_BUFFER_BYTES {
|
||||
st.input = Vec::new();
|
||||
} else {
|
||||
st.input.clear();
|
||||
}
|
||||
st.output = response;
|
||||
st.output.len()
|
||||
st.output.len() as u32
|
||||
})
|
||||
}
|
||||
|
||||
/// Reads 4 little-endian bytes from the response frame at `word_index * 4`.
|
||||
#[wasm_bindgen]
|
||||
pub fn affine_worker_output_u32(word_index: usize) -> u32 {
|
||||
WORKER_STATE.with(|cell| {
|
||||
let st = cell.borrow();
|
||||
let base = word_index.saturating_mul(4);
|
||||
let mut chunk = [0_u8; 4];
|
||||
for (offset, slot) in chunk.iter_mut().enumerate() {
|
||||
if let Some(&b) = st.output.get(base + offset) {
|
||||
*slot = b;
|
||||
}
|
||||
}
|
||||
u32::from_le_bytes(chunk)
|
||||
})
|
||||
/// Returns the address of the response frame of the last `invoke` in linear memory.
|
||||
#[wasm_bindgen(js_name = output_ptr)]
|
||||
pub fn affine_worker_output_ptr() -> u32 {
|
||||
WORKER_STATE.with(|cell| cell.borrow().output.as_ptr() as usize as u32)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -393,4 +403,109 @@ mod tests {
|
||||
let svg = std::str::from_utf8(&frame[5..]).unwrap();
|
||||
assert!(svg.contains("<svg") && svg.contains("<path"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepare_rejects_oversized_requests_and_invoke_releases_large_buffers() {
|
||||
assert_eq!(affine_worker_prepare(MAX_REQUEST_BYTES + 1), 0);
|
||||
let len = RETAINED_BUFFER_BYTES as u32 * 2;
|
||||
assert_ne!(affine_worker_prepare(len), 0);
|
||||
WORKER_STATE.with(|cell| assert_eq!(cell.borrow().input.len(), len as usize));
|
||||
let out_len = affine_worker_invoke();
|
||||
WORKER_STATE.with(|cell| {
|
||||
let st = cell.borrow();
|
||||
assert_eq!(st.input.capacity(), 0);
|
||||
assert_eq!(st.output.len(), out_len as usize);
|
||||
assert_eq!(st.output[0], 0, "a zero opcode is an unknown request");
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(feature = "pdf")]
|
||||
fn two_page_pdf() -> Vec<u8> {
|
||||
let objects = [
|
||||
"<< /Type /Catalog /Pages 2 0 R >>",
|
||||
"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>",
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 50] >>",
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 40 80] >>",
|
||||
];
|
||||
let mut out = b"%PDF-1.4\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (idx, body) in objects.iter().enumerate() {
|
||||
offsets.push(out.len());
|
||||
out.extend_from_slice(format!("{} 0 obj\n{body}\nendobj\n", idx + 1).as_bytes());
|
||||
}
|
||||
let xref = out.len();
|
||||
out.extend_from_slice(
|
||||
format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes(),
|
||||
);
|
||||
for offset in offsets {
|
||||
out.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
out.extend_from_slice(
|
||||
format!(
|
||||
"trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n",
|
||||
objects.len() + 1
|
||||
)
|
||||
.as_bytes(),
|
||||
);
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(feature = "pdf")]
|
||||
#[test]
|
||||
fn pdf_opcodes_keep_documents_by_doc_id_until_close() {
|
||||
fn open(doc_id: u32, bytes: &[u8]) -> Vec<u8> {
|
||||
[&[OPCODE_PDF_OPEN][..], &doc_id.to_le_bytes(), bytes].concat()
|
||||
}
|
||||
fn render(doc_id: u32, page: u32, scale: f32) -> Vec<u8> {
|
||||
[
|
||||
&[OPCODE_PDF_RENDER][..],
|
||||
&doc_id.to_le_bytes(),
|
||||
&page.to_le_bytes(),
|
||||
&scale.to_le_bytes(),
|
||||
]
|
||||
.concat()
|
||||
}
|
||||
fn close(doc_id: u32) -> Vec<u8> {
|
||||
[&[OPCODE_PDF_CLOSE][..], &doc_id.to_le_bytes()].concat()
|
||||
}
|
||||
enum Expect {
|
||||
Ok(&'static [u32]),
|
||||
Err(&'static str),
|
||||
}
|
||||
let pdf = two_page_pdf();
|
||||
let steps = [
|
||||
(open(7, &pdf), Expect::Ok(&[2])),
|
||||
(open(7, &pdf), Expect::Err("pdf handle 7 is already loaded")),
|
||||
(open(8, b"not a pdf"), Expect::Err("")),
|
||||
(render(7, 0, 1.0), Expect::Ok(&[2, 100, 50])),
|
||||
(render(7, 1, 2.0), Expect::Ok(&[2, 80, 160])),
|
||||
(render(8, 0, 1.0), Expect::Err("unknown pdf handle 8")),
|
||||
(close(7), Expect::Ok(&[])),
|
||||
(render(7, 0, 1.0), Expect::Err("unknown pdf handle 7")),
|
||||
(open(7, &pdf), Expect::Ok(&[2])),
|
||||
];
|
||||
let mut state = RawWorkerState::new();
|
||||
for (idx, (request, expect)) in steps.into_iter().enumerate() {
|
||||
state.input = request;
|
||||
let result = state.dispatch();
|
||||
match expect {
|
||||
Expect::Ok(words) => {
|
||||
let frame = result.unwrap_or_else(|e| panic!("step {idx}: {e}"));
|
||||
assert_eq!(frame[0], 1, "step {idx}");
|
||||
for (w, want) in words.iter().enumerate() {
|
||||
let at = 1 + w * 4;
|
||||
let got = u32::from_le_bytes(frame[at..at + 4].try_into().unwrap());
|
||||
assert_eq!(got, *want, "step {idx} word {w}");
|
||||
}
|
||||
if words.len() == 3 {
|
||||
assert_eq!(frame.len(), 13 + (words[1] * words[2] * 4) as usize);
|
||||
}
|
||||
}
|
||||
Expect::Err(text) => {
|
||||
let err = result.expect_err(&format!("step {idx} must fail"));
|
||||
assert!(err.contains(text), "step {idx}: {err}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -38,10 +38,10 @@ const REPO_ROOT = resolve(FRONTEND_ROOT, '../..');
|
||||
const WORKER_KINDS = ['mermaid', 'math', 'typst', 'pdf'];
|
||||
const MIN_REAL_WASM_BYTES = 10 * 1024;
|
||||
const PREVIEW_WORKER_REQUIRED_EXPORTS = [
|
||||
'affine_worker_reset_input',
|
||||
'affine_worker_push_input_u32',
|
||||
'affine_worker_invoke',
|
||||
'affine_worker_output_u32',
|
||||
'memory',
|
||||
'prepare',
|
||||
'invoke',
|
||||
'output_ptr',
|
||||
];
|
||||
const PLAYGROUND_REQUIRED_EXPORTS = ['merge_updates_v1', 'extract_subdoc_ids'];
|
||||
|
||||
@@ -86,12 +86,12 @@ export function validateRealWasmBinary(label, bytes, requiredExports) {
|
||||
`Invalid ${label}: failed to compile Wasm module (${err instanceof Error ? err.message : String(err)}).`
|
||||
);
|
||||
}
|
||||
const fnExports = WebAssembly.Module.exports(mod)
|
||||
.filter(exp => exp.kind === 'function')
|
||||
.map(exp => exp.name);
|
||||
const moduleExports = WebAssembly.Module.exports(mod);
|
||||
const hasExport = name =>
|
||||
fnExports.some(
|
||||
expName => expName === name || expName.startsWith(`${name}_`)
|
||||
moduleExports.some(
|
||||
exp =>
|
||||
exp.name === name ||
|
||||
(exp.kind === 'function' && exp.name.startsWith(`${name}_`))
|
||||
);
|
||||
const missing = requiredExports.filter(name => !hasExport(name));
|
||||
if (missing.length > 0) {
|
||||
|
||||
@@ -13,33 +13,59 @@ const WEB_ROOT = resolve(fileURLToPath(new URL('..', import.meta.url)));
|
||||
const ASSETS_DIR = join(WEB_ROOT, 'assets');
|
||||
|
||||
/**
|
||||
* Builds a minimal 300x200 PDF filled with a solid RGB color.
|
||||
* Builds a PDF with one 300x200 page per fill operator. `padBytes` adds an
|
||||
* unreferenced stream object of that size, so large inputs make the worker
|
||||
* grow its linear memory.
|
||||
*
|
||||
* @param {string} rgbOp
|
||||
* @param {string[]} pageFills
|
||||
* @param {number} [padBytes=0]
|
||||
* @returns {Uint8Array}
|
||||
*/
|
||||
function buildSolidColorPdf(rgbOp) {
|
||||
const streamBody = `${rgbOp} 0 0 300 200 re f\n`;
|
||||
const pdf =
|
||||
'%PDF-1.4\n' +
|
||||
'1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n' +
|
||||
'2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n' +
|
||||
'3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 200] /Contents 4 0 R >> endobj\n' +
|
||||
`4 0 obj << /Length ${streamBody.length} >> stream\n` +
|
||||
streamBody +
|
||||
'endstream endobj\n' +
|
||||
'xref\n' +
|
||||
'0 5\n' +
|
||||
'0000000000 65535 f \n' +
|
||||
'0000000009 00000 n \n' +
|
||||
'0000000058 00000 n \n' +
|
||||
'0000000115 00000 n \n' +
|
||||
'0000000201 00000 n \n' +
|
||||
'trailer << /Size 5 /Root 1 0 R >>\n' +
|
||||
'startxref\n' +
|
||||
'295\n' +
|
||||
'%%EOF\n';
|
||||
return new Uint8Array(Buffer.from(pdf, 'ascii'));
|
||||
function buildPdf(pageFills, padBytes = 0) {
|
||||
const bodies = [
|
||||
'<< /Type /Catalog /Pages 2 0 R >>',
|
||||
`<< /Type /Pages /Kids [${pageFills.map((_, i) => `${3 + i * 2} 0 R`).join(' ')}] /Count ${pageFills.length} >>`,
|
||||
];
|
||||
for (const [i, fill] of pageFills.entries()) {
|
||||
const stream = `${fill} 0 0 300 200 re f\n`;
|
||||
bodies.push(
|
||||
`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 200] /Contents ${4 + i * 2} 0 R >>`,
|
||||
`<< /Length ${stream.length} >>\nstream\n${stream}endstream`
|
||||
);
|
||||
}
|
||||
const chunks = [Buffer.from('%PDF-1.4\n', 'ascii')];
|
||||
let length = chunks[0].length;
|
||||
const offsets = [];
|
||||
const push = buf => {
|
||||
chunks.push(buf);
|
||||
length += buf.length;
|
||||
};
|
||||
for (const [i, body] of bodies.entries()) {
|
||||
offsets.push(length);
|
||||
push(Buffer.from(`${i + 1} 0 obj\n${body}\nendobj\n`, 'ascii'));
|
||||
}
|
||||
if (padBytes > 0) {
|
||||
offsets.push(length);
|
||||
push(
|
||||
Buffer.from(
|
||||
`${bodies.length + 1} 0 obj\n<< /Length ${padBytes} >>\nstream\n`,
|
||||
'ascii'
|
||||
)
|
||||
);
|
||||
push(Buffer.alloc(padBytes, 0x20));
|
||||
push(Buffer.from('\nendstream\nendobj\n', 'ascii'));
|
||||
}
|
||||
const xrefAt = length;
|
||||
const size = offsets.length + 1;
|
||||
push(
|
||||
Buffer.from(
|
||||
`xref\n0 ${size}\n0000000000 65535 f \n` +
|
||||
offsets.map(o => `${String(o).padStart(10, '0')} 00000 n \n`).join('') +
|
||||
`trailer\n<< /Size ${size} /Root 1 0 R >>\nstartxref\n${xrefAt}\n%%EOF\n`,
|
||||
'ascii'
|
||||
)
|
||||
);
|
||||
return new Uint8Array(Buffer.concat(chunks));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -151,7 +177,7 @@ const loader = createWorkerLoader(manifest, {
|
||||
});
|
||||
|
||||
return /** @type {unknown} */ ({
|
||||
async rpc(payload) {
|
||||
async rpc(payload, transfer = []) {
|
||||
const w = await readyWorker;
|
||||
return new Promise((resolveRpc, rejectRpc) => {
|
||||
const onMsg = msg => {
|
||||
@@ -167,7 +193,7 @@ const loader = createWorkerLoader(manifest, {
|
||||
};
|
||||
w.on('message', onMsg);
|
||||
w.once('error', onErr);
|
||||
w.postMessage(payload);
|
||||
w.postMessage(payload, transfer);
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -371,56 +397,213 @@ try {
|
||||
typstRes.result.svg.includes('<use'),
|
||||
'typst worker SVG must contain rendered glyph paths'
|
||||
);
|
||||
const typstPages =
|
||||
'#set page(width: 120pt, height: 80pt)\nFirst\n#pagebreak()\nSecond';
|
||||
const typstPage1 = await typstWorker.rpc({
|
||||
id: 60,
|
||||
source: typstPages,
|
||||
pageIndex: 1,
|
||||
});
|
||||
const typstPage0 = await typstWorker.rpc({
|
||||
id: 61,
|
||||
source: typstPages,
|
||||
pageIndex: 0,
|
||||
});
|
||||
assert.equal(typstPage1.ok, true, `typst page 1 failed: ${typstPage1.error}`);
|
||||
assert.equal(typstPage1.result.pageCount, 2);
|
||||
assert.ok(typstPage1.result.svg.includes('<svg'));
|
||||
assert.notEqual(typstPage1.result.svg, typstPage0.result.svg);
|
||||
const typstOutOfRange = await typstWorker.rpc({
|
||||
id: 62,
|
||||
source: typstPages,
|
||||
pageIndex: 2,
|
||||
});
|
||||
assert.equal(typstOutOfRange.ok, false);
|
||||
assert.match(typstOutOfRange.error, /out of range/);
|
||||
|
||||
// 5. PDF (Hayro) worker: two distinct 300x200 PDFs must return transferable RGBA pixels matching fill color.
|
||||
// 5. PDF (Hayro) worker. Messages sent back to back before the worker has
|
||||
// started run in arrival order, so an open, a render and a close need no
|
||||
// round trip between them.
|
||||
const pdfWorker = /** @type {any} */ (loader.loadWorker('pdf'));
|
||||
const redRes = await pdfWorker.rpc({
|
||||
id: 7,
|
||||
pdfBytes: buildSolidColorPdf('0.9 0.1 0.1 rg'),
|
||||
pageIndex: 0,
|
||||
});
|
||||
const blueRes = await pdfWorker.rpc({
|
||||
id: 8,
|
||||
pdfBytes: buildSolidColorPdf('0.1 0.2 0.9 rg'),
|
||||
pageIndex: 0,
|
||||
});
|
||||
assert.equal(redRes.ok, true, `pdf red failed: ${redRes.error}`);
|
||||
assert.equal(blueRes.ok, true, `pdf blue failed: ${blueRes.error}`);
|
||||
const RED = '0.9 0.1 0.1 rg';
|
||||
const BLUE = '0.1 0.2 0.9 rg';
|
||||
const GREEN = '0.1 0.8 0.2 rg';
|
||||
const twoPagePdf = buildPdf([RED, BLUE]);
|
||||
const coldOpenBytes = twoPagePdf.slice();
|
||||
const [coldOpen, coldRender, coldClose, renderAfterClose] = await Promise.all(
|
||||
[
|
||||
pdfWorker.rpc(
|
||||
{ id: 70, op: 'pdf_open', docId: 1, pdfBytes: coldOpenBytes },
|
||||
[coldOpenBytes.buffer]
|
||||
),
|
||||
pdfWorker.rpc({
|
||||
id: 71,
|
||||
op: 'pdf_render',
|
||||
docId: 1,
|
||||
pageIndex: 1,
|
||||
scale: 1,
|
||||
}),
|
||||
pdfWorker.rpc({ id: 72, op: 'pdf_close', docId: 1 }),
|
||||
pdfWorker.rpc({
|
||||
id: 73,
|
||||
op: 'pdf_render',
|
||||
docId: 1,
|
||||
pageIndex: 0,
|
||||
scale: 1,
|
||||
}),
|
||||
]
|
||||
);
|
||||
assert.equal(
|
||||
coldOpenBytes.byteLength,
|
||||
0,
|
||||
'the open message transfers its bytes'
|
||||
);
|
||||
assert.equal(coldOpen.ok, true, `pdf cold open failed: ${coldOpen.error}`);
|
||||
assert.equal(coldOpen.result.pageCount, 2);
|
||||
assert.equal(
|
||||
coldRender.ok,
|
||||
true,
|
||||
`pdf cold render failed: ${coldRender.error}`
|
||||
);
|
||||
assert.equal(coldClose.ok, true, `pdf close failed: ${coldClose.error}`);
|
||||
assert.equal(renderAfterClose.ok, false);
|
||||
assert.match(renderAfterClose.error, /unknown pdf handle 1/);
|
||||
|
||||
for (const [label, res] of /** @type {const} */ ([
|
||||
['red', redRes.result],
|
||||
['blue', blueRes.result],
|
||||
])) {
|
||||
assert.equal(res.pageCount, 1);
|
||||
assert.ok(res.widthPx > 0 && res.heightPx > 0);
|
||||
/** @param {any} res */
|
||||
const centerPixel = res => {
|
||||
const off =
|
||||
(Math.floor(res.heightPx / 2) * res.widthPx +
|
||||
Math.floor(res.widthPx / 2)) *
|
||||
4;
|
||||
return [res.rgba[off], res.rgba[off + 1], res.rgba[off + 2]];
|
||||
};
|
||||
/**
|
||||
* @param {string} label
|
||||
* @param {any} msg
|
||||
* @param {'r' | 'g' | 'b'} channel
|
||||
*/
|
||||
const assertFill = (label, msg, channel) => {
|
||||
assert.equal(msg.ok, true, `${label} failed: ${msg.error}`);
|
||||
const res = msg.result;
|
||||
assert.ok(
|
||||
res.rgba instanceof Uint8Array,
|
||||
`${label} PDF result must return Uint8Array RGBA pixels`
|
||||
`${label} must return Uint8Array RGBA`
|
||||
);
|
||||
assert.equal(
|
||||
res.rgba.byteLength,
|
||||
res.widthPx * res.heightPx * 4,
|
||||
`${label} PDF RGBA length must equal widthPx * heightPx * 4`
|
||||
assert.equal(res.rgba.byteOffset, 0, `${label} RGBA must own its buffer`);
|
||||
assert.equal(res.rgba.buffer.byteLength, res.widthPx * res.heightPx * 4);
|
||||
const [r, g, b] = centerPixel(res);
|
||||
const value = { r, g, b }[channel];
|
||||
assert.ok(
|
||||
value > 180 && value > Math.max(r, g, b) - 1,
|
||||
`${label} center pixel mismatch: ${r},${g},${b}`
|
||||
);
|
||||
}
|
||||
};
|
||||
assertFill('pdf cold render page 1', coldRender, 'b');
|
||||
|
||||
const centerOffset = res =>
|
||||
(Math.floor(res.heightPx / 2) * res.widthPx + Math.floor(res.widthPx / 2)) *
|
||||
4;
|
||||
const redOff = centerOffset(redRes.result);
|
||||
const redR = redRes.result.rgba[redOff];
|
||||
const redB = redRes.result.rgba[redOff + 2];
|
||||
assert.ok(
|
||||
redR > 180 && redR > redB + 100,
|
||||
`red PDF center pixel mismatch: R=${redR}, B=${redB}`
|
||||
// Two documents stay open together and their renders interleave. The
|
||||
// second one is larger than 32 MiB, so opening it grows linear memory.
|
||||
const bigPadBytes = 32 * 1024 * 1024;
|
||||
const bigPdf = buildPdf([GREEN, RED, BLUE], bigPadBytes);
|
||||
const docs = await Promise.all([
|
||||
pdfWorker.rpc({ id: 80, op: 'pdf_open', docId: 2, pdfBytes: twoPagePdf }),
|
||||
pdfWorker.rpc({ id: 81, op: 'pdf_open', docId: 3, pdfBytes: bigPdf }, [
|
||||
bigPdf.buffer,
|
||||
]),
|
||||
]);
|
||||
assert.deepEqual(
|
||||
docs.map(msg => [msg.ok, msg.result?.pageCount]),
|
||||
[
|
||||
[true, 2],
|
||||
[true, 3],
|
||||
]
|
||||
);
|
||||
const interleaved = await Promise.all([
|
||||
pdfWorker.rpc({
|
||||
id: 82,
|
||||
op: 'pdf_render',
|
||||
docId: 3,
|
||||
pageIndex: 0,
|
||||
scale: 1,
|
||||
}),
|
||||
pdfWorker.rpc({
|
||||
id: 83,
|
||||
op: 'pdf_render',
|
||||
docId: 2,
|
||||
pageIndex: 0,
|
||||
scale: 1,
|
||||
}),
|
||||
pdfWorker.rpc({
|
||||
id: 84,
|
||||
op: 'pdf_render',
|
||||
docId: 3,
|
||||
pageIndex: 2,
|
||||
scale: 2,
|
||||
}),
|
||||
pdfWorker.rpc({
|
||||
id: 85,
|
||||
op: 'pdf_render',
|
||||
docId: 2,
|
||||
pageIndex: 1,
|
||||
scale: 1,
|
||||
}),
|
||||
]);
|
||||
assertFill('pdf big page 0', interleaved[0], 'g');
|
||||
assertFill('pdf small page 0', interleaved[1], 'r');
|
||||
assertFill('pdf big page 2', interleaved[2], 'b');
|
||||
assertFill('pdf small page 1', interleaved[3], 'b');
|
||||
assert.deepEqual(
|
||||
[interleaved[2].result.widthPx, interleaved[2].result.heightPx],
|
||||
[600, 400],
|
||||
'scale 2 doubles the page size'
|
||||
);
|
||||
const redRes = interleaved[1];
|
||||
const blueRes = interleaved[3];
|
||||
const [redR, , redB] = centerPixel(redRes.result);
|
||||
const [blueR, , blueB] = centerPixel(blueRes.result);
|
||||
|
||||
const blueOff = centerOffset(blueRes.result);
|
||||
const blueR = blueRes.result.rgba[blueOff];
|
||||
const blueB = blueRes.result.rgba[blueOff + 2];
|
||||
assert.ok(
|
||||
blueB > 180 && blueB > blueR + 100,
|
||||
`blue PDF center pixel mismatch: R=${blueR}, B=${blueB}`
|
||||
// Error frames keep their worker error text.
|
||||
const errors = await Promise.all([
|
||||
pdfWorker.rpc({ id: 90, op: 'pdf_open', docId: 2, pdfBytes: twoPagePdf }),
|
||||
pdfWorker.rpc({
|
||||
id: 91,
|
||||
op: 'pdf_open',
|
||||
docId: 4,
|
||||
pdfBytes: new TextEncoder().encode('%PDF-1.4 not a pdf'),
|
||||
}),
|
||||
pdfWorker.rpc({
|
||||
id: 92,
|
||||
op: 'pdf_render',
|
||||
docId: 2,
|
||||
pageIndex: 9,
|
||||
scale: 1,
|
||||
}),
|
||||
pdfWorker.rpc({
|
||||
id: 93,
|
||||
op: 'pdf_render',
|
||||
docId: 99,
|
||||
pageIndex: 0,
|
||||
scale: 1,
|
||||
}),
|
||||
pdfWorker.rpc({ id: 94, pdfBytes: twoPagePdf, pageIndex: 0 }),
|
||||
]);
|
||||
assert.deepEqual(
|
||||
errors.map(msg => msg.ok),
|
||||
[false, false, false, false, false]
|
||||
);
|
||||
assert.match(errors[0].error, /pdf handle 2 is already loaded/);
|
||||
assert.match(errors[3].error, /unknown pdf handle 99/);
|
||||
assert.match(errors[4].error, /Unsupported pdf worker op/);
|
||||
// The documents stay usable after the errors.
|
||||
assertFill(
|
||||
'pdf small page 0 after errors',
|
||||
await pdfWorker.rpc({
|
||||
id: 95,
|
||||
op: 'pdf_render',
|
||||
docId: 2,
|
||||
pageIndex: 0,
|
||||
scale: 1,
|
||||
}),
|
||||
'r'
|
||||
);
|
||||
|
||||
// 6. Main playground Wasm bundle (`assets/pkg/playground.js`): real Yjs v1 extract + merge + corrupt fail.
|
||||
@@ -467,7 +650,7 @@ try {
|
||||
);
|
||||
|
||||
console.log(
|
||||
`E2E 4-worker + main-wasm-crdt + static-font verification passed: fonts(${Object.keys(loadedFonts).join(',')}), playground_bg.wasm(${playgroundWasmBytes.byteLength}B, merged=${mergedV1.byteLength}B), mermaid(light=${mermaidLight.result.svg.length}B vs dark=${mermaidDark.result.svg.length}B), math(${mathRes.result.svg.length}B), typst(1p ${typstRes.result.svg.length}B), pdf(red R=${redR}/B=${redB}, blue R=${blueR}/B=${blueB}, ${redRes.result.rgba.byteLength}B RGBA)`
|
||||
`E2E 4-worker + main-wasm-crdt + static-font verification passed: fonts(${Object.keys(loadedFonts).join(',')}), playground_bg.wasm(${playgroundWasmBytes.byteLength}B, merged=${mergedV1.byteLength}B), mermaid(light=${mermaidLight.result.svg.length}B vs dark=${mermaidDark.result.svg.length}B), math(${mathRes.result.svg.length}B), typst(1p ${typstRes.result.svg.length}B, 2p), pdf(red R=${redR}/B=${redB}, blue R=${blueR}/B=${blueB}, ${redRes.result.rgba.byteLength}B RGBA, 32 MiB doc open)`
|
||||
);
|
||||
} finally {
|
||||
await Promise.all(activeWorkers.map(w => w.terminate()));
|
||||
|
||||
@@ -592,6 +592,22 @@ try {
|
||||
scale: 1,
|
||||
});
|
||||
|
||||
// New bytes under the same docKey reopen the document and update its page count.
|
||||
const onePageText = new TextDecoder()
|
||||
.decode(pdfBytes)
|
||||
.replace('/Kids [3 0 R 5 0 R] /Count 2', '/Kids [3 0 R] /Count 1 ');
|
||||
const onePagePdf = new TextEncoder().encode(onePageText);
|
||||
const changedPageCount = await host.pdfClient.getPageCount({
|
||||
docKey: 'r2-pdf',
|
||||
pdfBytes: onePagePdf,
|
||||
});
|
||||
const changedPage = await host.pdfClient.renderPage({
|
||||
docKey: 'r2-pdf',
|
||||
pdfBytes: onePagePdf,
|
||||
pageIndex: 0,
|
||||
scale: 1,
|
||||
});
|
||||
|
||||
// Composite the 2x hayro PDF bitmap onto production index.html #app-canvas.
|
||||
const off = document.createElement('canvas');
|
||||
off.width = p2x.widthPx;
|
||||
@@ -671,6 +687,8 @@ try {
|
||||
two: { w: p2x.widthPx, h: p2x.heightPx },
|
||||
afterTransferBytes: p1AfterTransfer.rgba.byteLength,
|
||||
afterTransferFromCache: p1AfterTransfer.fromCache,
|
||||
changedPageCount,
|
||||
changedPage: { count: changedPage.pageCount, fromCache: changedPage.fromCache },
|
||||
stats,
|
||||
};
|
||||
})()`);
|
||||
@@ -683,6 +701,9 @@ try {
|
||||
assert.equal(pdfResult.one.h, pdfResult.half.h * 2);
|
||||
assert.equal(pdfResult.two.h, pdfResult.one.h * 2);
|
||||
assert.equal(pdfResult.afterTransferFromCache, true);
|
||||
assert.equal(pdfResult.changedPageCount, 1);
|
||||
assert.deepEqual(pdfResult.changedPage, { count: 1, fromCache: false });
|
||||
assert.equal(pdfResult.stats.openDocs, 1);
|
||||
assert.equal(
|
||||
pdfResult.afterTransferBytes,
|
||||
pdfResult.one.w * pdfResult.one.h * 4
|
||||
|
||||
@@ -62,11 +62,61 @@ export function buildPdfPageCacheKey(docKey, pageIndex, scale) {
|
||||
return `${docKey}:${pageIndex}:${normalizeScale(scale)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* One `docKey` and the PDF bytes it was last opened with.
|
||||
*
|
||||
* @typedef {Object} PdfDocEntry
|
||||
* @property {WeakRef<Uint8Array>} bytes The caller's bytes. Only identity is kept, never a copy.
|
||||
* @property {number} byteLength
|
||||
* @property {number | null} docId Handle in the current worker, or `null` when not open there.
|
||||
* @property {number | undefined} pageCount
|
||||
* @property {Promise<number> | null} opened Answer to the last `pdf_open`, with the page count.
|
||||
* @property {number} inFlight Worker requests not answered yet.
|
||||
*/
|
||||
|
||||
const MAX_OPEN_DOCS = 8;
|
||||
const MAX_OPEN_DOC_BYTES = 256 * 1024 * 1024;
|
||||
const MAX_KNOWN_DOCS = 64;
|
||||
const MAX_DOC_ID = 0xffffffff;
|
||||
|
||||
/**
|
||||
* Tells whether `next` holds the same PDF as the bytes an entry was opened
|
||||
* with. The same object is the same PDF. Another object is compared byte for
|
||||
* byte while the first one is still alive, and is a different PDF otherwise.
|
||||
*
|
||||
* @param {PdfDocEntry} entry
|
||||
* @param {Uint8Array} next
|
||||
*/
|
||||
function holdsSameBytes(entry, next) {
|
||||
const prev = entry.bytes.deref();
|
||||
if (prev === next) {
|
||||
return true;
|
||||
}
|
||||
if (!prev || prev.byteLength !== next.byteLength) {
|
||||
return false;
|
||||
}
|
||||
for (let i = 0; i < next.byteLength; i += 1) {
|
||||
if (prev[i] !== next[i]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
entry.bytes = new WeakRef(next);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a lazy PDF preview client with request multiplexing, in-flight
|
||||
* deduplication, Transferable zero-copy RGBA delivery, and byte-bounded LRU
|
||||
* eviction for offscreen pages.
|
||||
*
|
||||
* The worker keeps each opened PDF parsed under a `docId` that this client
|
||||
* assigns. The bytes cross to the worker once per open. At most
|
||||
* `MAX_OPEN_DOCS` documents and `MAX_OPEN_DOC_BYTES` are open at any time.
|
||||
* An open closes least recently used documents with no unanswered request,
|
||||
* and only when that makes room. Otherwise it waits until a request is
|
||||
* answered or a document closes. Empty documents and documents larger than
|
||||
* `MAX_OPEN_DOC_BYTES` never go to the worker.
|
||||
*
|
||||
* @param {Object} options
|
||||
* @param {PdfWorkerLoaderLike} options.workerLoader
|
||||
* @param {number} [options.maxCacheBytes]
|
||||
@@ -80,8 +130,11 @@ export function createPdfPreviewClient(options) {
|
||||
|
||||
/** @type {PdfWorkerLike | null} */
|
||||
let worker = null;
|
||||
/** @type {(() => void) | null} */
|
||||
let detachWorker = null;
|
||||
let disposed = false;
|
||||
let nextRequestId = 1;
|
||||
let nextDocId = 1;
|
||||
let totalCacheBytes = 0;
|
||||
let evictions = 0;
|
||||
let dedupHits = 0;
|
||||
@@ -93,11 +146,8 @@ export function createPdfPreviewClient(options) {
|
||||
/** @type {Map<string, Promise<PdfRenderedPage>>} */
|
||||
const inFlightRenders = new Map();
|
||||
|
||||
/** @type {Map<string, Promise<number>>} */
|
||||
const inFlightPageCounts = new Map();
|
||||
|
||||
/** @type {Map<string, number>} */
|
||||
const pageCountCache = new Map();
|
||||
/** Known documents by `docKey`, least recently used first. @type {Map<string, PdfDocEntry>} */
|
||||
const docs = new Map();
|
||||
|
||||
/** @type {Map<string, { pageCount: number, widthPx: number, heightPx: number, rgba: Uint8Array, scale: number, byteLength: number }>} */
|
||||
const lruCache = new Map();
|
||||
@@ -105,45 +155,45 @@ export function createPdfPreviewClient(options) {
|
||||
/** @type {Set<string>} */
|
||||
let visibleKeys = new Set();
|
||||
|
||||
/** @param {MessageEvent} event */
|
||||
function handleWorkerMessage(event) {
|
||||
const msg = event?.data;
|
||||
if (!msg || typeof msg !== 'object') {
|
||||
return;
|
||||
}
|
||||
const entry = pendingRpc.get(msg.id);
|
||||
if (!entry) {
|
||||
return;
|
||||
}
|
||||
pendingRpc.delete(msg.id);
|
||||
if (msg.ok) {
|
||||
entry.resolve(msg.result);
|
||||
} else {
|
||||
entry.reject(new Error(msg.error || 'PDF worker request failed'));
|
||||
/** Opens that wait for room in the open budget. @type {(() => void)[]} */
|
||||
let openWaiters = [];
|
||||
|
||||
function wakeOpenWaiters() {
|
||||
const waiters = openWaiters;
|
||||
openWaiters = [];
|
||||
for (const wake of waiters) {
|
||||
wake();
|
||||
}
|
||||
}
|
||||
|
||||
/** @param {Event} event */
|
||||
function handleWorkerError(event) {
|
||||
const message =
|
||||
/** @type {{ message?: string }} */ (
|
||||
/** @type {unknown} */ (event)
|
||||
)?.message || 'PDF worker error';
|
||||
const err = new Error(message);
|
||||
for (const entry of pendingRpc.values()) {
|
||||
entry.reject(err);
|
||||
}
|
||||
/**
|
||||
* Stops listening to the current worker, terminates it, and fails every
|
||||
* unanswered request. Every document then counts as closed.
|
||||
*
|
||||
* @param {Error} err
|
||||
*/
|
||||
function dropWorker(err) {
|
||||
const rpcs = Array.from(pendingRpc.values());
|
||||
pendingRpc.clear();
|
||||
if (worker) {
|
||||
const deadWorker = worker;
|
||||
worker = null;
|
||||
deadWorker.removeEventListener('message', handleWorkerMessage);
|
||||
deadWorker.removeEventListener('error', handleWorkerError);
|
||||
detachWorker?.();
|
||||
detachWorker = null;
|
||||
if (typeof workerLoader.terminateWorker === 'function') {
|
||||
workerLoader.terminateWorker('pdf');
|
||||
} else {
|
||||
deadWorker.terminate?.();
|
||||
}
|
||||
deadWorker.terminate?.();
|
||||
}
|
||||
for (const entry of docs.values()) {
|
||||
entry.docId = null;
|
||||
}
|
||||
nextDocId = 1;
|
||||
for (const rpc of rpcs) {
|
||||
rpc.reject(err);
|
||||
}
|
||||
wakeOpenWaiters();
|
||||
}
|
||||
|
||||
function ensureWorker() {
|
||||
@@ -151,9 +201,47 @@ export function createPdfPreviewClient(options) {
|
||||
throw new Error('PDF preview client is disposed');
|
||||
}
|
||||
if (!worker) {
|
||||
worker = workerLoader.loadWorker('pdf');
|
||||
worker.addEventListener('message', handleWorkerMessage);
|
||||
worker.addEventListener('error', handleWorkerError);
|
||||
const ownWorker = workerLoader.loadWorker('pdf');
|
||||
/** @param {MessageEvent} event */
|
||||
const onMessage = event => {
|
||||
if (ownWorker !== worker) {
|
||||
return;
|
||||
}
|
||||
const msg = event?.data;
|
||||
if (!msg || typeof msg !== 'object') {
|
||||
return;
|
||||
}
|
||||
const entry = pendingRpc.get(msg.id);
|
||||
if (!entry) {
|
||||
return;
|
||||
}
|
||||
pendingRpc.delete(msg.id);
|
||||
if (msg.ok) {
|
||||
entry.resolve(msg.result);
|
||||
} else {
|
||||
entry.reject(new Error(msg.error || 'PDF worker request failed'));
|
||||
}
|
||||
};
|
||||
/** @param {Event} event */
|
||||
const onError = event => {
|
||||
if (ownWorker !== worker) {
|
||||
return;
|
||||
}
|
||||
const message =
|
||||
/** @type {{ message?: string }} */ (
|
||||
/** @type {unknown} */ (event)
|
||||
)?.message || `PDF worker ${event?.type || 'error'}`;
|
||||
dropWorker(new Error(message));
|
||||
};
|
||||
ownWorker.addEventListener('message', onMessage);
|
||||
ownWorker.addEventListener('error', onError);
|
||||
ownWorker.addEventListener('messageerror', onError);
|
||||
detachWorker = () => {
|
||||
ownWorker.removeEventListener('message', onMessage);
|
||||
ownWorker.removeEventListener('error', onError);
|
||||
ownWorker.removeEventListener('messageerror', onError);
|
||||
};
|
||||
worker = ownWorker;
|
||||
}
|
||||
return worker;
|
||||
}
|
||||
@@ -173,6 +261,224 @@ export function createPdfPreviewClient(options) {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends one RPC for a document and keeps it open while the RPC is unanswered.
|
||||
*
|
||||
* @param {PdfDocEntry} entry
|
||||
* @param {Record<string, unknown>} payload
|
||||
*/
|
||||
function sendDocRpc(entry, payload) {
|
||||
entry.inFlight += 1;
|
||||
return sendRpc(payload).finally(() => {
|
||||
entry.inFlight -= 1;
|
||||
if (entry.inFlight === 0) {
|
||||
wakeOpenWaiters();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** @param {string} docKey */
|
||||
function dropCachedPages(docKey) {
|
||||
const prefix = `${docKey}:`;
|
||||
for (const [key, item] of lruCache) {
|
||||
if (key.startsWith(prefix)) {
|
||||
lruCache.delete(key);
|
||||
totalCacheBytes -= item.byteLength;
|
||||
}
|
||||
}
|
||||
for (const key of inFlightRenders.keys()) {
|
||||
if (key.startsWith(prefix)) {
|
||||
inFlightRenders.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @param {PdfDocEntry} entry */
|
||||
function closeDoc(entry) {
|
||||
if (entry.docId === null) {
|
||||
return;
|
||||
}
|
||||
const docId = entry.docId;
|
||||
entry.docId = null;
|
||||
sendRpc({ op: 'pdf_close', docId }).catch(() => {});
|
||||
wakeOpenWaiters();
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes room for `entry` in the open budget. Closes least recently used
|
||||
* open documents with no unanswered request, but only when closing them
|
||||
* makes `entry` fit. Returns whether `entry` fits.
|
||||
*
|
||||
* @param {PdfDocEntry} entry
|
||||
*/
|
||||
function admitOpen(entry) {
|
||||
let openDocs = 0;
|
||||
let openBytes = 0;
|
||||
/** @type {PdfDocEntry[]} */
|
||||
const idle = [];
|
||||
for (const known of docs.values()) {
|
||||
if (known.docId !== null) {
|
||||
openDocs += 1;
|
||||
openBytes += known.byteLength;
|
||||
if (known.inFlight === 0) {
|
||||
idle.push(known);
|
||||
}
|
||||
}
|
||||
}
|
||||
const fits = () =>
|
||||
openDocs < MAX_OPEN_DOCS &&
|
||||
openBytes + entry.byteLength <= MAX_OPEN_DOC_BYTES;
|
||||
const victims = [];
|
||||
for (const known of idle) {
|
||||
if (fits()) {
|
||||
break;
|
||||
}
|
||||
victims.push(known);
|
||||
openDocs -= 1;
|
||||
openBytes -= known.byteLength;
|
||||
}
|
||||
if (!fits()) {
|
||||
return false;
|
||||
}
|
||||
for (const victim of victims) {
|
||||
closeDoc(victim);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the entry of `docKey` for `pdfBytes`. New bytes for a known
|
||||
* `docKey` replace its entry and drop its page count, cached pages and
|
||||
* shared in-flight renders.
|
||||
*
|
||||
* @param {string} docKey
|
||||
* @param {Uint8Array} pdfBytes
|
||||
* @returns {PdfDocEntry}
|
||||
*/
|
||||
function resolveDoc(docKey, pdfBytes) {
|
||||
let entry = docs.get(docKey);
|
||||
if (entry && !holdsSameBytes(entry, pdfBytes)) {
|
||||
closeDoc(entry);
|
||||
dropCachedPages(docKey);
|
||||
docs.delete(docKey);
|
||||
entry = undefined;
|
||||
}
|
||||
if (entry) {
|
||||
docs.delete(docKey);
|
||||
} else {
|
||||
entry = {
|
||||
bytes: new WeakRef(pdfBytes),
|
||||
byteLength: pdfBytes.byteLength,
|
||||
docId: null,
|
||||
pageCount: undefined,
|
||||
opened: null,
|
||||
inFlight: 0,
|
||||
};
|
||||
}
|
||||
docs.set(docKey, entry);
|
||||
if (docs.size > MAX_KNOWN_DOCS) {
|
||||
for (const [key, known] of docs) {
|
||||
if (docs.size <= MAX_KNOWN_DOCS) {
|
||||
break;
|
||||
}
|
||||
if (known.docId === null && known.inFlight === 0) {
|
||||
docs.delete(key);
|
||||
dropCachedPages(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
return entry;
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens `entry` in the current worker unless it is open there, and returns
|
||||
* its `docId`, or `null` when the open budget has no room now. The open
|
||||
* message goes out before any render of the same document, so renders
|
||||
* follow at once without waiting for its answer.
|
||||
*
|
||||
* @param {string} docKey
|
||||
* @param {PdfDocEntry} entry
|
||||
* @param {Uint8Array} pdfBytes
|
||||
* @returns {number | null}
|
||||
*/
|
||||
function openDoc(docKey, entry, pdfBytes) {
|
||||
ensureWorker();
|
||||
if (entry.docId !== null) {
|
||||
return entry.docId;
|
||||
}
|
||||
if (nextDocId > MAX_DOC_ID) {
|
||||
dropWorker(new Error('PDF worker restarted after its last document id'));
|
||||
ensureWorker();
|
||||
}
|
||||
if (!admitOpen(entry)) {
|
||||
return null;
|
||||
}
|
||||
const docId = nextDocId++;
|
||||
entry.docId = docId;
|
||||
const opened = sendDocRpc(entry, { op: 'pdf_open', docId, pdfBytes }).then(
|
||||
result => {
|
||||
const count = Number(result.pageCount ?? 0);
|
||||
if (docs.get(docKey) === entry) {
|
||||
entry.pageCount = count;
|
||||
}
|
||||
return count;
|
||||
},
|
||||
err => {
|
||||
// The worker holds no document for a failed open.
|
||||
if (entry.docId === docId) {
|
||||
entry.docId = null;
|
||||
wakeOpenWaiters();
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
);
|
||||
// Callers that need the page count read `entry.opened`; nobody else must see a rejection.
|
||||
opened.catch(() => {});
|
||||
entry.opened = opened;
|
||||
return docId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens `entry` and calls `send` with its `docId`: at once when the open
|
||||
* budget has room, or after a request is answered or a document closes.
|
||||
*
|
||||
* @template T
|
||||
* @param {string} docKey
|
||||
* @param {PdfDocEntry} entry
|
||||
* @param {Uint8Array} pdfBytes
|
||||
* @param {(docId: number) => Promise<T>} send
|
||||
* @returns {Promise<T>}
|
||||
*/
|
||||
function withOpenDoc(docKey, entry, pdfBytes, send) {
|
||||
const docId = openDoc(docKey, entry, pdfBytes);
|
||||
if (docId !== null) {
|
||||
return send(docId);
|
||||
}
|
||||
return new Promise(resolve => openWaiters.push(resolve)).then(() => {
|
||||
if (disposed) {
|
||||
throw new Error('PDF preview client is disposed');
|
||||
}
|
||||
if (docs.get(docKey) !== entry) {
|
||||
throw new Error('PDF bytes changed before the document opened');
|
||||
}
|
||||
return withOpenDoc(docKey, entry, pdfBytes, send);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Uint8Array} pdfBytes
|
||||
* @returns {Error | null}
|
||||
*/
|
||||
function rejectSize(pdfBytes) {
|
||||
const size = pdfBytes?.byteLength ?? 0;
|
||||
if (size > 0 && size <= MAX_OPEN_DOC_BYTES) {
|
||||
return null;
|
||||
}
|
||||
return new Error(
|
||||
`PDF of ${size} B is outside the 1..${MAX_OPEN_DOC_BYTES} B worker limit`
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Evicts least-recently-used entries until `totalCacheBytes <= maxCacheBytes`.
|
||||
* Prefers evicting offscreen keys before visible keys.
|
||||
@@ -230,31 +536,25 @@ export function createPdfPreviewClient(options) {
|
||||
if (disposed) {
|
||||
return Promise.reject(new Error('PDF preview client is disposed'));
|
||||
}
|
||||
const cached = pageCountCache.get(params.docKey);
|
||||
if (cached !== undefined) {
|
||||
const sizeError = rejectSize(params.pdfBytes);
|
||||
if (sizeError) {
|
||||
return Promise.reject(sizeError);
|
||||
}
|
||||
const entry = resolveDoc(params.docKey, params.pdfBytes);
|
||||
if (entry.pageCount !== undefined) {
|
||||
cacheHits += 1;
|
||||
return Promise.resolve(cached);
|
||||
return Promise.resolve(entry.pageCount);
|
||||
}
|
||||
const existing = inFlightPageCounts.get(params.docKey);
|
||||
if (existing) {
|
||||
if (entry.docId !== null && entry.opened) {
|
||||
dedupHits += 1;
|
||||
return existing;
|
||||
return entry.opened;
|
||||
}
|
||||
const promise = sendRpc({
|
||||
op: 'page_count',
|
||||
pdfBytes: params.pdfBytes,
|
||||
pageIndex: 0,
|
||||
})
|
||||
.then(result => {
|
||||
const count = Number(result.pageCount ?? 0);
|
||||
pageCountCache.set(params.docKey, count);
|
||||
return count;
|
||||
})
|
||||
.finally(() => {
|
||||
inFlightPageCounts.delete(params.docKey);
|
||||
});
|
||||
inFlightPageCounts.set(params.docKey, promise);
|
||||
return promise;
|
||||
return withOpenDoc(
|
||||
params.docKey,
|
||||
entry,
|
||||
params.pdfBytes,
|
||||
() => /** @type {Promise<number>} */ (entry.opened)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -269,6 +569,11 @@ export function createPdfPreviewClient(options) {
|
||||
if (disposed) {
|
||||
return Promise.reject(new Error('PDF preview client is disposed'));
|
||||
}
|
||||
const sizeError = rejectSize(params.pdfBytes);
|
||||
if (sizeError) {
|
||||
return Promise.reject(sizeError);
|
||||
}
|
||||
const entry = resolveDoc(params.docKey, params.pdfBytes);
|
||||
const scale = normalizeScale(params.scale);
|
||||
const cacheKey = buildPdfPageCacheKey(
|
||||
params.docKey,
|
||||
@@ -313,11 +618,24 @@ export function createPdfPreviewClient(options) {
|
||||
return wrapPrivateResult(inFlight);
|
||||
}
|
||||
|
||||
const sharedPromise = sendRpc({
|
||||
pdfBytes: params.pdfBytes,
|
||||
pageIndex: params.pageIndex,
|
||||
scale,
|
||||
})
|
||||
const sharedPromise = withOpenDoc(
|
||||
params.docKey,
|
||||
entry,
|
||||
params.pdfBytes,
|
||||
docId => {
|
||||
const opened = entry.opened;
|
||||
return sendDocRpc(entry, {
|
||||
op: 'pdf_render',
|
||||
docId,
|
||||
pageIndex: params.pageIndex,
|
||||
scale,
|
||||
}).catch(async err => {
|
||||
// A failed open reports its parse error instead of the unknown docId error.
|
||||
await opened;
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
)
|
||||
.then(result => {
|
||||
const rgba =
|
||||
result.rgba instanceof Uint8Array
|
||||
@@ -326,25 +644,27 @@ export function createPdfPreviewClient(options) {
|
||||
const pageCount = Number(result.pageCount);
|
||||
const widthPx = Number(result.widthPx);
|
||||
const heightPx = Number(result.heightPx);
|
||||
pageCountCache.set(params.docKey, pageCount);
|
||||
|
||||
const byteLength = rgba.byteLength;
|
||||
if (byteLength <= maxCacheBytes) {
|
||||
const prev = lruCache.get(cacheKey);
|
||||
if (prev) {
|
||||
totalCacheBytes -= prev.byteLength;
|
||||
lruCache.delete(cacheKey);
|
||||
if (docs.get(params.docKey) === entry) {
|
||||
entry.pageCount = pageCount;
|
||||
if (byteLength <= maxCacheBytes) {
|
||||
const prev = lruCache.get(cacheKey);
|
||||
if (prev) {
|
||||
totalCacheBytes -= prev.byteLength;
|
||||
lruCache.delete(cacheKey);
|
||||
}
|
||||
lruCache.set(cacheKey, {
|
||||
pageCount,
|
||||
widthPx,
|
||||
heightPx,
|
||||
rgba,
|
||||
scale,
|
||||
byteLength,
|
||||
});
|
||||
totalCacheBytes += byteLength;
|
||||
enforceCacheBudget(cacheKey);
|
||||
}
|
||||
lruCache.set(cacheKey, {
|
||||
pageCount,
|
||||
widthPx,
|
||||
heightPx,
|
||||
rgba,
|
||||
scale,
|
||||
byteLength,
|
||||
});
|
||||
totalCacheBytes += byteLength;
|
||||
enforceCacheBudget(cacheKey);
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -357,7 +677,9 @@ export function createPdfPreviewClient(options) {
|
||||
};
|
||||
})
|
||||
.finally(() => {
|
||||
inFlightRenders.delete(cacheKey);
|
||||
if (inFlightRenders.get(cacheKey) === sharedPromise) {
|
||||
inFlightRenders.delete(cacheKey);
|
||||
}
|
||||
});
|
||||
|
||||
inFlightRenders.set(cacheKey, sharedPromise);
|
||||
@@ -373,28 +695,12 @@ export function createPdfPreviewClient(options) {
|
||||
return;
|
||||
}
|
||||
disposed = true;
|
||||
const err = new Error('PDF preview client disposed');
|
||||
for (const entry of pendingRpc.values()) {
|
||||
entry.reject(err);
|
||||
}
|
||||
pendingRpc.clear();
|
||||
dropWorker(new Error('PDF preview client disposed'));
|
||||
inFlightRenders.clear();
|
||||
inFlightPageCounts.clear();
|
||||
pageCountCache.clear();
|
||||
docs.clear();
|
||||
lruCache.clear();
|
||||
visibleKeys.clear();
|
||||
totalCacheBytes = 0;
|
||||
|
||||
if (worker) {
|
||||
worker.removeEventListener('message', handleWorkerMessage);
|
||||
worker.removeEventListener('error', handleWorkerError);
|
||||
if (typeof workerLoader.terminateWorker === 'function') {
|
||||
workerLoader.terminateWorker('pdf');
|
||||
} else {
|
||||
worker.terminate?.();
|
||||
}
|
||||
worker = null;
|
||||
}
|
||||
}
|
||||
|
||||
return Object.freeze({
|
||||
@@ -402,16 +708,23 @@ export function createPdfPreviewClient(options) {
|
||||
renderPage,
|
||||
setVisibleKeys,
|
||||
dispose,
|
||||
getStats: () => ({
|
||||
workerSpawned: worker !== null,
|
||||
disposed,
|
||||
activeRequests: pendingRpc.size,
|
||||
cacheEntries: lruCache.size,
|
||||
cacheBytes: totalCacheBytes,
|
||||
maxCacheBytes,
|
||||
evictions,
|
||||
dedupHits,
|
||||
cacheHits,
|
||||
}),
|
||||
getStats: () => {
|
||||
let openDocs = 0;
|
||||
for (const entry of docs.values()) {
|
||||
if (entry.docId !== null) openDocs += 1;
|
||||
}
|
||||
return {
|
||||
workerSpawned: worker !== null,
|
||||
disposed,
|
||||
activeRequests: pendingRpc.size,
|
||||
openDocs,
|
||||
cacheEntries: lruCache.size,
|
||||
cacheBytes: totalCacheBytes,
|
||||
maxCacheBytes,
|
||||
evictions,
|
||||
dedupHits,
|
||||
cacheHits,
|
||||
};
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -7,7 +7,7 @@ const ALLOWED_STUB_IMPORT_MODULES = new Set([
|
||||
|
||||
/**
|
||||
* Builds stub imports strictly for unused `wasm-bindgen` placeholder entries
|
||||
* so pure scalar `u32` Wasm exports run directly under `WebAssembly.instantiate`
|
||||
* so the scalar worker exports run directly under `WebAssembly.instantiate`
|
||||
* without `wasm-bindgen-cli`. Any unexpected external host import module throws
|
||||
* immediately instead of silently returning `0`.
|
||||
*
|
||||
@@ -57,45 +57,87 @@ export function resolveWasmExport(rawExports, baseName, label = 'Wasm') {
|
||||
}
|
||||
|
||||
/**
|
||||
* Streams `[opcode, ...payload]` into a scalar `u32` Wasm ABI and reads back
|
||||
* the raw binary response frame (`[0x01, ...ok]` or `[0x00, ...utf8Err]`).
|
||||
* @typedef {Object} WorkerAbi
|
||||
* @property {WebAssembly.Memory} memory
|
||||
* @property {Function} prepare
|
||||
* @property {Function} invoke
|
||||
* @property {Function} outputPtr
|
||||
*/
|
||||
|
||||
/**
|
||||
* Binds the four exports of the preview worker linear-memory ABI: `memory`,
|
||||
* `prepare(len) -> ptr`, `invoke() -> len`, and `output_ptr() -> ptr`.
|
||||
*
|
||||
* @param {{
|
||||
* resetInput: Function,
|
||||
* pushInputU32: Function,
|
||||
* invoke: Function,
|
||||
* outputU32: Function,
|
||||
* }} abi
|
||||
* @param {number} opcode
|
||||
* @param {Uint8Array} payload
|
||||
* @param {Record<string, unknown>} rawExports
|
||||
* @param {string} [label='Worker']
|
||||
* @returns {WorkerAbi}
|
||||
*/
|
||||
export function bindWorkerAbi(rawExports, label = 'Worker') {
|
||||
const memory = rawExports.memory;
|
||||
if (!(memory instanceof WebAssembly.Memory)) {
|
||||
throw new Error(`${label} wasm missing required export: memory`);
|
||||
}
|
||||
return {
|
||||
memory,
|
||||
prepare: resolveWasmExport(rawExports, 'prepare', label),
|
||||
invoke: resolveWasmExport(rawExports, 'invoke', label),
|
||||
outputPtr: resolveWasmExport(rawExports, 'output_ptr', label),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a view of `len` bytes at the wasm32 address `ptr`. Reads
|
||||
* `memory.buffer` again on every call because any export call can grow the
|
||||
* memory and detach the previous buffer.
|
||||
*
|
||||
* @param {WebAssembly.Memory} memory
|
||||
* @param {number} ptr
|
||||
* @param {number} len
|
||||
* @returns {Uint8Array}
|
||||
*/
|
||||
export function invokeScalarRpc(abi, opcode, payload) {
|
||||
abi.resetInput();
|
||||
const full = new Uint8Array(1 + payload.byteLength);
|
||||
full[0] = opcode;
|
||||
full.set(payload, 1);
|
||||
|
||||
for (let i = 0; i < full.length; i += 4) {
|
||||
const valid = Math.min(4, full.length - i);
|
||||
const word =
|
||||
(full[i] || 0) |
|
||||
((full[i + 1] || 0) << 8) |
|
||||
((full[i + 2] || 0) << 16) |
|
||||
((full[i + 3] || 0) << 24);
|
||||
abi.pushInputU32(word >>> 0, valid);
|
||||
function linearView(memory, ptr, len) {
|
||||
const buffer = memory.buffer;
|
||||
const start = ptr >>> 0;
|
||||
const size = len >>> 0;
|
||||
if (start > buffer.byteLength || size > buffer.byteLength - start) {
|
||||
throw new Error(
|
||||
`Worker wasm range ${start}+${size} is outside its ${buffer.byteLength} B memory`
|
||||
);
|
||||
}
|
||||
|
||||
const outLen = Number(abi.invoke());
|
||||
const outBytes = new Uint8Array(outLen);
|
||||
const wordCount = Math.ceil(outLen / 4);
|
||||
for (let w = 0; w < wordCount; w += 1) {
|
||||
const word = Number(abi.outputU32(w)) >>> 0;
|
||||
const base = w * 4;
|
||||
if (base < outLen) outBytes[base] = word & 0xff;
|
||||
if (base + 1 < outLen) outBytes[base + 1] = (word >>> 8) & 0xff;
|
||||
if (base + 2 < outLen) outBytes[base + 2] = (word >>> 16) & 0xff;
|
||||
if (base + 3 < outLen) outBytes[base + 3] = (word >>> 24) & 0xff;
|
||||
}
|
||||
return outBytes;
|
||||
return new Uint8Array(buffer, start, size);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the request frame `[opcode, ...parts]` into worker linear memory,
|
||||
* runs it, and returns the response frame (`[0x01, ...ok]` or
|
||||
* `[0x00, ...utf8Err]`).
|
||||
*
|
||||
* The returned view points into linear memory. It stays valid only until the
|
||||
* next call into the same instance, so the caller must decode or copy it
|
||||
* synchronously and never keep or transfer it.
|
||||
*
|
||||
* @param {WorkerAbi} abi
|
||||
* @param {number} opcode
|
||||
* @param {Uint8Array[]} parts
|
||||
* @returns {Uint8Array}
|
||||
*/
|
||||
export function invokeScalarRpc(abi, opcode, parts) {
|
||||
let total = 1;
|
||||
for (const part of parts) {
|
||||
total += part.byteLength;
|
||||
}
|
||||
const ptr = Number(abi.prepare(total)) >>> 0;
|
||||
if (ptr === 0) {
|
||||
throw new Error(`Worker request of ${total} B exceeds the worker limit`);
|
||||
}
|
||||
const input = linearView(abi.memory, ptr, total);
|
||||
input[0] = opcode;
|
||||
let at = 1;
|
||||
for (const part of parts) {
|
||||
input.set(part, at);
|
||||
at += part.byteLength;
|
||||
}
|
||||
const outLen = Number(abi.invoke());
|
||||
const outPtr = Number(abi.outputPtr());
|
||||
return linearView(abi.memory, outPtr, outLen);
|
||||
}
|
||||
@@ -1,34 +1,31 @@
|
||||
// @ts-check
|
||||
|
||||
import {
|
||||
bindWorkerAbi,
|
||||
buildStubImports,
|
||||
invokeScalarRpc,
|
||||
resolveWasmExport,
|
||||
} from '../wasm-scalar-rpc.js';
|
||||
|
||||
const OPCODE_REGISTER_FONT = 1;
|
||||
const OPCODE_MERMAID_SVG = 2;
|
||||
const OPCODE_MATH_SVG = 3;
|
||||
const OPCODE_TYPST_SVG = 4;
|
||||
const OPCODE_PDF_PAGE = 5;
|
||||
const OPCODE_PDF_PAGE_SCALED = 6;
|
||||
const OPCODE_PDF_PAGE_COUNT = 7;
|
||||
const OPCODE_PDF_OPEN = 5;
|
||||
const OPCODE_PDF_RENDER = 6;
|
||||
const OPCODE_PDF_CLOSE = 7;
|
||||
const OPCODE_MATH_RGBA = 8;
|
||||
|
||||
const KIND_OPCODES = {
|
||||
mermaid: OPCODE_MERMAID_SVG,
|
||||
math: OPCODE_MATH_SVG,
|
||||
typst: OPCODE_TYPST_SVG,
|
||||
pdf: OPCODE_PDF_PAGE,
|
||||
};
|
||||
const PDF_PAGE_HEADER_BYTES = 13;
|
||||
const MATH_RGBA_HEADER_BYTES = 21;
|
||||
|
||||
const KINDS = new Set(['mermaid', 'math', 'typst', 'pdf']);
|
||||
|
||||
/**
|
||||
* Instantiates the pinned `.wasm` binary from `globalThis.AFFINE_WORKER_WASM_URL`
|
||||
* and returns a synchronous RPC invoker over the scalar `affine_worker_*` ABI.
|
||||
* Instantiates the pinned `.wasm` binary and binds its linear-memory ABI.
|
||||
*
|
||||
* @param {string} wasmUrl
|
||||
*/
|
||||
async function loadWorkerExports(wasmUrl) {
|
||||
async function loadWorkerAbi(wasmUrl) {
|
||||
const response = await globalThis.fetch(wasmUrl);
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
@@ -38,87 +35,59 @@ async function loadWorkerExports(wasmUrl) {
|
||||
const bytes = new Uint8Array(await response.arrayBuffer());
|
||||
const mod = await WebAssembly.compile(bytes);
|
||||
const instance = await WebAssembly.instantiate(mod, buildStubImports(mod));
|
||||
const rawExports = /** @type {Record<string, unknown>} */ (
|
||||
/** @type {unknown} */ (instance.exports)
|
||||
return bindWorkerAbi(
|
||||
/** @type {Record<string, unknown>} */ (
|
||||
/** @type {unknown} */ (instance.exports)
|
||||
),
|
||||
'Worker'
|
||||
);
|
||||
return {
|
||||
resetInput: resolveWasmExport(
|
||||
rawExports,
|
||||
'affine_worker_reset_input',
|
||||
'Worker'
|
||||
),
|
||||
pushInputU32: resolveWasmExport(
|
||||
rawExports,
|
||||
'affine_worker_push_input_u32',
|
||||
'Worker'
|
||||
),
|
||||
invoke: resolveWasmExport(rawExports, 'affine_worker_invoke', 'Worker'),
|
||||
outputU32: resolveWasmExport(
|
||||
rawExports,
|
||||
'affine_worker_output_u32',
|
||||
'Worker'
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes `affine_worker_invoke` with `[opcode, ...payload]` and returns the
|
||||
* raw binary response frame (`[0x01, ...ok]` or `[0x00, ...utf8Err]`).
|
||||
*
|
||||
* @param {{ resetInput: Function, pushInputU32: Function, invoke: Function, outputU32: Function }} exports
|
||||
* @param {number} opcode
|
||||
* @param {Uint8Array} payload
|
||||
* @param {...number} words
|
||||
* @returns {Uint8Array}
|
||||
*/
|
||||
function invokeRaw(exports, opcode, payload) {
|
||||
return invokeScalarRpc(exports, opcode, payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepends a 4-byte little-endian `pageIndex` header to a byte payload.
|
||||
*
|
||||
* @param {number} pageIndex
|
||||
* @param {Uint8Array} body
|
||||
* @returns {Uint8Array}
|
||||
*/
|
||||
function prependPageIndex(pageIndex, body) {
|
||||
const buf = new Uint8Array(4 + body.length);
|
||||
new DataView(buf.buffer).setUint32(0, pageIndex >>> 0, true);
|
||||
buf.set(body, 4);
|
||||
return buf;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepends a 4-byte little-endian `pageIndex` and 4-byte little-endian `scale`
|
||||
* float header to a byte payload.
|
||||
*
|
||||
* @param {number} pageIndex
|
||||
* @param {number} scale
|
||||
* @param {Uint8Array} body
|
||||
* @returns {Uint8Array}
|
||||
*/
|
||||
function prependPageIndexAndScale(pageIndex, scale, body) {
|
||||
const buf = new Uint8Array(8 + body.length);
|
||||
function u32Words(...words) {
|
||||
const buf = new Uint8Array(words.length * 4);
|
||||
const view = new DataView(buf.buffer);
|
||||
view.setUint32(0, pageIndex >>> 0, true);
|
||||
view.setFloat32(4, scale, true);
|
||||
buf.set(body, 8);
|
||||
words.forEach((word, idx) => view.setUint32(idx * 4, word >>> 0, true));
|
||||
return buf;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {unknown} value
|
||||
* @returns {Uint8Array}
|
||||
*/
|
||||
function toBytes(value) {
|
||||
if (value instanceof Uint8Array) {
|
||||
return value;
|
||||
}
|
||||
if (value instanceof ArrayBuffer) {
|
||||
return new Uint8Array(value);
|
||||
}
|
||||
return new Uint8Array(/** @type {ArrayLike<number>} */ (value || []));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Uint8Array} frame
|
||||
*/
|
||||
function frameView(frame) {
|
||||
return new DataView(frame.buffer, frame.byteOffset, frame.byteLength);
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes a `math` RGBA rasterization request (`OPCODE_MATH_RGBA = 8`).
|
||||
*
|
||||
* @param {TextEncoder} encoder
|
||||
* @param {{ display?: boolean, fontSizePt?: number, paddingPt?: number, scaleFactor?: number, colorCss?: string, latex?: string, source?: string }} msg
|
||||
* @returns {Uint8Array}
|
||||
* @returns {Uint8Array[]}
|
||||
*/
|
||||
function encodeMathRgbaPayload(encoder, msg) {
|
||||
function encodeMathRgbaParts(encoder, msg) {
|
||||
const colorBytes = encoder.encode(String(msg.colorCss || '#000000'));
|
||||
const latexBytes = encoder.encode(String(msg.latex ?? msg.source ?? ''));
|
||||
const buf = new Uint8Array(15 + colorBytes.length + latexBytes.length);
|
||||
const view = new DataView(buf.buffer);
|
||||
buf[0] = msg.display ? 1 : 0;
|
||||
const head = new Uint8Array(15);
|
||||
const view = new DataView(head.buffer);
|
||||
head[0] = msg.display ? 1 : 0;
|
||||
view.setFloat32(1, Number(msg.fontSizePt) || 16.0, true);
|
||||
view.setFloat32(
|
||||
5,
|
||||
@@ -131,9 +100,7 @@ function encodeMathRgbaPayload(encoder, msg) {
|
||||
);
|
||||
view.setFloat32(9, Number(msg.scaleFactor) || 2.0, true);
|
||||
view.setUint16(13, colorBytes.length, true);
|
||||
buf.set(colorBytes, 15);
|
||||
buf.set(latexBytes, 15 + colorBytes.length);
|
||||
return buf;
|
||||
return [head, colorBytes, latexBytes];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -141,18 +108,21 @@ function encodeMathRgbaPayload(encoder, msg) {
|
||||
* `typst`, or `pdf`), reading its pinned `.wasm` URL from
|
||||
* `globalThis.AFFINE_WORKER_WASM_URL`.
|
||||
*
|
||||
* Messages that arrive before the module is ready wait on one shared start-up
|
||||
* promise and then run in arrival order. Each request runs synchronously after
|
||||
* that, so a `pdf_open`, `pdf_render`, `pdf_close` sequence keeps its order.
|
||||
*
|
||||
* @param {'mermaid' | 'math' | 'typst' | 'pdf'} kind
|
||||
*/
|
||||
export function startPreviewWorker(kind) {
|
||||
const defaultOpcode = KIND_OPCODES[kind];
|
||||
if (!defaultOpcode) {
|
||||
if (!KINDS.has(kind)) {
|
||||
throw new Error(`Unsupported preview worker kind: ${kind}`);
|
||||
}
|
||||
/** @type {Promise<Record<string, Function>> | null} */
|
||||
let exportsPromise = null;
|
||||
/** @type {Promise<import('../wasm-scalar-rpc.js').WorkerAbi> | null} */
|
||||
let abiPromise = null;
|
||||
|
||||
function ensureExports() {
|
||||
if (!exportsPromise) {
|
||||
function ensureAbi() {
|
||||
if (!abiPromise) {
|
||||
const wasmUrl =
|
||||
/** @type {{ AFFINE_WORKER_WASM_URL?: string }} */ (
|
||||
/** @type {unknown} */ (globalThis)
|
||||
@@ -162,17 +132,176 @@ export function startPreviewWorker(kind) {
|
||||
new Error('Missing globalThis.AFFINE_WORKER_WASM_URL')
|
||||
);
|
||||
}
|
||||
exportsPromise = loadWorkerExports(wasmUrl).catch(err => {
|
||||
exportsPromise = null;
|
||||
abiPromise = loadWorkerAbi(wasmUrl).catch(err => {
|
||||
abiPromise = null;
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
return exportsPromise;
|
||||
return abiPromise;
|
||||
}
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
const decoder = new TextDecoder();
|
||||
|
||||
/**
|
||||
* Runs one request and returns the response frame view. Throws the worker
|
||||
* error text for a failure frame.
|
||||
*
|
||||
* @param {import('../wasm-scalar-rpc.js').WorkerAbi} abi
|
||||
* @param {number} opcode
|
||||
* @param {Uint8Array[]} parts
|
||||
* @param {number} minLength
|
||||
*/
|
||||
function call(abi, opcode, parts, minLength) {
|
||||
const frame = invokeScalarRpc(abi, opcode, parts);
|
||||
if (frame.length === 0 || frame[0] !== 1) {
|
||||
throw new Error(decoder.decode(frame.subarray(1)) || 'worker error');
|
||||
}
|
||||
if (frame.length < minLength) {
|
||||
throw new Error(`Truncated worker response (${frame.length} B)`);
|
||||
}
|
||||
return frame;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies `widthPx * heightPx * 4` RGBA bytes after `headerBytes` out of
|
||||
* linear memory into a compact buffer that the caller can transfer.
|
||||
*
|
||||
* @param {Uint8Array} frame
|
||||
* @param {number} headerBytes
|
||||
* @param {number} widthPx
|
||||
* @param {number} heightPx
|
||||
*/
|
||||
function copyRgba(frame, headerBytes, widthPx, heightPx) {
|
||||
const expected = widthPx * heightPx * 4;
|
||||
if (frame.byteLength - headerBytes !== expected) {
|
||||
throw new Error(
|
||||
`RGBA length mismatch: got ${frame.byteLength - headerBytes}, expected ${expected}`
|
||||
);
|
||||
}
|
||||
return frame.slice(headerBytes);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import('../wasm-scalar-rpc.js').WorkerAbi} abi
|
||||
* @param {Record<string, any>} msg
|
||||
* @returns {{ result: Record<string, unknown>, transfer: Transferable[] }}
|
||||
*/
|
||||
function handle(abi, msg) {
|
||||
if (msg.op === 'register_font') {
|
||||
const frame = call(
|
||||
abi,
|
||||
OPCODE_REGISTER_FONT,
|
||||
[toBytes(msg.fontBytes)],
|
||||
5
|
||||
);
|
||||
return {
|
||||
result: { faceCount: frameView(frame).getUint32(1, true) },
|
||||
transfer: [],
|
||||
};
|
||||
}
|
||||
if (kind === 'pdf') {
|
||||
const docId = Number(msg.docId) >>> 0;
|
||||
if (msg.op === 'pdf_open') {
|
||||
const frame = call(
|
||||
abi,
|
||||
OPCODE_PDF_OPEN,
|
||||
[u32Words(docId), toBytes(msg.pdfBytes)],
|
||||
5
|
||||
);
|
||||
return {
|
||||
result: { kind, pageCount: frameView(frame).getUint32(1, true) },
|
||||
transfer: [],
|
||||
};
|
||||
}
|
||||
if (msg.op === 'pdf_render') {
|
||||
const head = u32Words(docId, Number(msg.pageIndex ?? 0), 0);
|
||||
new DataView(head.buffer).setFloat32(8, Number(msg.scale) || 1, true);
|
||||
const frame = call(
|
||||
abi,
|
||||
OPCODE_PDF_RENDER,
|
||||
[head],
|
||||
PDF_PAGE_HEADER_BYTES
|
||||
);
|
||||
const view = frameView(frame);
|
||||
const pageCount = view.getUint32(1, true);
|
||||
const widthPx = view.getUint32(5, true);
|
||||
const heightPx = view.getUint32(9, true);
|
||||
const rgba = copyRgba(frame, PDF_PAGE_HEADER_BYTES, widthPx, heightPx);
|
||||
return {
|
||||
result: { kind, pageCount, widthPx, heightPx, rgba },
|
||||
transfer: [rgba.buffer],
|
||||
};
|
||||
}
|
||||
if (msg.op === 'pdf_close') {
|
||||
call(abi, OPCODE_PDF_CLOSE, [u32Words(docId)], 1);
|
||||
return { result: { kind }, transfer: [] };
|
||||
}
|
||||
throw new Error(`Unsupported pdf worker op: ${String(msg.op)}`);
|
||||
}
|
||||
if (kind === 'math' && msg.op === 'rgba') {
|
||||
const frame = call(
|
||||
abi,
|
||||
OPCODE_MATH_RGBA,
|
||||
encodeMathRgbaParts(encoder, msg),
|
||||
MATH_RGBA_HEADER_BYTES
|
||||
);
|
||||
const view = frameView(frame);
|
||||
const widthPx = view.getUint32(13, true);
|
||||
const heightPx = view.getUint32(17, true);
|
||||
const rgba = copyRgba(frame, MATH_RGBA_HEADER_BYTES, widthPx, heightPx);
|
||||
return {
|
||||
result: {
|
||||
kind,
|
||||
widthPt: view.getFloat32(1, true),
|
||||
ascentPt: view.getFloat32(5, true),
|
||||
descentPt: view.getFloat32(9, true),
|
||||
widthPx,
|
||||
heightPx,
|
||||
rgba,
|
||||
},
|
||||
transfer: [rgba.buffer],
|
||||
};
|
||||
}
|
||||
if (kind === 'typst') {
|
||||
const frame = call(
|
||||
abi,
|
||||
OPCODE_TYPST_SVG,
|
||||
[
|
||||
u32Words(Number(msg.pageIndex ?? 0)),
|
||||
encoder.encode(String(msg.source ?? '')),
|
||||
],
|
||||
5
|
||||
);
|
||||
return {
|
||||
result: {
|
||||
kind,
|
||||
pageCount: frameView(frame).getUint32(1, true),
|
||||
svg: decoder.decode(frame.subarray(5)),
|
||||
},
|
||||
transfer: [],
|
||||
};
|
||||
}
|
||||
/** @type {Uint8Array[]} */
|
||||
let parts;
|
||||
let opcode = OPCODE_MATH_SVG;
|
||||
if (kind === 'mermaid') {
|
||||
opcode = OPCODE_MERMAID_SVG;
|
||||
const themeTag = msg.theme === 'light' ? 1 : msg.theme === 'dark' ? 2 : 0;
|
||||
parts = [
|
||||
Uint8Array.of(themeTag),
|
||||
encoder.encode(String(msg.source ?? '')),
|
||||
];
|
||||
} else {
|
||||
parts = [encoder.encode(String(msg.latex ?? msg.source ?? ''))];
|
||||
}
|
||||
const frame = call(abi, opcode, parts, 1);
|
||||
return {
|
||||
result: { kind, svg: decoder.decode(frame.subarray(1)) },
|
||||
transfer: [],
|
||||
};
|
||||
}
|
||||
|
||||
globalThis.addEventListener('message', async event => {
|
||||
const msg = event?.data;
|
||||
if (!msg || typeof msg !== 'object') {
|
||||
@@ -180,170 +309,9 @@ export function startPreviewWorker(kind) {
|
||||
}
|
||||
const id = msg.id ?? null;
|
||||
try {
|
||||
const exports = await ensureExports();
|
||||
if (msg.op === 'register_font') {
|
||||
const fontBytes =
|
||||
msg.fontBytes instanceof Uint8Array
|
||||
? msg.fontBytes
|
||||
: new Uint8Array(msg.fontBytes || []);
|
||||
const frame = invokeRaw(exports, OPCODE_REGISTER_FONT, fontBytes);
|
||||
if (frame.length < 5 || frame[0] !== 1) {
|
||||
throw new Error(decoder.decode(frame.subarray(1)) || 'font error');
|
||||
}
|
||||
const faceCount = new DataView(
|
||||
frame.buffer,
|
||||
frame.byteOffset,
|
||||
frame.byteLength
|
||||
).getUint32(1, true);
|
||||
globalThis.postMessage({ id, ok: true, result: { faceCount } });
|
||||
return;
|
||||
}
|
||||
|
||||
/** @type {Uint8Array} */
|
||||
let payloadBytes;
|
||||
let opcode = defaultOpcode;
|
||||
if (kind === 'mermaid') {
|
||||
const themeTag =
|
||||
msg.theme === 'light' ? 1 : msg.theme === 'dark' ? 2 : 0;
|
||||
const src = encoder.encode(String(msg.source ?? ''));
|
||||
payloadBytes = new Uint8Array(1 + src.length);
|
||||
payloadBytes[0] = themeTag;
|
||||
payloadBytes.set(src, 1);
|
||||
} else if (kind === 'typst') {
|
||||
payloadBytes = prependPageIndex(
|
||||
Number(msg.pageIndex ?? 0),
|
||||
encoder.encode(String(msg.source ?? ''))
|
||||
);
|
||||
} else if (kind === 'pdf') {
|
||||
const pdfBytes =
|
||||
msg.pdfBytes instanceof Uint8Array
|
||||
? msg.pdfBytes
|
||||
: new Uint8Array(msg.pdfBytes || []);
|
||||
if (msg.op === 'page_count') {
|
||||
opcode = OPCODE_PDF_PAGE_COUNT;
|
||||
payloadBytes = pdfBytes;
|
||||
} else if (
|
||||
typeof msg.scale === 'number' &&
|
||||
Number.isFinite(msg.scale) &&
|
||||
msg.scale > 0
|
||||
) {
|
||||
opcode = OPCODE_PDF_PAGE_SCALED;
|
||||
payloadBytes = prependPageIndexAndScale(
|
||||
Number(msg.pageIndex ?? 0),
|
||||
msg.scale,
|
||||
pdfBytes
|
||||
);
|
||||
} else {
|
||||
payloadBytes = prependPageIndex(Number(msg.pageIndex ?? 0), pdfBytes);
|
||||
}
|
||||
} else if (kind === 'math' && msg.op === 'rgba') {
|
||||
opcode = OPCODE_MATH_RGBA;
|
||||
payloadBytes = encodeMathRgbaPayload(encoder, msg);
|
||||
} else {
|
||||
payloadBytes = encoder.encode(String(msg.latex ?? msg.source ?? ''));
|
||||
}
|
||||
|
||||
const frame = invokeRaw(exports, opcode, payloadBytes);
|
||||
if (frame.length === 0 || frame[0] !== 1) {
|
||||
throw new Error(decoder.decode(frame.subarray(1)) || 'worker error');
|
||||
}
|
||||
|
||||
if (kind === 'math' && opcode === OPCODE_MATH_RGBA) {
|
||||
if (frame.length < 21) {
|
||||
throw new Error(`Truncated math RGBA response (${frame.length})`);
|
||||
}
|
||||
const view = new DataView(
|
||||
frame.buffer,
|
||||
frame.byteOffset,
|
||||
frame.byteLength
|
||||
);
|
||||
const widthPt = view.getFloat32(1, true);
|
||||
const ascentPt = view.getFloat32(5, true);
|
||||
const descentPt = view.getFloat32(9, true);
|
||||
const widthPx = view.getUint32(13, true);
|
||||
const heightPx = view.getUint32(17, true);
|
||||
const rgba = frame.slice(21);
|
||||
const expectedBytes = widthPx * heightPx * 4;
|
||||
if (rgba.byteLength !== expectedBytes) {
|
||||
throw new Error(
|
||||
`Math RGBA length mismatch: got ${rgba.byteLength}, expected ${expectedBytes}`
|
||||
);
|
||||
}
|
||||
globalThis.postMessage(
|
||||
{
|
||||
id,
|
||||
ok: true,
|
||||
result: {
|
||||
kind,
|
||||
widthPt,
|
||||
ascentPt,
|
||||
descentPt,
|
||||
widthPx,
|
||||
heightPx,
|
||||
rgba,
|
||||
},
|
||||
},
|
||||
[rgba.buffer]
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (kind === 'typst') {
|
||||
const pageCount = new DataView(
|
||||
frame.buffer,
|
||||
frame.byteOffset,
|
||||
frame.byteLength
|
||||
).getUint32(1, true);
|
||||
const svg = decoder.decode(frame.subarray(5));
|
||||
globalThis.postMessage({
|
||||
id,
|
||||
ok: true,
|
||||
result: { kind, pageCount, svg },
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (kind === 'pdf') {
|
||||
const view = new DataView(
|
||||
frame.buffer,
|
||||
frame.byteOffset,
|
||||
frame.byteLength
|
||||
);
|
||||
const pageCount = view.getUint32(1, true);
|
||||
if (msg.op === 'page_count') {
|
||||
globalThis.postMessage({
|
||||
id,
|
||||
ok: true,
|
||||
result: { kind, pageCount },
|
||||
});
|
||||
return;
|
||||
}
|
||||
const widthPx = view.getUint32(5, true);
|
||||
const heightPx = view.getUint32(9, true);
|
||||
const rgba = frame.slice(13);
|
||||
const expectedBytes = widthPx * heightPx * 4;
|
||||
if (rgba.byteLength !== expectedBytes) {
|
||||
throw new Error(
|
||||
`PDF RGBA length mismatch: got ${rgba.byteLength}, expected ${expectedBytes}`
|
||||
);
|
||||
}
|
||||
globalThis.postMessage(
|
||||
{
|
||||
id,
|
||||
ok: true,
|
||||
result: { kind, pageCount, widthPx, heightPx, rgba },
|
||||
},
|
||||
[rgba.buffer]
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const svg = decoder.decode(frame.subarray(1));
|
||||
globalThis.postMessage({
|
||||
id,
|
||||
ok: true,
|
||||
result: { kind, svg },
|
||||
});
|
||||
const abi = await ensureAbi();
|
||||
const { result, transfer } = handle(abi, msg);
|
||||
globalThis.postMessage({ id, ok: true, result }, transfer);
|
||||
} catch (error) {
|
||||
globalThis.postMessage({
|
||||
id,
|
||||
|
||||
@@ -14,7 +14,7 @@ export function writeWasmFixture(tmpWasm) {
|
||||
return out;
|
||||
};
|
||||
const section = (id, body) => [id, ...encodeUleb(body.length), ...body];
|
||||
const makeValidTestWasm = exportNames => {
|
||||
const makeValidTestWasm = (exportNames, { memory = false } = {}) => {
|
||||
const typeSec = section(1, [1, 0x60, 0, 0]);
|
||||
const funcSec = section(3, [
|
||||
...encodeUleb(exportNames.length),
|
||||
@@ -30,8 +30,13 @@ export function writeWasmFixture(tmpWasm) {
|
||||
...encodeUleb(idx)
|
||||
);
|
||||
}
|
||||
if (memory) {
|
||||
const nb = Buffer.from('memory', 'utf8');
|
||||
expEntries.push(...encodeUleb(nb.length), ...nb, 0x02, 0);
|
||||
}
|
||||
const memorySec = memory ? section(5, [1, 0x00, 1]) : [];
|
||||
const exportSec = section(7, [
|
||||
...encodeUleb(exportNames.length),
|
||||
...encodeUleb(exportNames.length + (memory ? 1 : 0)),
|
||||
...expEntries,
|
||||
]);
|
||||
const codeBodies = [];
|
||||
@@ -59,21 +64,17 @@ export function writeWasmFixture(tmpWasm) {
|
||||
0x00,
|
||||
...typeSec,
|
||||
...funcSec,
|
||||
...memorySec,
|
||||
...exportSec,
|
||||
...codeSec,
|
||||
...customSec,
|
||||
]);
|
||||
};
|
||||
const workerExports = [
|
||||
'affine_worker_reset_input',
|
||||
'affine_worker_push_input_u32',
|
||||
'affine_worker_invoke',
|
||||
'affine_worker_output_u32',
|
||||
];
|
||||
const workerExports = ['prepare', 'invoke', 'output_ptr'];
|
||||
for (const kind of ['mermaid', 'math', 'typst', 'pdf']) {
|
||||
writeFileSync(
|
||||
join(tmpWasm, `${kind}.wasm`),
|
||||
makeValidTestWasm(workerExports)
|
||||
makeValidTestWasm(workerExports, { memory: true })
|
||||
);
|
||||
}
|
||||
mkdirSync(join(tmpWasm, 'pkg'), { recursive: true });
|
||||
|
||||
@@ -571,23 +571,21 @@ void test('registerFont syncs fonts to mermaidWorker across restarts', () => {
|
||||
}
|
||||
});
|
||||
|
||||
void test('single-page PDF error dispatches deliver_pdf_page_error without poisoning other pages', () => {
|
||||
const env = createFakeDom();
|
||||
try {
|
||||
const docErrors = [];
|
||||
const pageErrors = [];
|
||||
const pageSuccesses = [];
|
||||
const countSuccesses = [];
|
||||
installPlaygroundPreviewBridge({
|
||||
deliver_pdf_error(pdfKey) {
|
||||
docErrors.push(pdfKey);
|
||||
function pdfDeliveryRecorder() {
|
||||
const events = [];
|
||||
return {
|
||||
events,
|
||||
exports: {
|
||||
deliver_pdf_open(docId, count) {
|
||||
events.push(['open', docId, count]);
|
||||
},
|
||||
deliver_pdf_page_error(pdfKey, pageIndex, scale) {
|
||||
pageErrors.push([pdfKey, pageIndex, scale]);
|
||||
deliver_pdf_open_error(docId) {
|
||||
events.push(['open_error', docId]);
|
||||
},
|
||||
deliver_pdf_page(pdfKey, pageIndex, pageCount, scale, wPx, hPx, rgba) {
|
||||
pageSuccesses.push([
|
||||
pdfKey,
|
||||
deliver_pdf_page(docId, pageIndex, pageCount, scale, wPx, hPx, rgba) {
|
||||
events.push([
|
||||
'page',
|
||||
docId,
|
||||
pageIndex,
|
||||
pageCount,
|
||||
scale,
|
||||
@@ -596,47 +594,160 @@ void test('single-page PDF error dispatches deliver_pdf_page_error without poiso
|
||||
rgba.byteLength,
|
||||
]);
|
||||
},
|
||||
deliver_pdf_page_count(pdfKey, count) {
|
||||
countSuccesses.push([pdfKey, count]);
|
||||
deliver_pdf_page_error(docId, pageIndex, scale) {
|
||||
events.push(['page_error', docId, pageIndex, scale]);
|
||||
},
|
||||
});
|
||||
const bridge = globalThis.window.__playgroundPreview;
|
||||
const pdfBytes = new Uint8Array([37, 80, 68, 70]);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
bridge.requestPdfPageCount('doc', pdfBytes);
|
||||
bridge.requestPdfPage('doc', pdfBytes, 0, 1);
|
||||
bridge.requestPdfPage('doc', pdfBytes, 1, 1);
|
||||
bridge.requestPdfPageCount('corrupt', pdfBytes);
|
||||
void test('PDF bridge sends each document once by docId and keeps page errors per page', () => {
|
||||
const env = createFakeDom();
|
||||
try {
|
||||
const { events, exports } = pdfDeliveryRecorder();
|
||||
installPlaygroundPreviewBridge(exports);
|
||||
const bridge = globalThis.window.__playgroundPreview;
|
||||
const wasmMemory = new Uint8Array([0, 37, 80, 68, 70, 0]);
|
||||
const pdfView = wasmMemory.subarray(1, 5);
|
||||
|
||||
// Open and render go out back to back, without waiting for the open answer.
|
||||
assert.equal(bridge.isPdfOpen(7), false);
|
||||
bridge.openPdf(7, pdfView);
|
||||
assert.equal(bridge.isPdfOpen(7), true);
|
||||
bridge.requestPdfPage(7, 0, 1);
|
||||
bridge.requestPdfPage(7, 1, 1);
|
||||
bridge.openPdf(8, pdfView);
|
||||
bridge.closePdf(99);
|
||||
|
||||
assert.equal(env.workers.length, 1);
|
||||
const [reqCount, reqP0, reqP1, reqCorrupt] = env.workers[0].posted;
|
||||
const [open7, p0, p1, open8] = env.workers[0].posted;
|
||||
assert.equal(
|
||||
env.workers[0].posted.length,
|
||||
4,
|
||||
'closing an unknown docId sends nothing'
|
||||
);
|
||||
assert.deepEqual(
|
||||
[open7.op, open7.docId, [...open7.pdfBytes]],
|
||||
['pdf_open', 7, [37, 80, 68, 70]]
|
||||
);
|
||||
assert.notEqual(
|
||||
open7.pdfBytes.buffer,
|
||||
wasmMemory.buffer,
|
||||
'never send the main Wasm memory'
|
||||
);
|
||||
assert.equal(open7.pdfBytes.byteOffset, 0);
|
||||
assert.deepEqual(
|
||||
[p0.op, p0.docId, p0.pageIndex, p0.scale],
|
||||
['pdf_render', 7, 0, 1]
|
||||
);
|
||||
assert.equal(
|
||||
'pdfBytes' in p0,
|
||||
false,
|
||||
'a page request carries no PDF bytes'
|
||||
);
|
||||
|
||||
env.workers[0].emit('message', {
|
||||
data: { id: reqCount.id, ok: true, result: { pageCount: 5 } },
|
||||
});
|
||||
env.workers[0].emit('message', {
|
||||
data: { id: reqP0.id, ok: false, error: 'page 0 render error' },
|
||||
});
|
||||
env.workers[0].emit('message', {
|
||||
data: {
|
||||
id: reqP1.id,
|
||||
ok: true,
|
||||
result: {
|
||||
pageCount: 5,
|
||||
widthPx: 2,
|
||||
heightPx: 2,
|
||||
rgba: new Uint8Array(16),
|
||||
},
|
||||
const answer = (msg, data) =>
|
||||
env.workers[0].emit('message', { data: { id: msg.id, ...data } });
|
||||
answer(open7, { ok: true, result: { pageCount: 5 } });
|
||||
answer(p0, { ok: false, error: 'page 0 render error' });
|
||||
answer(p1, {
|
||||
ok: true,
|
||||
result: {
|
||||
pageCount: 5,
|
||||
widthPx: 2,
|
||||
heightPx: 2,
|
||||
rgba: new Uint8Array(16),
|
||||
},
|
||||
});
|
||||
env.workers[0].emit('message', {
|
||||
data: { id: reqCorrupt.id, ok: false, error: 'bad xref' },
|
||||
});
|
||||
answer(open8, { ok: false, error: 'Decryption(PasswordProtected)' });
|
||||
|
||||
assert.deepEqual(countSuccesses, [['doc', 5]]);
|
||||
assert.deepEqual(pageErrors, [['doc', 0, 1]]);
|
||||
assert.deepEqual(pageSuccesses, [['doc', 1, 5, 1, 2, 2, 16]]);
|
||||
assert.deepEqual(docErrors, ['corrupt']);
|
||||
bridge.closePdf(7);
|
||||
const close7 = env.workers[0].posted.at(-1);
|
||||
assert.deepEqual([close7.op, close7.docId], ['pdf_close', 7]);
|
||||
assert.equal(bridge.isPdfOpen(7), false);
|
||||
answer(close7, { ok: true, result: {} });
|
||||
|
||||
assert.deepEqual(events, [
|
||||
['open', 7, 5],
|
||||
['page_error', 7, 0, 1],
|
||||
['page', 7, 1, 5, 1, 2, 2, 16],
|
||||
['open_error', 8],
|
||||
]);
|
||||
} finally {
|
||||
env.restore();
|
||||
}
|
||||
});
|
||||
|
||||
void test('PDF bridge answers every sent request on a crash, ignores a late error of a replaced worker and restarts without stale documents', () => {
|
||||
const env = createFakeDom();
|
||||
try {
|
||||
const { events, exports } = pdfDeliveryRecorder();
|
||||
installPlaygroundPreviewBridge(exports);
|
||||
const bridge = globalThis.window.__playgroundPreview;
|
||||
const pdf = new Uint8Array([37, 80, 68, 70]);
|
||||
|
||||
bridge.openPdf(1, pdf);
|
||||
// The same page twice: each request sent gets its own answer.
|
||||
bridge.requestPdfPage(1, 0, 1);
|
||||
bridge.requestPdfPage(1, 0, 1);
|
||||
const workerA = env.workers[0];
|
||||
// A message that cannot be sent leaves no pending request behind.
|
||||
const postMessage = workerA.postMessage;
|
||||
workerA.postMessage = () => {
|
||||
throw new Error('DataCloneError');
|
||||
};
|
||||
assert.throws(() => bridge.requestPdfPage(1, 9, 1), /DataCloneError/);
|
||||
workerA.postMessage = postMessage;
|
||||
workerA.emit('error', { message: 'boom' });
|
||||
assert.equal(workerA.terminated, true);
|
||||
assert.equal(
|
||||
bridge.isPdfOpen(1),
|
||||
false,
|
||||
'a crash forgets the open documents'
|
||||
);
|
||||
assert.deepEqual(events.splice(0), [
|
||||
['open_error', 1],
|
||||
['page_error', 1, 0, 1],
|
||||
['page_error', 1, 0, 1],
|
||||
]);
|
||||
|
||||
bridge.openPdf(2, pdf);
|
||||
bridge.requestPdfPage(2, 0, 1);
|
||||
const workerB = env.workers[1];
|
||||
// Worker A answers late: an error event, a message error, and a message with B's id.
|
||||
workerA.emit('messageerror', {});
|
||||
workerA.emit('error', { message: 'late' });
|
||||
workerA.emit('message', {
|
||||
data: { id: workerB.posted[0].id, ok: true, result: { pageCount: 9 } },
|
||||
});
|
||||
assert.equal(workerB.terminated, false);
|
||||
assert.equal(bridge.isPdfOpen(2), true);
|
||||
assert.deepEqual(events, []);
|
||||
|
||||
workerB.emit('message', {
|
||||
data: { id: workerB.posted[0].id, ok: true, result: { pageCount: 3 } },
|
||||
});
|
||||
assert.deepEqual(events.splice(0), [['open', 2, 3]]);
|
||||
|
||||
// A restart drops the pending page request without an answer.
|
||||
bridge.restartPdfWorker();
|
||||
assert.equal(workerB.terminated, true);
|
||||
assert.equal(bridge.isPdfOpen(2), false);
|
||||
workerB.emit('message', {
|
||||
data: {
|
||||
id: workerB.posted[1].id,
|
||||
ok: true,
|
||||
result: { rgba: new Uint8Array(4) },
|
||||
},
|
||||
});
|
||||
assert.deepEqual(events, []);
|
||||
|
||||
// Disposing the bridge fails what is on its way and terminates the worker.
|
||||
bridge.openPdf(3, pdf);
|
||||
const workerC = env.workers[2];
|
||||
globalThis.window.__playgroundPreviewDispose();
|
||||
assert.equal(workerC.terminated, true);
|
||||
assert.deepEqual(events, [['open_error', 3]]);
|
||||
} finally {
|
||||
env.restore();
|
||||
}
|
||||
|
||||
@@ -1565,13 +1565,24 @@ void test('pdf client lazy-spawns worker, deduplicates in-flight renders, evicts
|
||||
scale: 1,
|
||||
});
|
||||
|
||||
// One open message carries the bytes; both page requests follow it at once by docId.
|
||||
assert.equal(spawnCount, 1);
|
||||
assert.equal(posted.length, 2);
|
||||
assert.deepEqual(
|
||||
posted.map(msg => [msg.op, msg.docId, msg.pageIndex]),
|
||||
[
|
||||
['pdf_open', 1, undefined],
|
||||
['pdf_render', 1, 0],
|
||||
['pdf_render', 1, 1],
|
||||
]
|
||||
);
|
||||
assert.equal(posted[0].pdfBytes, pdfBytes);
|
||||
assert.equal(client.getStats().dedupHits, 1);
|
||||
assert.equal(client.getStats().openDocs, 1);
|
||||
|
||||
// Resolve out-of-order to verify requestId multiplexing.
|
||||
emitResponse({ id: posted[0].id, ok: true, result: { pageCount: 3 } });
|
||||
emitResponse({
|
||||
id: posted[1].id,
|
||||
id: posted[2].id,
|
||||
ok: true,
|
||||
result: {
|
||||
pageCount: 3,
|
||||
@@ -1581,7 +1592,7 @@ void test('pdf client lazy-spawns worker, deduplicates in-flight renders, evicts
|
||||
},
|
||||
});
|
||||
emitResponse({
|
||||
id: posted[0].id,
|
||||
id: posted[1].id,
|
||||
ok: true,
|
||||
result: {
|
||||
pageCount: 3,
|
||||
@@ -1599,7 +1610,7 @@ void test('pdf client lazy-spawns worker, deduplicates in-flight renders, evicts
|
||||
|
||||
// Page count is already cached (0 extra worker RPCs).
|
||||
assert.equal(await client.getPageCount({ docKey: 'doc-pdf', pdfBytes }), 3);
|
||||
assert.equal(posted.length, 2);
|
||||
assert.equal(posted.length, 3);
|
||||
|
||||
// Protect page 0 as visible; rendering page 2 evicts offscreen page 1 first.
|
||||
client.setVisibleKeys([buildPdfPageCacheKey('doc-pdf', 0, 1)]);
|
||||
@@ -1609,9 +1620,9 @@ void test('pdf client lazy-spawns worker, deduplicates in-flight renders, evicts
|
||||
pageIndex: 2,
|
||||
scale: 1,
|
||||
});
|
||||
assert.equal(posted.length, 3);
|
||||
assert.equal(posted.length, 4);
|
||||
emitResponse({
|
||||
id: posted[2].id,
|
||||
id: posted[3].id,
|
||||
ok: true,
|
||||
result: {
|
||||
pageCount: 3,
|
||||
@@ -1632,7 +1643,33 @@ void test('pdf client lazy-spawns worker, deduplicates in-flight renders, evicts
|
||||
scale: 1,
|
||||
});
|
||||
assert.equal(page0Cached.fromCache, true);
|
||||
assert.equal(posted.length, 3);
|
||||
assert.equal(posted.length, 4);
|
||||
|
||||
// New bytes under the same docKey close the old document and drop its count and pages.
|
||||
const changedBytes = new Uint8Array([37, 80, 68, 70, 45]);
|
||||
const changedCount = client.getPageCount({
|
||||
docKey: 'doc-pdf',
|
||||
pdfBytes: changedBytes,
|
||||
});
|
||||
assert.deepEqual(
|
||||
posted.slice(4).map(msg => [msg.op, msg.docId]),
|
||||
[
|
||||
['pdf_close', 1],
|
||||
['pdf_open', 2],
|
||||
]
|
||||
);
|
||||
emitResponse({ id: posted[5].id, ok: true, result: { pageCount: 7 } });
|
||||
assert.equal(await changedCount, 7);
|
||||
assert.equal(client.getStats().cacheEntries, 0);
|
||||
// An equal copy of the bytes keeps the open document.
|
||||
assert.equal(
|
||||
await client.getPageCount({
|
||||
docKey: 'doc-pdf',
|
||||
pdfBytes: changedBytes.slice(),
|
||||
}),
|
||||
7
|
||||
);
|
||||
assert.equal(posted.length, 6);
|
||||
|
||||
client.dispose();
|
||||
assert.equal(terminated, true);
|
||||
@@ -1816,6 +1853,96 @@ void test('gpu recovery single-flight mutex blocks late restore, deduplicates co
|
||||
assert.equal(fakeDoc.getElementById('boot'), null);
|
||||
});
|
||||
|
||||
void test('pdf client keeps at most 8 documents open, waits for room, rejects out-of-range sizes, and reopens after a failed open', async () => {
|
||||
/** @type {any[]} */
|
||||
const posted = [];
|
||||
/** @type {Set<(ev: { data: any }) => void>} */
|
||||
const listeners = new Set();
|
||||
const client = createPdfPreviewClient({
|
||||
workerLoader: {
|
||||
loadWorker: () => ({
|
||||
postMessage(msg) {
|
||||
posted.push(msg);
|
||||
},
|
||||
addEventListener(type, fn) {
|
||||
if (type === 'message') listeners.add(fn);
|
||||
},
|
||||
removeEventListener(type, fn) {
|
||||
if (type === 'message') listeners.delete(fn);
|
||||
},
|
||||
terminate() {},
|
||||
}),
|
||||
},
|
||||
});
|
||||
const answer = (msg, data) => {
|
||||
for (const fn of listeners) fn({ data: { id: msg.id, ...data } });
|
||||
};
|
||||
const opens = () => posted.filter(msg => msg.op === 'pdf_open');
|
||||
// Runs every pending promise reaction before the next check.
|
||||
const tick = () => new Promise(resolve => setImmediate(resolve));
|
||||
|
||||
const counts = Array.from({ length: 9 }, (_, i) =>
|
||||
client.getPageCount({ docKey: `doc-${i}`, pdfBytes: Uint8Array.of(i + 1) })
|
||||
);
|
||||
assert.equal(opens().length, 8, 'the ninth open waits for room');
|
||||
assert.equal(client.getStats().openDocs, 8);
|
||||
|
||||
// An answered open frees its document: the ninth one replaces it.
|
||||
answer(opens()[0], { ok: true, result: { pageCount: 1 } });
|
||||
assert.equal(await counts[0], 1);
|
||||
await tick();
|
||||
assert.deepEqual(
|
||||
posted.slice(8).map(msg => [msg.op, msg.docId]),
|
||||
[
|
||||
['pdf_close', 1],
|
||||
['pdf_open', 9],
|
||||
]
|
||||
);
|
||||
assert.equal(client.getStats().openDocs, 8);
|
||||
|
||||
// A failed open frees its slot and the next request opens the bytes again.
|
||||
answer(opens()[1], { ok: false, error: 'Decryption(PasswordProtected)' });
|
||||
await assert.rejects(counts[1], /PasswordProtected/);
|
||||
await tick();
|
||||
assert.equal(client.getStats().openDocs, 7);
|
||||
const retry = client.getPageCount({
|
||||
docKey: 'doc-1',
|
||||
pdfBytes: Uint8Array.of(2),
|
||||
});
|
||||
assert.deepEqual([posted.at(-1).op, posted.at(-1).docId], ['pdf_open', 10]);
|
||||
answer(posted.at(-1), { ok: true, result: { pageCount: 4 } });
|
||||
assert.equal(await retry, 4);
|
||||
|
||||
const before = posted.length;
|
||||
for (const pdfBytes of [
|
||||
new Uint8Array(0),
|
||||
{ byteLength: 256 * 1024 * 1024 + 1 },
|
||||
]) {
|
||||
await assert.rejects(
|
||||
client.getPageCount({
|
||||
docKey: 'bad',
|
||||
pdfBytes: /** @type {any} */ (pdfBytes),
|
||||
}),
|
||||
/worker limit/
|
||||
);
|
||||
await assert.rejects(
|
||||
client.renderPage({
|
||||
docKey: 'bad',
|
||||
pdfBytes: /** @type {any} */ (pdfBytes),
|
||||
pageIndex: 0,
|
||||
}),
|
||||
/worker limit/
|
||||
);
|
||||
}
|
||||
assert.equal(
|
||||
posted.length,
|
||||
before,
|
||||
'out-of-range sizes never reach the worker'
|
||||
);
|
||||
client.dispose();
|
||||
await Promise.allSettled(counts);
|
||||
});
|
||||
|
||||
void test('pdf client recovers from worker error by spawning a fresh worker and protects cached RGBA buffers from caller transfer', async () => {
|
||||
let spawnCount = 0;
|
||||
let respond = false;
|
||||
@@ -2218,7 +2345,8 @@ void test('cut requires non-null selection token, concurrent PDF dedup survives
|
||||
});
|
||||
}
|
||||
const [lenA, lenB] = await Promise.all([callerA, callerB]);
|
||||
assert.equal(rpcCount, 1);
|
||||
// One open and one shared render.
|
||||
assert.equal(rpcCount, 2);
|
||||
assert.equal(lenA, 4);
|
||||
assert.equal(lenB, 4);
|
||||
client.dispose();
|
||||
|
||||
@@ -30,6 +30,9 @@ export const ZERO_IN_PRODUCTION = Object.freeze([
|
||||
'overlay.linked_doc_menu.item.',
|
||||
'overlay.linked_doc_menu.group.',
|
||||
'overlay.linked_doc_menu.journal.',
|
||||
'overlay.pdf_viewer.page.',
|
||||
'overlay.pdf_viewer.thumb.',
|
||||
'overlay.attachment_toolbar.',
|
||||
]);
|
||||
|
||||
const WASM_MAGIC = new Uint8Array([0x00, 0x61, 0x73, 0x6d]);
|
||||
|
||||
Reference in new issue
Block a user