diff --git a/.github/actions/run-gates/action.yml b/.github/actions/run-gates/action.yml index 651fb519d..6b4e63c81 100644 --- a/.github/actions/run-gates/action.yml +++ b/.github/actions/run-gates/action.yml @@ -183,6 +183,13 @@ runs: - name: Unit-test the IDE's main.js tool (test/ide-js.test.mjs) shell: bash run: node --test test/ide-js.test.mjs + # Unit tests for builder/discover.mjs and discover-read.mjs: the source + # tree's inventory, which the build reads in pieces on its lanes. They read + # a small tree of their own in any number of pieces, with a picture pair + # that has a file from outside the tree. No build, no lanes. + - name: Unit-test the source tree's inventory (test/discover.test.mjs) + shell: bash + run: node --test test/discover.test.mjs # A regex that backtracks exponentially does not fail a build, it stops # one: the corpus passes until a page happens to contain the trigger, and # then a render worker sits inside String.replace forever. Nothing else diff --git a/WIP.Build.md b/WIP.Build.md index dae25e78e..ae1ff7b22 100644 --- a/WIP.Build.md +++ b/WIP.Build.md @@ -64,6 +64,7 @@ The roster, by wrapper ([Tools and Scripts](docs/Documentation/Tools.md) owns th | `test.bat` | `test/addin-project.test.mjs` | `builder/addin-project.mjs` packs exactly the files git tracks in `add-in/`, the same bytes from a CRLF and an LF checkout. Needs git | | `test.bat` | `test/indexer.test.mjs` | the package indexer (`indexer/lib/`) changes a snapshot only when the API changes | | `test.bat` | `test/ide-js.test.mjs` | `scripts/ide_js.mjs` and `scripts/ide-js/lib.mjs` on a few lines of minified JavaScript, and that the tool writes only under `%TEMP%` | +| `test.bat` | `test/discover.test.mjs` | the source tree's inventory (`builder/discover.mjs`, `discover-read.mjs`) is the same in any number of pieces, with a picture pair that has a `bundle_extra` file | | `test.bat` | `check_pdf_shims_equiv` | the book's pdf-lib shims write what stock pdf-lib writes, and patch only the members `PATCHES` lists | | `test.bat` | `check_impexp_parity` | the Node and Python editions of `impexp` (and, with `IMPEXP_EXE`, the twinBASIC one) behave alike | | `test.bat` | `check_publish_policy`, `check_gate_lists`, `check_page_baseline`, `check_book_coverage`, `check_axe_patch_equiv` | the gates on the gates | @@ -85,10 +86,10 @@ A dynamic barrier must list every chunk task in its `expected`, even when its ow So every skip on the chunk-merge path refuses to continue when a piece is missing --- see [where the completeness checks are](builder/PLAN-sab-pull-scheduler.md#where-the-completeness-checks-are). On this path, "the piece is missing" is a bug, not a case to handle. -**A sort key on this path must be total.** `discover()` fills `pages` from inside -a `Promise.all`, so a page is pushed when its `readFile` resolves, not in -`allFiles` order. `pages.sort(byName)` is stable and Jekyll's key is the -*basename*, so a tie would keep that I/O completion order --- and over a hundred +**A sort key on this path must be total.** The pages arrive piece by piece (see +[The source tree is read on the lanes](#the-source-tree-is-read-on-the-lanes)), +not in the listing's order. `pages.sort(byName)` is stable and Jekyll's key is the +*basename*, so a tie would keep the order of arrival --- and over a hundred folder-style classes are all named `index.md`. Tied pages would reorder the chunking and make `search-data.json` differ between two builds of one commit. `byName` breaks ties on `srcRel`. Two builds of a commit are byte-identical @@ -109,6 +110,209 @@ would differ. Measured on the dev box: the online build takes about 2 s; the offline pass adds about 700 ms, the PDF pass about 150 ms, and `--check` about 1.7 s. +### No task starts a thread + +**The lanes are the build's only threads** (owner, 2026-11-17: "That's what the lanes +are for, and we lose important diagnostics that way too"). A task whose work can run in +parallel splits it into pieces and adds each to the graph as a lane task, with `fanOut` +(`builder/fan-out.mjs`) from the `submit()` of the main-thread task that plans them. The +search index (`indexAdd:i`, `indexVectors:i`) and the help archive (`archiveDeflate:i`, +`archiveLateDeflate:i`) are the models; `render:i` and `flush:i` are the same idea, wired +by `dispatch.submit`. + +So a task never: + +- starts a worker thread (`node:worker_threads`), a cluster or a process for its work; +- puts CPU work on Node's thread pool: the functions of `node:zlib` whose name does not + end in `Sync` run there, as do the asynchronous key-derivation functions of + `node:crypto`. File reads and writes may use the pool: that is I/O. + +**Why.** A thread a task starts is one the scheduler cannot place and the Gantt chart +does not show. The search index once built on threads of its own: two on a 4-core CI +runner (half the machine), beside lanes that had nothing to do, and the chart showed one +bar on one lane for the whole of it. The help archive deflated on the thread pool, so its +one bar hid a 55 MB file deflating on a single thread for most of its length. As lane +tasks, the index runs on every lane, the archive is deflated while the index is built, +and each piece is a bar on the lane that ran it. + +**The gate is `check_lint.mjs`**, through `noRestrictedImports` in `biome.jsonc`: +`builder/` may not import `worker_threads`, `cluster` or `child_process`, and `builder/` +and `lib/` may import from `node:zlib` only the `Sync` functions, `crc32` and +`constants`, by name (a default import would hide which function is called). The files +that may are named there, each with its reason: `worker-pool.mjs` and `cpu-worker.mjs` +are the lanes, and `build-info.mjs` and `addin-project.mjs` run `git`. The rule reads +imports, so it cannot see a function of another module that does the same; a new +dependency that starts threads is a review matter. + +**`fanOut`'s own rules** are in its header: every piece waits for the task whose +`submit` adds it, so none can run while its edges are written; a join lists that task in +its `expected`, and `fanOut` adds the pieces to that list, which is what holds the join +until every piece's `submit` has run. `book/` is not the build: `book.bat`'s renderer +deflates on the thread pool (`book/lib/parallel-deflate.mjs`), and has no lanes. + +### The source tree is read on the lanes + +`discover` was one main-thread task: a glob, then every page read and its frontmatter +parsed, every static file sized and every picture pair's two headers read, all through +the asynchronous file calls. On a four-CPU CI runner it took about 1.0 s, as a fifth +thread beside four lanes that were booting, and everything up to the first render waits +for it. It is three steps now (`builder/discover.mjs`): `discoverList` lists the tree on +the main thread and cuts the listing into pieces, each `discoverRead:i` does a piece on +a lane (`builder/discover-read.mjs`, every file opened there, synchronously), and +`discover` puts the results together. `discover()` is the same code in one piece, for +the tools. + +What makes it worth doing, and what to keep when changing it: + +- **A lane boots in two stages** (`builder/cpu-worker.mjs`). The first loads the + scheduler and what `discoverRead` needs, and the lane is in the pull loop after it. The + second (`loadRest`: the renderer, the search index, the archive) runs before the + lane's first task that is not a `discoverRead`. Without the split a piece would start + only after a whole boot, later than the main thread used to start reading. **A module + `discover-read.mjs` imports is paid for by every lane before the first piece**: keep it + to the YAML parser and `paths.mjs`. The glob library stays in `discover.mjs`. +- **The other early lane tasks wait for `discoverList`**: `scssLight`, `scssDark`, `dot`, + `packTests` and `warmInit`. They are READY at the start otherwise, the first lanes up + would take them and load the second stage, and the pieces would wait for a lane. The + listing takes a few hundredths of a second, less than a lane takes to start. The + pieces have the highest priority, so the first lanes that look take them. + `buildInfo` waits too, since nothing early needs it: see + [dispatch does not wait for buildInfo](#dispatch-does-not-wait-for-buildinfo). +- **Two pieces below eight CPUs, four from eight on** (`discoverPieces`; owner, + 2026-11-18). On four CPUs the other two lanes compile the stylesheets meanwhile; with + four pieces there `dot` and `packTests` queued behind the reads and `dispatch`, which + waits for `dot`, started late. With eight lanes or more, four of them reading leave + lanes for the rest. On the dev box (16 CPUs) `discover` ended at 0.10 to 0.11 s in a + serve rebuild with four pieces, 0.14 to 0.19 s with two; in a one-off build at 0.23 to + 0.38 s against 0.32 to 0.46 s. +- **The reads are synchronous.** Asynchronous calls from every lane queue on libuv's one + pool of four threads; synchronous ones on two lanes are two reads at a time, and the + lane has nothing else to do. Alone, every page read on one thread takes 67 ms on the + dev box, 40 ms on two and 23 ms on four. + +Measured, each `discover` ending at: + +| | before | two pieces | +|---|---|---| +| CI (Linux, four CPUs): one run before, two after | 1.05 s | 0.26 s, 0.38 s | +| dev box (Windows, 16 CPUs), one-off build | 0.48 to 0.50 s | 0.43 to 0.51 s | +| dev box, four CPUs (`start /affinity F`) | 0.51 to 0.59 s | 0.35 to 0.46 s | +| dev box, serve rebuild | 0.16 to 0.22 s | 0.14 to 0.16 s | + +On CI the first render started at about 1.2 s in the first run after and about 1.65 s in +the second, where it had started at 2.05 s. The first run's runner was about a quarter +faster than the one before (render itself took 10 s against 13 s); the second's was as +slow as it (render 14 s), so about 0.4 s is the change. `dispatch` ended at 1.45 s in the +second run against 2.0 s. The whole build's time did not change beyond what the runners +differ by (24.6 s against 24.2 s on the two slow ones). **On Windows a one-off build gains nothing**: +while the other lanes boot, a lane's piece takes 0.2 to 0.3 s for half the tree, where +the same reads alone take 40 ms, and `markdownInit` and `dispatch` then run beside +every lane's second stage and `warmInit` and take longer than they did. The first +render started at 1.15 to 1.28 s against 0.96 to 0.99 s in the prototype's runs, on a +machine that was not quiet; not measured again since. The change is for CI and for +serve rebuilds. + +### The pages' text does not go through the main thread's JSON + +`dispatch.submit` packed every page into the render chunks' payloads as JSON +(`packPayloads`): 12 MB, nearly all of it the pages' text, 50 to 60 ms on the main thread +of the dev box between the end of `dispatch` and the lanes' first look at a chunk. The +timing line's `dispatch=` does not count a `submit`; in the chart it is the gap between +`dispatch`'s bar and `prepDest`'s. + +The text is now packed where it is read. Each `discoverRead:i` lane writes its pages' +`rawContent` as UTF-8 into one SharedArrayBuffer (`packPageText`, +`builder/discover-read.mjs`) and returns it beside the pages; a shared buffer is not +copied on the way back. `discover` broadcasts the buffers (`"pageText:"`) and +keeps where each page's text is (`state.pageTextAt`). A chunk's payload is +`{ pages, texts }`: the pages without `rawContent`, and each one's piece, offset and +length. `render:i` reads the text back (`pageText`) before it renders. + +What to keep when changing it: + +- **The main thread still has every page's `rawContent`**: the pages come back from the + lanes with it, and `vendorAssets`, `markdownInit` and the later tasks read it. Only the + chunks' payloads lost it. +- **Nothing may change a page's `rawContent` after `discoverRead`**: the render lanes + would not see the change. Nothing does today (the one assignment is `buildPage`'s). A + page with no place in `state.pageTextAt` keeps its text in the payload, so a page + added later still renders. +- **The gap is a `submit`'s**, so it is on the main thread whatever the lanes do. + +Measured on the dev box, from the end of `dispatch`'s bar to the start of `prepDest`'s: +0.05 to 0.13 s before, 0.01 to 0.02 s since, in one-off builds on sixteen CPUs and on +four. In a serve rebuild the first render started at 0.27 to 0.35 s before and at 0.23 +to 0.27 s since (builds 2 to 5 on one pool). A one-off build's first render is within +the noise of the runs (0.78 to 0.88 s against 0.82 to 0.84 s): the lanes are still +loading their second stage and Shiki then. `discover` ends when it did. Not measured: CI. + +### dispatch does not wait for buildInfo + +`buildInfo` is two `git` processes, and only the book's title page states what they +return (`book.mjs`, `renderTitlePage`). `dispatch` listed it in `expected` and put its +result in the shared payload, from when every lane held the whole site object; no render +reads it. On Windows a process takes long to start while every lane boots: `buildInfo` +took 0.34 to 0.61 s in a one-off build on the dev box (0.15 s in the best run of eight), +ended later than `markdownInit` did, and `dispatch` started only then, 0.1 to 0.25 s +late. In a serve rebuild it took 0.03 to 0.3 s, with the same effect. On CI's Linux it +was done long before. + +`bookPayload` waits for it now, which reads `state.site.buildInfo` and runs after the +render; the shared payload and the lanes' site object hold it no longer. `buildInfo` +also waits for `discoverList`, as the other early lane tasks do, so that it does not +take a lane the source tree's pieces want. + +Measured on the dev box, with four pieces of the source tree as well (the two changes +were measured together), the first render starting at: + +| | before | since | +|---|---|---| +| serve rebuild (builds 2 to 5 on one pool) | 0.25 to 0.27 s | 0.16 to 0.20 s | +| one-off build, 16 CPUs (4 runs) | 0.76 to 0.87 s | 0.66 to 0.78 s | +| one-off build, 4 CPUs (8 runs) | 0.91 to 1.20 s | 0.79 to 1.17 s | + +On four CPUs nothing changes: the lanes are not up before `dispatch` ends either way, +and `dispatch` there still waits a few hundredths of a second for `dot` in some runs. +Not measured: CI, where neither change should show (four CPUs, and `git` is quick). + +**`nav` was looked at and gains nothing in a build.** `computeNav` sorted every page's +children twice and built a map for each page's levels; it now sorts once and the walk +carries the levels, which takes 6 ms alone on its first call where it took 19 to 24 ms. +In a build the task still reads 29 to 69 ms (28 to 64 ms before): its time there is +not its own work but the main thread's share of a machine whose lanes are all booting. + +### What markdownInit is made of + +Every render waits for `markdownInit`. On the dev box it took 117 to 151 ms in a one-off +build, of which `checkPlaceholders` was 70 to 80 ms and `deriveCounts` 20 to 48 ms; the +link tables, the parser, the SEO constants and the rest are a few milliseconds each. +Both are scans of page source that need a block parse, and they are the first block +parses of the build, so they run before the engine has compiled the parser: alone and +warm, the same two take about 15 ms and 3 ms. + +- **`findCountRefs` cuts into code spans only the lines that hold a placeholder.** It + called `maskCode` on the whole of each page that holds one, and those are the longest + pages of the site (the developer pages: 0.6 MB in all). A placeholder cannot span + lines, so a line of a fence is skipped and any other line with a placeholder is cut + with `splitCodeSpans`. The block parse remains: it is what says where the fences are. + `checkPlaceholders` is 30 to 43 ms since, and `markdownInit` 78 to 109 ms. +- **`maskCode` finds line ends and backticks with a regular expression and `indexOf`** + (`lib/markdown.mjs`: `splitLines`, `splitCodeSpans`), where it read one character at a + time. Over every page it took about 200 ms on one thread and takes about 115 ms, of + which the block parse is 80 ms. The render lanes call it on every page + (`applyPreRenderRewrites`), so that is about 85 ms of CPU off the render, shared among + the lanes. Old and new were compared over every page of the site: the same masked + text, the same segments of every line, the same placeholders. +- **The package tests' folders are listed once.** `packageTestRels` is a few dozen + synchronous file calls (5 to 20 ms); `markdownInit` keeps its result + (`state.site.packageTestRels`) for `dispatch`, which made the listing again. + +What is left is the two cold block parses: of `Reference/Attributes.md` and +`Reference/Enumerations.md` in `deriveCounts`, and of the pages with a placeholder in +`checkPlaceholders`. Giving them to a lane would need the site's parser there, which is +the second stage of a lane's boot: on Windows a one-off build's lanes are still loading +it when `markdownInit` runs, so it would wait for them. Not done. + ### A hung build times out and says where it hung Readers get this at [When a build stops instead of @@ -1012,7 +1216,7 @@ The decisions, each with what it rules out: commit behind the add-in being edited. `Resources/HELP/` is also refused by name, in case it is ever added. A file git does not track is named in the build's output. - **The archive in the project is the one this build wrote, handed over in memory.** - The `helpArchive` task (a worker task) returns the zip it wrote, as bytes, and + The `helpArchive` task returns the zip it wrote, as bytes, and `addinProject` waits for it and packs those bytes as `Resources/HELP/site.zip`. Reading the file back from `add-in/Resources/HELP/` could pick up the archive of an earlier build whenever this one wrote none (`--no-help-archive`, `--serve`, another `--dest`, a fixture): that @@ -1023,12 +1227,15 @@ The decisions, each with what it rules out: download that held it would differ from one build of a tree to the next. `recheckHelpArchive` checks at the end of `runBuild` that the offline tree still lists the archive's files and that only those two differ. -- **The task waits for every writer of the offline tree.** `flushJoin` (the render - lanes write each page's offline HTML in their flush), `scss` (the offline - stylesheet), `searchIndex` (`search-index.js`) and `writeOffline` (statics, theme - assets, redirect stubs, `nav.js`). Nothing else writes there before the injection; a writer added +- **The archive waits for every writer of the offline tree.** `archivePlan` waits for + `flushJoin` (the render lanes write each page's offline HTML in their flush), `scss` + (the offline stylesheet) and `writeOffline` (statics, theme assets, redirect stubs, + `nav.js`); `archiveLate` waits for `searchIndex` (`search-index.js`, the one file in + `LATE_FILES`). Nothing else writes there before the injection; a writer added later and missed here fails the build in `recheckHelpArchive`, which is why that - check compares every file's content. + check compares every file's size and CRC-32. **A file a new task writes into the + offline tree after `archivePlan` goes in `LATE_FILES`**, with `archiveLate` waiting + for that task. - **The offline tree has no copy, and its link goes to the website.** The project carries the offline tree's archive, so a copy in that tree would be inside its own archive. `deriveTreeRels` takes the path as an online-only file. The page links to @@ -1086,7 +1293,7 @@ and the reader builds it. `test/addin-project.test.mjs` is the gate. ### The help archive -- **The help archive is the `helpArchive` task of the build's graph.** `builder/help-archive-step.mjs` writes `add-in/Resources/HELP/site.zip` from `docs/_site-offline` through `lib/help-archive.mjs`, once every task that writes into the offline tree has finished (`flushJoin`, `scss`, `searchIndex`, `writeOffline`; the archive task lists exactly those) and **before** the Gantt injection. **The archive leaves out `HELP_ARCHIVE_SKIP`** (`builder/help-archive-step.mjs`): the Documentation Development section (`BuildInfo.html` and `assets/images/gantt.svg` with it, so the chart never reaches the zip), Videos and their poster frames, Challenges, and **every download, which stays online** (owner): a file readers download goes in a `downloads` folder beside its page, and the step fails the build when the Downloads page offers a file the archive would hold. The add-in's server redirects any file the archive lacks to the website, because pages link to all of these; a new entry needs nothing else. It reads the file back to verify it. A mismatch fails the build (exit 1). After the Gantt injection `recheckHelpArchive` checks that the offline tree on disk lists the same files as the archive and differs from it only in `BuildInfo.html` and `gantt.svg`; a task that wrote into the offline tree late fails the build there. The help add-in embeds the zip as a resource and serves the pages from it with its own server; a build of the add-in without it uses the live site. The file is gitignored (about 60 MB, 10 MB of it the search index's `search-index.js`, deflated), so a build of the add-in from a clean clone is the online one until `build.bat` has run. The download carries the same zip ([The help add-in's project file](#the-help-add-ins-project-file)). **`--no-help-archive` turns the step off, and neither CI workflow may pass it** (`check_ci_workflows.mjs` refuses it, in `ALLOWED.forbiddenBuildFlags`), because CI's published download would then hold no archive. It runs only for the guarded source tree (`docs`) built into the default `docs/_site-offline` (not another `--dest`, so `compare_trees` and `check_links_diff` leave it alone), never under `--serve` or `--dry-run`, never without an offline tree, and not keyed on `$CI`. There is no command-line tool for the archive: the `help-offline` lane makes its own with `writeHelpArchive`. The zip's format is fixed by the add-in's reader, which does no inflating ([WIP.HelpAddin.md](WIP.HelpAddin.md), Stage 4, increment 5). +- **The help archive is made by tasks of the build's graph, its deflating on the lanes.** `builder/help-archive-step.mjs` writes `add-in/Resources/HELP/site.zip` from `docs/_site-offline` through `lib/help-archive.mjs`, **before** the Gantt injection. `archivePlan` runs once `flushJoin`, `scss` and `writeOffline` have finished, lists the tree less `LATE_FILES` (`search-index.js`) and deals the deflating into one group of units for each lane (`archiveDeflate:i`), so the tree is deflated while the search index is built. `archiveLate` does the same for `search-index.js` once `searchIndex` has written it (`archiveLateDeflate:i`), and `helpArchive` writes the zip from every group. A unit is a whole file or one 1 MB piece of a larger one; a large file's pieces are one deflate stream, each ending with a sync flush and primed with the 32 KB before it (pigz's method), so the bytes depend only on the piece size. Measured on the 55 MB `search-index.js` at level 9: 3.2 s as one stream, 0.8 s as pieces on four threads, at the same size to within 0.02%. Each unit inflates what it deflated and compares it with the bytes it read; the zip is read back and compared with what was assembled. **The archive leaves out `HELP_ARCHIVE_SKIP`** (`builder/help-archive-step.mjs`): the Documentation Development section (`BuildInfo.html` and `assets/images/gantt.svg` with it, so the chart never reaches the zip), Videos and their poster frames, Challenges, and **every download, which stays online** (owner): a file readers download goes in a `downloads` folder beside its page, and the step fails the build when the Downloads page offers a file the archive would hold. The add-in's server redirects any file the archive lacks to the website, because pages link to all of these; a new entry needs nothing else. A mismatch fails the build (exit 1). After the Gantt injection `recheckHelpArchive` checks that the offline tree on disk lists the same files as the archive and differs from it, in size or CRC-32, only in `BuildInfo.html` and `gantt.svg`; a task that wrote into the offline tree late fails the build there. The help add-in embeds the zip as a resource and serves the pages from it with its own server; a build of the add-in without it uses the live site. The file is gitignored (about 60 MB, 10 MB of it the search index's `search-index.js`, deflated), so a build of the add-in from a clean clone is the online one until `build.bat` has run. The download carries the same zip ([The help add-in's project file](#the-help-add-ins-project-file)). **`--no-help-archive` turns the step off, and neither CI workflow may pass it** (`check_ci_workflows.mjs` refuses it, in `ALLOWED.forbiddenBuildFlags`), because CI's published download would then hold no archive. It runs only for the guarded source tree (`docs`) built into the default `docs/_site-offline` (not another `--dest`, so `compare_trees` and `check_links_diff` leave it alone), never under `--serve` or `--dry-run`, never without an offline tree, and not keyed on `$CI`. There is no command-line tool for the archive: the `help-offline` lane makes its own with `writeHelpArchive`. The zip's format is fixed by the add-in's reader, which does no inflating ([WIP.HelpAddin.md](WIP.HelpAddin.md), Stage 4, increment 5). ### Build-time counts as named values @@ -1380,9 +1587,9 @@ light one alone, a plain `` (`lightOnly` in `.light.png` is an ordinary static file to the publish allowlist, the link check and the index audit, and each one adds one to the page baseline's static-file count. - **Each is shown at its own size, at one scale.** The page's `{:width height}` is the dark - picture's; the light `` gets it scaled by the two files' pixel sizes, which `discover` - reads from their PNG headers on the main thread (`pairSizes`) and the workers receive with the - shared render data. The Light theme lays the IDE out a few pixels differently (the toolbar + picture's; the light `` gets it scaled by the two files' pixel sizes, which the + `discoverRead:i` lanes read from their PNG headers (`picturePairs` names the pairs) and the + workers receive with the shared render data. The Light theme lays the IDE out a few pixels differently (the toolbar 4 CSS px shorter, a panel's title bar 3, some buttons narrower), so a light screenshot is up to a few pixels off the dark one's size. Forcing the dark size on it instead either pulls neighbouring UI into the frame (a line of the blue title bar over every light toolbar) or @@ -1410,8 +1617,17 @@ SVGs: online and book do, offline (and so the help archive) does not. Why: - **An offline tree that shows PNGs holds no picture SVG.** `tbdocs.mjs` adds each one's path to `offline_exclude` in memory, so the offline copy, the help archive, the offline link check and the index audit agree without knowing about pictures. That adds a few hundred literal - patterns, so `offlineExcluded` (and its copy in `check-tree.mjs`) compares a pattern with no - wildcard as a string instead of compiling it. The archive is a stored zip, 37 MB without + patterns, and `dispatch` tests every path of both trees against the list, so the list is + compiled once (`matchesAny`, [builder/fnmatch.mjs](builder/fnmatch.mjs), which + `offlineExcluded` and `check-tree.mjs` both call): the patterns with no wildcard in a `Set`, + the others as regular expressions. Testing each path against each pattern, with a regular + expression made for every test, was most of `dispatch`: 0.32 to 0.39 s on four CPUs + (`start /affinity F`), 0.07 to 0.12 s since; 0.14 s and 0.05 s on sixteen. On CI (one run + each, the second on a faster runner: 16.5 s against 24 s in all) about 0.6 s became about + 0.1 s, and the first render started near 0.9 s where it had started near 1.5 s. What is left in + `dispatch` is the JSON of the shared payload (about 10 ms); its `submit` is the subject of + [The pages' text does not go through the main thread's JSON](#the-pages-text-does-not-go-through-the-main-threads-json). + The archive is a stored zip, 37 MB without the SVGs, and the 310 of them would add 18 MB. - **A picture's SVG is never inlined.** `figurePlugin` inlines a diagram's SVG in its figure; a picture's (`isPictureSvg`: an `.svg` with its `.png` beside it) stays an `` in the diff --git a/WIP.HelpAddin.md b/WIP.HelpAddin.md index 4549e6653..f24570bb2 100644 --- a/WIP.HelpAddin.md +++ b/WIP.HelpAddin.md @@ -634,7 +634,7 @@ The table gives each answer in brief; the sections above have the detail. ### Stage 3: the symbol index, generated by the docs build -The index is the `symbolIndex` task of the build, in [builder/symbols.mjs](builder/symbols.mjs), +The index is made by the `symbolPlace` task of the build and written by `symbolIndex`, in [builder/symbols.mjs](builder/symbols.mjs), and it publishes [`/tB/symbols.json`](docs/Documentation/Permanent-Links.md#the-symbol-index) --- under `/tB/` because the file is part of the same contract as the URLs in it, and its URL is fixed from here on. Permanent Links documents the format for any reader; diff --git a/WIP.Search.md b/WIP.Search.md index 016484f14..21269a6d0 100644 --- a/WIP.Search.md +++ b/WIP.Search.md @@ -371,10 +371,11 @@ single boost: have a container -- a bare statement or operator does not), space-separated and deduplicated. Boost 500 (see "Qualified names and stem twins"). -- In the build, `searchData` also waits for `symbolIndex`. Both run on the - main thread after `renderJoin`. `symbolIndex` returns its symbols, and - `searchData` joins them by URL before it writes (`joinSymbolsToEntries` in - `search.mjs`). Workers derive sections; the join is a map lookup per entry. +- In the build, `searchEntries` waits for `symbolPlace`. Both run on the + main thread after `renderJoin`. `symbolPlace` returns its symbols, and + `searchEntries` joins them by URL (`joinSymbolsToEntries` in `search.mjs`). + Workers derive sections; the join is a map lookup per entry. `searchData` + writes the file afterwards. - `renderEntryString` adds `names` / `qualified` only when non-empty, so a page with no symbols produces the same bytes as without the join. @@ -564,35 +565,86 @@ gzipped). With the one file, the page shows results 0.86 to 0.99 s after the keystroke, the typing and the drawing included, as with two; offline, 2.1 to 2.2 s (1.6 s with two scripts, the entries then an object literal). -**The build makes it on threads** (`builder/search-index.mjs`, -`search-index-worker.mjs`). On one thread lunr takes 3.6 to 4.8 s: `add()` -76% of it, the field vectors 13%, the token set 6% (never needed here: it is -not in the JSON, and `Index.load` makes it), the average lengths and the -fields' preparation the rest. lunr cannot merge two indexes, but `add()` is -independent per entry, so each thread adds a contiguous run of the entries; -the build merges their postings, numbers every term in the order a single -build first meets it (a thread's terms in its own order, the threads in +**The build makes it in slices, on its lanes** (`builder/search-index.mjs`; +the tasks `indexSlices`, `indexAdd:i`, `indexMerge`, `indexTerms`, +`indexVectors:i` and `searchIndex` in `tbdocs.mjs`). On one thread lunr takes +3.6 to 4.8 s: `add()` 76% of it, the field vectors 13%, the token set 6% +(never needed here: it is not in the JSON, and `Index.load` makes it), the +average lengths and the fields' preparation the rest. lunr cannot merge two +indexes, but `add()` is independent per entry, so each slice, a contiguous +run of the entries, is added to a builder of its own on a lane; +`indexMerge` merges their postings, numbers every term in the order a single +build first meets it (a slice's terms in its own order, the slices in entry order; never in key order, which puts number-like terms first), sums each term's document count and each field's length, computes `lunr.idf` and -the averages (the `index` field's pinned at 1), and has each thread make its +the averages (the `index` field's pinned at 1), and each slice's lane makes its entries' vectors with lunr's own `createFieldVectors`, `lunr.idf` answering from those totals. The JSON is written as `toJSON` writes it. The result is -byte for byte `JSON.stringify(lunr(config))` for any number of threads, on -the site (checked at 1, 3 and 8 threads) and on `test/search-index.test.mjs`'s -fixture, which fails when the pinned average or the term order is broken. -On 16 threads: 4.8 s on one, 2.8 on two, 1.9 on four, 1.6 on six, 1.4 on -eight; the build uses half the machine, at most eight, and one for every 500 -entries. - -**What it costs the build.** The `searchIndex` task runs on a lane, reading -`search-data.json` from disk: as a main-thread task it would hold back -`bookPayload`, `writeAux` and `writeOffline` (the main thread runs one task -at a time), at a cost of 1.9 s. On a lane it takes about 2.3 s after -`searchData`, and it is the last task of a build without the help -archive (about 1.7 s more in `compare_trees`, 7.9 s); with the archive, -`helpArchive` waits for it. The index adds about 8.4 MB to the help archive -and to the add-in's project download (owner: fine, for now). The build time -is the price of the index (owner). +byte for byte `JSON.stringify(lunr(config))` for any number of slices, on +the site (`compare_trees` against the build that made it on threads of its +own) and on `test/search-index.test.mjs`'s fixture, which fails when the +pinned average or the term order is broken. + +**It was once made on threads the task started itself**, half the machine's +and at most eight, which the Gantt chart did not show and which left the lanes +idle beside them; no task starts a thread now (WIP.Build.md, "No task starts a +thread"). The slices are of about equal text, not of equal entries, since +adding an entry costs about what its text is long: of eight slices the +longest then takes 0.71 s and the shortest 0.54 s. There are two for each +lane, so that a lane which finishes early takes another while a lane busy +with the PDF tree catches up, and one for every 500 entries at most. The +total does not grow with the slices: 6.1 s of CPU as one slice, 4.5 to 5.2 s +as 2 to 32, on the dev box. + +**Adding the entries during render was considered and not done** (owner asked, +2026-11-17). An entry has its final form only once every page is rendered: +its number depends on every entry before it and on the term entries +`settleLabels` drops, its `names`, `qualified` and `primary` come from the +symbol index, `qualified` needs the stem twins of all entries, and its index +terms and the words appended to its content come from `settleLabels` too. The +fields known at render time (title, content, page, URL) could be indexed then +under provisional numbers, in a builder of their own, and patched afterwards. +It would not shorten a build on a 4-core runner: every lane is busy for the +whole of render, so the index's CPU would lengthen render by what it took off +the tail. The only idle time it could use is the ragged end of render, up to +0.3 s on some of 16 lanes, and one slice for each of the render chunks would be +about five times the builders. + +**What the lanes wait for after the last render chunk** is three main-thread +tasks, `symbolPlace`, `searchEntries` and `indexSlices`, with every lane idle, +so they do only what needs every page (`tbdocs.mjs`, "From the last render +chunk to the search index's slices"). The rule for anything added there: what +one page or one entry decides is done by the lane that renders it, what is +known from the start is read during render, and what only writes a file comes +after `indexSlices`. So the render lanes read the headings of the pages the +symbol index reads, work out each entry's settle keys (`entryKeys`: the +normalising was most of `settleLabels`), and pack each chunk's entries as the +head and tail of their text in `search-data.json` into a SharedArrayBuffer +(`packSearchEntries`). The index's lanes read their entries from those +buffers, and a slice's payload holds only where its entries are and the fields +decided since (`planIndexSegments`); `searchData` copies the same bytes into +the file around each entry's number and late fields. Before, the entries went +to the lanes a second time, as JSON the main thread wrote from a parse of the +file it had just written. + +Measured on the dev box (16 threads), from the end of the last render chunk +to the end of `indexSlices`: 0.25 to 0.32 s before and 0.09 to 0.15 s after +in a full build, 0.37 to 0.38 s and 0.15 to 0.25 s on 4 CPUs, 0.26 to 0.31 s +and 0.08 to 0.12 s in a serve rebuild. What is left, by a CPU profile of the +main thread: `deriveSymbolIndex` about 45 ms, `settleLabels` and the join about +35 ms, the stem twins about 20 ms, the plan and its payload about 20 ms. Not +done: making `deriveSymbolIndex` faster (`placeOwnPages` goes through every +page of a folder for every type), and the stem twins on a lane while the main +thread settles the entries (they need only the symbols and which URLs an entry +matched). An entry's settle keys go beside the entries, not on them: +`delete` of a property on each of 13,500 entries took 11 ms. + +**What it costs the build.** About 5 s of CPU, spread over the lanes after +`indexSlices`, and about 0.6 s on the main thread for `indexMerge`, +`indexTerms` and the writing. `archiveLate` waits for it, and deflates +`search-index.js` for the help archive in pieces on the lanes. The index adds +about 8.4 MB to the help archive and to the add-in's project download (owner: +fine, for now). The build time is the price of the index (owner). ## Step numbers in code comments diff --git a/WIP.md b/WIP.md index 9a21e2a5d..a924ec12e 100644 --- a/WIP.md +++ b/WIP.md @@ -275,6 +275,8 @@ The site builds via [builder/](builder/), a custom Node.js static site generator The task-graph scheduler and parallelisation are described in [builder/PLAN-scheduler.md](builder/PLAN-scheduler.md). A task that never finishes fails the build after `--stall-timeout` seconds ([WIP.Build.md](WIP.Build.md#a-hung-build-times-out-and-says-where-it-hung)). +**No task of the build starts a thread** (owner): the lanes are its only threads. Work that should run in parallel is split into lane tasks with `fanOut` (`builder/fan-out.mjs`), so that the scheduler places it and the Gantt chart shows it. A task starts no worker thread and no process for its work, and puts no CPU work on Node's thread pool, which zlib's functions without `Sync` in their name do. `check_lint.mjs` refuses the imports; the reasons and the exceptions are in [WIP.Build.md](WIP.Build.md#no-task-starts-a-thread). + ### Compiling the reference's own code samples No build gate evaluates a `tb` fence: `check_code_regions.mjs` only protects its diff --git a/biome.jsonc b/biome.jsonc index 2db474633..40047cbfb 100644 --- a/biome.jsonc +++ b/biome.jsonc @@ -102,6 +102,17 @@ // exception is scripts/impexp.mjs, which builder/addin-project.mjs packs // the help add-in's project file with: it imports nothing, the build // already publishes it, and check_tree_fresh.mjs watches it by name. + // + // `paths` is the other rule here: no task of the build starts a thread + // (WIP.Build.md, "No task starts a thread"). The lanes are the build's + // threads, and work that should run in parallel is split into lane + // tasks (builder/fan-out.mjs), so that the scheduler places it and the + // Gantt chart shows it. So nothing in builder/ may import + // worker_threads or cluster, start a process, or put CPU work on + // Node's thread pool, which is what zlib's functions do unless their + // name ends in Sync. The overrides after this one name the files that + // may: each repeats `patterns`, since an override replaces the rule's + // options whole. "includes": ["builder/**/*.mjs"], "linter": { "rules": { @@ -114,7 +125,86 @@ "group": ["**/scripts/**", "!**/scripts/impexp.mjs"], "message": "builder/ must not depend on scripts/." } - ] + ], + "paths": { + "node:worker_threads": "No task starts a thread: split the work into lane tasks (builder/fan-out.mjs). Only worker-pool.mjs and cpu-worker.mjs import worker_threads.", + "worker_threads": "No task starts a thread: split the work into lane tasks (builder/fan-out.mjs). Only worker-pool.mjs and cpu-worker.mjs import worker_threads.", + "node:cluster": "No task starts a process: split the work into lane tasks (builder/fan-out.mjs).", + "cluster": "No task starts a process: split the work into lane tasks (builder/fan-out.mjs).", + "node:child_process": "No task starts a process for its work: split it into lane tasks (builder/fan-out.mjs). Only build-info.mjs and addin-project.mjs run a program, git.", + "child_process": "No task starts a process for its work: split it into lane tasks (builder/fan-out.mjs). Only build-info.mjs and addin-project.mjs run a program, git.", + "node:zlib": { + "allowImportNames": [ + "constants", + "crc32", + "deflateSync", + "deflateRawSync", + "inflateSync", + "inflateRawSync", + "gzipSync", + "gunzipSync", + "unzipSync", + "brotliCompressSync", + "brotliDecompressSync" + ], + "message": "Import zlib's Sync functions by name: the others run on Node's thread pool, outside the lanes. Split CPU work into lane tasks (builder/fan-out.mjs)." + }, + "zlib": "Import from node:zlib, by name." + } + } + } + } + } + } + }, + { + // The two modules that are the lanes: the pool that starts them, and + // the harness each one runs. + "includes": ["builder/worker-pool.mjs", "builder/cpu-worker.mjs"], + "linter": { + "rules": { + "style": { + "noRestrictedImports": { + "level": "error", + "options": { + "patterns": [ + { + "group": ["**/scripts/**", "!**/scripts/impexp.mjs"], + "message": "builder/ must not depend on scripts/." + } + ], + "paths": { + "node:cluster": "No task starts a process: split the work into lane tasks (builder/fan-out.mjs).", + "node:child_process": "No task starts a process for its work: split it into lane tasks (builder/fan-out.mjs).", + "node:zlib": "The lanes' own modules deflate nothing: import the module that does." + } + } + } + } + } + } + }, + { + // The two modules that run a program: git, for the build's commit and + // for the files the add-in's project file packs. + "includes": ["builder/build-info.mjs", "builder/addin-project.mjs"], + "linter": { + "rules": { + "style": { + "noRestrictedImports": { + "level": "error", + "options": { + "patterns": [ + { + "group": ["**/scripts/**", "!**/scripts/impexp.mjs"], + "message": "builder/ must not depend on scripts/." + } + ], + "paths": { + "node:worker_threads": "No task starts a thread: split the work into lane tasks (builder/fan-out.mjs).", + "node:cluster": "No task starts a process: split the work into lane tasks (builder/fan-out.mjs).", + "node:zlib": "These modules deflate nothing: import the module that does." + } } } } @@ -125,6 +215,11 @@ // lib/ holds modules every other part of the tooling may import // (lib/README.md), so it imports none of them; a lib/ module that reached // into scripts/ would take builder/ there with it. + // + // The build imports lib/, so the thread rule above holds here for what + // lib/ uses today: no thread of its own, and zlib's Sync functions by + // name. A tool outside the build that needs a thread starts it in its + // own module, not in lib/. "includes": ["lib/**/*.mjs"], "linter": { "rules": { @@ -145,7 +240,28 @@ ], "message": "lib/ must not import builder/, scripts/, book/, eval/, wisdom/, indexer/ or test/." } - ] + ], + "paths": { + "node:worker_threads": "lib/ starts no thread: the build imports it, and no task of the build starts a thread (WIP.Build.md).", + "worker_threads": "lib/ starts no thread: the build imports it, and no task of the build starts a thread (WIP.Build.md).", + "node:zlib": { + "allowImportNames": [ + "constants", + "crc32", + "deflateSync", + "deflateRawSync", + "inflateSync", + "inflateRawSync", + "gzipSync", + "gunzipSync", + "unzipSync", + "brotliCompressSync", + "brotliDecompressSync" + ], + "message": "Import zlib's Sync functions by name: the others run on Node's thread pool, outside the build's lanes (WIP.Build.md, \"No task starts a thread\")." + }, + "zlib": "Import from node:zlib, by name." + } } } } diff --git a/builder/README.md b/builder/README.md index e4d4b6992..1a4c7553a 100644 --- a/builder/README.md +++ b/builder/README.md @@ -102,7 +102,7 @@ render-worker sub-stage. | Phase | Module(s) | Job | |---|---|---| -| 1 | [discover.mjs](discover.mjs) + [publish-policy.mjs](publish-policy.mjs) | Read .md/.html + frontmatter, enumerate static files, refuse any that is not a publishable type | +| 1 | [discover.mjs](discover.mjs) + [discover-read.mjs](discover-read.mjs) + [publish-policy.mjs](publish-policy.mjs) | List the source tree; on two lanes, read .md/.html + frontmatter and size the static files; refuse any that is not a publishable type | | 2 | [nav.mjs](nav.mjs) / [seo.mjs](seo.mjs) / [book.mjs](book.mjs) / [build-info.mjs](build-info.mjs) / [data.mjs](data.mjs) | Compute nav tree, SEO, book chapters, git commit info, `_data/*.yml` | | 3 | [render.mjs](render.mjs) + [highlight.mjs](highlight.mjs) + [highlight-theme.mjs](highlight-theme.mjs) | Markdown -> HTML body | | 4 | [template.mjs](template.mjs) + [compress.mjs](compress.mjs) | Wrap in layout, anchor-heading injection, whitespace compress | diff --git a/builder/check-tree.mjs b/builder/check-tree.mjs index 3b7389708..e59acbb7a 100644 --- a/builder/check-tree.mjs +++ b/builder/check-tree.mjs @@ -3,8 +3,9 @@ // Split out of builder/check.mjs so the main thread can compute it // during `dispatch` -- which is on the render fan-out's critical path -- // without pulling in link-check.mjs and, through it, htmlparser2's -// ~23 ms import. This module imports nothing but node:path, so a build -// without --check pays nothing for its presence. +// ~23 ms import. This module imports nothing but fnmatch.mjs, the offline +// tree's exclusion rule, so a build without --check pays nothing for its +// presence. // // This is the piece that replaces check_links.mjs's directory walk, and // the piece most able to fail silently. An entry missing here turns a @@ -19,6 +20,8 @@ // reading the site, and links to the markdown copies, which only it has. // nav.html is the whole nav tree, which only an online page fetches; an // offline page has it from nav.js. +import { matchesAny } from "./fnmatch.mjs"; + const ONLINE_AUX = [ "sitemap.xml", "robots.txt", @@ -48,7 +51,7 @@ export function deriveTreeRels( which === "offline" ? (rel) => { const r = posix(rel); - if (!excluded(r, excludePatterns)) rels.add(r); + if (!matchesAny(r, excludePatterns)) rels.add(r); } : (rel) => rels.add(posix(rel)); @@ -68,33 +71,3 @@ export function deriveTreeRels( export function posix(p) { return String(p).replaceAll("\\", "/"); } - -// offlineExcluded's rule, inlined rather than imported: offline-rewrite.mjs -// is a much larger module and this is two functions. -function excluded(rel, patterns) { - if (!patterns || !patterns.length) return false; - return patterns.some((pat) => (/[*?]/.test(pat) ? fnmatch(pat, rel) : pat === rel)); -} - -// File.fnmatch(..., FNM_PATHNAME): `*` does not cross `/`, `**` does. -function fnmatch(pattern, str) { - let re = "^"; - for (let i = 0; i < pattern.length; i++) { - const c = pattern[i]; - if (c === "*") { - if (pattern[i + 1] === "*") { - re += ".*"; - i++; - } else { - re += "[^/]*"; - } - } else if (c === "?") { - re += "[^/]"; - } else if (".+^$()|[]{}\\".includes(c)) { - re += "\\" + c; - } else { - re += c; - } - } - return new RegExp(re + "$").test(str); -} diff --git a/builder/check.mjs b/builder/check.mjs index 81824c969..43d85ff2f 100644 --- a/builder/check.mjs +++ b/builder/check.mjs @@ -339,7 +339,8 @@ export function joinChunks(chunks, { root, tree, basePath = "", relFiles = [], s } else { let data = null; try { - data = JSON.parse(aux.searchJson); + // The file's text, or its bytes as the build wrote them. + data = JSON.parse(String(aux.searchJson)); } catch { data = null; } diff --git a/builder/counts.mjs b/builder/counts.mjs index c26ced13b..4bcc92e85 100644 --- a/builder/counts.mjs +++ b/builder/counts.mjs @@ -76,16 +76,20 @@ // // So `expandDownloadPlaceholders` expands them in the page's source, between // `maskCode` and its `restore` (render.mjs, applyPreRenderRewrites), where code -// is already hidden. Their values are settled before any page renders, because -// the test projects are packed first (tbdocs.mjs, packTests) and the packageTests -// task writes those same bytes. `checkPlaceholders` is `validateCountNames` for -// them: it rejects, naming the file and the line, a path the build does not -// publish or whose size cannot be known before render. The help add-in's -// project is the deliberate case: it embeds the offline tree, which holds every -// page that states a size, so its size would depend on itself. +// is already hidden. A static file's size is known before any page renders. The +// test projects and the published tools are packed on a lane while the pages +// render (tbdocs.mjs, packTests; the packageTests task writes those same bytes), +// so their sizes arrive later: `checkPlaceholders` names the pages that state +// one, the render chunks that hold such a page wait for the downloadSizes task, +// and `packedDownloads` gives them the sizes. `checkPlaceholders` is +// `validateCountNames` for these placeholders: it rejects, naming the file and +// the line, a path the build does not publish or whose size cannot be known +// before the page renders. The help add-in's project is the deliberate case: it +// embeds the offline tree, which holds every page that states a size, so its +// size would depend on itself. import path from "node:path"; -import { blockRegions, maskCode } from "../lib/markdown.mjs"; +import { blockRegions, splitCodeSpans } from "../lib/markdown.mjs"; import { CODE_OR_PRE } from "./code-guard.mjs"; // The optional `:` is a site path for `size`; a count name takes none. @@ -276,13 +280,12 @@ export function substituteCounts(text, counts) { /** * Find every `{{tbdocs:...}}` in a page's source that is not inside code. * - * Masks code with `maskCode` and the site's parser `md`, as the pre-render + * Code is what `maskCode` hides with the site's parser `md`, as the pre-render * rewrites do, so "what is code" has one definition here and there. Without * it this would reject the very examples the documentation of this feature * has to contain. * - * `line` is 1-based in `rawContent`. It is counted with the code put back, - * because a masked fence is one line however many it holds. + * `line` is 1-based in `rawContent`. * * `arg` is the text after the name's colon, or undefined. * @@ -290,10 +293,23 @@ export function substituteCounts(text, counts) { */ export function findCountRefs(rawContent, md) { if (!rawContent.includes("{{tbdocs:")) return []; - const { masked, restore } = maskCode(rawContent.replace(/\r\n?/g, "\n"), { md }); + // What maskCode would leave of the page, worked out for the lines that hold a + // placeholder alone: a line of a fence is code whole, and any other line is + // code in its code spans. A placeholder cannot span lines, so the lines can be + // read one by one, and masking the whole of each page that holds a placeholder + // was half of markdownInit, which every render waits for. + const src = rawContent.replace(/\r\n?/g, "\n"); + const lines = src.split("\n"); + const fenced = new Uint8Array(lines.length); + for (const r of blockRegions(src, { md })) if (r.type === "fence") fenced.fill(1, r.start, r.end); const out = []; - for (const m of masked.matchAll(PLACEHOLDER_RE)) { - out.push({ name: m[1], arg: m[2], line: restore(masked.slice(0, m.index)).split("\n").length }); + for (const [i, text] of lines.entries()) { + if (fenced[i] || !text.includes("{{tbdocs:")) continue; + // A code span is replaced by what cannot be part of a placeholder's name. + const prose = splitCodeSpans(text) + .map((part) => (part.code ? "`\u{0}`" : part.text)) + .join(""); + for (const m of prose.matchAll(PLACEHOLDER_RE)) out.push({ name: m[1], arg: m[2], line: i + 1 }); } return out; } @@ -338,15 +354,21 @@ function editDistance(a, b) { * It also checks the two download placeholders against `downloads` (from * `deriveDownloads`; null when the caller has none, which makes them errors) and * returns the size of each file a `size` placeholder names, for the render - * workers. + * workers. A file in `downloads.packed` has no size yet: its placeholder is + * accepted, and so is the table of test projects, and the page is named in + * `late`, for the build to render it once `packedDownloads` has the sizes. * - * @returns {{problems: string[], sizes: Record}} one message per - * bad reference, empty meaning clean; and the bytes of each file named + * @returns {{problems: string[], sizes: Record, packedArgs: Record, + * late: string[]}} one message per bad reference, empty meaning clean; the bytes of each file + * named; the path of each packed file named, by the placeholder's argument; and the `srcRel` + * of each page that states a packed file's size or lists the test projects */ export function checkPlaceholders(pages, counts, downloads, md) { const names = [...Object.keys(counts), ...DOWNLOAD_NAMES].sort(); const problems = []; const sizes = {}; + const packedArgs = {}; + const late = new Set(); for (const p of pages) { for (const { name, arg, line } of findCountRefs(p.rawContent ?? "", md)) { const where = `${p.srcRel}:${line + (p.contentLine ?? 1) - 1}`; @@ -358,11 +380,15 @@ export function checkPlaceholders(pages, counts, downloads, md) { const rel = arg.replace(/^\/+/, ""); const bytes = downloads.files.get(rel); if (bytes !== undefined) sizes[arg] = bytes; - else refuse(downloads.refused.get(rel) ?? notPublished(rel, downloads)); + else if (downloads.packed?.has(rel)) { + packedArgs[arg] = rel; + late.add(p.srcRel); + } else refuse(downloads.refused.get(rel) ?? notPublished(rel, downloads)); } } else if (name === ROWS_NAME) { if (arg) refuse("takes no argument"); else if (!downloads) refuse("this build has no downloads to list"); + else late.add(p.srcRel); } else if (Object.hasOwn(counts, name)) { if (arg) refuse("a count name takes no argument"); } else { @@ -376,7 +402,7 @@ export function checkPlaceholders(pages, counts, downloads, md) { } } } - return { problems, sizes }; + return { problems, sizes, packedArgs, late: [...late] }; } /** `checkPlaceholders` for a caller with no downloads: the problems alone. */ @@ -388,7 +414,8 @@ export function validateCountNames(pages, counts, md) { // elsewhere, the usual slip. function notPublished(rel, downloads) { const base = path.posix.basename(rel); - const same = [...downloads.files.keys()].filter((k) => path.posix.basename(k) === base); + const known = [...downloads.files.keys(), ...(downloads.packed ?? [])]; + const same = known.filter((k) => path.posix.basename(k) === base); return ( `the build does not publish ${rel}; a size is known for the static files under docs/, the ` + "bundle_extra files and the package test projects" + @@ -406,21 +433,21 @@ const REGENERATED_REFUSAL = "so its size cannot be known before render"; /** - * What the download placeholders know, from build state. + * What the download placeholders know before any page renders, from build state. * - * `files` holds the bytes of every file whose size is settled before any page renders: the - * static files discover found (the `bundle_extra` files among them), and the package test - * projects. `refused` holds the paths that are published but cannot be sized, with the reason. + * `files` holds the bytes of every file whose size is settled by then: the static files + * discover found (the `bundle_extra` files among them). `refused` holds the paths that are + * published but cannot be sized, with the reason. `packed` holds the paths of the package test + * projects and the published tools, which are packed while the pages render: each can be + * sized, by `packedDownloads`, once it is. * * @param {object} state scheduler state: needs `staticFiles` * @param {object} extra - * @param {{dest: string, packed: {pkg: string, rel: string, bytes: Buffer}[]}|null} extra.tests - * the packed test projects, and where the online tree has them + * @param {string[]} [extra.packed] the packed files' paths in the online tree * @param {string|null} extra.addinDest the help add-in's project file, which is refused - * @returns {{files: Map, refused: Map, - * tests: {dest: string, packages: {pkg: string, rel: string, bytes: number}[]}}} + * @returns {{files: Map, refused: Map, packed: Set}} */ -export function deriveDownloads(state, { tests = null, addinDest = null }) { +export function deriveDownloads(state, { packed = [], addinDest = null }) { const files = new Map(); const refused = new Map(); for (const f of state.staticFiles ?? []) { @@ -431,12 +458,33 @@ export function deriveDownloads(state, { tests = null, addinDest = null }) { else files.set(rel, f.size); } if (addinDest) refused.set(addinDest, HELP_ADDIN_REFUSAL); - // Every packed file can be sized; only the test projects are rows of the table. - for (const { rel, bytes } of tests?.packed ?? []) files.set(rel, bytes.length); - const packages = (tests?.packed ?? []) + return { files, refused, packed: new Set(packed) }; +} + +/** + * The downloads as the late pages need them: `sizes` with each packed file a placeholder + * names added, and `tests`, the rows of the test projects' table. Every packed file can be + * sized; only the test projects are rows. + * + * @param {object} o + * @param {Record} o.sizes the sizes known before render (`checkPlaceholders`) + * @param {Record} o.packedArgs the packed files the pages name (`checkPlaceholders`) + * @param {string} o.dest where the online tree has the test projects + * @param {{pkg: string, rel: string, bytes: Uint8Array, kind: string}[]} o.packed the packed files + * @returns {{sizes: Record, + * tests: {dest: string, packages: {pkg: string, rel: string, bytes: number}[]}}} + */ +export function packedDownloads({ sizes, packedArgs, dest, packed }) { + const bytesOf = new Map(packed.map(({ rel, bytes }) => [rel, bytes.length])); + const all = { ...sizes }; + for (const [arg, rel] of Object.entries(packedArgs)) { + if (!bytesOf.has(rel)) throw new Error(`{{tbdocs:size:${arg}}}: ${rel} was to be packed, and was not`); + all[arg] = bytesOf.get(rel); + } + const packages = packed .filter((t) => t.kind !== "tool") .map(({ pkg, rel, bytes }) => ({ pkg, rel, bytes: bytes.length })); - return { files, refused, tests: { dest: tests?.dest ?? "", packages } }; + return { sizes: all, tests: { dest, packages } }; } /** `43 KB` below a mebibyte (never less than 1 KB), `1.2 MB` from there. */ @@ -463,11 +511,13 @@ function linkFrom(permalink, target) { * the caller has already masked of code. * * `downloads` is the object the build hands the render workers: `sizes`, the bytes of each - * path the pages name, and `tests`, as `deriveDownloads` returns it. `checkPlaceholders` has - * rejected what cannot be expanded, so a miss here is a bug in the build and throws. + * path the pages name, and `tests`, the test projects' rows. Before the files are packed it + * has the static files' sizes and no `tests`; a page that needs more renders after + * `packedDownloads` has it. `checkPlaceholders` has rejected what cannot be expanded and named + * the pages that wait, so a miss here is a bug in the build and throws. * * @param {string} src - * @param {{sizes: Record, tests: {dest: string, packages: object[]}}} downloads + * @param {{sizes: Record, tests: {dest: string, packages: object[]}|null}} downloads * @param {string} permalink the page's URL; the table rows' links are relative to it */ export function expandDownloadPlaceholders(src, downloads, permalink) { @@ -476,10 +526,14 @@ export function expandDownloadPlaceholders(src, downloads, permalink) { if (name === SIZE_NAME && arg !== undefined) { const bytes = downloads.sizes[arg]; if (bytes === undefined) - throw new Error(`{{tbdocs:size:${arg}}} has no size; checkPlaceholders should have refused it`); + throw new Error( + `{{tbdocs:size:${arg}}} has no size; checkPlaceholders should have refused it, or named its page as one that waits for the packed files`, + ); return formatSize(bytes); } if (name === ROWS_NAME && arg === undefined) { + if (!downloads.tests) + throw new Error("{{tbdocs:packageTestRows}} was expanded before the test projects were packed"); const { dest, packages } = downloads.tests; return packages .map(({ pkg, rel, bytes }) => { diff --git a/builder/cpu-worker.mjs b/builder/cpu-worker.mjs index 359a5ca98..30329c206 100644 --- a/builder/cpu-worker.mjs +++ b/builder/cpu-worker.mjs @@ -6,24 +6,49 @@ import { promises as fsP } from "node:fs"; import path from "node:path"; import { parentPort, workerData } from "node:worker_threads"; -import { compileLightScss, compileDarkScss } from "./scss.mjs"; -import { regenerateDot } from "./dot.mjs"; -import { captureBuildInfo } from "./build-info.mjs"; -import { helpArchiveStep } from "./help-archive-step.mjs"; -import { writePdf } from "./pdf.mjs"; -import { unpackBookPayload } from "./book-payload.mjs"; -import { REPO_ROOT } from "../lib/repo-paths.mjs"; - -import { createMarkdownIt, renderPhase } from "./render.mjs"; -import { markdownCopy, markdownCopyRel } from "./markdown-copy.mjs"; -import { navTreeVersion, renderFullNav, templatePhase, withOnlineNav, withPartialNav } from "./template.mjs"; +import { packPageText, pageText, readPiece } from "./discover-read.mjs"; import { unpackShared } from "./sab-broadcast.mjs"; -import { deriveSearchEntries } from "./search.mjs"; -import { writeSearchIndex } from "./search-index.mjs"; -import { computeChunkSeo } from "./seo.mjs"; -import { pictureSvgOutputs, pngPictures } from "./theme-pictures.mjs"; -import { deriveOfflinePage, isWebsiteOnlyLink, websiteOf } from "./offline-rewrite.mjs"; -import { normalizeBaseurl } from "./url.mjs"; + +// A lane boots in two stages. The first is this module's static imports: the +// scheduler, and what discoverRead needs, which is the first work of a build +// and needs little (discover-read.mjs). A lane is in the pull loop after it, +// and two lanes read the source tree while the others load the rest. +// +// The second stage is everything else, below: the renderer and its plugins, +// the search index, the archive. A lane loads it before its first task that is +// not a discoverRead (loadRest, from the pull loop), and reports it as a +// second boot bar. The names are module-level bindings that loadRest fills, so +// that the handlers read as they would with static imports. +// biome-ignore format: one module per line +let compileLightScss, compileDarkScss, regenerateDot, captureBuildInfo, deflateGroup, writePdf, unpackBookPayload, + createMarkdownIt, renderPhase, markdownCopy, markdownCopyRel, + navTreeVersion, renderFullNav, templatePhase, withOnlineNav, withPartialNav, + deriveSearchEntries, entryKeys, labelKey, packSearchEntries, readSearchEntries, + addSlice, loadSearchLunr, sliceDocs, sliceVectors, unpackTotals, + headingsOf, isSymbolPage, computeChunkSeo, pictureSvgOutputs, pngPictures, + deriveOfflinePage, isWebsiteOnlyLink, websiteOf, normalizeBaseurl; +let _rest = null; +const loadRest = () => + (_rest ??= (async () => { + const start = Date.now(); + ({ compileLightScss, compileDarkScss } = await import("./scss.mjs")); + ({ regenerateDot } = await import("./dot.mjs")); + ({ captureBuildInfo } = await import("./build-info.mjs")); + ({ deflateGroup } = await import("./help-archive-step.mjs")); + ({ writePdf } = await import("./pdf.mjs")); + ({ unpackBookPayload } = await import("./book-payload.mjs")); + ({ createMarkdownIt, renderPhase } = await import("./render.mjs")); + ({ markdownCopy, markdownCopyRel } = await import("./markdown-copy.mjs")); + ({ navTreeVersion, renderFullNav, templatePhase, withOnlineNav, withPartialNav } = await import("./template.mjs")); + ({ deriveSearchEntries, entryKeys, labelKey, packSearchEntries, readSearchEntries } = await import("./search.mjs")); + ({ addSlice, loadSearchLunr, sliceDocs, sliceVectors, unpackTotals } = await import("./search-index.mjs")); + ({ headingsOf, isSymbolPage } = await import("./symbols.mjs")); + ({ computeChunkSeo } = await import("./seo.mjs")); + ({ pictureSvgOutputs, pngPictures } = await import("./theme-pictures.mjs")); + ({ deriveOfflinePage, isWebsiteOnlyLink, websiteOf } = await import("./offline-rewrite.mjs")); + ({ normalizeBaseurl } = await import("./url.mjs")); + parentPort.postMessage({ coldBoot: { type: "cold2", start, end: Date.now() } }); + })()); import { createViews, @@ -57,8 +82,8 @@ let _shared = null; // _sharedSAB decoded, once per lane // What dispatch broadcast. A task that reads it runs after dispatch, but the // message is not here by then: this lane may still be inside the pull loop -// that claimed the task, so yield until it lands, as taskData does. A -// searchIndex claimed that way threw here. +// that claimed the task, so yield until it lands, as taskData does. A task +// claimed that way threw here. async function sharedData() { while (!_sharedSAB) await new Promise((resolve) => setImmediate(resolve)); _shared ??= unpackShared(_sharedSAB); @@ -68,6 +93,16 @@ async function sharedData() { // ── Handler table ─────────────────────────────────────────────────────────── const handlers = { + // One piece of the source tree (tbdocs.mjs, discoverList): its pages read + // and their frontmatter parsed, its static files sized. The one handler + // that runs after the first stage of the boot alone. + // The pages' text goes back a second time, packed for the render lanes + // (packPageText): the buffer is shared, not copied. + async discoverRead(taskIdx) { + const result = readPiece(ctx.srcRoot, await fanOutPayload(taskIdx)); + return { ...result, text: packPageText(result.pages) }; + }, + async warmInit() { const { initHighlighter } = await import("./highlight.mjs"); await initHighlighter(); @@ -81,7 +116,6 @@ const handlers = { linkTablesData, staticFilesArr, baseurl, - buildInfo, sitePathsArr, onlineSitePathsArr, skipOffline, @@ -92,6 +126,7 @@ const handlers = { pictureSizes, counts, downloads, + latePages, } = await sharedData(); const { initHighlighter } = await import("./highlight.mjs"); @@ -114,7 +149,7 @@ const handlers = { downloads, termPrefixes: siteData.config.search?.term_entries ?? [], }); - const site = { ...siteData, markdown, buildInfo }; + const site = { ...siteData, markdown }; let offlineBase = null; if (!skipOffline) { @@ -148,7 +183,7 @@ const handlers = { // each picture's SVG named back as its PNG; the others get it as rendered. const svgOutputs = pictureSvgOutputs(siteData.config); const asPng = (html) => pngPictures(html, staticFiles, baseurl || ""); - _renderEnv = { site, initData, offlineBase, svgOutputs, asPng }; + _renderEnv = { site, initData, offlineBase, svgOutputs, asPng, latePages: new Set(latePages ?? []) }; return {}; }, @@ -220,29 +255,50 @@ const handlers = { return { buildInfo }; }, - // On a worker because it is the main thread's longest task after the - // pages are written, and it needs nothing from the main thread that - // dispatch has not already broadcast: it reads the offline tree from disk. - async helpArchive() { - const { skipOffline } = await sharedData(); - return helpArchiveStep({ - src: path.relative(REPO_ROOT, ctx.srcRoot).replaceAll(path.sep, "/"), - offlineRoot: skipOffline ? null : `${ctx.destRoot}-offline`, - serve: !!ctx.opts.serve, - dryRun: !!ctx.opts.dryRun, - disabled: !!ctx.opts.skipHelpArchive, - }); + // The contributed packages' test projects and published tools, packed in + // memory (package-tests.mjs) from the package_tests entry that config + // broadcast. The bytes go back to the main thread, where downloadSizes reads + // their sizes and packageTests writes them. A failure goes back too, for + // packageTests to report: it fails the build without stopping it. The + // module is imported here, by the one lane that packs. + async packTests() { + const { packAllPackageTests, packageTestsOf } = await import("./package-tests.mjs"); + const cfg = packageTestsOf({ package_tests: unpackShared(await taskData("packageTests")) }, ctx.srcRoot); + if (!cfg) return {}; + try { + return await packAllPackageTests(cfg); + } catch (err) { + return { failed: true, error: err.message }; + } }, - // search-index.json, the entries of the search-data.json searchData wrote - // with their lunr index, and the offline tree's search-index.js. On a lane - // because the main thread runs one task at a time, and the index takes a - // second or two: as a main-thread task it held back the book and the - // offline tree. It builds on threads of its own (search-index.mjs). - async searchIndex() { - if (ctx.opts.dryRun) return { entries: 0, workers: 0, bytes: 0 }; - const { skipOffline } = await sharedData(); - return writeSearchIndex(ctx.destRoot, { offline: !skipOffline }); + // One slice of the search index (search-index.mjs, step 1): its entries + // added to a builder that stays on this lane, for the indexVectors:i pinned + // here; what it returns goes to indexMerge. + // The slice's entries are read from the buffers the render lanes packed + // them into, with what indexSlices decided since beside it in the payload. + async indexAdd(taskIdx) { + const plan = await fanOutPayload(taskIdx); + const { chunks, twins } = await taskData("indexEntries"); + const docs = sliceDocs(plan, (chunk, from, to) => readSearchEntries(chunks[chunk], from, to)); + const { state, added } = addSlice(loadSearchLunr(), docs, twins); + _indexSlices.set(plan.slice, state); + return added; + }, + + // The same slice's field vectors (step 3), with the totals indexMerge + // broadcast; the builder is let go. + async indexVectors(taskIdx) { + const { slice } = await fanOutPayload(taskIdx); + const state = _indexSlices.get(slice); + if (!state) throw new Error(`search index: slice ${slice} was not added on lane ${myLane}`); + _indexSlices.delete(slice); + return sliceVectors(loadSearchLunr(), state, unpackTotals(await taskData("indexTotals"), slice)); + }, + + // One group of the help archive's units (help-archive-step.mjs). + async archiveDeflate(taskIdx) { + return deflateGroup(await fanOutPayload(taskIdx)); }, // The PDF tree, from what bookPayload packed on the main thread. The book @@ -283,10 +339,22 @@ const handlers = { async render(taskIdx) { const offset = Atomics.load(views.payloadOffset, taskIdx); const length = Atomics.load(views.payloadLength, taskIdx); - const chunk = JSON.parse(new TextDecoder().decode(new Uint8Array(_payloadSAB, offset, length))); + const { pages: chunk, texts } = JSON.parse(new TextDecoder().decode(new Uint8Array(_payloadSAB, offset, length))); + // A page's text is not in the payload: it is where the lane that read the + // page packed it (discoverRead), in the buffer discover broadcast. + for (const [i, p] of chunk.entries()) { + const at = texts[i]; + if (at) p.rawContent = pageText(await taskData(`pageText:${at[0]}`), at[1], at[2]); + } const env = _renderEnv; + // A chunk with a late page ran after downloadSizes, which broadcast the + // packed files' sizes: this lane's parser has them from here on. + if (chunk.some((p) => env.latePages.has(p.srcRel))) { + env.site.markdown.downloads = unpackShared(await taskData("downloads")); + } + await renderPhase(chunk, env.site); computeChunkSeo(chunk, env.site.seoSiteTitle, env.site.config, env.site.markdown); await templatePhase(chunk, env.site, env.initData); @@ -345,11 +413,22 @@ const handlers = { } _pendingFlush.push(batch); - // Per-chunk search entries; consolidated on main during searchData. + // Per-chunk search entries; consolidated on main during searchEntries. // Drop `sourcePage` (workers hold cloned page objects, not master // refs) and `i` (chunk-local indices are meaningless; main assigns - // global indices during consolidation). - const searchEntries = deriveSearchEntries(chunk, env.site).map((e) => ({ + // global indices during consolidation). Beside them go the keys + // settleLabels compares each by, with its labels: worked out here rather + // than on the main thread after the last chunk, when every lane waits + // for it. + const keyOf = new Map(); + const key = (s) => { + let k = keyOf.get(s); + if (k === undefined) keyOf.set(s, (k = labelKey(s))); + return k; + }; + const derived = deriveSearchEntries(chunk, env.site); + const searchKeys = derived.map((e) => entryKeys(e, key)); + const searchEntries = derived.map((e) => ({ doc: e.doc, title: e.title, content: e.content, @@ -358,7 +437,6 @@ const handlers = { index: e.index, index_also: e.index_also, indexWritten: e.indexWritten, - labels: e.labels, })); return { @@ -366,8 +444,14 @@ const handlers = { destPath: p.destPath, renderedContent: p.renderedContent, offlineMisses: p.offlineMisses, + // For the symbol index, which every lane waits for likewise. + headings: isSymbolPage(p) && typeof p.renderedContent === "string" ? headingsOf(p.renderedContent) : undefined, })), searchEntries, + searchKeys, + // The same entries for the lanes that build the search index, which + // read them from here: the main thread never sends them on. + searchPacked: packSearchEntries(searchEntries), }; }, }; @@ -382,6 +466,8 @@ let _pendingFlush = []; let _taskData = new Map(); // key → SAB a main-thread task broadcast (broadcastTaskData) let _bookCheck = null; // writePdf's book for checkBook, which is pinned to the same lane +let _indexSlices = new Map(); // search index slice -> its builder, from indexAdd for indexVectors + // The data a main-thread predecessor broadcast for this task. The message // is queued before the predecessor is marked done, but this lane may still // be inside the pull loop that claimed the task, so yield until it lands. @@ -389,6 +475,23 @@ async function taskData(key) { while (!_taskData.has(key)) await new Promise((resolve) => setImmediate(resolve)); return _taskData.get(key); } + +// A fan-out piece's payload (fan-out.mjs): its fan-out's SharedArrayBuffer is +// broadcast as `fan::`, and the scheduling SAB holds where in it +// each piece's JSON is. Waits for the broadcast as taskData does. +const FAN_KEY = /^fan:(\d+):(\d+)$/; +async function fanOutPayload(taskIdx) { + for (;;) { + for (const [key, sab] of _taskData) { + const m = FAN_KEY.exec(key); + if (!m || taskIdx < Number(m[1]) || taskIdx >= Number(m[1]) + Number(m[2])) continue; + const offset = Atomics.load(views.payloadOffset, taskIdx); + const length = Atomics.load(views.payloadLength, taskIdx); + return JSON.parse(new TextDecoder().decode(new Uint8Array(sab, offset, length))); + } + await new Promise((resolve) => setImmediate(resolve)); + } +} let _checkEnv = null; // set by renderEnvInit when --check is on let _checkChunk = null; // builder/check.mjs's checkChunk, imported with it @@ -440,6 +543,7 @@ parentPort.on("message", (msg) => { _pendingFlush = []; _taskData = new Map(); _bookCheck = null; + _indexSlices = new Map(); pullLoop(); return; } @@ -504,6 +608,7 @@ function findIdleTask(views, lane) { // reports its timing and output. Returns false once a throw has been // reported, and the caller then ends the pull loop. async function runPerWorkerTask(taskIdx, meta) { + await loadRest(); const t0 = Date.now(); let output; try { @@ -627,6 +732,7 @@ async function pullLoop() { return; } + if (meta.handlerIdx !== HANDLERS.discoverRead) await loadRest(); const t0 = Date.now(); let result; try { diff --git a/builder/discover-read.mjs b/builder/discover-read.mjs new file mode 100644 index 000000000..b98066460 --- /dev/null +++ b/builder/discover-read.mjs @@ -0,0 +1,158 @@ +// The part of discover that opens files: a page's frontmatter split off and +// parsed into the page object every later phase consumes, a static file's +// size, and a picture pair's dimensions. Apart from discover.mjs so that a lane +// can run it after loading no more than this, the YAML parser and paths.mjs +// (the first stage of a lane's boot, cpu-worker.mjs): discover.mjs itself +// loads the glob library, which only the main thread needs. +// +// Everything here is synchronous. A lane has nothing else to do while it +// reads, and several lanes reading at once is what makes it parallel; the +// asynchronous calls would all queue on libuv's one pool of four threads. + +import { closeSync, openSync, readFileSync, readSync, statSync } from "node:fs"; +import path from "node:path"; + +import { parseFrontmatter, unquotedHashValues } from "../lib/frontmatter.mjs"; +import { permalinkToDestPath } from "./paths.mjs"; + +export const PAGE_EXT = /\.(md|html)$/i; +const IMAGE_SCOPE = /(^|\/)Images\//; + +export const toPosix = (p) => p.replace(/\\/g, "/"); + +/** + * One piece of the source tree (discover.mjs, cutPieces), read one file after + * the other. Every path is relative to `srcRoot`. + * + * @param {string} srcRoot + * @param {object} piece + * @param {string[]} piece.pageRels .md and .html files + * @param {string[]} piece.statSrcs static files to size + * @param {[string, string][]} piece.pairs a light picture's file and its dark picture's + * @returns {{ pages: object[], plain: { srcRel: string, size: number }[], warnings: string[], + * sizes: number[], pairSizes: (number[] | null)[] }} + * the pages among `pageRels`; the files among them with no frontmatter + * (`plain`, which are static files), each with its size; the warnings to + * print; the size of each of `statSrcs`; and for each of `pairs` + * [lightW, lightH, darkW, darkH], or null when either is no PNG + */ +export function readPiece(srcRoot, { pageRels, statSrcs, pairs }) { + const pages = []; + const plain = []; + const warnings = []; + for (const srcRel of pageRels) { + const file = path.join(srcRoot, srcRel); + const parsed = readFrontmatter(readFileSync(file, "utf8"), srcRel, warnings); + if (parsed) pages.push(buildPage(srcRoot, srcRel, parsed)); + // .md/.html without frontmatter falls through to static treatment. + else plain.push({ srcRel: toPosix(srcRel), size: statSync(file).size }); + } + const sizes = statSrcs.map((src) => statSync(path.resolve(srcRoot, src)).size); + const pairSizes = pairs.map(([light, dark]) => { + const l = pngSize(path.resolve(srcRoot, light)); + const d = pngSize(path.resolve(srcRoot, dark)); + return l && d ? [...l, ...d] : null; + }); + return { pages, plain, warnings, sizes, pairSizes }; +} + +/** + * The pages' text (`rawContent`) as UTF-8 in one SharedArrayBuffer, for the + * lanes that render them (tbdocs.mjs: discover broadcasts it, and a render + * chunk's payload names where each page's text is instead of holding it). The + * lane that read the pages packs them, so the main thread never turns the + * site's text into JSON for the chunks. + * + * @param {{ rawContent: string }[]} pages + * @returns {{ sab: SharedArrayBuffer, spans: number[] }} `spans` holds each + * page's offset and length in bytes, two numbers a page, in the pages' order + */ +export function packPageText(pages) { + const spans = []; + let total = 0; + for (const page of pages) { + const length = Buffer.byteLength(page.rawContent, "utf8"); + spans.push(total, length); + total += length; + } + const sab = new SharedArrayBuffer(total); + const bytes = Buffer.from(sab); + for (const [i, page] of pages.entries()) bytes.write(page.rawContent, spans[2 * i], spans[2 * i + 1], "utf8"); + return { sab, spans }; +} + +/** One page's text, from what packPageText packed. */ +export function pageText(sab, offset, length) { + return Buffer.from(sab, offset, length).toString("utf8"); +} + +// A PNG file's width and height in pixels, from its header; null when it is no PNG. +function pngSize(file) { + const fd = openSync(file, "r"); + try { + const b = Buffer.alloc(24); + const bytesRead = readSync(fd, b, 0, 24, 0); + if (bytesRead < 24 || b.toString("latin1", 12, 16) !== "IHDR") return null; + return [b.readUInt32BE(16), b.readUInt32BE(20)]; + } finally { + closeSync(fd); + } +} + +// Every .md and .html passes through here, and `parseFrontmatter` drops a +// leading BOM, so a page an editor saved with one is still a page rather than +// a static asset served as raw markdown. +// +// `contentLine` is the file's 1-based line on which `content` starts, so a +// message about a line of the content can name the line of the file. The +// content is the text after the frontmatter block, so the lines before it are +// the lines of the block. +// +// A value left unquoted that ends in `#` is warned about, not refused: YAML +// drops a `#` after a space as a comment, so `title: Input #` titles the page +// `Input`, while `lang: C#` is read as written. Quoting the value keeps the `#` +// and silences the warning either way. The warning goes into `warnings`, for +// the main thread to print. +function readFrontmatter(raw, srcRel, warnings) { + let parsed; + try { + parsed = parseFrontmatter(raw); + } catch (err) { + throw new Error(`Failed to parse frontmatter in ${srcRel}: ${err.message}`); + } + if (!parsed) return null; + for (const { line, text } of unquotedHashValues(raw)) { + warnings.push( + `discover: ${srcRel}:${line}: an unquoted value ends in #, and YAML drops a # after a space as a comment; quote the value to keep it: ${text.trim()}`, + ); + } + const { data, content } = parsed; + const block = raw.slice(0, raw.length - content.length); + return { data, content, contentLine: (block.match(/\r\n?|\n/g) ?? []).length + 1 }; +} + +function buildPage(srcRoot, srcRel, { data, content, contentLine }) { + const srcRelPosix = toPosix(srcRel); + const ext = path.extname(srcRel).toLowerCase(); + const permalink = computePermalink(data.permalink, srcRelPosix); + const destPath = permalinkToDestPath(permalink); + return { + srcPath: path.join(srcRoot, srcRel), + srcRel: srcRelPosix, + ext, + frontmatter: data, + rawContent: content, + contentLine, + permalink, + destPath, + layoutDefault: data.layout === undefined || data.layout === null, + imageScope: IMAGE_SCOPE.test(srcRelPosix), + }; +} + +function computePermalink(fmPermalink, srcRelPosix) { + if (typeof fmPermalink === "string" && fmPermalink.length > 0) { + return fmPermalink; + } + return "/" + srcRelPosix.replace(PAGE_EXT, "") + ".html"; +} diff --git a/builder/discover.mjs b/builder/discover.mjs index aad54b7b5..e19cd3925 100644 --- a/builder/discover.mjs +++ b/builder/discover.mjs @@ -1,18 +1,26 @@ // Phase 1 of tbdocs: walk the source tree once and produce a normalized // inventory that every later phase consumes. See builder/PLAN-1.md for the // full spec, design decisions, and edge-case handling. +// +// It is three steps, so that the build can give the middle one to its lanes +// (tbdocs.mjs: discoverList, discoverRead:i, discover): listSources and +// cutPieces on the main thread, discover-read.mjs's readPiece for each piece, +// which is every file opened, and assemble on the main thread again. +// `discover` is the same steps in one call and one piece, for the tools that +// want the inventory and have no lanes. import fg from "fast-glob"; -import { promises as fs } from "node:fs"; import path from "node:path"; -import { parseFrontmatter, unquotedHashValues } from "../lib/frontmatter.mjs"; -import { permalinkToDestPath } from "./paths.mjs"; - -const PAGE_EXT = /\.(md|html)$/i; -const IMAGE_SCOPE = /(^|\/)Images\//; +import { PAGE_EXT, readPiece, toPosix } from "./discover-read.mjs"; +import { picturePairs } from "./theme-pictures.mjs"; -export async function discover(srcRoot, ignore = []) { +/** + * The files under `srcRoot` that `ignore` does not leave out, sorted, in two + * lists: the .md and .html files, each a page if it has frontmatter, and the + * others, which are static files. + */ +export async function listSources(srcRoot, ignore = []) { const allFiles = await fg("**/*", { cwd: srcRoot, dot: false, @@ -21,59 +29,100 @@ export async function discover(srcRoot, ignore = []) { ignore, }); allFiles.sort(); + const pageRels = []; + const otherRels = []; + for (const srcRel of allFiles) (PAGE_EXT.test(srcRel) ? pageRels : otherRels).push(srcRel); + return { pageRels, otherRels }; +} +/** + * A listing cut into `count` pieces for readPiece, and what assemble needs to + * put their results together. `extra` is the static files from outside the + * tree ({ src, dest }, `src` relative to the source root: _config.yml's + * bundle_extra), which are sized and paired with the others. + * + * Piece i holds every count-th page file, static file and picture pair from + * the i-th on, so that each piece has its share of every folder: the listing + * is sorted, and a folder's files are alike in size. + */ +export function cutPieces({ pageRels, otherRels }, count, extra = []) { + const statics = [ + ...otherRels.map((rel) => ({ srcRel: toPosix(rel), src: rel, extra: false })), + ...extra.map((e) => ({ srcRel: e.dest, src: e.src, extra: true })), + ]; + const pairs = picturePairs(statics); + const pieces = Array.from({ length: Math.max(1, count) }, () => ({ pageRels: [], statSrcs: [], pairs: [] })); + const share = (list, add) => { + for (const [i, item] of list.entries()) add(pieces[i % pieces.length], item); + }; + share(pageRels, (piece, rel) => piece.pageRels.push(rel)); + share(statics, (piece, s) => piece.statSrcs.push(s.src)); + share(pairs, (piece, [, light, dark]) => piece.pairs.push([light, dark])); + return { pieces, statics, pairs }; +} + +/** + * The inventory, from cutPieces' plan and each piece's result (readPiece), in + * the pieces' order: the pages and the static files, sorted, with the files + * from outside the tree after the others, and the picture pairs' sizes. + */ +export function assemble(srcRoot, { pieces, statics, pairs }, results) { + const count = pieces.length; + // Item j of a shared-out list is item floor(j / count) of piece j % count. + const from = (j, field) => results[j % count][field][Math.floor(j / count)]; const pages = []; const staticFiles = []; + const extras = []; + for (const result of results) { + for (const page of result.pages) pages.push(page); + for (const { srcRel, size } of result.plain) { + staticFiles.push({ srcPath: path.join(srcRoot, srcRel), srcRel, destRel: srcRel, size }); + } + } + for (const [j, s] of statics.entries()) { + const srcPath = s.extra ? path.resolve(srcRoot, s.src) : path.join(srcRoot, s.src); + (s.extra ? extras : staticFiles).push({ srcPath, srcRel: s.srcRel, destRel: s.srcRel, size: from(j, "sizes") }); + } + sortInventory(pages, staticFiles); + staticFiles.push(...extras); + const pictureSizes = Object.create(null); + for (const [j, [light]] of pairs.entries()) { + const size = from(j, "pairSizes"); + if (size) pictureSizes[light] = size; + } + return { pages, staticFiles, pictureSizes }; +} - await Promise.all( - allFiles.map(async (srcRel) => { - const srcPath = path.join(srcRoot, srcRel); - - if (PAGE_EXT.test(srcRel)) { - const raw = await fs.readFile(srcPath, "utf8"); - const parsed = readFrontmatter(raw, srcRel); - if (parsed) { - pages.push(buildPage(srcRoot, srcRel, parsed)); - return; - } - // .md/.html without frontmatter falls through to static treatment. - } - - const stat = await fs.stat(srcPath); - const srcRelPosix = toPosix(srcRel); - staticFiles.push({ - srcPath, - srcRel: srcRelPosix, - destRel: srcRelPosix, - size: stat.size, - }); - }), - ); - - // Jekyll sorts site.pages by basename (`name` = basename with - // extension) via `lib/jekyll/reader.rb:44`'s `site.pages.sort_by! - // (&:name)`. Mirror that, but with an explicit `srcRel` tie-break - // rather than by leaning on Array#sort's stability. - // - // Stability is not enough here, and the reason is easy to miss: - // `pages` is filled from inside the `Promise.all` above, so a page - // is pushed when its `readFile` resolves, NOT in `allFiles` order. - // A stable sort then preserves that I/O completion order for every - // tied basename -- and ~111 folder-style classes are all named - // `index.md`, so the ties are not rare. Two builds of identical - // sources ordered those pages differently, which reordered - // `search-data.json` (545 of 3724 entries moved between two runs of - // the same commit) and made the file non-reproducible. - // - // `allFiles` is sorted by full path, so breaking ties on `srcRel` - // reproduces exactly the input order the old comment claimed was - // already in effect -- same output, now actually deterministic. +// Puts the pages and the static files in the order every later phase relies +// on, in place. +// +// Jekyll sorts site.pages by basename (`name` = basename with extension) via +// `lib/jekyll/reader.rb:44`'s `site.pages.sort_by!(&:name)`. Mirror that, but +// with an explicit `srcRel` tie-break rather than by leaning on Array#sort's +// stability. +// +// Stability is not enough here, and the reason is easy to miss: the pages +// arrive piece by piece, NOT in the listing's order, and before the pieces +// they arrived as each file's read resolved. A stable sort then preserves that +// order for every tied basename -- and ~111 folder-style classes are all named +// `index.md`, so the ties are not rare. Two builds of identical sources +// ordered those pages differently, which reordered `search-data.json` (545 of +// 3724 entries moved between two runs of the same commit) and made the file +// non-reproducible. +// +// Static files keep the full-path sort -- Jekyll's reader sorts them with +// `site.static_files.sort_by!(&:relative_path)`, which is what `bySrcRel` +// does. +function sortInventory(pages, staticFiles) { pages.sort(byName); - // Static files keep the full-path sort -- Jekyll's reader sorts - // them with `site.static_files.sort_by!(&:relative_path)`, which - // is what `bySrcRel` does. staticFiles.sort(bySrcRel); +} +export async function discover(srcRoot, ignore = []) { + const plan = cutPieces(await listSources(srcRoot, ignore), 1); + const result = readPiece(srcRoot, plan.pieces[0]); + for (const w of result.warnings) console.warn(w); + const { pages, staticFiles } = assemble(srcRoot, plan, [result]); return { pages, staticFiles }; } @@ -92,64 +141,3 @@ function byName(a, b) { function bySrcRel(a, b) { return a.srcRel < b.srcRel ? -1 : a.srcRel > b.srcRel ? 1 : 0; } - -// Every .md and .html passes through here, and `parseFrontmatter` drops a -// leading BOM, so a page an editor saved with one is still a page rather than -// a static asset served as raw markdown. -// -// `contentLine` is the file's 1-based line on which `content` starts, so a -// message about a line of the content can name the line of the file. The -// content is the text after the frontmatter block, so the lines before it are -// the lines of the block. -// -// A value left unquoted that ends in `#` is warned about, not refused: YAML -// drops a `#` after a space as a comment, so `title: Input #` titles the page -// `Input`, while `lang: C#` is read as written. Quoting the value keeps the `#` -// and silences the warning either way. -function readFrontmatter(raw, srcRel) { - let parsed; - try { - parsed = parseFrontmatter(raw); - } catch (err) { - throw new Error(`Failed to parse frontmatter in ${srcRel}: ${err.message}`); - } - if (!parsed) return null; - for (const { line, text } of unquotedHashValues(raw)) { - console.warn( - `discover: ${srcRel}:${line}: an unquoted value ends in #, and YAML drops a # after a space as a comment; quote the value to keep it: ${text.trim()}`, - ); - } - const { data, content } = parsed; - const block = raw.slice(0, raw.length - content.length); - return { data, content, contentLine: (block.match(/\r\n?|\n/g) ?? []).length + 1 }; -} - -function buildPage(srcRoot, srcRel, { data, content, contentLine }) { - const srcRelPosix = toPosix(srcRel); - const ext = path.extname(srcRel).toLowerCase(); - const permalink = computePermalink(data.permalink, srcRelPosix); - const destPath = permalinkToDestPath(permalink); - return { - srcPath: path.join(srcRoot, srcRel), - srcRel: srcRelPosix, - ext, - frontmatter: data, - rawContent: content, - contentLine, - permalink, - destPath, - layoutDefault: data.layout === undefined || data.layout === null, - imageScope: IMAGE_SCOPE.test(srcRelPosix), - }; -} - -function computePermalink(fmPermalink, srcRelPosix) { - if (typeof fmPermalink === "string" && fmPermalink.length > 0) { - return fmPermalink; - } - return "/" + srcRelPosix.replace(PAGE_EXT, "") + ".html"; -} - -function toPosix(p) { - return p.replace(/\\/g, "/"); -} diff --git a/builder/fan-out.mjs b/builder/fan-out.mjs new file mode 100644 index 000000000..e999dc07f --- /dev/null +++ b/builder/fan-out.mjs @@ -0,0 +1,159 @@ +// Lane tasks added to the graph while it runs. A main-thread task whose work +// splits into pieces calls fanOut from its submit() with one payload per +// piece; each becomes a task `${prefix}:${i}` that a lane runs with `handler` +// (cpu-worker.mjs), drawn on its lane in the Gantt chart. This is how the build +// runs work in parallel: no task starts a thread of its own (WIP.Build.md, "No +// task starts a thread"). +// +// dispatch.submit adds render:i and flush:i with the same primitives +// (sab-scheduler.mjs); this wraps them for a fan-out that has its submitter and +// any other main-thread task as predecessors, may be pinned piece by piece to +// an earlier fan-out's lanes, and feeds one or more static joins. +// +// The order the pieces are wired in is what makes it safe: +// +// - Every piece waits for `from`, the task whose submit() is running. That +// task is CLAIMED until submit returns, so no piece can become READY, let +// alone finish, while the edges are still being written. A predecessor in +// `after` must be a main-thread task, or a piece of a fan-out made in the +// same submit; a lane task could finish between the check of its status +// and the edge, and the edge would never be counted down. +// - A join's dep count grows by the number of pieces, and its `expected` list +// by their names, before `from` finishes; the join lists `from`, so it +// cannot run before then. Its `expected` list is what holds it back until +// every piece's submit has run (PLAN-sab-pull-scheduler.md, "A dep count of +// zero does not mean the submits have run"). +// +// Each piece's payload is JSON, packed with the others into one +// SharedArrayBuffer that every lane is sent under the key `fan::`; +// cpu-worker.mjs's fanOutPayload finds a task's by its index. The payload is +// broadcast before `from` is marked done, so it is queued on every lane before +// one can claim a piece. + +import { + allocDynamicSlots, + appendDynamicSuccessors, + DONE, + F_PIN_TO_PRED, + F_RUN_ON_MAIN, + HANDLERS, + NOT_READY, + packPayloads, + setDepCount, + wireDynamicEdges, + writeTaskMeta, +} from "./sab-scheduler.mjs"; + +/** + * @param {import("./scheduler.mjs").Scheduler} scheduler + * @param {object} o + * @param {string} o.from the main-thread task whose submit() this is + * @param {string} o.prefix the pieces are `${prefix}:0` ... + * @param {string} o.handler the lane handler that runs each piece (HANDLERS) + * @param {unknown[]} o.payloads one per piece, JSON + * @param {string[]} [o.after] tasks each piece waits for besides `from` + * @param {string} [o.pinTo] the prefix of an earlier fan-out from the same + * submit: piece i runs on the lane that ran its piece i + * @param {string[]} [o.joins] static tasks that wait for every piece + * @param {string} [o.ganttSection] the chart's colour for the pieces + * @param {number} [o.priority] a lane takes the READY task of highest priority + * @param {(payload: unknown) => string[]} [o.describe] lines for the stall report + * @returns {string[]} the pieces' names + */ +export function fanOut( + scheduler, + { from, prefix, handler, payloads, after = [], pinTo = null, joins = [], ganttSection, priority = 0, describe }, +) { + const views = scheduler._views; + const idMap = scheduler._idMapping; + const count = payloads.length; + if (count === 0) return []; + const handlerIdx = HANDLERS[handler]; + if (handlerIdx == null) throw new Error(`fanOut ${prefix}: unknown handler "${handler}"`); + const indexOf = (name) => { + const idx = idMap.nameToIdx.get(name); + if (idx == null) throw new Error(`fanOut ${prefix}: no task "${name}"`); + return idx; + }; + const fromIdx = indexOf(from); + if (Atomics.load(views.status, fromIdx) === DONE) throw new Error(`fanOut ${prefix}: "${from}" is done already`); + + const base = allocDynamicSlots(views, idMap, count); + const names = Array.from({ length: count }, (_, i) => `${prefix}:${i}`); + + // Predecessors: `from`, the `after` tasks not yet done, and each piece's pin. + const waits = [from]; + for (const name of after) { + const idx = indexOf(name); + if (Atomics.load(views.status, idx) === DONE) continue; + const isMain = (Atomics.load(views.flags, idx) & F_RUN_ON_MAIN) !== 0; + if (!isMain && Atomics.load(views.status, idx) !== NOT_READY) { + throw new Error(`fanOut ${prefix}: "${name}" is a lane task that may finish before it is wired`); + } + waits.push(name); + } + const successors = new Map(); // predecessor index -> the pieces it gains + const gain = (predIdx, idx) => { + if (!successors.has(predIdx)) successors.set(predIdx, []); + successors.get(predIdx).push(idx); + }; + + const joinIdxs = joins.map((join) => { + const idx = indexOf(join); + const def = scheduler.tasks.get(join); + if (!def?.expected.includes(from)) { + throw new Error(`fanOut ${prefix}: join "${join}" must list "${from}" in its expected`); + } + if (Atomics.load(views.status, idx) !== NOT_READY) throw new Error(`fanOut ${prefix}: join "${join}" has started`); + return idx; + }); + + const edges = []; + for (let i = 0; i < count; i++) { + const idx = base + i; + const name = names[i]; + idMap.nameToIdx.set(name, idx); + idMap.idxToName[idx] = name; + writeTaskMeta(views, idx, { handlerIdx, priority }); + + const expected = [...waits]; + for (const w of waits) gain(indexOf(w), idx); + if (pinTo) { + const pin = `${pinTo}:${i}`; + const pinIdx = indexOf(pin); + if (Atomics.load(views.status, pinIdx) !== NOT_READY) { + throw new Error(`fanOut ${prefix}: "${pin}" has started; pin only to a fan-out of the same submit`); + } + expected.push(pin); + gain(pinIdx, idx); + Atomics.store(views.pinnedTo, idx, pinIdx); + Atomics.or(views.flags, idx, F_PIN_TO_PRED); + } + setDepCount(views, idx, expected.length); + edges.push({ from: idx, to: joinIdxs }); + + const payload = payloads[i]; + scheduler.tasks.set(name, { + expected, + consolidate: true, + ganttSection, + describe: describe ? () => describe(payload) : undefined, + submit() {}, + }); + } + wireDynamicEdges(views, edges); + appendDynamicSuccessors( + views, + [...successors].map(([predIdx, to]) => ({ from: predIdx, to })), + ); + + for (const join of joins) { + const def = scheduler.tasks.get(join); + scheduler.tasks.set(join, { ...def, expected: [...def.expected, ...names] }); + Atomics.add(views.depCount, indexOf(join), count); + } + + scheduler.addDynamicTasks(count); + scheduler.pool.broadcastTaskData(`fan:${base}:${count}`, packPayloads(views, base, payloads)); + return names; +} diff --git a/builder/fnmatch.mjs b/builder/fnmatch.mjs new file mode 100644 index 000000000..e82b4e520 --- /dev/null +++ b/builder/fnmatch.mjs @@ -0,0 +1,66 @@ +// Path patterns with File.fnmatch(..., FNM_PATHNAME) semantics: `*` does not +// cross `/`, `**` does, `?` is one character that is not `/`. The rule of +// `offline_exclude` and of the help archive's skip list. +// +// A module of its own, importing nothing, because check-tree.mjs needs it on +// the render fan-out's critical path and offline-rewrite.mjs is much larger. + +// The pattern as a regular expression's source. +function fnmatchSource(pattern) { + let re = "^"; + for (let i = 0; i < pattern.length; i++) { + const c = pattern[i]; + if (c === "*") { + if (pattern[i + 1] === "*") { + re += ".*"; + i++; + } else { + re += "[^/]*"; + } + } else if (c === "?") { + re += "[^/]"; + } else if (".+^$()|[]{}\\".includes(c)) { + re += "\\" + c; + } else { + re += c; + } + } + return re + "$"; +} + +export function fnmatchPathname(pattern, str) { + return new RegExp(fnmatchSource(pattern)).test(str); +} + +// A list of patterns, compiled once: a pattern with no wildcard matches only +// itself and goes into a Set, the others are regular expressions. The build +// adds a few hundred literal patterns (the pictures' SVGs, when +// picture_svg.offline is false) and tests every path of a tree against the +// list, more than once: testing each path against each pattern, with a regular +// expression made for every test, was half of `dispatch`. +function compile(patterns) { + const literals = new Set(); + const wild = []; + for (const pat of patterns) { + if (/[*?]/.test(pat)) wild.push(new RegExp(fnmatchSource(pat))); + else literals.add(pat); + } + return { length: patterns.length, literals, wild }; +} + +// By the list's identity. The length is compared as well, since a list a +// caller appended to is the same array. +const compiled = new WeakMap(); + +// True when `rel` matches one of `patterns`. +export function matchesAny(rel, patterns) { + if (!patterns?.length) return false; + let c = compiled.get(patterns); + if (!c || c.length !== patterns.length) { + c = compile(patterns); + compiled.set(patterns, c); + } + if (c.literals.has(rel)) return true; + for (const re of c.wild) if (re.test(rel)) return true; + return false; +} diff --git a/builder/gantt.mjs b/builder/gantt.mjs index 2993ebbf5..0346dd322 100644 --- a/builder/gantt.mjs +++ b/builder/gantt.mjs @@ -8,6 +8,7 @@ const COLORS = { Spine: { light: "#6eb5d9", dark: "#3c7db0" }, Render: { light: "#b09cd8", dark: "#8066a8" }, Write: { light: "#e8a756", dark: "#c08030" }, + Index: { light: "#5cbcb0", dark: "#2b8a80" }, Check: { light: "#e59ac6", dark: "#b35c8c" }, Boot: { light: "#e57373", dark: "#c62828" }, Cold: { light: "#5b7fb5", dark: "#2c4a7c" }, @@ -16,14 +17,19 @@ const COLORS = { // The bands a main-thread task can be drawn in, top to bottom; the // worker lanes go between Spine and Write. Render's main-thread tasks -// (dispatch, prepDest, prepPageDirs) are drawn in Spine. -const BANDS = ["Seeds", "Spine", "Write", "Check"]; +// (dispatch, prepDest, prepPageDirs) are drawn in Spine. Index is the +// search index's tasks (tbdocs.mjs: indexSlices ... searchIndex), on the +// lanes and on the main thread, with the two the lanes wait for before +// them (symbolPlace, searchEntries). +const BANDS = ["Seeds", "Spine", "Write", "Index", "Check"]; const BAND_OF = { Render: "Spine" }; const SECTION_W = 24; const BOOT_STYLE = { cold: { label: "cold", cls: "cold" }, + // The second stage of a lane's boot (cpu-worker.mjs, loadRest). + cold2: { label: "load", cls: "cold" }, warmInit: { label: "warm", cls: "boot" }, renderEnvInit: { label: "env", cls: "env" }, }; @@ -41,16 +47,19 @@ const BAR_PAD = 4; export const GANTT_SECTION = { config: "Seeds", buildInfo: "Seeds", scssLight: "Seeds", scssDark: "Seeds", scss: "Write", dot: "Spine", highlighterInit: "Seeds", loadData: "Seeds", - discover: "Spine", vendorAssets: "Spine", nav: "Spine", markdownInit: "Spine", buildInit: "Spine", + discoverList: "Spine", discover: "Spine", vendorAssets: "Spine", nav: "Spine", markdownInit: "Spine", buildInit: "Spine", resolveBookChapters: "Spine", - deriveRedirects: "Spine", deriveSitemap: "Spine", packTests: "Spine", + deriveRedirects: "Spine", deriveSitemap: "Spine", packTests: "Spine", downloadSizes: "Spine", packageApi: "Spine", dispatch: "Render", prepDest: "Render", prepPageDirs: "Render", renderJoin: "Render", flushJoin: "Write", - writeAssets: "Write", searchData: "Write", searchIndex: "Write", symbolIndex: "Write", helpArchive: "Write", addinProject: "Write", packageTests: "Write", writeAux: "Write", + writeAssets: "Write", searchData: "Write", symbolIndex: "Write", addinProject: "Write", packageTests: "Write", writeAux: "Write", + symbolPlace: "Index", searchEntries: "Index", + indexSlices: "Index", indexMerge: "Index", indexTerms: "Index", searchIndex: "Index", + archivePlan: "Write", archiveLate: "Write", helpArchive: "Write", writeOffline: "Write", bookPayload: "Write", writePdf: "Write", linkJoin: "Check", checkBook: "Check", checkReport: "Check", }; -const GANTT_SECTION_ORDER = ["Seeds", "Spine", "Render", "Write", "Check"]; +const GANTT_SECTION_ORDER = ["Seeds", "Spine", "Render", "Write", "Index", "Check"]; const CHECK_TASKS = new Set(["linkJoin", "checkBook", "checkReport"]); // The scheduler's timings, relative to the first start and grouped by diff --git a/builder/help-archive-step.mjs b/builder/help-archive-step.mjs index 882b73281..6c7d66388 100644 --- a/builder/help-archive-step.mjs +++ b/builder/help-archive-step.mjs @@ -10,14 +10,27 @@ // search and from prose; the add-in's server answers a request for a file the // archive lacks with a redirect to the website. // -// `helpArchiveStep` is the build's `helpArchive` task. It waits for every task -// that writes into the offline tree, and runs before the Gantt injection, which -// rewrites BuildInfo.html in both trees after the task graph is done and -// writes assets/images/gantt.svg. Both are left out of the archive; were they -// not, the archive would hold BuildInfo.html without the chart, and gantt.svg -// as the placeholder the offline tree copied from the sources. Two builds of -// one tree write the same archive, and the same project file with it, which -// the chart (it holds the build's timings) would prevent. +// The build makes the archive in four tasks (tbdocs.mjs), so that its deflating +// runs on the lanes and starts before the search index is done: +// +// - archivePlan, once every task that writes into the offline tree but +// searchIndex is done (planHelpArchive): it decides whether this build +// writes the archive, refuses one that would hold a download, lists the +// tree less LATE_FILES and deals the deflating into one group of units per +// lane, which its submit fans out as archiveDeflate:i; +// - archiveLate, once searchIndex has written search-index.js (planLateFiles): +// the same for LATE_FILES, fanned out as archiveLateDeflate:i; +// - archiveDeflate:i and archiveLateDeflate:i, on the lanes (deflateGroup); +// - helpArchive, once every group is done (finishHelpArchive): it joins the +// units into entries, writes the zip and reads it back. +// +// It all runs before the Gantt injection, which rewrites BuildInfo.html in both +// trees after the task graph is done and writes assets/images/gantt.svg. Both +// are left out of the archive; were they not, the archive would hold +// BuildInfo.html without the chart, and gantt.svg as the placeholder the +// offline tree copied from the sources. Two builds of one tree write the same +// archive, and the same project file with it, which the chart (it holds the +// build's timings) would prevent. // // `recheckHelpArchive` runs at the end of runBuild, after the Gantt injection, // and checks that the offline tree on disk still lists the archive's files and @@ -33,12 +46,23 @@ // download published from CI's build holds the archive. The step does not look // at $CI. +import { statSync } from "node:fs"; import { readFile } from "node:fs/promises"; import path from "node:path"; -import { checkHelpArchive, writeHelpArchive } from "../lib/help-archive.mjs"; +import { + checkHelpArchive, + checkZipLimits, + collectEntries, + deflateUnit, + groupUnits, + listFiles, + planUnits, + writeArchive, +} from "../lib/help-archive.mjs"; import { REPO_ROOT } from "../lib/repo-paths.mjs"; import { GUARDED_SRC } from "./baseline.mjs"; import { offlineExcluded } from "./offline-rewrite.mjs"; +import { OFFLINE_SEARCH_INDEX_REL } from "./search-index.mjs"; export const HELP_ARCHIVE_REL = "add-in/Resources/HELP/site.zip"; @@ -109,10 +133,18 @@ const mb = (n) => (n / 1048576).toFixed(1); const OFFLINE_TREE = path.join(REPO_ROOT, GUARDED_SRC, "_site-offline"); const sameDir = (a, b) => path.relative(a, b) === ""; +// The files of the offline tree that a task archivePlan does not wait for +// writes: searchIndex writes search-index.js, and archivePlan does not wait +// for it, so that the rest of the tree is deflated while the index is built. +// archiveLate deflates these once their task is done. A file here that is in +// the tree when archivePlan runs is a previous build's, and is left alone. +export const LATE_FILES = [OFFLINE_SEARCH_INDEX_REL]; +const isLate = (name) => LATE_FILES.includes(name); + const NOT_WRITTEN = { text: "", failed: false, zip: null, out: null }; /** - * Write the add-in's archive of the offline tree this build wrote. + * Where this build writes the add-in's archive, or null when it writes none. * * @param {object} o * @param {string} o.src the source tree built, repo-relative with forward slashes @@ -120,25 +152,35 @@ const NOT_WRITTEN = { text: "", failed: false, zip: null, out: null }; * @param {boolean} o.serve the build is a `--serve` session * @param {boolean} o.dryRun the build wrote no trees * @param {boolean} o.disabled `--no-help-archive` was given - * @param {string} [o.out] the zip; the add-in's by default - * @returns {Promise<{text: string, failed: boolean, zip: Buffer | null, out: string | null}>} what to - * print, "" when the step did not run; the archive's bytes and path, null when this build wrote none + * @returns {string | null} */ -export async function helpArchiveStep({ - src, - offlineRoot, - serve, - dryRun, - disabled, - out = path.join(REPO_ROOT, HELP_ARCHIVE_REL), -}) { - if (src !== GUARDED_SRC || serve || dryRun || disabled || !offlineRoot) return NOT_WRITTEN; - if (!sameDir(path.resolve(offlineRoot), OFFLINE_TREE)) return NOT_WRITTEN; +export function helpArchiveOut({ src, offlineRoot, serve, dryRun, disabled }) { + if (src !== GUARDED_SRC || serve || dryRun || disabled || !offlineRoot) return null; + if (!sameDir(path.resolve(offlineRoot), OFFLINE_TREE)) return null; + return path.join(REPO_ROOT, HELP_ARCHIVE_REL); +} + +/** + * The archivePlan task: the tree's files less LATE_FILES, and their deflating + * dealt into at most `groups` groups, one archiveDeflate:i each. A plan with no + * `out` writes nothing; its `text` and `failed` say why, when that is a fault. + * + * @param {object} o + * @param {string | null} o.out helpArchiveOut's answer + * @param {string} o.offlineRoot the offline tree + * @param {number} o.groups how many groups at most: the lanes + * @param {(name: string) => boolean} [o.skip] the files the archive leaves out + */ +export async function planHelpArchive({ out, offlineRoot, groups, skip = helpArchiveSkips }) { + const started = Date.now(); + if (!out) return { ...NOT_WRITTEN, groups: [] }; + const root = path.resolve(offlineRoot); try { - const kept = await downloadsKept(path.resolve(offlineRoot), helpArchiveSkips); + const kept = await downloadsKept(root, skip); if (kept.length > 0) { return { ...NOT_WRITTEN, + groups: [], text: `help archive: not written: it would hold ${kept.length} file(s) the Downloads page offers, ` + `which stay on the website; put each in a downloads folder, or add it to HELP_ARCHIVE_SKIP:\n` + @@ -146,12 +188,81 @@ export async function helpArchiveStep({ failed: true, }; } - const s = await writeHelpArchive({ src: path.resolve(offlineRoot), out, skip: helpArchiveSkips }); + const files = listFiles(root, (name) => skip(name) || isLate(name)); + checkZipLimits(files); + return { ...NOT_WRITTEN, out, root, files, groups: groupUnits(planUnits(files), groups), started }; + } catch (err) { + return { ...NOT_WRITTEN, groups: [], text: `help archive: not written: ${err.message}\n`, failed: true }; + } +} + +/** + * The archiveLate task: LATE_FILES, once their tasks have written them, dealt + * as planHelpArchive deals the rest; none when the plan writes nothing. + */ +export function planLateFiles({ plan, groups, skip = helpArchiveSkips }) { + if (!plan.out) return { files: [], groups: [] }; + try { + const files = LATE_FILES.filter((name) => !skip(name)) + .map((name) => ({ name, file: path.join(plan.root, ...name.split("/")) })) + .filter((f) => { + try { + f.size = statSync(f.file).size; + return true; + } catch (err) { + if (err.code === "ENOENT") return false; + throw err; + } + }); + return { files, groups: groupUnits(planUnits(files), groups) }; + } catch (err) { + return { files: [], groups: [], error: err.message }; + } +} + +/** + * One archiveDeflate:i or archiveLateDeflate:i, on a lane: each unit of the + * group deflated (lib/help-archive.mjs, deflateUnit). A failure comes back as + * `{ error }` for finishHelpArchive to report, so that it fails the build + * without stopping it: the trees are still written. + */ +export function deflateGroup({ root, units }) { + try { + return { results: units.map((unit) => deflateUnit(root, unit)) }; + } catch (err) { + return { error: err.message }; + } +} + +/** + * The helpArchive task: every group's units joined into the archive's + * entries, written to the plan's `out`, read back and checked. + * + * @param {object} o + * @param {object} o.plan archivePlan's result + * @param {object} o.late archiveLate's result + * @param {object[]} o.groups every archiveDeflate:i's and archiveLateDeflate:i's result + * @returns {Promise<{text: string, failed: boolean, zip: Buffer | null, out: string | null}>} what to + * print, "" when the step did not run; the archive's bytes and path, null when this build wrote none + */ +export async function finishHelpArchive({ plan, late, groups }) { + if (!plan.out) return { text: plan.text, failed: plan.failed, zip: null, out: null }; + try { + if (late.error) throw new Error(late.error); + const failed = groups.find((g) => g.error); + if (failed) throw new Error(failed.error); + const files = [...plan.files, ...late.files].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); + const entries = collectEntries( + files, + groups.flatMap((g) => g.results), + ); + const s = await writeArchive({ out: plan.out, files, entries }); + const secs = ((Date.now() - plan.started) / 1000).toFixed(1); return { - text: `help archive: ${HELP_ARCHIVE_REL}, ${s.entries} entries, ${mb(s.zipBytes)} MB (${(s.ms / 1000).toFixed(1)} s)\n`, + text: `help archive: ${HELP_ARCHIVE_REL}, ${s.entries} entries, ${mb(s.zipBytes)} MB (${secs} s)\n`, failed: false, zip: s.zip, - out, + out: plan.out, }; } catch (err) { if (err.verifyFailed) { diff --git a/builder/nav.mjs b/builder/nav.mjs index dc474b386..64d1abfd8 100644 --- a/builder/nav.mjs +++ b/builder/nav.mjs @@ -147,23 +147,36 @@ function buildSharedNavState(pages, config) { caseInsensitive, ); + // Each page's children, worked out once for both lists: `childrenOf` is + // what the children substep lists, and `orderedChildren` the same without + // the nav_exclude pages, which is what nav-tree and nav-levels go through. + // Most pages have no child: they share one empty list and are not sorted. + const childrenOf = new Map(); const orderedChildren = new Map(); for (const parent of titled) { - orderedChildren.set(parent.permalink, orderedChildrenFor(parent, byParentTitle, caseInsensitive)); + const all = childrenFor(parent, byParentTitle, caseInsensitive); + childrenOf.set(parent, all); + orderedChildren.set( + parent.permalink, + all.some((c) => c.frontmatter.nav_exclude) ? all.filter((c) => !c.frontmatter.nav_exclude) : all, + ); } - return { titled, byTitle, byParentTitle, caseInsensitive, topLevel, orderedChildren }; + return { titled, byTitle, byParentTitle, caseInsensitive, topLevel, childrenOf, orderedChildren }; } -// Mirrors the upstream nav/children.html filter: drop nav_exclude pages, -// drop pages whose grand_parent contradicts the candidate parent's own -// parent, then apply child_nav_order reversal so positions match render -// order. Shared by nav-tree and nav-levels. -function orderedChildrenFor(parent, byParentTitle, caseInsensitive) { - const parentTitle = String(parent.frontmatter.title); - const candidates = byParentTitle.get(parentTitle) || []; +const NO_CHILDREN = Object.freeze([]); + +// Mirrors the upstream nav/children.html filter: drop pages whose +// grand_parent contradicts the candidate parent's own parent, then apply +// child_nav_order reversal so positions match render order. The nav_exclude +// pages are dropped from the result for nav-tree and nav-levels +// (buildSharedNavState): the sort is stable within each of its buckets, so +// leaving them out afterwards gives the order that sorting without them does. +function childrenFor(parent, byParentTitle, caseInsensitive) { + const candidates = byParentTitle.get(String(parent.frontmatter.title)); + if (!candidates) return NO_CHILDREN; const filtered = candidates.filter((c) => { - if (c.frontmatter.nav_exclude) return false; const gp = c.frontmatter.grand_parent; return gp == null || gp === parent.frontmatter.parent; }); @@ -177,6 +190,7 @@ function orderedChildrenFor(parent, byParentTitle, caseInsensitive) { // ---------- §6.2 four-bucket sort ------------------------------------------ function sortPages(pages, caseInsensitive) { + if (pages.length < 2) return pages.slice(); const navNum = [], navStr = [], titleNum = [], @@ -228,56 +242,30 @@ function buildNavNode(page, chain, orderedChildren, depth) { // ---------- §5.4 nav-levels ------------------------------------------------ +// A page's levels are 1, its top-level ancestor's position among the top +// level, then each page's position among its parent's ordered children, down +// to the page: all from 1, along the first path the tree reaches the page by. +// The walk carries them, since it goes through each list in order. function computeNavLevels(_pages, state) { - const topIndex = new Map(); - state.topLevel.forEach((p, i) => { - topIndex.set(p.permalink, i + 1); - }); - - const childIndex = new Map(); - for (const [parentUrl, list] of state.orderedChildren) { - const m = new Map(); - list.forEach((c, i) => { - m.set(c.permalink, i + 1); - }); - childIndex.set(parentUrl, m); - } - - const paths = new Map(); - for (const top of state.topLevel) { - walkNavSubtree(top, [top], paths, state.orderedChildren, 0); + const levels = new Map(); + for (const [i, top] of state.topLevel.entries()) { + walkNavSubtree(top, [top], [1, i + 1], levels, state.orderedChildren, 0); } for (const page of state.titled) { - page.navLevels = levelsFromPath(paths.get(page.permalink), topIndex, childIndex); + page.navLevels = levels.get(page.permalink); } } -function walkNavSubtree(node, chain, paths, orderedChildren, depth) { +function walkNavSubtree(node, chain, path, levels, orderedChildren, depth) { if (depth > NAV_TREE_MAX_DEPTH) return; - if (!paths.has(node.permalink)) paths.set(node.permalink, chain); + if (!levels.has(node.permalink)) levels.set(node.permalink, path); - const children = orderedChildren.get(node.permalink) || []; - for (const child of children) { + const children = orderedChildren.get(node.permalink) || NO_CHILDREN; + for (const [i, child] of children.entries()) { if (chain.some((p) => p.permalink === child.permalink)) continue; - walkNavSubtree(child, [...chain, child], paths, orderedChildren, depth + 1); - } -} - -function levelsFromPath(chain, topIndex, childIndex) { - if (!chain) return undefined; - - const topIdx = topIndex.get(chain[0].permalink); - if (topIdx == null) return undefined; - - const levels = [1, topIdx]; - for (let i = 1; i < chain.length; i++) { - const map = childIndex.get(chain[i - 1].permalink); - const idx = map?.get(chain[i].permalink); - if (idx == null) return undefined; - levels.push(idx); + walkNavSubtree(child, [...chain, child], [...path, i + 1], levels, orderedChildren, depth + 1); } - return levels; } // ---------- §5.5 breadcrumbs ----------------------------------------------- @@ -320,16 +308,7 @@ function resolveParent(parentTitle, grandParentTitle, byTitle) { function computeChildren(_pages, state) { for (const page of state.titled) { - const candidates = state.byParentTitle.get(String(page.frontmatter.title)) || []; - const filtered = candidates.filter((c) => { - const gp = c.frontmatter.grand_parent; - return gp == null || gp === page.frontmatter.parent; - }); - const sorted = sortPages(filtered, state.caseInsensitive); - if (REVERSE_FLAGS.has(String(page.frontmatter.child_nav_order || ""))) { - sorted.reverse(); - } - page.children = sorted.map((c) => ({ + page.children = state.childrenOf.get(page).map((c) => ({ title: c.frontmatter.title, url: c.permalink, summary: c.frontmatter.summary, diff --git a/builder/offline-rewrite.mjs b/builder/offline-rewrite.mjs index 7b7328ae2..e70938d10 100644 --- a/builder/offline-rewrite.mjs +++ b/builder/offline-rewrite.mjs @@ -5,8 +5,7 @@ // // Sections: // -// §B Site-paths set (buildSitePathsSync, offlineExcluded, -// fnmatchPathname) +// §B Site-paths set (buildSitePathsSync, offlineExcluded) // §C URL resolution (computeRelative, resolveRaw, computeRelUrl, // computeWebsiteUrl, isWebsiteOnlyLink, websiteOf, // buildSegs, decode, fileDirSegsFromRel, @@ -21,6 +20,7 @@ import { escapeRegExp } from "./escape.mjs"; import { CODE_OR_PRE } from "./code-guard.mjs"; import { posix } from "./paths.mjs"; +import { matchesAny } from "./fnmatch.mjs"; // --------------------------------------------------------------------------- // §B Site-paths set @@ -57,34 +57,9 @@ export function buildSitePathsSync(pages, staticFiles, excludePatterns, stubs, t // §6.5 offlineExcluded -- File.fnmatch(..., FNM_PATHNAME) semantics: // `*` does NOT cross `/`, `**` does. +// The patterns are compiled once for each list (fnmatch.mjs). export function offlineExcluded(rel, patterns) { - if (!patterns.length) return false; - // A pattern with no wildcard matches only itself; the build adds a few hundred such - // (the pictures' SVGs, when picture_svg.offline is false), so they skip the regex. - return patterns.some((pat) => (/[*?]/.test(pat) ? fnmatchPathname(pat, rel) : pat === rel)); -} - -export function fnmatchPathname(pattern, str) { - let re = "^"; - for (let i = 0; i < pattern.length; i++) { - const c = pattern[i]; - if (c === "*") { - if (pattern[i + 1] === "*") { - re += ".*"; - i++; - } else { - re += "[^/]*"; - } - } else if (c === "?") { - re += "[^/]"; - } else if (".+^$()|[]{}\\".includes(c)) { - re += "\\" + c; - } else { - re += c; - } - } - re += "$"; - return new RegExp(re).test(str); + return matchesAny(rel, patterns); } // --------------------------------------------------------------------------- diff --git a/builder/render.mjs b/builder/render.mjs index b7affafd6..7c823f88b 100644 --- a/builder/render.mjs +++ b/builder/render.mjs @@ -1886,7 +1886,7 @@ function walkTokens(tokens, fn) { // An image whose file has a light sibling among the static files (`X.png` and `X.light.png`) // becomes two images, the light one first, with the same alt text and attributes, each with // its theme's class and `loading="lazy"`; the light one's width and height are the page's -// scaled by the two files' pixel sizes (`ctx.pictureSizes`, pairSizes in theme-pictures.mjs), +// scaled by the two files' pixel sizes (`ctx.pictureSizes`, picturePairs in theme-pictures.mjs), // since the Light theme lays the IDE out a few pixels differently. The stylesheet hides the one for the other theme, // and a lazy image that is not displayed is never fetched. A link to such a picture (the // feature map's "Full size") becomes two links the same way, so that it opens the picture diff --git a/builder/sab-scheduler.mjs b/builder/sab-scheduler.mjs index 81e354eaf..dc061e1f6 100644 --- a/builder/sab-scheduler.mjs +++ b/builder/sab-scheduler.mjs @@ -4,9 +4,11 @@ // ── Constants ──────────────────────────────────────────────────────────────── -export const MAX_TASKS = 512; +// render:i and flush:i take 2 x SLICES_PER_WORKER x lanes of the tasks, and +// the fan-outs after them (fan-out.mjs) up to a few per lane more. +export const MAX_TASKS = 1024; export const MAX_LANES = 64; -export const MAX_EDGES = 2048; +export const MAX_EDGES = 4096; export const SLICES_PER_WORKER = 10; // Status values (Int32) @@ -34,10 +36,14 @@ export const HANDLERS = { dot: 5, buildInfo: 6, render: 7, - helpArchive: 8, writePdf: 9, checkBook: 10, - searchIndex: 11, + packTests: 11, + // The pieces of fan-outs (fan-out.mjs). + indexAdd: 12, + indexVectors: 13, + archiveDeflate: 14, + discoverRead: 15, }; // ── SAB layout ─────────────────────────────────────────────────────────────── @@ -271,6 +277,7 @@ export function allocSchedulerSAB(taskDefs, workerCount, opts = {}) { perWorkerDeps, expectedDeps, idlePriority: def.idle_priority ?? 0, + priority: def.priority ?? 0, }); } @@ -533,6 +540,9 @@ export function verifySchedulerSAB(taskDefs, views, idMapping) { const wantPri = def.idle_priority ?? 0; if (Atomics.load(views.idlePriority, idx) !== wantPri) errors.push(`idlePriority "${name}": got ${Atomics.load(views.idlePriority, idx)}, want ${wantPri}`); + const wantClaim = def.priority ?? 0; + if (Atomics.load(views.priority, idx) !== wantClaim) + errors.push(`priority "${name}": got ${Atomics.load(views.priority, idx)}, want ${wantClaim}`); } } diff --git a/builder/scheduler.mjs b/builder/scheduler.mjs index 79bfc5581..17f59cf31 100644 --- a/builder/scheduler.mjs +++ b/builder/scheduler.mjs @@ -11,6 +11,8 @@ export class SharedState { site = {}; pageByDest = new Map(); searchChunks = []; // Phase 17: per-chunk search entries from render workers + searchKeys = []; // the entries' settle keys, by chunk likewise + searchPacked = []; // the entries again, each chunk's packed by its lane for search-data.json and the index's lanes } export class Scheduler { diff --git a/builder/search-index-worker.mjs b/builder/search-index-worker.mjs deleted file mode 100644 index 860ebe06f..000000000 --- a/builder/search-index-worker.mjs +++ /dev/null @@ -1,74 +0,0 @@ -// A worker thread of the search index's split build (search-index.mjs, which -// describes the steps). It keeps its builder between the two requests. - -import { parentPort } from "node:worker_threads"; -import { entryFor, FIELD_SEPARATOR, loadSearchLunr, newBuilder } from "./search-index.mjs"; - -let lunr = null; -let builder = null; -let terms = null; - -const steps = { - // Adds the entries, and returns each term (in the order this builder met - // it) with its document count, its postings field by field, and each - // field's total length. - add({ lunrPath, docs, twins }) { - lunr = loadSearchLunr(lunrPath); - builder = newBuilder(lunr); - const entries = JSON.parse(docs); - const twinSet = new Set(twins); - for (const id in entries) builder.add(entryFor(lunr, entries, id, twinSet)); - - const fields = Object.keys(builder._fields); - // In the order the builder met them (each posting's _index), not in key - // order, which puts terms that look like numbers ("1", "2025") first. - terms = new Array(builder.termIndex); - for (const term in builder.invertedIndex) terms[builder.invertedIndex[term]._index] = term; - const df = new Int32Array(terms.length); - const postings = new Array(terms.length); - for (let k = 0; k < terms.length; k++) { - const posting = builder.invertedIndex[terms[k]]; - const parts = []; - // lunr.idf counts an entry once for each field it has the term in. - for (const f of fields) { - df[k] += Object.keys(posting[f]).length; - parts.push(JSON.stringify(posting[f]).slice(1, -1)); - } - postings[k] = parts.join(FIELD_SEPARATOR); - } - const lengths = Object.fromEntries(fields.map((f) => [f, [0, 0]])); - for (const ref in builder.fieldLengths) { - const field = lengths[lunr.FieldRef.fromString(ref).fieldName]; - field[0] += builder.fieldLengths[ref]; - field[1] += 1; - } - return { terms, df, postings, lengths, documentCount: builder.documentCount }; - }, - - // lunr's createFieldVectors, with every term numbered as the whole index - // numbers it, and the counts and averages of every entry; returns the - // vectors as toJSON writes them, in the order of this worker's entries. - vectors({ numbers, idf, documentCount, averageFieldLength }) { - for (let k = 0; k < terms.length; k++) builder.invertedIndex[terms[k]]._index = numbers[k]; - builder.documentCount = documentCount; - builder.averageFieldLength = averageFieldLength; - const ownIdf = lunr.idf; - lunr.idf = (posting) => idf[posting._index]; - try { - builder.createFieldVectors(); - } finally { - lunr.idf = ownIdf; - } - return Object.keys(builder.fieldVectors) - .map((ref) => JSON.stringify([ref, builder.fieldVectors[ref].toJSON()])) - .join(","); - }, -}; - -parentPort.on("message", (msg) => { - try { - parentPort.postMessage({ result: steps[msg.step](msg) }); - } catch (err) { - parentPort.postMessage({ error: err?.stack ?? String(err) }); - } -}); diff --git a/builder/search-index.mjs b/builder/search-index.mjs index af17c7d3d..a1cc4851a 100644 --- a/builder/search-index.mjs +++ b/builder/search-index.mjs @@ -10,30 +10,36 @@ // keeps its own copies of what a query needs too -- the tokenizer, exactName, // indexTermKey -- and test/search.test.mjs checks that they agree with these. // -// The index is built on several threads. lunr has no way to merge two -// indexes, but most of a build is independent per entry, so: +// The index is built in slices, which the build runs on its lanes as tasks +// of its graph (tbdocs.mjs: indexSlices, indexAdd:i, indexMerge, indexTerms, +// indexVectors:i, searchIndex). lunr has no way to merge two indexes, but +// most of a build is independent per entry, so: // -// 1. each worker adds a contiguous run of the entries to a lunr.Builder of -// its own, and returns its postings, its counts and its field lengths; -// 2. the postings are merged, every term numbered as one build would number -// it (in order of first appearance, entry by entry), and each term's -// document count and each field's average length are worked out over all -// the entries; -// 3. each worker makes its entries' field vectors (lunr's own -// createFieldVectors) with those totals; -// 4. the JSON is written as lunr's toJSON writes it. +// 1. each slice, a contiguous run of the entries, is added to a +// lunr.Builder of its own (addSlice), which returns its postings, its +// counts and its field lengths; +// 2. the postings are merged (mergeSlices), every term numbered as one +// build would number it (in order of first appearance, entry by entry), +// and each term's document count and each field's average length are +// worked out over all the entries; +// 3. each slice's builder makes its entries' field vectors (sliceVectors, +// lunr's own createFieldVectors) with those totals; +// 4. the JSON is written as lunr's toJSON writes it (invertedIndexJson, +// assembleIndexJson). // // The result is byte for byte what lunr(config) and JSON.stringify make on // one thread, which test/search-index.test.mjs checks, for any number of -// workers. The token set, a third of a one-thread build, is never made here: +// slices. The token set, a third of a one-thread build, is never made here: // it is not part of the JSON, and Index.load makes it in the page. +// +// Nothing here starts a thread: every step runs on the thread that calls it, +// and the build's graph decides where (WIP.Build.md, "No task starts a +// thread"). buildIndexJson runs every step on one thread, for the tests and +// for any tool that wants the index outside a build. -import { promises as fs } from "node:fs"; import { createRequire } from "node:module"; -import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; -import { Worker } from "node:worker_threads"; import { writeFileMkdirp } from "./write.mjs"; @@ -178,11 +184,11 @@ export function exactName(name) { // The qualified names that the stemmer merges with another name's // (`Printer.Font` and `Printer.Fonts` both stem to `printer.font`), which // would otherwise tie in `qualified`. Keyed by the name as the tokenizer -// writes it. +// writes it. `docs` are the entries by number, or in an array. export function stemTwins(lunr, docs) { const byStem = new Map(); - for (const id in docs) { - for (const token of lunr.tokenizer(docs[id].qualified || "")) { + for (const doc of Object.values(docs)) { + for (const token of lunr.tokenizer(doc.qualified || "")) { const stem = lunr.stemmer(lunr.trimmer(token.clone())).toString(); if (!byStem.has(stem)) byStem.set(stem, new Set()); byStem.get(stem).add(token.str); @@ -303,140 +309,330 @@ export function buildIndex(lunr, docs) { }); } -// How many threads the build gives an index of `entries` entries: about half -// the machine, since the build's own lanes are busy writing and checking the -// trees meanwhile; at most eight (on 16 threads, the site's index took 1.9 s -// on four, 1.6 s on six, 1.4 s on eight); and one for every 500 entries, so -// that a small tree (a test fixture) starts no thread at all. -export function defaultIndexWorkers(entries = Infinity) { - return Math.max(1, Math.min(8, Math.floor(os.availableParallelism() / 2), Math.floor(entries / 500))); +// How many slices the build cuts an index of `entries` entries into: +// SLICES_PER_LANE for each lane, so that a lane that finishes early takes +// another while a lane still busy with something else catches up; and one for +// every 500 entries, so that a small tree (a test fixture) is one slice. +export const SLICES_PER_LANE = 2; +export function indexSliceCount(entries, lanes) { + return Math.max(1, Math.min(lanes * SLICES_PER_LANE, Math.floor(entries / 500))); } -// The index of `docs` as lunr's JSON, built on `workers` threads (one: on -// this thread, by lunr itself). Every worker count gives the same bytes. -export async function buildIndexJson(docs, { workers = defaultIndexWorkers(), lunrPath = LUNR_PATH } = {}) { - const lunr = loadSearchLunr(lunrPath); +// `docs` cut into `count` slices, contiguous runs of the entries in order, +// each with the stem twins of every entry (qualifiedField needs all of them). +// Each is what one addSlice takes: { slice, docs, twins }. The runs are of +// about equal text rather than of equal entries: adding an entry costs about +// as much as its text is long, and the entries run from a line to a page. +export function planIndexSlices(lunr, docs, count) { const ids = Object.keys(docs); - const n = Math.max(1, Math.min(workers, ids.length)); - if (n === 1) return JSON.stringify(buildIndex(lunr, docs)); - const twins = [...stemTwins(lunr, docs)]; - const slices = Array.from({ length: n }, (_, s) => - ids.slice(Math.floor((s * ids.length) / n), Math.floor(((s + 1) * ids.length) / n)), - ); - const pool = slices.map(() => new IndexWorker()); - try { - // 1. Each worker adds its entries. - const added = await Promise.all( - pool.map((worker, s) => { - const slice = {}; - for (const id of slices[s]) slice[id] = docs[id]; - return worker.request({ step: "add", lunrPath, docs: JSON.stringify(slice), twins }); - }), - ); - - // 2. The postings merged, each term numbered as one build numbers it: - // a worker's terms come in the order it met them, and the slices in - // the order of their entries. - const fields = FIELDS.map(([name]) => name); - const merged = new Map(); - const lengths = Object.fromEntries(fields.map((f) => [f, [0, 0]])); - let documentCount = 0; - const numbers = added.map(({ terms, df, postings, lengths: own, documentCount: count }) => { - documentCount += count; - for (const f of fields) { - lengths[f][0] += own[f][0]; - lengths[f][1] += own[f][1]; + return cutIndexSlices( + ids.map((id) => docs[id]), + count, + ).map(([from, to], s) => ({ + slice: s, + docs: Object.fromEntries(ids.slice(from, to).map((id) => [id, docs[id]])), + twins, + })); +} + +// Where `count` slices of the entries `docs`, an array, start and end: each a +// `[from, to)` of contiguous entries, of about equal text. At most one slice +// for each entry, and at least one. +export function cutIndexSlices(docs, count) { + const n = Math.max(1, Math.min(count, docs.length)); + const weight = (doc) => 64 + (doc.content?.length ?? 0) + (doc.title?.length ?? 0) + (doc.names?.length ?? 0); + let total = 0; + for (const doc of docs) total += weight(doc); + const cuts = [[0, 0]]; + let s = 0; + let sofar = 0; + docs.forEach((doc, k) => { + // Move on once this slice has an entry and its share, or once the + // entries left are only enough for one in each slice still to come. + if (s < n - 1 && k > cuts[s][0] && (sofar >= ((s + 1) * total) / n || docs.length - k <= n - 1 - s)) { + cuts.push([k, k]); + s++; + } + cuts[s][1] = k + 1; + sofar += weight(doc); + }); + return cuts; +} + +// The build's slices (tbdocs.mjs, indexSlices): the same cuts as +// planIndexSlices makes, but each slice says where its entries are rather than +// holding them. The lanes that rendered the pages packed the entries, chunk by +// chunk (search.mjs, packSearchEntries), and a lane reads its slice's from +// there (sliceDocs); what was decided since, with every entry known, comes +// with the slice: +// +// first the number of its first entry; the rest follow in order +// segments `[chunk, from, to)` runs of the chunks' entries, in order +// dropped the places, counted along those runs, of entries that were +// dropped (settleLabels) and so have no number +// late by number, the fields of an entry that its packed text does not +// hold: its symbols' `names`, `qualified` and `primary`, and its +// index terms, `index` and `index_also` +// +// `entries` are the final entries in order, and `places[n]` is entry n's +// `[chunk, place in the chunk]` (search.mjs, consolidateSearchEntries). The +// stem twins come apart from the slices, once for all of them. +export function planIndexSegments(entries, places, count) { + // One slice at least, as cutIndexSlices cuts: an empty one for no entries. + if (!entries.length) return [{ slice: 0, first: 0, segments: [], dropped: [], late: {} }]; + return cutIndexSlices(entries, count).map(([from, to], slice) => { + const segments = []; + const dropped = []; + const late = {}; + let run = null; + let before = 0; // the entries of the runs before this one + for (let n = from; n < to; n++) { + const [chunk, place] = places[n]; + if (run && run[0] === chunk) { + // Places a run passes over held entries that were dropped. + for (let gone = run[2]; gone < place; gone++) dropped.push(before + gone - run[1]); + run[2] = place + 1; + } else { + if (run) before += run[2] - run[1]; + run = [chunk, place, place + 1]; + segments.push(run); } - const number = new Int32Array(terms.length); - for (let k = 0; k < terms.length; k++) { - let m = merged.get(terms[k]); - if (!m) { - m = { number: merged.size, df: 0, parts: fields.map(() => []) }; - merged.set(terms[k], m); - } - m.df += df[k]; - const parts = postings[k].split(FIELD_SEPARATOR); - for (let f = 0; f < fields.length; f++) if (parts[f]) m.parts[f].push(parts[f]); - number[k] = m.number; + const e = entries[n]; + const fields = {}; + if (e.names) fields.names = e.names; + if (e.qualified) fields.qualified = e.qualified; + if (e.primary) fields.primary = e.primary; + if (e.index?.length) fields.index = e.index; + if (e.index_also?.length) fields.index_also = e.index_also; + if (Object.keys(fields).length) late[n] = fields; + } + return { slice, first: from, segments, dropped, late }; + }); +} + +// One slice's entries as addSlice takes them, by number, from what +// planIndexSegments planned for it and the chunks' packed entries, read by +// `read(chunk, from, to)`. +export function sliceDocs({ first, segments, dropped, late }, read) { + const gone = new Set(dropped); + const docs = {}; + let along = 0; + let id = first; + for (const [chunk, from, to] of segments) { + for (const doc of read(chunk, from, to)) { + if (gone.has(along++)) continue; + if (late[id]) Object.assign(doc, late[id]); + docs[id++] = doc; + } + } + return docs; +} + +// Step 1: one slice's entries, added to a builder of its own. Returns the +// builder and its terms, which sliceVectors takes later on the same thread, +// and what mergeSlices takes: each term (in the order this builder met it) +// with its document count and its postings field by field, and each field's +// total length. +export function addSlice(lunr, docs, twins) { + const builder = newBuilder(lunr); + const twinSet = twins instanceof Set ? twins : new Set(twins); + for (const id in docs) builder.add(entryFor(lunr, docs, id, twinSet)); + + const fields = Object.keys(builder._fields); + // In the order the builder met them (each posting's _index), not in key + // order, which puts terms that look like numbers ("1", "2025") first. + const terms = new Array(builder.termIndex); + for (const term in builder.invertedIndex) terms[builder.invertedIndex[term]._index] = term; + const df = new Int32Array(terms.length); + const postings = new Array(terms.length); + for (let k = 0; k < terms.length; k++) { + const posting = builder.invertedIndex[terms[k]]; + const parts = []; + // lunr.idf counts an entry once for each field it has the term in. + for (const f of fields) { + df[k] += Object.keys(posting[f]).length; + parts.push(JSON.stringify(posting[f]).slice(1, -1)); + } + postings[k] = parts.join(FIELD_SEPARATOR); + } + const lengths = Object.fromEntries(fields.map((f) => [f, [0, 0]])); + for (const ref in builder.fieldLengths) { + const field = lengths[lunr.FieldRef.fromString(ref).fieldName]; + field[0] += builder.fieldLengths[ref]; + field[1] += 1; + } + return { + state: { builder, terms }, + added: { terms, df, postings, lengths, documentCount: builder.documentCount }, + }; +} + +// Separates a term's per-field postings in what addSlice returns. JSON text +// never holds a raw control character: JSON.stringify escapes them. +export const FIELD_SEPARATOR = "\u{1}"; + +// Step 2: what every slice added, in slice order, merged. Each term is +// numbered as one build numbers it: a slice's terms come in the order it met +// them, and the slices in the order of their entries. Returns the merged +// postings (for invertedIndexJson), each slice's term numbers, each term's +// idf, and the totals createFieldVectors needs (for sliceVectors). +export function mergeSlices(added) { + const fields = FIELDS.map(([name]) => name); + const merged = new Map(); + const lengths = Object.fromEntries(fields.map((f) => [f, [0, 0]])); + let documentCount = 0; + const numbers = added.map(({ terms, df, postings, lengths: own, documentCount: count }) => { + documentCount += count; + for (const f of fields) { + lengths[f][0] += own[f][0]; + lengths[f][1] += own[f][1]; + } + const number = new Int32Array(terms.length); + for (let k = 0; k < terms.length; k++) { + let m = merged.get(terms[k]); + if (!m) { + m = { number: merged.size, df: 0, parts: fields.map(() => []) }; + merged.set(terms[k], m); } - return number; - }); - // lunr.idf, from the term's document count over every entry. - const idf = new Float64Array(merged.size); - for (const m of merged.values()) { - const x = (documentCount - m.df + 0.5) / (m.df + 0.5); - idf[m.number] = Math.log(1 + Math.abs(x)); + m.df += df[k]; + const parts = postings[k].split(FIELD_SEPARATOR); + for (let f = 0; f < fields.length; f++) if (parts[f]) m.parts[f].push(parts[f]); + number[k] = m.number; } - // calculateAverageFieldLengths(), and pinIndexFieldLengths(). - const averageFieldLength = {}; - for (const f of fields) averageFieldLength[f] = lengths[f][0] / lengths[f][1]; - averageFieldLength.index = 1; - - // 3. Each worker makes its entries' field vectors. - const vectors = await Promise.all( - pool.map((worker, s) => - worker.request({ step: "vectors", numbers: numbers[s], idf, documentCount, averageFieldLength }), - ), - ); - - // 4. lunr's toJSON: the terms sorted, the postings as JSON.stringify - // writes them (`_index`, then each field, its refs in numeric order). - const invertedIndex = [...merged.keys()].sort().map((term) => { + return number; + }); + // lunr.idf, from the term's document count over every entry. + const idf = new Float64Array(merged.size); + for (const m of merged.values()) { + const x = (documentCount - m.df + 0.5) / (m.df + 0.5); + idf[m.number] = Math.log(1 + Math.abs(x)); + } + // calculateAverageFieldLengths(), and pinIndexFieldLengths(). + const averageFieldLength = {}; + for (const f of fields) averageFieldLength[f] = lengths[f][0] / lengths[f][1]; + averageFieldLength.index = 1; + return { merged, totals: { numbers, idf, documentCount, averageFieldLength } }; +} + +// Step 3: lunr's createFieldVectors over one slice's builder (addSlice's +// state), with every term numbered as the whole index numbers it, and the +// counts and averages of every entry (`totals`, from mergeSlices, with +// `numbers` this slice's). Returns the vectors as toJSON writes them, in the +// order of the slice's entries; "" for a slice with none. +export function sliceVectors(lunr, { builder, terms }, { numbers, idf, documentCount, averageFieldLength }) { + for (let k = 0; k < terms.length; k++) builder.invertedIndex[terms[k]]._index = numbers[k]; + builder.documentCount = documentCount; + builder.averageFieldLength = averageFieldLength; + const ownIdf = lunr.idf; + lunr.idf = (posting) => idf[posting._index]; + try { + builder.createFieldVectors(); + } finally { + lunr.idf = ownIdf; + } + return Object.keys(builder.fieldVectors) + .map((ref) => JSON.stringify([ref, builder.fieldVectors[ref].toJSON()])) + .join(","); +} + +// Step 4a: lunr's toJSON of the inverted index, from mergeSlices' merged +// postings: the terms sorted, the postings as JSON.stringify writes them +// (`_index`, then each field, its refs in numeric order). The text between +// the brackets. +export function invertedIndexJson(merged) { + const fields = FIELDS.map(([name]) => name); + return [...merged.keys()] + .sort() + .map((term) => { const m = merged.get(term); let s = `[${JSON.stringify(term)},{"_index":${m.number}`; for (let f = 0; f < fields.length; f++) s += `,${JSON.stringify(fields[f])}:{${m.parts[f].join(",")}}`; return `${s}}]`; - }); - const pipeline = newBuilder(lunr).searchPipeline.toJSON(); - return ( - `{"version":${JSON.stringify(lunr.version)},"fields":${JSON.stringify(fields)},` + - `"fieldVectors":[${vectors.filter(Boolean).join(",")}],` + - `"invertedIndex":[${invertedIndex.join(",")}],"pipeline":${JSON.stringify(pipeline)}}` - ); - } finally { - await Promise.all(pool.map((worker) => worker.close())); - } + }) + .join(","); } -// Separates a term's per-field postings in what a worker returns. JSON text -// never holds a raw control character: JSON.stringify escapes them. -export const FIELD_SEPARATOR = "\u0001"; - -// One worker thread (search-index-worker.mjs), which keeps its builder between -// the two steps. A request's answer, or the worker's failure, settles it. -class IndexWorker { - constructor() { - this.worker = new Worker(new URL("./search-index-worker.mjs", import.meta.url)); - this.pending = null; - const fail = (err) => { - this.failure = err; - this.pending?.reject(err); - this.pending = null; - }; - this.worker.on("message", (msg) => { - const pending = this.pending; - this.pending = null; - if (!pending) return; - if (msg.error) pending.reject(new Error(`search index worker: ${msg.error}`)); - else pending.resolve(msg.result); - }); - this.worker.on("error", fail); - this.worker.on("exit", (code) => fail(new Error(`search index worker exited with code ${code}`))); - } +// Step 4b: the index's JSON, from each slice's vectors in slice order and +// invertedIndexJson's text. +export function assembleIndexJson(lunr, vectors, invertedIndex) { + const fields = FIELDS.map(([name]) => name); + const pipeline = newBuilder(lunr).searchPipeline.toJSON(); + return ( + `{"version":${JSON.stringify(lunr.version)},"fields":${JSON.stringify(fields)},` + + `"fieldVectors":[${vectors.filter(Boolean).join(",")}],` + + `"invertedIndex":[${invertedIndex}],"pipeline":${JSON.stringify(pipeline)}}` + ); +} - request(msg) { - if (this.failure) return Promise.reject(this.failure); - return new Promise((resolve, reject) => { - this.pending = { resolve, reject }; - this.worker.postMessage(msg); - }); - } +// The index of `docs` as lunr's JSON, every step on this thread, in `slices` +// slices. Every slice count gives the same bytes, and they are lunr()'s. +export function buildIndexJson(docs, { slices = 1, lunrPath = LUNR_PATH } = {}) { + const lunr = loadSearchLunr(lunrPath); + const plan = planIndexSlices(lunr, docs, slices); + const states = []; + const added = plan.map((p) => { + const { state, added: a } = addSlice(lunr, p.docs, p.twins); + states.push(state); + return a; + }); + const { merged, totals } = mergeSlices(added); + const vectors = states.map((state, s) => sliceVectors(lunr, state, { ...totals, numbers: totals.numbers[s] })); + return assembleIndexJson(lunr, vectors, invertedIndexJson(merged)); +} - async close() { - this.worker.removeAllListeners("exit"); - await this.worker.terminate(); +// ── Between threads ──────────────────────────────────────────────────────── + +// mergeSlices' totals, packed into one SharedArrayBuffer for the lanes that +// make the vectors: a header (its length, then JSON of where each slice's term +// numbers are), then as float64 the document count, each field's average +// length in FIELDS order, and each term's idf, then as int32 every slice's term +// numbers. A lane reads it in place (unpackTotals). +export function packTotals({ numbers, idf, documentCount, averageFieldLength }) { + const fields = FIELDS.map(([name]) => name); + const ranges = []; + let ints = 0; + for (const n of numbers) { + ranges.push([ints, n.length]); + ints += n.length; } + const head = new TextEncoder().encode(JSON.stringify({ ranges, terms: idf.length })); + const headBytes = 8 + Math.ceil(head.length / 8) * 8; + const floats = 1 + fields.length + idf.length; + const sab = new SharedArrayBuffer(headBytes + floats * 8 + ints * 4); + new Uint32Array(sab, 0, 1)[0] = head.length; + new Uint8Array(sab, 8, head.length).set(head); + const f64 = new Float64Array(sab, headBytes, floats); + f64[0] = documentCount; + fields.forEach((f, i) => { + f64[1 + i] = averageFieldLength[f]; + }); + f64.set(idf, 1 + fields.length); + const i32 = new Int32Array(sab, headBytes + floats * 8, ints); + for (let s = 0; s < numbers.length; s++) i32.set(numbers[s], ranges[s][0]); + return sab; +} + +// packTotals' SharedArrayBuffer, read in place, with `numbers` slice `s`'s. +export function unpackTotals(sab, s) { + const fields = FIELDS.map(([name]) => name); + const headLength = new Uint32Array(sab, 0, 1)[0]; + const { ranges, terms } = JSON.parse(new TextDecoder().decode(new Uint8Array(sab, 8, headLength).slice())); + if (!ranges[s]) throw new Error(`search index: no term numbers for slice ${s}`); + const headBytes = 8 + Math.ceil(headLength / 8) * 8; + const floats = 1 + fields.length + terms; + const f64 = new Float64Array(sab, headBytes, floats); + const averageFieldLength = {}; + fields.forEach((f, i) => { + averageFieldLength[f] = f64[1 + i]; + }); + const [at, length] = ranges[s]; + return { + documentCount: f64[0], + averageFieldLength, + idf: f64.subarray(1 + fields.length), + numbers: new Int32Array(sab, headBytes + floats * 8 + at * 4, length), + }; } // ── The file the page loads ──────────────────────────────────────────────── @@ -463,17 +659,19 @@ export function offlineSearchIndexJs(fileText) { return `window.SEARCH_INDEX = JSON.parse('${literal}');\n`; } -// The build's searchIndex task (cpu-worker.mjs): reads the search-data.json -// the build wrote under `destRoot`, and writes search-index.json beside it -// and, when `offline`, search-index.js in the offline tree. -export async function writeSearchIndex(destRoot, { offline }) { - const docs = JSON.parse(await fs.readFile(path.join(destRoot, "assets/js/search-data.json"), "utf8")); - const entries = Object.keys(docs).length; - const workers = defaultIndexWorkers(entries); - const text = searchIndexFile(await buildIndexJson(docs, { workers }), docs); - await writeFileMkdirp(path.join(destRoot, "assets/js/search-index.json"), text); +// Where the two files go: search-index.json in the online tree, and +// search-index.js in the offline one. +export const SEARCH_INDEX_REL = "assets/js/search-index.json"; +export const OFFLINE_SEARCH_INDEX_REL = "assets/js/search-index.js"; + +// The build's searchIndex task (tbdocs.mjs): writes search-index.json under +// `destRoot` and, when `offline`, search-index.js in the offline tree, from +// the index's JSON and the entries it indexes. +export async function writeSearchIndex(destRoot, indexJson, docs, { offline }) { + const text = searchIndexFile(indexJson, docs); + await writeFileMkdirp(path.join(destRoot, SEARCH_INDEX_REL), text); if (offline) { - await writeFileMkdirp(path.join(`${destRoot}-offline`, "assets/js/search-index.js"), offlineSearchIndexJs(text)); + await writeFileMkdirp(path.join(`${destRoot}-offline`, OFFLINE_SEARCH_INDEX_REL), offlineSearchIndexJs(text)); } - return { entries, workers, bytes: Buffer.byteLength(text) }; + return { entries: Object.keys(docs).length, bytes: Buffer.byteLength(text) }; } diff --git a/builder/search.mjs b/builder/search.mjs index 17926cb8b..034b2d6b4 100644 --- a/builder/search.mjs +++ b/builder/search.mjs @@ -35,13 +35,27 @@ import { stripHtml } from "./seo.mjs"; import { encodeSpaces } from "./url.mjs"; import { writeFileMkdirp } from "./write.mjs"; -// Phase 17 consolidation path: per-worker render handlers call -// deriveSearchEntries on their chunk and stash the result on -// state.searchChunks[i]. This function flattens those chunks (in chunk- -// index order, matching the serial page iteration), renumbers `i` so it -// is globally sequential, and writes the same byte-for-byte search-data.json -// a single-pass derivation over all pages at once would have produced. -export async function writeSearchDataFromChunks(searchChunks, destRoot, symbols) { +// The search entries, final. Per-worker render handlers call +// deriveSearchEntries on their chunk, and each render:i.submit() stashes the +// result on state.searchChunks[i]. This flattens those chunks (in chunk- +// index order, matching the serial page iteration), settles the labels, +// renumbers `i` so it is globally sequential, and joins the symbols: the +// entries a single-pass derivation over all pages at once would have produced. +// +// It is what stands between the last render chunk and the search index's +// slices, with every lane waiting, so it does only what needs every entry: +// what an entry alone decides is done by the lane that rendered it +// (entryKeys, packSearchEntries), and the file is written afterwards +// (writeSearchData). +// +// `keyChunks` are the entries' settle keys, chunk by chunk as the entries are +// (entryKeys); without them settleLabels works them out. +// +// Returns the entries, and where each is among what the lanes sent: +// `places[n]` is entry n's `[chunk, place in the chunk]`. An entry that +// settleLabels dropped has no number, and its place is skipped. +// writeSearchData and planIndexSegments find an entry's packed text by it. +export function consolidateSearchEntries(searchChunks, symbols, keyChunks = null) { // searchChunks starts as `new Array(N)` -- holes, not undefined -- and // each render:i.submit() fills its own slot. Array.prototype.flat() // skips holes silently, so a slot that has not been filled yet does @@ -65,13 +79,157 @@ export async function writeSearchDataFromChunks(searchChunks, destRoot, symbols) const flat = searchChunks.flat(); checkIndexTerms(flat); - const allEntries = settleLabels(flat); - for (let idx = 0; idx < allEntries.length; idx++) allEntries[idx].i = idx; - if (symbols?.length) joinSymbolsToEntries(allEntries, symbols); - const body = allEntries.map(renderEntryString).join(","); - const json = `{` + body + `\n}\n`; + const keys = keyChunks?.flat(); + // Asserted: keys one out of step would settle every entry by another's. + if (keys && keys.length !== flat.length) { + throw new Error(`search index: ${flat.length} entries came with the settle keys of ${keys.length}`); + } + const entries = settleLabels(flat, keys); + // settleLabels keeps the order, so the kept entries are met in turn. + const places = new Array(entries.length); + let n = 0; + searchChunks.forEach((chunk, c) => { + for (let k = 0; k < chunk.length; k++) if (chunk[k] === entries[n]) places[n++] = [c, k]; + }); + if (n !== entries.length) { + throw new Error(`search index: ${entries.length} entries were kept, and ${n} of them are in the chunks`); + } + for (let idx = 0; idx < entries.length; idx++) entries[idx].i = idx; + if (symbols?.length) joinSymbolsToEntries(entries, symbols); + return { entries, places }; +} + +// The entries as search-data.json holds them, parsed: `{ "0": { doc, title, +// content, ... }, ... }`, each with its fields in the file's order. The search +// index writes them into search-index.json, and they are made from the entries +// rather than parsed from the file's text, which would cost the build a parse +// of 11 MB; test/search.test.mjs checks that the two are the same. +export function searchDocs(entries) { + const docs = {}; + for (const e of entries) { + const doc = { doc: e.doc, title: e.title, content: e.content }; + if (e.names) doc.names = e.names; + if (e.qualified) doc.qualified = e.qualified; + if (e.primary) doc.primary = e.primary; + if (e.index?.length) doc.index = e.index; + if (e.index_also?.length) doc.index_also = e.index_also; + doc.url = e.url; + doc.relUrl = e.relUrl; + docs[e.i] = doc; + } + return docs; +} + +// ── Between the lanes ────────────────────────────────────────────────────── +// +// The lane that renders a chunk writes its entries' text into a +// SharedArrayBuffer (packSearchEntries), once, for two readers. The lanes that +// build the search index read their entries from it in place +// (readSearchEntries), and the main thread copies each entry's text from it +// into search-data.json (searchDataBytes). The main thread gets the entries +// too, as objects, and decides what only it can (the numbers, the dropped term +// entries, the labels, the symbols); what it decided reaches the index's lanes +// as a few KB beside each slice (planIndexSegments in search-index.mjs), not as +// the entries all over again. + +const encoder = new TextEncoder(); +const decoder = new TextDecoder(); + +// A chunk's entries in one SharedArrayBuffer, each as the head and the tail of +// its text in search-data.json (entryHead, entryTail), which together are a +// JSON object of the fields known when the page is rendered: doc, title, +// content, url and relUrl. First the count, then for each entry where its text +// starts and where its tail does, then where the last entry's text ends +// (uint32, in bytes from the texts' start); then the texts, with a comma +// between them, so that any run of entries is the inside of a JSON array. +export function packSearchEntries(entries) { + const count = entries.length; + const texts = new Array(count); + const words = new Uint32Array(2 * count + 2); + words[0] = count; + let at = 0; + for (let k = 0; k < count; k++) { + const head = entryHead(entries[k]); + const tail = entryTail(entries[k]); + texts[k] = head + tail; + words[1 + 2 * k] = at; + at += Buffer.byteLength(head); + words[2 + 2 * k] = at; + at += Buffer.byteLength(tail) + 1; + } + words[1 + 2 * count] = at; + const sab = new SharedArrayBuffer(words.byteLength + at); + new Uint32Array(sab, 0, words.length).set(words); + const { written } = encoder.encodeInto(texts.join(","), new Uint8Array(sab, words.byteLength)); + // Asserted: a short write would leave an entry's text cut, and a reader's + // JSON.parse would say only where, not why. + if (written !== Math.max(0, at - 1)) throw new Error(`search entries: packed ${written} bytes, expected ${at - 1}`); + return sab; +} + +// What packSearchEntries packed, to read in place. Entry k's text is `bytes` +// from words[1 + 2k] to words[3 + 2k] - 1, the comma left out, and its tail +// starts at words[2 + 2k]. +function packedEntries(sab) { + const count = new Uint32Array(sab, 0, 1)[0]; + const words = new Uint32Array(sab, 0, 2 * count + 2); + return { count, words, bytes: Buffer.from(sab, words.byteLength) }; +} + +// Entries `from` to `to` (exclusive) of what packSearchEntries packed, each +// `{ doc, title, content, url, relUrl }`. +export function readSearchEntries(sab, from = 0, to = undefined) { + const { count, words, bytes } = packedEntries(sab); + const end = to ?? count; + if (from < 0 || end > count || from > end) { + throw new Error(`search entries: ${from} to ${end} is not within the chunk's ${count}`); + } + if (from === end) return []; + return JSON.parse(`[${decoder.decode(bytes.subarray(words[1 + 2 * from], words[1 + 2 * end] - 1))}]`); +} + +// search-data.json's bytes, from the final entries, where each is among the +// chunks (consolidateSearchEntries' `places`) and the chunks as their lanes +// packed them: `{`, then each entry as renderEntryString writes it, with a +// comma between them, then a line break, `}` and a line break. An entry's head +// and tail are copied from its lane's buffer, so the main thread writes only +// its number and the fields it got since. +export function searchDataBytes(entries, places, packed) { + const chunks = packed.map(packedEntries); + const prefixes = entries.map((e) => `${e.i === 0 ? "{" : ","}"${e.i}": `); + const extras = entries.map(entryExtra); + let size = 3; + if (!entries.length) size += 1; + for (let n = 0; n < entries.length; n++) { + const [c, k] = places[n]; + const { words } = chunks[c]; + size += prefixes[n].length + words[3 + 2 * k] - 1 - words[1 + 2 * k]; + if (extras[n]) size += Buffer.byteLength(extras[n]); + } + const out = Buffer.allocUnsafe(size); + let to = entries.length ? 0 : out.write("{", 0, "latin1"); + for (let n = 0; n < entries.length; n++) { + const [c, k] = places[n]; + const { words, bytes } = chunks[c]; + const tail = words[2 + 2 * k]; + to += out.write(prefixes[n], to, "latin1"); + to += bytes.copy(out, to, words[1 + 2 * k], tail); + if (extras[n]) to += out.write(extras[n], to, "utf8"); + to += bytes.copy(out, to, tail, words[3 + 2 * k] - 1); + } + to += out.write("\n}\n", to, "latin1"); + // Asserted: the buffer is not zeroed, so a short count would write whatever + // was in memory into the file. + if (to !== size) throw new Error(`search-data.json: wrote ${to} bytes of ${size}`); + return out; +} + +// Writes search-data.json; returns its bytes, which the link check reads, and +// the entries as the file holds them (searchDocs). +export async function writeSearchData({ entries, places }, packed, destRoot) { + const json = searchDataBytes(entries, places, packed); await writeFileMkdirp(path.join(destRoot, "assets/js/search-data.json"), json); - return { entries: allEntries.length, json }; + return { entries: entries.length, json, docs: searchDocs(entries) }; } // Pure-compute derivation: produces the search-data entry array @@ -410,31 +568,67 @@ function boldLabels(html) { // becomes a secondary index term of the entry that holds it, unless a heading, a // page title, a term entry or a hand mark already answers it. Returns the // entries kept, each without its labels. -export function settleLabels(entries) { - const key = (s) => - stripHtml(String(s)) - .toLowerCase() - .replace(/&[a-z]+;/g, " ") - .replace(/[^\p{L}\p{N}]+/gu, " ") - .trim(); +// +// Two names are compared by their keys (labelKey). `keys` holds each entry's +// (entryKeys), in the entries' order. The render lanes work them out and send +// them beside the entries, which then hold no `labels` at all, so that this, +// which every lane waits for, only compares: working the keys out here took +// longer than everything else it does, and so did deleting a property from +// every entry. +export function settleLabels(entries, keys = entries.map((e) => entryKeys(e))) { const isTerm = (e) => e.relUrl.includes(`#${TERM_ID_PREFIX}`); - const mains = new Set(entries.flatMap((e) => (e.index ?? []).map(key))); - const kept = entries.filter((e) => !(isTerm(e) && mains.has(key(e.title)))); + const mains = new Set(); + for (const k of keys) for (const t of k.index) mains.add(t); + const kept = []; + const keptKeys = []; + entries.forEach((e, n) => { + if (isTerm(e) && mains.has(keys[n].title)) return; + kept.push(e); + keptKeys.push(keys[n]); + }); const answered = new Set(mains); - for (const e of kept) { - answered.add(key(e.title)); - answered.add(key(e.doc)); - for (const t of e.index_also ?? []) answered.add(key(t)); - if (isTerm(e)) for (const l of e.labels ?? []) answered.add(key(l)); - } - for (const e of kept) { - const labels = (e.labels ?? []).filter((l) => !answered.has(key(l))); - if (labels.length) e.index_also = [...new Set([...(e.index_also ?? []), ...labels])]; - delete e.labels; - } + kept.forEach((e, n) => { + const k = keptKeys[n]; + answered.add(k.title); + answered.add(k.doc); + for (const t of k.also) answered.add(t); + if (k.labels.length && isTerm(e)) for (const l of k.labels) answered.add(l); + }); + kept.forEach((e, n) => { + const k = keptKeys[n]; + if (k.labels.length) { + const labels = k.written.filter((_, j) => !answered.has(k.labels[j])); + if (labels.length) e.index_also = [...new Set([...(e.index_also ?? []), ...labels])]; + } + if ("labels" in e) delete e.labels; + }); return kept; } +// A name as settleLabels compares it: without its HTML, lowercased, an entity +// and any run of other characters as one space. +export function labelKey(s) { + return stripHtml(String(s)) + .toLowerCase() + .replace(/&[a-z]+;/g, " ") + .replace(/[^\p{L}\p{N}]+/gu, " ") + .trim(); +} + +// The keys of everything settleLabels compares of one entry, and its labels as +// written, which `labels` holds the keys of. `key` may be a labelKey that +// remembers: a page's entries share its title. +export function entryKeys(e, key = labelKey) { + return { + title: key(e.title), + doc: key(e.doc), + index: (e.index ?? []).map(key), + also: (e.index_also ?? []).map(key), + labels: (e.labels ?? []).map(key), + written: e.labels ?? [], + }; +} + // Returns the heading-split sections plus the prose-before-first-heading // (`parts[0]`) and a `titleFound` flag indicating whether the title- // prefix entry should be suppressed. @@ -542,11 +736,11 @@ function extractSections(page, pageTitle, headingLevel, foldSet = new Set()) { function normalizeSymbolUrl(u) { const s = String(u ?? ""); const hashIdx = s.indexOf("#"); - const pathPart = hashIdx === -1 ? s : s.slice(0, hashIdx); - const hash = hashIdx === -1 ? "" : s.slice(hashIdx); - const noIndex = pathPart.replace(/\/index(\.html)?$/, ""); - const noTrailingSlash = noIndex.length > 1 && noIndex.endsWith("/") ? noIndex.slice(0, -1) : noIndex; - return noTrailingSlash + hash; + let pathPart = hashIdx === -1 ? s : s.slice(0, hashIdx); + if (pathPart.endsWith("/index")) pathPart = pathPart.slice(0, -"/index".length); + else if (pathPart.endsWith("/index.html")) pathPart = pathPart.slice(0, -"/index.html".length); + if (pathPart.length > 1 && pathPart.endsWith("/")) pathPart = pathPart.slice(0, -1); + return hashIdx === -1 ? pathPart : pathPart + s.slice(hashIdx); } // Joins `tB/symbols.json`'s in-memory symbols (each `{ name, container, @@ -572,10 +766,17 @@ export function joinSymbolsToEntries(entries, symbols) { const moduleNames = new Set(); for (const s of symbols ?? []) if (s.kind === "module") moduleNames.add(s.name.toLowerCase()); const byUrl = new Map(); + // The symbol index is in URL order, so a symbol is mostly at the URL of the + // one before it. + let url; + let bucket; for (const s of symbols ?? []) { - const key = normalizeSymbolUrl(s.url); - let bucket = byUrl.get(key); - if (!bucket) byUrl.set(key, (bucket = { names: new Set(), qualified: new Set(), primary: new Set() })); + if (s.url !== url || !bucket) { + url = s.url; + const key = normalizeSymbolUrl(url); + bucket = byUrl.get(key); + if (!bucket) byUrl.set(key, (bucket = { names: new Set(), qualified: new Set(), primary: new Set() })); + } bucket.names.add(s.name); if (s.container) bucket.qualified.add(`${s.container}.${s.name}`); if (isPrimarySymbol(s, moduleNames)) bucket.primary.add(s.name); @@ -620,23 +821,35 @@ function isPrimarySymbol(s, moduleNames) { // symbols (most of them -- see WIP.Search.md's "Design" §2) produces the // exact same bytes as before the join existed. export function renderEntryString(e) { + return `"${e.i}": ` + entryHead(e) + entryExtra(e) + entryTail(e); +} + +// An entry's text in three parts. The head and the tail hold what is known +// when its page is rendered, and together are a JSON object of those fields: +// the lane that renders the page writes them (packSearchEntries). The number +// before them and the fields between them are known only once every page is +// rendered. +function entryHead(e) { + return ( + `{\n` + + ` "doc": ${JSON.stringify(e.doc)},\n` + + ` "title": ${JSON.stringify(e.title)},\n` + + ` "content": ${JSON.stringify(e.content)},\n` + ); +} + +function entryExtra(e) { let extra = ""; if (e.names) extra += ` "names": ${JSON.stringify(e.names)},\n`; if (e.qualified) extra += ` "qualified": ${JSON.stringify(e.qualified)},\n`; if (e.primary) extra += ` "primary": ${JSON.stringify(e.primary)},\n`; if (e.index?.length) extra += ` "index": ${JSON.stringify(e.index)},\n`; if (e.index_also?.length) extra += ` "index_also": ${JSON.stringify(e.index_also)},\n`; - return ( - `"${e.i}": {\n` + - ` "doc": ${JSON.stringify(e.doc)},\n` + - ` "title": ${JSON.stringify(e.title)},\n` + - ` "content": ${JSON.stringify(e.content)},\n` + - extra + - ` "url": "${e.url}",\n` + - ` \n` + - ` "relUrl": "${e.relUrl}"\n` + - ` }` - ); + return extra; +} + +function entryTail(e) { + return ` "url": "${e.url}",\n` + ` \n` + ` "relUrl": "${e.relUrl}"\n` + ` }`; } // Content sanitiser. Port of the Liquid filter chain in the template's diff --git a/builder/symbols.mjs b/builder/symbols.mjs index d80b1c096..9755c781f 100644 --- a/builder/symbols.mjs +++ b/builder/symbols.mjs @@ -616,17 +616,24 @@ function isInternal(m) { export const SYMBOL_INDEX_FORMAT = 1; export const SYMBOL_INDEX_REL = "tB/symbols.json"; +/** + * Whether deriveSymbolIndex reads a page: one under /tB/, or a summary page. + * The lane that renders such a page reads its headings (headingsOf) and sends + * them back with it, so that the main thread need not, after the last chunk + * and with every lane waiting. + */ +export function isSymbolPage(p) { + return String(p.permalink ?? "").startsWith("/tB/") || SUMMARY_PAGES.has(p.srcRel); +} + /** * The build's pages as deriveSymbolIndex reads them: those under /tB/, and the - * summary pages, with the headings of their rendered HTML. + * summary pages, with the headings of their rendered HTML, which are the + * page's `headings` when it has them and are read here when it has not. */ export function symbolPages(pages) { return pages - .filter( - (p) => - (String(p.permalink ?? "").startsWith("/tB/") || SUMMARY_PAGES.has(p.srcRel)) && - typeof p.renderedContent === "string", - ) + .filter((p) => isSymbolPage(p) && typeof p.renderedContent === "string") .map((p) => { const fm = p.frontmatter ?? {}; // YAML reads an unquoted True, False or Null as a boolean or null, which would be @@ -642,7 +649,7 @@ export function symbolPages(pages) { parent: fm.parent, symbols: fm.symbols == null ? null : [].concat(fm.symbols), excludeFromDocs: fm.exclude_from_docs == null ? null : [].concat(fm.exclude_from_docs).map(String), - headings: headingsOf(p.renderedContent), + headings: p.headings ?? headingsOf(p.renderedContent), }; }); } diff --git a/builder/tbdocs.mjs b/builder/tbdocs.mjs index 8b605254a..ce03380bc 100644 --- a/builder/tbdocs.mjs +++ b/builder/tbdocs.mjs @@ -63,8 +63,8 @@ import { WorkerPool } from "./worker-pool.mjs"; import { Scheduler } from "./scheduler.mjs"; import { GANTT_SECTION, groupGanttTimings, renderGantt } from "./gantt.mjs"; -import { discover } from "./discover.mjs"; -import { checkPlaceholders, deriveCounts, deriveDownloads } from "./counts.mjs"; +import { assemble, cutPieces, listSources } from "./discover.mjs"; +import { checkPlaceholders, deriveCounts, deriveDownloads, packedDownloads } from "./counts.mjs"; import { computeNav } from "./nav.mjs"; import { vendorAssets } from "./vendor-assets.mjs"; import { computeSiteSeo } from "./seo.mjs"; @@ -73,7 +73,7 @@ import { packBookPayload } from "./book-payload.mjs"; import { loadData } from "./data.mjs"; import { createMarkdownIt, buildLinkTables, diagramIsTall, serializeLinkTables } from "./render.mjs"; import { assignPackageVersions } from "../lib/callout-labels.mjs"; -import { isPictureSvg, pairSizes, pictureSvgOutputs, unpairedLightPictures } from "./theme-pictures.mjs"; +import { isPictureSvg, pictureSvgOutputs, unpairedLightPictures } from "./theme-pictures.mjs"; import { loadHighlightTheme } from "./highlight-theme.mjs"; import { NAV_SCRIPT_REL, @@ -95,7 +95,7 @@ import { writeRedirects, deriveRedirectStubs } from "./redirects.mjs"; import { writeSitemap, deriveSitemapUrls } from "./sitemap.mjs"; import { writeLlmsTxt } from "./llms-txt.mjs"; import { markdownCopyRel } from "./markdown-copy.mjs"; -import { writeSearchDataFromChunks } from "./search.mjs"; +import { consolidateSearchEntries, writeSearchData } from "./search.mjs"; import { writeOffline, enumerateVendoredThemeAssets } from "./offline.mjs"; import { buildSitePathsSync, deriveOfflineCss, isWebsiteOnlyLink, websiteOf } from "./offline-rewrite.mjs"; import { normalizeBaseurl } from "./url.mjs"; @@ -107,14 +107,26 @@ import { normalizeBaseurl } from "./url.mjs"; import { deriveTreeRels } from "./check-tree.mjs"; import { syncAddinIndex } from "./addin-index.mjs"; import { addinProjectOf, formatAddinProject, writeAddinProject } from "./addin-project.mjs"; +import { formatPackageTests, packageTestRels, packageTestsOf, writePackageTests } from "./package-tests.mjs"; import { - formatPackageTests, - packageTestRels, - packageTestsOf, - packAllPackageTests, - writePackageTests, -} from "./package-tests.mjs"; -import { recheckHelpArchive } from "./help-archive-step.mjs"; + finishHelpArchive, + helpArchiveOut, + planHelpArchive, + planLateFiles, + recheckHelpArchive, +} from "./help-archive-step.mjs"; +import { fanOut } from "./fan-out.mjs"; +import { + assembleIndexJson, + indexSliceCount, + invertedIndexJson, + loadSearchLunr, + mergeSlices, + packTotals, + planIndexSegments, + stemTwins, + writeSearchIndex, +} from "./search-index.mjs"; import { baselineWrites } from "./baseline.mjs"; import { checkPageBaseline } from "./page-baseline.mjs"; import { checkSymbolBaseline } from "./symbol-baseline.mjs"; @@ -131,6 +143,7 @@ import { verifySchedulerSAB, SLICES_PER_WORKER, HANDLERS, + DONE, F_PIN_TO_PRED, writeTaskMeta, allocDynamicSlots, @@ -167,6 +180,13 @@ function failBuild() { // summary, and returns. const workerCount = os.availableParallelism(); +// How many pieces the source tree is read in, each on a lane (discoverList). +// Two on a machine with fewer than eight logical CPUs: on a four-CPU CI +// runner the other two lanes compile the stylesheets meanwhile, and more +// pieces would put those, dot and packTests behind the reads. On Linux two +// pieces took discover from about 1.0 s to under 0.3 s. Four from eight CPUs +// on (owner), where four lanes reading still leave lanes for the rest. +const discoverPieces = (cpus) => Math.max(1, Math.min(cpus >= 8 ? 4 : 2, cpus)); // Register a dynamic fan-in barrier: BOTH halves of its invariant, in // one call, because writing one without the other is a data-loss bug @@ -200,6 +220,21 @@ function registerBarrier(scheduler, views, join, joinIdx, prefix, n) { setDepCount(views, joinIdx, n); } +// The help archive's groups of units (help-archive-step.mjs) as lane tasks +// `${prefix}:i`, which helpArchive joins. +function fanOutArchive(scheduler, from, prefix, root, groups, priority = 1) { + fanOut(scheduler, { + from, + prefix, + handler: "archiveDeflate", + payloads: groups.map((units) => ({ root, units })), + joins: ["helpArchive"], + ganttSection: "Write", + priority, + describe: (p) => p.units.map((u) => (u.piece ? `${u.name}, piece ${u.piece[0] + 1} of ${u.piece[1]}` : u.name)), + }); +} + // Does this run skip the offline or the PDF pass? --no-offline and --no-pdf // (serve mode passes both), else _config.yml's also_build_offline and // also_build_pdf. Every task that writes or prepares a tree asks here, so that @@ -228,12 +263,20 @@ const TASKS = { config.url = String(config.url ?? "").replace(/\/+$/, ""); return { config }; }, - submit() {}, + // What packTests packs, for the lane that runs it: broadcast before this + // task is marked done, so it is queued on every lane before one can claim + // packTests. + submit({ config }, _state, scheduler) { + scheduler.pool.broadcastTaskData("packageTests", packShared(config.package_tests ?? null)); + }, }, - // Git rev-parse / log shell-outs. Worker so they overlap with the main spine. + // Git rev-parse / log shell-outs, for the book's title page: bookPayload + // waits for them, and nothing on the way to the first render does. Like the + // other early lane tasks it waits for discoverList, so that the first lanes + // up read the source tree. buildInfo: { - expected: [], + expected: ["discoverList"], handler: "buildInfo", submit(out, state) { state.site.buildInfo = out.buildInfo; @@ -243,13 +286,13 @@ const TASKS = { // Sass compilation split across two workers so light + dark run in parallel. // Each half is ~700 ms total serially; running concurrently saves ~200 ms. scssLight: { - expected: [], + expected: ["discoverList"], handler: "scssLight", submit() {}, }, scssDark: { - expected: [], + expected: ["discoverList"], handler: "scssDark", submit() {}, }, @@ -301,7 +344,7 @@ const TASKS = { // no in-tree patches. Runs on a worker as a seed so the Graphviz.load() // WASM init (~50 ms) hides behind the main spine. dot: { - expected: [], + expected: ["discoverList"], handler: "dot", submit(out, state) { const known = new Set(state.staticFiles.map((f) => f.srcRel)); @@ -369,7 +412,7 @@ const TASKS = { // worker has run it, the highlighter persists in module scope across // init messages, so survives_reset lets rebuilds skip it. warmInit: { - expected: [], + expected: ["discoverList"], on_demand: true, unique_per_worker: true, run_when_idle: true, @@ -460,16 +503,53 @@ const TASKS = { // ── Main-thread spine ───────────────────────────────────────────────────── - discover: { + // The source tree's inventory, in three steps (discover.mjs), of which the + // lanes do the middle one, where every file is opened. discoverList lists + // the tree and cuts the listing into pieces; each discoverRead:i reads its + // piece's pages and parses their frontmatter, sizes its static files and + // reads its picture pairs' headers (discover-read.mjs); discover puts the + // results together and checks them. + // + // The pieces are the first thing a lane takes: a lane runs one after the + // first stage of its boot alone (cpu-worker.mjs), and the lane tasks that + // would otherwise be READY before the pieces exist wait for this task, so + // that the first lanes up are free for the pieces. The listing takes a few + // hundredths of a second, less than a lane takes to start. + discoverList: { expected: ["config"], runOnMain: true, async execute({ config: { config } }, ctx) { - const { pages, staticFiles } = await discover(ctx.srcRoot, config.exclude ?? []); - for (const entry of config.bundle_extra ?? []) { - const srcPath = path.resolve(ctx.srcRoot, entry.src); - const stat = await fs.stat(srcPath); - staticFiles.push({ srcPath, srcRel: entry.dest, destRel: entry.dest, size: stat.size }); - } + const listing = await listSources(ctx.srcRoot, config.exclude ?? []); + return cutPieces(listing, discoverPieces(ctx.workerCount), config.bundle_extra ?? []); + }, + submit(out, _state, scheduler) { + fanOut(scheduler, { + from: "discoverList", + prefix: "discoverRead", + handler: "discoverRead", + payloads: out.pieces, + joins: ["discover"], + ganttSection: "Spine", + priority: 3, + describe: (p) => [`${p.pageRels.length} pages from ${p.pageRels[0]}, ${p.statSrcs.length} static files`], + }); + }, + }, + + discover: { + expected: ["config", "discoverList"], + runOnMain: true, + execute(inputs, ctx) { + const { config } = inputs.config; + const plan = inputs.discoverList; + const results = plan.pieces.map((_, i) => { + const result = inputs[`discoverRead:${i}`]; + // Asserted: a piece missing here would quietly drop its pages from the site. + if (!result) throw new Error(`discover: piece ${i} of the source tree never arrived`); + for (const w of result.warnings) console.warn(w); + return result; + }); + const { pages, staticFiles, pictureSizes } = assemble(ctx.srcRoot, plan, results); // Everything discover() could not parse frontmatter from is about to // be copied verbatim into a public tree. `exclude:` is a denylist and // only refuses what someone named in advance, so the allowlist runs @@ -488,10 +568,21 @@ const TASKS = { `X.light.png needs X.png in the same folder:\n${unpaired.map((r) => ` ${r}`).join("\n")}`, ); } - const pictureSizes = await pairSizes(staticFiles); - return { pages, staticFiles, config, pictureSizes }; + // Where each page's text is in the buffers the pieces' lanes packed + // (packPageText), for the render chunks' payloads (dispatch.submit). + const pageText = { sabs: results.map((r) => r.text.sab), at: new Map() }; + for (const [piece, r] of results.entries()) { + for (const [i, page] of r.pages.entries()) { + pageText.at.set(page.srcRel, [piece, r.text.spans[2 * i], r.text.spans[2 * i + 1]]); + } + } + return { pages, staticFiles, config, pictureSizes, pageText }; }, - submit(out, state) { + submit(out, state, scheduler) { + // The render lanes read the pages' text from these; a chunk is claimed + // long after, and its handler waits for the message as for any task data. + for (const [i, sab] of out.pageText.sabs.entries()) scheduler.pool.broadcastTaskData(`pageText:${i}`, sab); + state.pageTextAt = out.pageText.at; state.pages = out.pages; state.staticFiles = out.staticFiles; state.site.config = out.config; @@ -561,11 +652,11 @@ const TASKS = { markdownInit: { // deriveRedirects is here for the counts registry alone: {{tbdocs:redirectStubs}} // is derived from the stub set, and nothing else on this task needs it. - // packTests is here for {{tbdocs:size:...}} and {{tbdocs:packageTestRows}}, which state the - // test projects' sizes before any page renders. - expected: ["discover", "vendorAssets", "deriveRedirects", "packTests"], + // packTests is not here: the files it packs are named now and sized later, by + // downloadSizes, for the few pages that state one. + expected: ["discover", "vendorAssets", "deriveRedirects"], runOnMain: true, - execute({ deriveRedirects: { stubs }, packTests }, ctx, state) { + execute({ deriveRedirects: { stubs } }, ctx, state) { const linkTables = buildLinkTables(state.pages); const baseurl = String(state.site.config.baseurl || ""); const staticFileSet = new Set(state.staticFiles.map((s) => s.srcRel)); @@ -591,24 +682,30 @@ const TASKS = { // The downloads' sizes, for the placeholders the pre-render rewrites expand // ({{tbdocs:size:...}}, {{tbdocs:packageTestRows}}). The help add-in's project is named // only to refuse it: it embeds the offline tree, which holds the pages that state sizes. - if (packTests?.failed) throw new Error(`package tests: not packed: ${packTests.error}`); - const testsCfg = packageTestsOf(state.site.config, ctx.srcRoot); + // The files packTests packs are named, by a listing of their folders, and not yet sized: + // a lane may still be packing them. The pages that state one of their sizes are the + // late pages, whose render chunks wait for downloadSizes (dispatch). The listing is + // kept for dispatch, which puts the same files in the online tree: it is a few dozen + // synchronous file calls, on the way to the first render. + state.site.packageTestRels = packageTestRels(packageTestsOf(state.site.config, ctx.srcRoot)); const downloads = deriveDownloads(state, { - tests: testsCfg && packTests?.packed ? { dest: testsCfg.dest, packed: packTests.packed } : null, + packed: state.site.packageTestRels, addinDest: addinProjectOf(state.site.config)?.dest ?? null, }); - const { problems: badNames, sizes } = checkPlaceholders( - state.pages, - state.site.counts, - downloads, - state.site.markdown, - ); + const { + problems: badNames, + sizes, + packedArgs, + late, + } = checkPlaceholders(state.pages, state.site.counts, downloads, state.site.markdown); if (badNames.length) { throw new Error(`bad {{tbdocs:...}} placeholder in ${badNames.length} place(s):\n\n` + badNames.join("\n\n")); } // Only what the pages ask for goes to the workers. - state.site.downloads = { sizes, tests: downloads.tests }; + state.site.downloads = { sizes, tests: null }; state.site.markdown.downloads = state.site.downloads; + state.site.packedArgs = packedArgs; + state.site.latePages = late; state.site.linkTablesSerialized = serializeLinkTables(linkTables); const { seoSiteTitle, seoLogoUrl } = computeSiteSeo(state.site.config, state.site.markdown); @@ -619,6 +716,32 @@ const TASKS = { submit() {}, }, + // The sizes of the files packTests packed, for the late pages: those that state one + // ({{tbdocs:size:...}}) or list the test projects ({{tbdocs:packageTestRows}}), which + // markdownInit named. The render chunks that hold one wait for this task (dispatch), and + // read what it broadcasts; every other chunk renders without it. So the pack is on no + // page's path but theirs, and a lane does it at any time before they render. + downloadSizes: { + expected: ["markdownInit", "packTests"], + runOnMain: true, + execute({ packTests }, ctx, state) { + if (packTests?.failed) throw new Error(`package tests: not packed: ${packTests.error}`); + state.site.downloads = packedDownloads({ + sizes: state.site.downloads.sizes, + packedArgs: state.site.packedArgs, + dest: packageTestsOf(state.site.config, ctx.srcRoot)?.dest ?? "", + packed: packTests?.packed ?? [], + }); + state.site.markdown.downloads = state.site.downloads; + return packShared(state.site.downloads); + }, + // Before the task is marked done, so the data is queued on every lane + // before one can claim a chunk that waits for it. + submit(sab, _state, scheduler) { + scheduler.pool.broadcastTaskData("downloads", sab); + }, + }, + loadData: { expected: ["highlighterInit"], runOnMain: true, @@ -680,13 +803,15 @@ const TASKS = { // worker tasks plus a renderJoin barrier. Assembles initData from the // two parallel halves: nav (sidebar) + buildInit (config-only chrome). dispatch: { - expected: ["nav", "buildInit", "buildInfo", "dot", "deriveRedirects", "markdownInit"], + // buildInfo is not here: the book's title page alone states the commit, so + // bookPayload waits for it. Its two git processes take up to 0.6 s in a + // one-off build on Windows, and every render waited for them. + expected: ["nav", "buildInit", "dot", "deriveRedirects", "markdownInit"], runOnMain: true, async execute( { nav: { sidebar }, buildInit: { initData }, - buildInfo: { buildInfo }, dot: _dotSignal, markdownInit: _markdownInitSignal, deriveRedirects: { stubs }, @@ -722,7 +847,8 @@ const TASKS = { // so a link to the file there goes to the website (computeWebsiteUrl). const addin = addinProjectOf(state.site.config); // The package test projects, which the packageTests task writes, likewise. - const packageTestFiles = packageTestRels(packageTestsOf(state.site.config, ctx.srcRoot)); + // markdownInit listed them. + const packageTestFiles = state.site.packageTestRels; // And each page's markdown copy, which the render lanes write beside the page // (markdown-copy.mjs). The publish allowlist refuses a .md file anywhere else. const markdownCopies = state.pages.map(markdownCopyRel).filter((rel) => rel !== null); @@ -816,7 +942,6 @@ const TASKS = { navTree: state.site.navTree, }, initData: { ...initData, sidebar }, - buildInfo, linkTablesData: state.site.linkTablesSerialized, staticFilesArr: state.staticFiles.map((f) => f.srcRel), baseurl: String(state.site.config.baseurl || ""), @@ -831,12 +956,17 @@ const TASKS = { vendoredImagesObj: Object.fromEntries(state.site.vendoredImages ?? []), pictureSizes: state.site.pictureSizes ?? {}, counts: state.site.counts, + // As they are now: the static files' sizes, or everything if downloadSizes has run. downloads: state.site.downloads, + latePages: state.site.latePages, }; const sharedSAB = packShared(shared); - return { chunks, sharedSAB }; + // The chunks that hold a late page (markdownInit), which wait for downloadSizes. + const latePages = new Set(state.site.latePages); + const lateChunks = chunks.flatMap((chunk, i) => (chunk.some((p) => latePages.has(p.srcRel)) ? [i] : [])); + return { chunks, sharedSAB, lateChunks }; }, - submit(out, _state, scheduler) { + submit(out, state, scheduler) { const N = out.chunks.length; const views = scheduler._views; const idMap = scheduler._idMapping; @@ -850,6 +980,11 @@ const TASKS = { // renderJoin fires, scheduler.state.searchChunks[0..N-1] holds every // worker's per-chunk entries in pages-order. scheduler.state.searchChunks = new Array(N); + // By chunk likewise: the entries' settle keys (search.mjs, entryKeys), + // and the same entries as each lane packed them for search-data.json + // and the index's lanes (packSearchEntries). + scheduler.state.searchKeys = new Array(N); + scheduler.state.searchPacked = new Array(N); scheduler.state.checkChunks = []; // linkJoin compares against this: a chunk that never arrived would // otherwise mean the link check quietly examined fewer pages and @@ -897,6 +1032,17 @@ const TASKS = { views.flags[flushBase + i] |= F_PIN_TO_PRED; } + // A chunk that holds a late page waits for downloadSizes, unless that has + // run. It is a main-thread task and so is this submit, so it cannot finish + // between the look at its status and the edge. + const sizesIdx = idMap.nameToIdx.get("downloadSizes"); + const waiting = Atomics.load(views.status, sizesIdx) === DONE ? [] : out.lateChunks; + if (waiting.length) { + for (const i of waiting) setDepCount(views, renderBase + i, 1); + appendDynamicSuccessors(views, [{ from: sizesIdx, to: waiting.map((i) => renderBase + i) }]); + } + const waits = new Set(waiting); + // 5. Register names + task defs on the main-thread scheduler so // _onWorkerDone can look up consolidate/ganttSection/submit and // _assembleInputs can resolve flushJoin's expected list. @@ -905,7 +1051,7 @@ const TASKS = { idMap.nameToIdx.set(rName, renderBase + i); idMap.idxToName[renderBase + i] = rName; scheduler.tasks.set(rName, { - expected: [], + expected: waits.has(i) ? ["downloadSizes"] : [], consolidate: true, ganttSection: "Render", // Only consulted by the stall watchdog. "render:33 never @@ -926,8 +1072,12 @@ const TASKS = { } p.renderedContent = r.renderedContent; if (r.offlineMisses !== undefined) p.offlineMisses = r.offlineMisses; + // A page of the symbol index, with the headings its lane read. + if (r.headings !== undefined) p.headings = r.headings; } state.searchChunks[i] = renderOut.searchEntries; + state.searchKeys[i] = renderOut.searchKeys; + state.searchPacked[i] = renderOut.searchPacked; }, }); @@ -952,7 +1102,15 @@ const TASKS = { registerBarrier(scheduler, views, "flushJoin", flushJoinIdx, "flush", N); // 6. Pack payload, broadcast, account, activate. - const payloadSAB = packPayloads(views, renderBase, out.chunks); + // A chunk's payload is its pages without their text, and where each + // one's text is in the buffers discover broadcast: the text is most of + // a page, and as JSON of every page it was a third of this task. A + // page with no place there keeps its text in the payload. + const payloads = out.chunks.map((chunk) => { + const texts = chunk.map((p) => state.pageTextAt.get(p.srcRel) ?? null); + return { pages: chunk.map((p, i) => (texts[i] ? { ...p, rawContent: undefined } : p)), texts }; + }); + const payloadSAB = packPayloads(views, renderBase, payloads); scheduler.addDynamicTasks(2 * N + 2); // N render + N flush + renderJoin + flushJoin scheduler.pool.broadcastDynamicData(payloadSAB, out.sharedSAB); activateDynamicTasks(views, renderBase, 2 * N); // render:i activate (depCount 0); @@ -991,64 +1149,218 @@ const TASKS = { submit() {}, }, - // Write search-data.json. Depends on renderJoin (every render:i.submit - // has stored its searchEntries in state.searchChunks[i]), prepDest - // (_site/ exists), and symbolIndex -- whose `symbols` (each `{ name, - // container, url, ... }`) this task joins onto the matching entries by - // URL before writing, adding the `names` / `qualified` fields (see - // WIP.Search.md's "Design" §2 and `joinSymbolsToEntries` in - // search.mjs). Result passes through to writeAux so its search.json - // field reaches writeOffline. Heavy lifting (extractSections, stripHtml, - // sanitiseContent) ran on the workers; this task only joins, concatenates - // and renumbers. - searchData: { - expected: ["renderJoin", "prepDest", "symbolIndex"], + // ── From the last render chunk to the search index's slices ──────────────── + // + // Once the last chunk is rendered, every lane waits for the main thread to + // run symbolPlace, searchEntries and indexSlices, which then gives the lanes + // the search index to build. So those three do only what needs every page: + // what one page or one entry decides was done by the lane that rendered it + // (cpu-worker.mjs, render: the headings, the settle keys, the entries packed + // for the index's lanes), what is known from the start is read during render + // (packageApi), and what only writes a file comes after them (symbolIndex, + // searchData). They are declared here, before every other task that can be + // ready at that moment, because the main thread takes the first READY task + // in declaration order. + + // builder/package-api.json, the package half of the symbol index: a + // committed snapshot the build never regenerates, because regenerating it + // needs a twinBASIC install. Read while the lanes render. + packageApi: { + expected: ["dispatch"], runOnMain: true, - async execute({ symbolIndex }, ctx, state) { - if (ctx.opts.dryRun) return { entries: 0, json: "" }; - return writeSearchDataFromChunks(state.searchChunks, ctx.destRoot, symbolIndex.symbols); + async execute() { + try { + return JSON.parse(await fs.readFile(PACKAGE_API_PATH, "utf8")); + } catch (err) { + if (err.code !== "ENOENT") throw err; + throw new Error( + "builder/package-api.json is missing, and the symbol index needs it. " + + "Restore it from git, or regenerate it with node indexer/twin-index.mjs derive", + ); + } + }, + submit() {}, + }, + + // The symbol index, in memory: every name the reference documents, placed on + // the page or heading that documents it -- see builder/symbols.mjs. + // renderJoin because an entry's anchor is the id the render gave its + // heading; each page's headings came back with its render chunk. + // symbolIndex writes the file; searchEntries joins the symbols onto the + // search entries. + symbolPlace: { + expected: ["renderJoin", "packageApi"], + runOnMain: true, + execute({ packageApi: api }, _ctx, state) { + const pages = symbolPages(state.pages); + return { pages, api, result: deriveSymbolIndex({ pages, api }) }; + }, + submit() {}, + }, + + // The search entries, final (search.mjs, consolidateSearchEntries). Depends + // on renderJoin (every render:i.submit has stored its entries in + // state.searchChunks[i]) and on symbolPlace, whose symbols (each `{ name, + // container, url, ... }`) are joined onto the matching entries by URL, + // adding the `names` / `qualified` fields (WIP.Search.md's "Design" §2). + // Heavy lifting (extractSections, stripHtml, sanitiseContent, the settle + // keys) ran on the workers; this task only settles, renumbers and joins. + // searchData writes them to search-data.json; indexSlices plans their index. + searchEntries: { + expected: ["renderJoin", "symbolPlace"], + runOnMain: true, + execute({ symbolPlace }, ctx, state) { + if (ctx.opts.dryRun) return { entries: [], places: [] }; + return consolidateSearchEntries(state.searchChunks, symbolPlace.result.symbols, state.searchKeys); }, submit() {}, }, - // Write search-index.json, the search entries searchData wrote to - // search-data.json and their lunr index in one file, which the page loads - // instead of building the index -- see builder/search-index.mjs and - // WIP.Search.md, "The pre-built index" -- and the offline tree's - // search-index.js, which wraps it as a script. It - // runs on a lane (cpu-worker.mjs), reading search-data.json from disk: the - // main thread runs one task at a time, and as one of them the index held - // back the book and the offline tree. The index is built on threads of - // its own. The offline file is written here rather than by writeOffline so - // that the rest of the offline tree need not wait for the index; - // helpArchive, which zips that tree, waits for both. + // The search index: the search entries and their lunr index, in + // search-index.json, which the page loads instead of building the index + // (builder/search-index.mjs; WIP.Search.md, "The pre-built index"), and the + // offline tree's search-index.js, which wraps it as a script. Six tasks, so + // that the work runs on the lanes: + // + // indexSlices main cuts the entries into slices, two for each lane + // indexAdd:i lane adds slice i to a builder that stays on the lane + // indexMerge main merges the slices' postings; broadcasts the totals + // indexTerms main writes the inverted index's JSON, meanwhile + // indexVectors:i lane slice i's field vectors, on indexAdd:i's lane + // searchIndex main joins the JSON and writes both files + // + // The entries themselves never leave the lanes for this: each render lane + // packed its chunk's into a SharedArrayBuffer (state.searchPacked), all of + // which every lane is sent here, and a slice's payload says only where its + // entries are and what searchEntries decided about them since + // (planIndexSegments). + // + // The offline file is written here rather than by writeOffline so that the + // rest of the offline tree need not wait for the index; archiveLate + // deflates it for the help archive. + indexSlices: { + expected: ["searchEntries"], + runOnMain: true, + execute({ searchEntries: { entries, places } }, ctx) { + if (ctx.opts.dryRun) return { entries: 0, slices: 0, payloads: [], twins: [] }; + const payloads = planIndexSegments(entries, places, indexSliceCount(entries.length, ctx.workerCount)); + const twins = [...stemTwins(loadSearchLunr(), entries)]; + return { entries: entries.length, slices: payloads.length, payloads, twins }; + }, + submit(out, state, scheduler) { + const { payloads, twins } = out; + // In the lanes' payload now; the results map need not keep them. + delete out.payloads; + delete out.twins; + // Before the task is marked done, so that it is queued on every lane + // before one can claim an indexAdd:i. + if (payloads.length) scheduler.pool.broadcastTaskData("indexEntries", { chunks: state.searchPacked, twins }); + fanOut(scheduler, { + from: "indexSlices", + prefix: "indexAdd", + handler: "indexAdd", + payloads, + joins: ["indexMerge"], + ganttSection: "Index", + priority: 2, + describe: (p) => [`slice ${p.slice}: entries from ${p.first}`], + }); + fanOut(scheduler, { + from: "indexSlices", + prefix: "indexVectors", + handler: "indexVectors", + payloads: payloads.map((p) => ({ slice: p.slice })), + after: ["indexMerge"], + pinTo: "indexAdd", + joins: ["searchIndex"], + ganttSection: "Index", + priority: 2, + describe: (p) => [`slice ${p.slice}`], + }); + }, + }, + + // Merges what each indexAdd:i added (search-index.mjs, mergeSlices) and + // broadcasts the totals the vectors need, before the task is marked done, + // so they are queued on every lane before one can claim an indexVectors:i. + // indexAdd:i are added to `expected` by indexSlices.submit. + indexMerge: { + expected: ["indexSlices"], + runOnMain: true, + execute(inputs) { + const added = []; + for (let s = 0; s < inputs.indexSlices.slices; s++) { + const a = inputs[`indexAdd:${s}`]; + // Asserted: a slice missing here would quietly drop its entries' words. + if (!a) throw new Error(`search index: slice ${s} never reached the merge`); + added.push(a); + } + const { merged, totals } = mergeSlices(added); + return { merged, totals: packTotals(totals) }; + }, + submit(out, _state, scheduler) { + scheduler.pool.broadcastTaskData("indexTotals", out.totals); + }, + }, + + // The inverted index's JSON (search-index.mjs, invertedIndexJson), on the + // main thread while the lanes make the vectors. + indexTerms: { + expected: ["indexMerge"], + runOnMain: true, + execute({ indexMerge }) { + return { json: invertedIndexJson(indexMerge.merged) }; + }, + submit() {}, + }, + + // Joins the index's JSON and writes search-index.json and the offline + // tree's search-index.js, with the entries as searchData wrote them. + // indexVectors:i are added to `expected` by indexSlices.submit. searchIndex: { - expected: ["searchData"], - handler: "searchIndex", + expected: ["indexSlices", "indexMerge", "indexTerms", "searchData"], + runOnMain: true, + async execute(inputs, ctx, state) { + const { indexSlices: plan, indexTerms, searchData } = inputs; + if (ctx.opts.dryRun) return { entries: 0, slices: 0, bytes: 0 }; + const vectors = []; + for (let s = 0; s < plan.slices; s++) { + const v = inputs[`indexVectors:${s}`]; + if (typeof v !== "string") throw new Error(`search index: slice ${s}'s vectors never arrived`); + vectors.push(v); + } + const json = assembleIndexJson(loadSearchLunr(), vectors, indexTerms.json); + const written = await writeSearchIndex(ctx.destRoot, json, searchData.docs, { + offline: !skipsOffline(ctx, state), + }); + return { ...written, slices: plan.slices }; + }, submit() {}, }, - // Write tB/symbols.json, the symbol index the IDE help add-in reads -- see - // builder/symbols.mjs. renderJoin because an entry's anchor is the id the - // render gave its heading, read from the HTML; prepDest for the tree. The - // package half comes from builder/package-api.json, a committed snapshot the - // build never regenerates, because regenerating it needs a twinBASIC install. + // Write search-data.json, from the entries searchEntries settled, each + // one's text copied from the buffer its render lane packed it into + // (search.mjs, searchDataBytes); prepDest for the tree. The result passes + // through writeAux, so that its `json`, the file's bytes, reaches the link + // check; `docs`, the entries as the file holds them, are searchIndex's. + // After the index's tasks in this list: the lanes are adding their slices + // while this writes. + searchData: { + expected: ["searchEntries", "prepDest"], + runOnMain: true, + async execute({ searchEntries }, ctx, state) { + if (ctx.opts.dryRun) return { entries: 0, json: "", docs: {} }; + return writeSearchData(searchEntries, state.searchPacked, ctx.destRoot); + }, + submit() {}, + }, + + // Write tB/symbols.json, the symbol index the IDE help add-in reads, from + // what symbolPlace placed -- see builder/symbols.mjs; prepDest for the tree. symbolIndex: { - expected: ["renderJoin", "prepDest"], + expected: ["symbolPlace", "prepDest"], runOnMain: true, - async execute(_, ctx, state) { - let api; - try { - api = JSON.parse(await fs.readFile(PACKAGE_API_PATH, "utf8")); - } catch (err) { - if (err.code !== "ENOENT") throw err; - throw new Error( - "builder/package-api.json is missing, and the symbol index needs it. " + - "Restore it from git, or regenerate it with node indexer/twin-index.mjs derive", - ); - } - const pages = symbolPages(state.pages); - const result = deriveSymbolIndex({ pages, api }); + async execute({ symbolPlace: { pages, api, result } }, ctx) { const gaps = reportableGaps(result, pages, api); const json = ctx.opts.dryRun ? "" : serializeSymbolIndex(result, api); if (json) await writeFileMkdirp(path.join(ctx.destRoot, SYMBOL_INDEX_REL), json); @@ -1060,10 +1372,6 @@ const TASKS = { urls: [...new Set(result.symbols.map((s) => s.url))], gaps: gaps.length, unplaced: result.unplaced, - // Consumed by searchData's join (see joinSymbolsToEntries in - // search.mjs), not written anywhere itself -- symbolIndex's own - // file output is tB/symbols.json, above. - symbols: result.symbols, // The file's text, for the add-in's copy (addin-index.mjs) and its // project file (addinProject). json, @@ -1072,26 +1380,64 @@ const TASKS = { submit() {}, }, - // Write the IDE help add-in's archive of the offline tree -- see - // builder/help-archive-step.mjs. The offline tree must be complete, so it - // waits for every task that writes into it: flushJoin (the pages, written by - // the render lanes' flushes), scss (the offline stylesheet), searchIndex - // (search-index.js) and writeOffline (the rest: statics, theme assets, - // redirect stubs, nav.js). + // The IDE help add-in's archive of the offline tree -- see + // builder/help-archive-step.mjs, whose header lays out the four tasks. The + // offline tree must be complete, so the archive waits for every task that + // writes into it: archivePlan for flushJoin (the pages, written by the render + // lanes' flushes), scss (the offline stylesheet) and writeOffline (the rest: + // statics, theme assets, redirect stubs, nav.js), and archiveLate for + // searchIndex (search-index.js, LATE_FILES), so that the rest is deflated + // while the index is built. // Nothing else writes there before the Gantt injection, which runBuild does // after the graph; recheckHelpArchive checks that at the end. The Gantt chart - // is injected after this task; the archive leaves out both files it writes + // is injected after these tasks; the archive leaves out both files it writes // (HELP_ARCHIVE_SKIP), and would otherwise hold BuildInfo.html without it. - // It runs on a worker (cpu-worker.mjs), so the main thread writes the book - // meanwhile; it reads skipOffline from dispatch's broadcast. + archivePlan: { + expected: ["flushJoin", "scss", "writeOffline"], + runOnMain: true, + async execute(_, ctx, state) { + const offlineRoot = skipsOffline(ctx, state) ? null : `${ctx.destRoot}-offline`; + const out = helpArchiveOut({ + src: path.relative(REPO_ROOT, ctx.srcRoot).replaceAll(path.sep, "/"), + offlineRoot, + serve: !!ctx.opts.serve, + dryRun: !!ctx.opts.dryRun, + disabled: !!ctx.opts.skipHelpArchive, + }); + return planHelpArchive({ out, offlineRoot, groups: ctx.workerCount }); + }, + submit(plan, _state, scheduler) { + fanOutArchive(scheduler, "archivePlan", "archiveDeflate", plan.root, plan.groups); + }, + }, + + // search-index.js, deflated for the archive once searchIndex has written it. + archiveLate: { + expected: ["archivePlan", "searchIndex"], + runOnMain: true, + execute({ archivePlan: plan }, ctx) { + return planLateFiles({ plan, groups: ctx.workerCount }); + }, + // Before archivePlan's groups: the index's file is the last the archive waits for. + submit(late, _state, scheduler) { + const { root } = scheduler.results.get("archivePlan"); + fanOutArchive(scheduler, "archiveLate", "archiveLateDeflate", root, late.groups, 2); + }, + }, + + // Writes the archive from what every group deflated, and reads it back. + // archiveDeflate:i and archiveLateDeflate:i are added to `expected` by the + // two plans' submits. helpArchive: { - expected: ["flushJoin", "scss", "searchIndex", "writeOffline"], - handler: "helpArchive", - // The zip crosses the thread boundary as a plain Uint8Array; make it a - // Buffer again, without copying, for addinProject. - submit(out) { - if (out.zip) out.zip = Buffer.from(out.zip.buffer, out.zip.byteOffset, out.zip.byteLength); + expected: ["archivePlan", "archiveLate"], + runOnMain: true, + execute(inputs) { + const groups = Object.entries(inputs) + .filter(([name]) => name.startsWith("archiveDeflate:") || name.startsWith("archiveLateDeflate:")) + .map(([, g]) => g); + return finishHelpArchive({ plan: inputs.archivePlan, late: inputs.archiveLate, groups }); }, + submit() {}, }, // Write the help add-in's project file, packed from add-in/, into the online @@ -1144,22 +1490,16 @@ const TASKS = { submit() {}, }, - // Pack the contributed packages' test projects in memory, before any page renders: a page can + // Pack the contributed packages' test projects and published tools in memory: a page can // state a download's size ({{tbdocs:size:...}}), and the packageTests task writes these bytes. // A tree whose config declares no package_tests (the test fixtures) packs nothing; a failure // is reported by packageTests, which fails the build. + // + // On a lane (cpu-worker.mjs), and on no page's path but the late pages': downloadSizes takes + // the sizes from here, and only the render chunks that hold a late page wait for it. packTests: { - expected: ["config"], - runOnMain: true, - async execute({ config: { config } }, ctx) { - const cfg = packageTestsOf(config, ctx.srcRoot); - if (!cfg) return {}; - try { - return await packAllPackageTests(cfg); - } catch (err) { - return { failed: true, error: err.message }; - } - }, + expected: ["config", "discoverList"], + handler: "packTests", submit() {}, }, @@ -1175,8 +1515,9 @@ const TASKS = { // It holds transitively today via flush:i being lane-pinned to // render:i, which is not something to rely on in a list whose whole // job is to say what must have merged. renderJoin is DONE by this - // point, so it costs nothing. - expected: ["flushJoin", "renderJoin", "dot", "resolveBookChapters"], + // point, so it costs nothing. buildInfo is the commit the title page + // states (state.site.buildInfo), which nothing before this reads. + expected: ["flushJoin", "renderJoin", "dot", "resolveBookChapters", "buildInfo"], runOnMain: true, execute(_, ctx, state) { const skip = !!ctx.opts.dryRun || skipsPdf(ctx, state); @@ -1248,9 +1589,13 @@ const TASKS = { // Produce _site-pdf/ on a worker (cpu-worker.mjs), while the main thread // writes the offline tree and checks the links. Sources CSS directly: // tb-highlight.css from state.site.highlighter, print.css from staticFiles. + // Priority 2, as the index's slices have: with checkBook it is as long as the + // index's chain after it, and at 0 it waited for every slice and then ended + // the build. writePdf: { expected: ["bookPayload"], handler: "writePdf", + priority: 2, submit() {}, }, @@ -1377,6 +1722,7 @@ const TASKS = { expected: ["writePdf"], handler: "checkBook", pin_to_predecessor: "writePdf", + priority: 2, submit() {}, }, @@ -1695,8 +2041,8 @@ export async function runBuild(opts) { const searchIndexStats = results.get("searchIndex"); if (searchIndexStats?.bytes) { console.log( - ` ${pc.bold("search:")} index of ${searchIndexStats.entries} entries built on ` + - `${searchIndexStats.workers} thread(s), ${(searchIndexStats.bytes / 1048576).toFixed(1)} MB`, + ` ${pc.bold("search:")} index of ${searchIndexStats.entries} entries built in ` + + `${searchIndexStats.slices} slice(s), ${(searchIndexStats.bytes / 1048576).toFixed(1)} MB`, ); } const symbolStats = results.get("symbolIndex"); diff --git a/builder/theme-pictures.mjs b/builder/theme-pictures.mjs index ff6b2c839..9fdea844b 100644 --- a/builder/theme-pictures.mjs +++ b/builder/theme-pictures.mjs @@ -3,14 +3,13 @@ // renderer (render.mjs's themePairPlugin) writes both, each with a class that the stylesheet // hides in the other theme (custom.scss, `.pic-light` and `.pic-dark`), and both lazy, so the // browser fetches only the one it shows; the light one's width and height are the page's -// scaled by the two files' sizes (pairSizes). The book keeps the light one alone (lightOnly, +// scaled by the two files' sizes (picturePairs). The book keeps the light one alone (lightOnly, // from book.mjs). WIP.Build.md says why it is done this way. // // A picture may also have been drawn as SVG (shoot_docs.mjs --svg): `X.svg` beside `X.png`, // `X.light.svg` beside `X.light.png`. The renderer shows each theme's SVG where it exists, // unless the page's attribute block says `png`; the PNGs stay, as the SVGs' reference. -import { open } from "node:fs/promises"; import { replaceOutsideCode } from "./code-guard.mjs"; export const PIC_LIGHT = "pic-light"; @@ -66,40 +65,26 @@ export function unpairedLightPictures(rels) { return rels.filter((r) => LIGHT_RE.test(r) && !all.has(r.replace(LIGHT_RE, ".png"))).sort(); } -// A PNG file's width and height in pixels, from its header; null when it is no PNG. -async function pngSize(file) { - const fh = await open(file, "r"); - try { - const b = Buffer.alloc(24); - const { bytesRead } = await fh.read(b, 0, 24, 0); - if (bytesRead < 24 || b.toString("latin1", 12, 16) !== "IHDR") return null; - return [b.readUInt32BE(16), b.readUInt32BE(20)]; - } finally { - await fh.close(); - } -} - -// For each light picture among the static files ({ srcRel, srcPath }), its size and its dark -// picture's, in pixels: { "": [lightW, lightH, darkW, darkH] }. The Light theme -// lays the IDE out a few pixels differently, so a light screenshot can be a little off the -// dark one's size; the renderer scales the page's width and height by it, so that each -// picture is shown at the same scale as the other. Read on the main thread, once, from the -// headers alone. -export async function pairSizes(staticFiles) { - const byRel = new Map(staticFiles.map((s) => [s.srcRel, s.srcPath])); - const out = Object.create(null); - for (const [rel, file] of byRel) { +// The light pictures among the static files ({ srcRel, src }, `src` being where the file is) +// that have their dark picture among them, in the files' order: [light srcRel, light src, +// dark src]. The build reads each pair's two sizes from the files' headers (discover-read.mjs, +// on the lanes) into `pictureSizes`: { "": [lightW, lightH, darkW, darkH] }. The +// Light theme lays the IDE out a few pixels differently, so a light screenshot can be a little +// off the dark one's size; the renderer scales the page's width and height by it, so that each +// picture is shown at the same scale as the other. +export function picturePairs(staticFiles) { + const byRel = new Map(staticFiles.map((s) => [s.srcRel, s.src])); + const pairs = []; + for (const [rel, src] of byRel) { if (!LIGHT_RE.test(rel)) continue; const dark = byRel.get(rel.replace(LIGHT_RE, ".png")); - if (!dark) continue; - const [l, d] = await Promise.all([pngSize(file), pngSize(dark)]); - if (l && d) out[rel] = [...l, ...d]; + if (dark) pairs.push([rel, src, dark]); } - return out; + return pairs; } // The light image's width and height, as the page's for the dark one scaled by the two -// pictures' sizes: `sizes` is pairSizes' entry. A value that is not a whole number of pixels +// pictures' sizes: `sizes` is the pair's entry in `pictureSizes`. A value that is not a whole number of pixels // (a percentage, an em) is left as it is. export function lightDimension(value, light, dark) { if (!/^\d+$/.test(String(value)) || !dark) return value; diff --git a/docs/Documentation/Builder.md b/docs/Documentation/Builder.md index d3a9b8f63..d17e78da9 100644 --- a/docs/Documentation/Builder.md +++ b/docs/Documentation/Builder.md @@ -62,7 +62,8 @@ Modules grouped by role. [Pipeline Stages](Pipeline-Stages) covers each in depth | [`command-line.mjs`](https://github.com/twinbasic/documentation/blob/main/builder/command-line.mjs) | `tbdocs`'s option table and defaults, and `parseCommandLine`, which reads the command line through `lib/cli.mjs` and applies the flags in order. | | [`scheduler.mjs`](https://github.com/twinbasic/documentation/blob/main/builder/scheduler.mjs) | Main-thread side of the pull scheduler: claim loop, results map, completion detection, summary printer. | | [`worker-pool.mjs`](https://github.com/twinbasic/documentation/blob/main/builder/worker-pool.mjs) | Worker lifecycle wrapper: spawn, send the SAB, forward messages to the scheduler, terminate. No dispatch logic. | -| [`cpu-worker.mjs`](https://github.com/twinbasic/documentation/blob/main/builder/cpu-worker.mjs) | Worker harness. Runs the pull loop, holds the eight named handlers, handles speculative idle execution. | +| [`cpu-worker.mjs`](https://github.com/twinbasic/documentation/blob/main/builder/cpu-worker.mjs) | Worker harness. Runs the pull loop, holds the named handlers, handles speculative idle execution. | +| [`fan-out.mjs`](https://github.com/twinbasic/documentation/blob/main/builder/fan-out.mjs) | `fanOut`, which a main-thread task's `submit` calls to add the pieces of its work to the graph as lane tasks. It is how a task runs work in parallel: [no task starts a thread](Pipeline-Stages#no-task-starts-a-thread). | | [`sab-scheduler.mjs`](https://github.com/twinbasic/documentation/blob/main/builder/sab-scheduler.mjs) | SAB layout, allocation, task-metadata API. Constants and atomics primitives consumed by both the scheduler and the workers. | | [`sab-broadcast.mjs`](https://github.com/twinbasic/documentation/blob/main/builder/sab-broadcast.mjs) | JSON-over-SAB pack/unpack for the shared payload (config, link tables, sidebar HTML, the nav tree when the offline tree is built, etc.) broadcast to every render worker. | @@ -70,7 +71,8 @@ Modules grouped by role. [Pipeline Stages](Pipeline-Stages) covers each in depth | File | Role | |---|---| -| [`discover.mjs`](https://github.com/twinbasic/documentation/blob/main/builder/discover.mjs) | Source tree walk; parses frontmatter and classifies each file as a page or a static file. | +| [`discover.mjs`](https://github.com/twinbasic/documentation/blob/main/builder/discover.mjs) | The source tree's inventory: lists the tree, cuts the listing into pieces for the lanes, and puts their results together as the sorted pages and static files. | +| [`discover-read.mjs`](https://github.com/twinbasic/documentation/blob/main/builder/discover-read.mjs) | What a lane does with a piece: reads each page and parses its frontmatter, sizes each static file, reads each picture pair's dimensions. | | [`nav.mjs`](https://github.com/twinbasic/documentation/blob/main/builder/nav.mjs) | Sidebar tree, integrity check, breadcrumbs, per-page `navLevels`. | | [`seo.mjs`](https://github.com/twinbasic/documentation/blob/main/builder/seo.mjs) | Site-level SEO on main (`computeSiteSeo`); per-page SEO on workers (`computeChunkSeo`). | | [`url.mjs`](https://github.com/twinbasic/documentation/blob/main/builder/url.mjs) | The URL helpers every other module shares: `absoluteUrl` and `relativeUrl` (ports of Jekyll's two URL filters), `normalizeBaseurl`, `encodeSpaces`, `splitFragment`. | @@ -111,8 +113,8 @@ Modules grouped by role. [Pipeline Stages](Pipeline-Stages) covers each in depth | [`sitemap.mjs`](https://github.com/twinbasic/documentation/blob/main/builder/sitemap.mjs) | `sitemap.xml` + `robots.txt`. | | [`markdown-copy.mjs`](https://github.com/twinbasic/documentation/blob/main/builder/markdown-copy.mjs) | Each page's markdown copy, which the online tree holds beside the page's HTML (`/tB/Core/Dim.md` beside `/tB/Core/Dim`, `index.md` for a URL ending in `/`), and which the page's head names in ``. The copy is the page's source without its front matter and HTML comments, with the `{{tbdocs:...}}` placeholders expanded, each link to a page replaced by the URL of that page's copy, and each link to a file the build resolves replaced by the URL the HTML has; all of it outside code. `render.mjs`'s `resolveTarget` and `pageAtSitePath` say which page a link reaches. See [Markdown for agents](Building#markdown-for-agents). | | [`llms-txt.mjs`](https://github.com/twinbasic/documentation/blob/main/builder/llms-txt.mjs) | `/llms.txt`, the index for language models: the site's summary, then a section of links to the markdown copies for each top-level part of the nav tree. Configured by `llms_txt` in `_config.yml`. | -| [`search.mjs`](https://github.com/twinbasic/documentation/blob/main/builder/search.mjs) | `deriveSearchEntries` (per-chunk, on workers) + `writeSearchDataFromChunks` (consolidator, on main). | -| [`search-index.mjs`](https://github.com/twinbasic/documentation/blob/main/builder/search-index.mjs) + [`search-index-worker.mjs`](https://github.com/twinbasic/documentation/blob/main/builder/search-index-worker.mjs) | The search box's lunr index, built from `search-data.json` on threads of its own and merged into exactly the index `lunr()` makes, and written with the entries into one file, `search-index.json`; the one definition of the index's fields and boosts. | +| [`search.mjs`](https://github.com/twinbasic/documentation/blob/main/builder/search.mjs) | `deriveSearchEntries`, `entryKeys` and `packSearchEntries` (per-chunk, on workers) + `consolidateSearchEntries` and `writeSearchData` (on main). | +| [`search-index.mjs`](https://github.com/twinbasic/documentation/blob/main/builder/search-index.mjs) | The search box's lunr index, built from the search entries in slices on the lanes and merged into exactly the index `lunr()` makes, and written with the entries into one file, `search-index.json`; the one definition of the index's fields and boosts. | | [`symbols.mjs`](https://github.com/twinbasic/documentation/blob/main/builder/symbols.mjs) | The symbol index, `tB/symbols.json`, for the IDE help add-in: every name the reference pages document, and the page or heading that documents it. The entries come from the pages; `builder/package-api.json` only annotates them. See [Building and Deployment](Building#the-symbol-index). | **Offline and PDF** @@ -130,7 +132,7 @@ Modules grouped by role. [Pipeline Stages](Pipeline-Stages) covers each in depth | [`link-check.mjs`](https://github.com/twinbasic/documentation/blob/main/builder/link-check.mjs) | The pure core: HTML in, findings out, with no filesystem traversal and no CLI. The build's check and the standalone [`scripts/check_links.mjs`](Tools-Site-Checks#check-links) share it. | | [`check.mjs`](https://github.com/twinbasic/documentation/blob/main/builder/check.mjs) | The check over rendered pages, which `scripts/check_links.mjs` runs too: per-chunk `checkChunk`, the `joinChunks` merge and `findingsFor`. Also the build's `TREES` table, report formatting, and the `--check-audit-index` tree-index audit. | | [`check-tree.mjs`](https://github.com/twinbasic/documentation/blob/main/builder/check-tree.mjs) | `deriveTreeRels` --- every relative path the build believes it emitted into a tree. The check's existence oracle comes from this, not from a `readdir`; the audit verifies it against the disk. | -| [`counts.mjs`](https://github.com/twinbasic/documentation/blob/main/builder/counts.mjs) | The registry behind `{{tbdocs:}}` in prose. `deriveCounts(state)` computes every name from build state; `countPlugin` substitutes them as a core rule over the inline token stream, so code is never touched. `checkPlaceholders` rejects an unknown name on main before any worker renders, and `findSurvivingPlaceholder` rejects a placeholder that reached the output. `{{tbdocs:size:}}` and `{{tbdocs:packageTestRows}}` are not numbers but text for the Downloads page: `deriveDownloads` settles the sizes of the static files and the packed package test projects, and `expandDownloadPlaceholders` expands them in the page source, where the inline rule cannot reach. See [Authoring Pages](Authoring#counts). | +| [`counts.mjs`](https://github.com/twinbasic/documentation/blob/main/builder/counts.mjs) | The registry behind `{{tbdocs:}}` in prose. `deriveCounts(state)` computes every name from build state; `countPlugin` substitutes them as a core rule over the inline token stream, so code is never touched. `checkPlaceholders` rejects an unknown name on main before any worker renders, and `findSurvivingPlaceholder` rejects a placeholder that reached the output. `{{tbdocs:size:}}` and `{{tbdocs:packageTestRows}}` are not numbers but text for the Downloads page: `deriveDownloads` settles the sizes of the static files, `packedDownloads` adds those of the package test projects and tools once a lane has packed them, and `expandDownloadPlaceholders` expands them in the page source, where the inline rule cannot reach. See [Authoring Pages](Authoring#counts). | | [`page-baseline.mjs`](https://github.com/twinbasic/documentation/blob/main/builder/page-baseline.mjs) | The page-count drift guard, and the committed `page-baseline.json` it compares against. A rise rewrites the file, a fall fails the build, and neither CI nor `--serve` may write. See [Building and Deployment](Building#the-page-count-drift-guard). | | [`symbol-baseline.mjs`](https://github.com/twinbasic/documentation/blob/main/builder/symbol-baseline.mjs) | The symbol index's drift guard, and the committed `symbol-baseline.json`, every URL `tB/symbols.json` has published. A new URL rewrites the file, a lost one fails the build. | | [`addin-index.mjs`](https://github.com/twinbasic/documentation/blob/main/builder/addin-index.mjs) | The help add-in's committed copy of the index, `add-in/Resources/SYMBOLS/symbols.json`: a local build rewrites it when it differs from `tB/symbols.json`, and CI and `--serve` only say so. | @@ -199,11 +201,11 @@ The SAB holds one `notify` Int32 used as a generation counter. A worker that fin ## SAB memory layout -One `SharedArrayBuffer` holds every Int32 array the scheduler needs, at static sizes: `MAX_TASKS = 512`, `MAX_LANES = 64`, `MAX_EDGES = 2048`, total 174,100 bytes (170 KB). The main arrays: +One `SharedArrayBuffer` holds every Int32 array the scheduler needs, at static sizes: `MAX_TASKS = 1024`, `MAX_LANES = 64`, `MAX_EDGES = 4096`, total 348,180 bytes (340 KB). The main arrays: - `status[i]` --- the task lifecycle enum above. - `depCount[i]` --- remaining predecessor count. Decremented atomically on each predecessor's completion. -- `succOffset[i]` / `succCount[i]` / `succList` --- flat successor edge list. `dispatch.submit()` extends it at runtime for the dynamic render and flush tasks. +- `succOffset[i]` / `succCount[i]` / `succList` --- flat successor edge list. `dispatch.submit()` extends it at runtime for the dynamic render and flush tasks, and `fanOut` for the pieces of the search index and of the help archive. - `perWorkerDone[i*MAX_LANES + lane]` --- per-lane done flag for `unique_per_worker` tasks. - `flags[i]` --- bitmask of the flags above. - `notify` --- generation counter for `Atomics.wait` / `notify`. @@ -213,15 +215,16 @@ The full layout, the allocation helper and the `readTaskMeta` / `writeTaskMeta` ## Task DAG by section -The pipeline has 37 named static tasks plus 2N dynamic ones (N render chunks + N flush tasks). The Gantt chart groups them into five sections, and so does the rest of this page: +The pipeline has the named static tasks below, plus dynamic ones: a `render:i` and a `flush:i` for each render chunk, and the pieces of the search index and of the help archive. The Gantt chart groups them into these sections, and so does the rest of this page: - **Seeds**: `config`, `buildInfo`, `scssLight`, `scssDark`, `highlighterInit`, `loadData` -- **Spine**: `discover`, `vendorAssets`, `nav`, `dot`, `buildInit`, `markdownInit`, `deriveRedirects`, `deriveSitemap`, `resolveBookChapters`, `packTests` +- **Spine**: `discoverList`, `discoverRead:i`, `discover`, `vendorAssets`, `nav`, `dot`, `buildInit`, `markdownInit`, `deriveRedirects`, `deriveSitemap`, `resolveBookChapters`, `packTests`, `downloadSizes`, `packageApi` - **Render**: `dispatch`, `prepDest`, `prepPageDirs`, `render:i`, `renderJoin` -- **Write**: `scss`, `flush:i`, `flushJoin`, `writeAssets`, `searchData`, `symbolIndex`, `helpArchive`, `addinProject`, `packageTests`, `writeAux`, `writeOffline`, `bookPayload`, `writePdf` +- **Write**: `scss`, `flush:i`, `flushJoin`, `writeAssets`, `searchData`, `symbolIndex`, `archivePlan`, `archiveDeflate:i`, `archiveLate`, `archiveLateDeflate:i`, `helpArchive`, `addinProject`, `packageTests`, `writeAux`, `writeOffline`, `bookPayload`, `writePdf` +- **Index**: `symbolPlace`, `searchEntries`, `indexSlices`, `indexAdd:i`, `indexMerge`, `indexTerms`, `indexVectors:i`, `searchIndex` - **Check**: `linkJoin`, `checkBook`, `checkReport` --- present on every ordinary build, because `build.bat` always passes `--check-audit-index` -`warmInit` and `renderEnvInit` belong to none of the five; the chart draws them as start-up bars in the worker rows, and they are described under Render. The chart does not draw the three `Join` barriers. +`warmInit` and `renderEnvInit` belong to none of these sections; the chart draws them as start-up bars in the worker rows, and they are described under Render. The chart does not draw the `Join` barriers. Every static task and dependency: @@ -231,10 +234,10 @@ Every static task and dependency: ### Seeds -`config`, `buildInfo`, `scssLight` and `scssDark` have no predecessors and start at once; `highlighterInit` waits for `config`, and `loadData` for `highlighterInit`. The three worker tasks run while the main thread traverses the source tree. +`config` has no predecessor and starts at once; `highlighterInit` waits for `config`, and `loadData` for `highlighterInit`. `buildInfo`, `scssLight` and `scssDark` wait for `discoverList`, the listing of the source tree, so that the first workers up are free to read it (see [Spine](#spine)). The three worker tasks run while the source tree is read and the main thread prepares the render. - `config` (main) --- reads `_config.yml` and applies CLI overrides. -- `buildInfo` (worker) --- two `git` shell-outs. Falls back to `"unknown"` on failure. +- `buildInfo` (worker) --- two `git` shell-outs. Falls back to `"unknown"` on failure. Only the book's title page states the result, so `bookPayload` waits for it and the render does not. - `scssLight` (worker) --- compiles `just-the-docs-combined.scss` against the light palette. - `scssDark` (worker) --- the same against the dark palette. - `highlighterInit` (main) --- loads the `Light.theme` + `Dark.theme` palette and emits `tb-highlight.css`. Each worker initialises its own Shiki. @@ -242,18 +245,21 @@ Every static task and dependency: ### Spine -`discover` and the main-thread tasks it feeds, with `dot` running on a worker beside them. They are cheap; the aim is to fork into independent streams as soon as the source tree is known. `deriveSitemap` and `resolveBookChapters` wait for `dispatch`, described under Render. +The source tree's inventory and the main-thread tasks it feeds, with `dot` running on a worker beside them. They are cheap; the aim is to fork into independent streams as soon as the source tree is known. `deriveSitemap` and `resolveBookChapters` wait for `dispatch`, described under Render. ``` config ┬→ highlighterInit → loadData - └→ discover ┬→ nav ──────────────────────────────┐ + └→ discoverList → discoverRead:i (workers) → discover + discover ┬→ nav ──────────────────────────────┐ ├→ buildInit ────────────────────────┤ ├→ vendorAssets ────┐ │ └→ deriveRedirects ─┴→ markdownInit ─┼→ dispatch → deriveSitemap → resolveBookChapters - buildInfo, dot (workers) ─┘ + dot (worker) ─┘ ``` -- `discover` --- traverses `docs/`, classifies pages and static files, builds `state.pageByDest`. +- `discoverList` --- lists `docs/` and cuts the listing into pieces: four on a machine with eight or more logical CPUs, two below that. Piece `i` of `n` holds every `n`-th page file, static file and picture pair, so each has its share of every folder. +- `discoverRead:i` (worker) --- reads a piece: each page and its frontmatter, each static file's size, each picture pair's dimensions. Every file the inventory opens is opened here, on two lanes at once. A lane needs only the first stage of its boot for this task (see [Worker boot](#worker-boot)), so the pieces are the first work a lane takes. `scssLight`, `scssDark`, `dot`, `packTests` and `warmInit` wait for `discoverList`, which leaves the first lanes free for the pieces. +- `discover` --- puts the pieces' results together as the sorted pages and static files, refuses a file that is not a publishable type or a light picture with no dark one, and builds `state.pageByDest`. - `vendorAssets` --- finds the YouTube video markers and GitHub user-attachment URLs in the pages, downloads any file not already in `docs/assets/thumbnails/` or `docs/assets/attachments/`, and adds the new files to the static-file copy. `markdownInit` and `writeAssets` depend on it. - `nav` --- builds the sidebar tree, runs the integrity check (an orphan or ambiguous `parent:` aborts the build here) and pre-renders the sidebar HTML. - `dot` (worker) --- regenerates stale `.dot` → `.svg` with the WASM build of Graphviz. WASM init takes ~50 ms and overlaps the main spine; each diagram then renders synchronously. @@ -275,17 +281,19 @@ dispatch ┬→ render:0 ┬→ flush:0 ┐ ↓ ↓ renderJoin flushJoin ↓ - symbolIndex ─→ addinProject + symbolPlace ───→ symbolIndex ─→ addinProject ↓ - searchData + searchEntries ──→ searchData + ↓ + indexSlices ``` - `prepDest` (main) --- cleans and recreates the destination trees the run writes: the online tree, and the offline and PDF trees when their passes run. A build removes a tree whose pass it skips; serve mode prepares `_serve/` alone. Deferred until after `dispatch` so the wipe does not contend with `discover`'s reads. - `prepPageDirs` (main) --- creates every page output directory, so `flush:i` needs no `mkdir`. - `warmInit` (worker, `on_demand` + `unique_per_worker` + `run_when_idle` + `survives_reset`) --- per-lane Shiki bootstrap. A worker with nothing else claimable runs it during the main-thread spine, every render worker needs it on its own lane, and in serve mode the per-lane done flag survives rebuilds, so later builds skip it. - `renderEnvInit` (worker, `on_demand` + `unique_per_worker`) --- per-lane render environment: unpacks the shared SAB, rebuilds the link-table Maps and instantiates the worker's own markdown-it. Every `render:i` lists it in `perWorkerDeps`, so the first render claim on a lane pulls it in. -- `render:i` (worker, dynamic) --- the per-chunk compute, in the five sub-stages listed under "Render fan-out in detail". Returns a delta with `renderedContent` per page and the chunk's search entries. -- `renderJoin` (main, `on_demand`) --- barrier that unblocks `searchData`, `symbolIndex` and `bookPayload`. `dispatch.submit()` sets its dep count to N *and* rewrites its `expected` list with every chunk name; the dep count alone is not a barrier over the submits. See [Pipeline Stages](Pipeline-Stages#renderjoin-main-on_demand). +- `render:i` (worker, dynamic) --- the per-chunk compute, in the five sub-stages listed under "Render fan-out in detail". Returns a delta with `renderedContent` per page and the chunk's search entries. It also returns the part of `symbolPlace`'s and `searchEntries`' work that one page or one entry decides: the headings of each page the symbol index reads, each entry's settle keys, and the entries' text packed into a `SharedArrayBuffer`. +- `renderJoin` (main, `on_demand`) --- barrier that unblocks `symbolPlace`, `searchEntries` and `bookPayload`. `dispatch.submit()` sets its dep count to N *and* rewrites its `expected` list with every chunk name; the dep count alone is not a barrier over the submits. See [Pipeline Stages](Pipeline-Stages#renderjoin-main-on_demand). ### Write @@ -295,11 +303,12 @@ dispatch ┬→ render:0 ┬→ flush:0 ┐ - `flush:i` (worker, dynamic, `pin_to_predecessor`) --- writes the chunk's page HTML on the worker that rendered it: the online tree always, the offline tree unless `skipOffline`. Each page's markdown copy, which `render:i` made after rendering the page, goes beside it in the online tree. The pinning matters because the worker keeps the batch on its own `_pendingFlush` FIFO at the end of `render`, and only the matching `flush:i` drains it. **With `--check`, the link and integrity check runs here too**, over the chunk's just-written HTML, which is already decoded and in worker memory, so the check never writes ~270 MB out to read it back. - `flushJoin` (main, `on_demand`) --- barrier that aggregates per-chunk write stats and gates `writeAux` + `bookPayload`. - `writeAssets` (main) --- writes generated CSS, copies vendored theme JS and the project's static files. It does not write page HTML; `flush:i` did. Depends on `prepPageDirs`. -- `searchData` (main) --- concatenates `state.searchChunks` (filled by each `render:i`'s `submit()`), joins `symbolIndex`'s symbols onto the matching entries by URL (adding the `names` / `qualified` / `primary` fields; see [Site search](Pipeline-Stages#searchdata-main) and `WIP.Search.md`'s "Design" §2), renumbers the global `i` index and writes `search-data.json`. The workers already did the heavy work (heading split, content sanitisation, URL encoding). Depends on `renderJoin`, `prepDest` and `symbolIndex`. -- `searchIndex` (worker) --- reads `search-data.json` and writes `search-index.json`, the entries and their lunr index in one file, which the search box loads instead of building the index, and the offline tree's `search-index.js`. It builds the index on threads of its own and merges them into exactly the index `lunr()` makes (see [Pipeline Stages](Pipeline-Stages#searchindex-worker)). On a worker because, as a main-thread task, it held back the tasks after it. Depends on `searchData`; `helpArchive` and `checkReport` wait for it. -- `symbolIndex` (main) --- writes `tB/symbols.json`, the [symbol index](Building#the-symbol-index) the IDE help add-in reads, and passes its `symbols` array to `searchData`'s join. It reads the heading ids from every `/tB/` page's `renderedContent`, joins them with the committed `builder/package-api.json`, and returns the index's URLs for the drift guard that `runBuild` runs at the end. Depends on `renderJoin` and `prepDest`. `checkReport`, `searchData` and `addinProject` wait for it. -- `helpArchive` (worker) --- writes `add-in/Resources/HELP/site.zip`, the archive of the offline tree that the IDE help add-in embeds (see [Build and Generation Tools](Tools-Build#the-help-archive)). Depends on `flushJoin`, `scss`, `searchIndex` and `writeOffline`, which between them write the whole offline tree. It leaves out the sections `HELP_ARCHIVE_SKIP` lists, `BuildInfo.html` and its chart among them, and runs before the Gantt chart is injected. It runs only for a `docs` build into the default `--dest`, `docs/_site`, with an offline tree, and not under `--serve`, `--dry-run` or `--no-help-archive`. After the chart is injected, `runBuild` checks that the offline tree still lists the archive's files and differs from it in `BuildInfo.html` and `assets/images/gantt.svg` alone. -- `addinProject` (main) --- packs the help add-in's source folder, `add-in/`, into `tbDocsHelp.twinproj` and writes it into the online tree at the path `_config.yml`'s `addin_project` names (see [Build and Generation Tools](Tools-Build#the-help-add-ins-project-file)). The files are those git tracks there, the symbol index is the one `symbolIndex` wrote, and `Resources/HELP/site.zip` is the archive `helpArchive` wrote, if any. The zip comes back from the worker as a plain byte array, which `helpArchive`'s `submit` wraps again as a `Buffer` without copying it. Depends on `symbolIndex`, `prepDest` and `helpArchive`; `checkReport` waits for it. Does nothing under `--dry-run` or for a config that declares no download. +- `packageApi`, `symbolPlace`, `searchEntries` (main) --- what the search index waits for after the last render chunk, with every lane idle, so they do only the work that needs every page (see [Pipeline Stages](Pipeline-Stages#symbolplace-main)). `packageApi` reads the committed `builder/package-api.json` while the lanes render. `symbolPlace` makes the [symbol index](Building#the-symbol-index) in memory, from the headings each `render:i` returned and the package API. `searchEntries` concatenates `state.searchChunks` (filled by each `render:i`'s `submit()`), settles the labels, renumbers the global `i` index and joins `symbolPlace`'s symbols onto the matching entries by URL (adding the `names` / `qualified` / `primary` fields; see `WIP.Search.md`'s "Design" §2). The workers already did the heavy work (heading split, content sanitisation, URL encoding, the settle keys). +- `searchData` (main) --- writes `search-data.json`, each entry's text copied from the buffer its render lane packed it into (see [Site search](Pipeline-Stages#searchdata-main)). Depends on `searchEntries` and `prepDest`, and runs while the lanes build the search index. +- `indexSlices`, `indexMerge`, `indexTerms`, `searchIndex` (main) and `indexAdd:i`, `indexVectors:i` (worker) --- build the lunr index of the search entries and write `search-index.json`, the entries and their index in one file, which the search box loads instead of building the index, and the offline tree's `search-index.js`. The index is built in slices on the lanes and merged into exactly the index `lunr()` makes (see [Pipeline Stages](Pipeline-Stages#searchindex-worker)). A lane reads its slice's entries from the buffers the render lanes packed, so the main thread does not send them. `indexSlices` depends on `searchEntries`; `archiveLate` and `checkReport` wait for `searchIndex`. +- `symbolIndex` (main) --- writes `tB/symbols.json`, the [symbol index](Building#the-symbol-index) the IDE help add-in reads, from what `symbolPlace` placed, and returns the index's URLs for the drift guard that `runBuild` runs at the end. Depends on `symbolPlace` and `prepDest`. `checkReport` and `addinProject` wait for it. +- `archivePlan`, `archiveLate`, `helpArchive` (main) and `archiveDeflate:i`, `archiveLateDeflate:i` (worker) --- write `add-in/Resources/HELP/site.zip`, the archive of the offline tree that the IDE help add-in embeds (see [Build and Generation Tools](Tools-Build#the-help-archive) and [Pipeline Stages](Pipeline-Stages#helparchive-worker)). `archivePlan` depends on `flushJoin`, `scss` and `writeOffline`, which between them write the whole offline tree but `search-index.js`, and the lanes deflate that tree while the search index is built. `archiveLate` depends on `searchIndex` and has the lanes deflate `search-index.js`, in pieces. `helpArchive` writes the zip from what the lanes deflated. The archive leaves out the sections `HELP_ARCHIVE_SKIP` lists, `BuildInfo.html` and its chart among them, and is made before the Gantt chart is injected. It is made only for a `docs` build into the default `--dest`, `docs/_site`, with an offline tree, and not under `--serve`, `--dry-run` or `--no-help-archive`. After the chart is injected, `runBuild` checks that the offline tree still lists the archive's files and differs from it in `BuildInfo.html` and `assets/images/gantt.svg` alone. +- `addinProject` (main) --- packs the help add-in's source folder, `add-in/`, into `tbDocsHelp.twinproj` and writes it into the online tree at the path `_config.yml`'s `addin_project` names (see [Build and Generation Tools](Tools-Build#the-help-add-ins-project-file)). The files are those git tracks there, the symbol index is the one `symbolIndex` wrote, and `Resources/HELP/site.zip` is the archive `helpArchive` wrote, if any. Depends on `symbolIndex`, `prepDest` and `helpArchive`; `checkReport` waits for it. Does nothing under `--dry-run` or for a config that declares no download. - `writeAux` (main) --- writes redirect stubs, the sitemap, robots.txt, llms.txt and the online tree's `nav.html`, the whole nav tree, which `linkJoin` checks with the stubs. Depends on `writeAssets`, `searchData`, `flushJoin`, `renderJoin` (llms.txt takes each page's note from its `renderedContent`), `deriveRedirects`, `deriveSitemap`. - `writeOffline` (main) --- produces `_site-offline/`. `render:i` and `flush:i` already computed and wrote the per-page HTML, so this task does the cross-cutting work: CSS url() rewriting, the just-the-docs.js AST patch, the offline `nav.js`, theme assets and redirect stubs. The offline search index, `search-index.js`, is `searchIndex`'s. - `bookPayload` (main) --- packs what the book needs into one shared buffer and broadcasts it to every worker. It renders each part's subtitle and intro first, because markdown-it cannot cross to a worker, and replaces every page reference in `bookData` with the page's index in the page list, so the worker resolves it back to the same object. Depends on `flushJoin` (`renderedContent` is filled), `renderJoin`, `resolveBookChapters` (`bookData._chapters` is set) and `dot` (diagram SVGs are in `staticFiles`). The broadcast is posted before the task is marked done, so it is queued on every lane before any lane can claim `writePdf`. Under `--dry-run`, or when the build writes no PDF tree, it packs a marker that tells `writePdf` there is nothing to write. @@ -316,7 +325,8 @@ Every task and where it runs: | Seeds | `scssLight`, `scssDark` | workers | Light + dark palettes compile concurrently. | | Seeds | `highlighterInit` | main | Palette CSS only. | | Seeds | `loadData` | main | Reads `_book.yml`. | -| Spine | `discover`, `vendorAssets`, `nav`, `buildInit`, `markdownInit`, `deriveRedirects`, `deriveSitemap`, `resolveBookChapters` | main | Single-threaded. | +| Spine | `discoverList`, `discover`, `vendorAssets`, `nav`, `buildInit`, `markdownInit`, `deriveRedirects`, `deriveSitemap`, `resolveBookChapters`, `packageApi` | main | Single-threaded. | +| Spine | `discoverRead:i` | workers | The pieces of the source tree, read at once. | | Spine | `dot` | worker | WASM Graphviz; init hides behind the main spine. | | Render | `dispatch`, `prepDest`, `prepPageDirs` | main | `prepDest` and `prepPageDirs` are deferred to after `dispatch`. | | Render | `render:i` | worker | Body + SEO + template + offline + search per chunk. | @@ -327,7 +337,11 @@ Every task and where it runs: | Write | `flush:i` | worker (pinned) | Page HTML write, online + offline. | | Write | `flushJoin` | main | Barrier. | | Write | `writeAssets`, `searchData`, `symbolIndex`, `addinProject`, `writeAux`, `writeOffline`, `bookPayload` | main | One at a time, in declaration order: the main thread finishes a task before it claims the next, and the tail is CPU-bound there. | -| Write | `searchIndex`, `helpArchive`, `writePdf` | worker | Run beside the main-thread writers. `searchIndex` follows `searchData` and builds on threads of its own; `helpArchive` follows it and `writeOffline`; `writePdf` follows `bookPayload`. | +| Write | `writePdf`, `archiveDeflate:i`, `archiveLateDeflate:i` | worker | Run beside the main-thread writers. `writePdf` follows `bookPayload`; the archive's pieces follow `archivePlan` and `archiveLate`. | +| Write | `archivePlan`, `archiveLate`, `helpArchive` | main | Plan the archive's pieces for the lanes, and write the zip from them. | +| Index | `symbolPlace`, `searchEntries` | main | Place the symbols and settle the search entries. Every lane waits for them after the last render chunk. | +| Index | `indexSlices`, `indexMerge`, `indexTerms`, `searchIndex` | main | Cut the search entries into slices, merge what the lanes added, and write the index. | +| Index | `indexAdd:i`, `indexVectors:i` | worker (`indexVectors:i` pinned) | One slice of the search index each. `indexVectors:i` runs on the lane that ran `indexAdd:i`, which holds the slice's builder. | | Check | `linkJoin`, `checkReport` | main | No-ops without `--check`. | | Check | `checkBook` | worker (pinned) | Runs on the lane that wrote the book, so the book never crosses back. Returns null without `--check`. | @@ -358,7 +372,7 @@ Worker output flow: a worker posts `{ done: taskIdx, output, timing, lane }` to `dispatch.execute()` runs on the main thread and assembles two SAB payloads: -- **Per-task payload SAB** --- one JSON blob per `render:i`, each containing the chunk's `Page` objects. `chunkOffset[i]` / `chunkLength[i]` index into the buffer. +- **Per-task payload SAB** --- one JSON blob per `render:i`, each containing the chunk's `Page` objects without their text, and where each page's text is. `payloadOffset[i]` / `payloadLength[i]` index into the buffer. The text is in the buffers the `discoverRead:i` lanes packed and `discover` broadcast, so the main thread does not turn the site's text into JSON. - **Shared payload SAB** --- one JSON blob broadcast to every worker, containing the site config, site-level SEO constants, the pre-rendered sidebar + chrome (`initData`), the nav tree when the offline tree is built, serialized link tables (`[key, permalink]` pair arrays), the static-file relative-path set, the baseurl, the site-paths set for offline rewriting, the `offline_exclude` patterns, and the `skipOffline` flag. `dispatch.submit()` allocates 2N dynamic slots from the generic pool in `sab-scheduler.mjs`, writes their handler IDs and per-worker dep lists, adds the successor edges, pins each `flush:i` to its `render:i`, calls `broadcastDynamicData(payloadSAB, sharedSAB)` (one `postMessage` per worker carrying the two SAB references, shared and not cloned), and sets the `render:i` slots to `READY`. Workers see the new tasks on their next scan. @@ -390,7 +404,13 @@ Three details make the reuse work: - **Per-lane Shiki survives.** `warmInit` has `survives_reset`, so the per-lane done flags are pre-filled when later builds allocate the SAB. Workers keep the highlighter in module scope, so `warmInit` never re-runs; `render:i` goes straight to `renderEnvInit`, which must re-run because it reads config and link tables from the new shared SAB. - **`_buildCount`** tells the first build from later ones. `runBuild` tests `pool._buildCount > 0` to decide whether to skip injecting boot timings into the Gantt chart. -- **Boot timings are emitted once.** Workers post a `coldBoot` message on their first init only. +- **Boot timings are emitted once.** Workers post a `coldBoot` message for each stage of their boot, on the first build only. + +### Worker boot + +A worker boots in two stages. The first is the static imports of `cpu-worker.mjs`: the scheduler and `discover-read.mjs`, which needs only the YAML parser. The worker is in its pull loop after it and can run a `discoverRead:i`. The second stage loads everything else (the renderer and its plugins, the search index, the archive), and a worker runs it before its first task of any other kind. Two workers therefore read the source tree while the others load the second stage, and the main thread, which read the tree itself before, is idle meanwhile. + +A module that `discover-read.mjs` imports is loaded by every worker before the first piece can start. Keep that list short; the glob library is in `discover.mjs`, which only the main thread loads. ## Figures @@ -462,11 +482,11 @@ The residual 0.5% is kerning, which a per-character table cannot express. The ta ## Gantt chart and build introspection -Every build emits an inline-SVG Gantt chart of its task timeline. [`gantt.mjs`](https://github.com/twinbasic/documentation/blob/main/builder/gantt.mjs)'s `groupGanttTimings` sorts the scheduler's timings into a `Map`, and `renderGantt(grouped)` draws one SVG row per main-thread task plus one row per worker lane. The main-thread rows form four bands --- Seeds, Spine, Write and Check --- with Render's main-thread tasks in the Spine band and the worker rows between Spine and Write. The `Join` barriers are not drawn. Each worker row has one rectangle per task it ran, in start order, coloured by the task's section. The start-up bars share that row, labelled `cold` (the worker's cold start, drawn on the first build only), `warm` (`warmInit`) and `env` (`renderEnvInit`). +Every build emits an inline-SVG Gantt chart of its task timeline. [`gantt.mjs`](https://github.com/twinbasic/documentation/blob/main/builder/gantt.mjs)'s `groupGanttTimings` sorts the scheduler's timings into a `Map`, and `renderGantt(grouped)` draws one SVG row per main-thread task plus one row per worker lane. The main-thread rows form bands --- Seeds, Spine, Write, Index and Check --- with Render's main-thread tasks in the Spine band and the worker rows between Spine and Write. Index holds the search index's tasks, which have a colour of their own, so that they stand apart from the tasks that write files. The `Join` barriers are not drawn. Each worker row has one rectangle per task it ran, in start order, coloured by the task's section. The start-up bars share that row, labelled `cold` and `load` (the two stages of the worker's [boot](#worker-boot), drawn on the first build only), `warm` (`warmInit`) and `env` (`renderEnvInit`). The chart goes through the same figure pipeline as other diagrams. The [Build Info](BuildInfo) page contains a markdown image reference to a placeholder `gantt.svg`, which the render pass turns into a figure with an inline SVG. After `writeOffline` completes, `tbdocs.mjs:injectGanttChart` finds the wrapper's `data-svg-src` marker in the rendered HTML and replaces the placeholder with the real chart. It patches the online and offline copies of the page, and updates the on-disk `gantt.svg` for the offline mirror's fallback. The help archive and the help add-in's project file are made before the injection and hold the placeholder, because the chart holds the build's own timings and would make every download differ. -When adding a new task to `TASKS`, give it a section in `GANTT_SECTION` in `gantt.mjs`: `Seeds`, `Spine`, `Render`, `Write` or `Check`. The build fails, naming the task, if a task has no section or one the chart does not draw. Only a `unique_per_worker` task needs none: its timings are drawn in each worker's lane. +When adding a new task to `TASKS`, give it a section in `GANTT_SECTION` in `gantt.mjs`: `Seeds`, `Spine`, `Render`, `Write`, `Index` or `Check`. A piece that `fanOut` adds names its section in the call. The build fails, naming the task, if a task has no section or one the chart does not draw. Only a `unique_per_worker` task needs none: its timings are drawn in each worker's lane. ## Dependencies diff --git a/docs/Documentation/Building.md b/docs/Documentation/Building.md index 9a800ee11..a76f58fff 100644 --- a/docs/Documentation/Building.md +++ b/docs/Documentation/Building.md @@ -87,6 +87,7 @@ Do not drop `--check-audit-index` when typing the underlying build command: with && node --test test/addin-project.test.mjs \ && node --test test/indexer.test.mjs \ && node --test test/ide-js.test.mjs \ + && node --test test/discover.test.mjs \ && node scripts/check_regex_safety.mjs \ && node scripts/check_code_regions.mjs \ && node scripts/check_page_baseline.mjs \ @@ -188,7 +189,7 @@ A watchdog catches this. When no task has completed for two minutes, it abandons Blocked on a predecessor (consequence, not cause): renderJoin <- render:19 flushJoin <- flush:19 - searchData <- renderJoin + symbolPlace <- renderJoin flush:19 <- render:19 ... and 8 more diff --git a/docs/Documentation/Extending.md b/docs/Documentation/Extending.md index 9c9cb1ef3..ac215f012 100644 --- a/docs/Documentation/Extending.md +++ b/docs/Documentation/Extending.md @@ -219,8 +219,9 @@ export const HANDLERS = { warmInit: 0, renderEnvInit: 1, flush: 2, scssLight: 3, scssDark: 4, dot: 5, buildInfo: 6, render: 7, - helpArchive: 8, writePdf: 9, checkBook: 10, - myHandler: 11, // ← new + writePdf: 9, checkBook: 10, + indexAdd: 12, indexVectors: 13, archiveDeflate: 14, + myHandler: 15, // ← new }; ``` @@ -248,7 +249,36 @@ const handlers = { The handler's return value comes back to main as `{ done: taskIdx, output, timing, lane }`. The scheduler stores `output` in `results` and passes it to your task's `submit()`. -A worker cannot read `state`, so it cannot see what a main-thread task produced. Work that follows one takes one of two forms. A worker that needs only what `dispatch` broadcast reads it with `sharedData()`, as `helpArchive` does. A worker that needs a main-thread task's output gets a main task in front of it that packs the output into a `SharedArrayBuffer` and broadcasts it from its `submit`, with `scheduler.pool.broadcastTaskData("", sab)`; the handler reads it with `await taskData("")`. The `bookPayload` task and the `writePdf` handler are the model. Broadcast in `submit`, which runs before the task is marked done, so that the message is queued on every lane before any lane can claim the worker task. Whatever the output holds must survive structured cloning: a markdown-it instance does not, so `bookPayload` renders the parts' subtitles and intros before it packs, and replaces each page reference with the page's index in the list. +A worker cannot read `state`, so it cannot see what a main-thread task produced. Work that follows one takes one of two forms. A worker that needs only what `dispatch` broadcast reads it with `sharedData()`, as `renderEnvInit` does. A worker that needs a main-thread task's output gets a main task in front of it that packs the output into a `SharedArrayBuffer` and broadcasts it from its `submit`, with `scheduler.pool.broadcastTaskData("", sab)`; the handler reads it with `await taskData("")`. The `bookPayload` task and the `writePdf` handler are the model. Broadcast in `submit`, which runs before the task is marked done, so that the message is queued on every lane before any lane can claim the worker task. Whatever the output holds must survive structured cloning: a markdown-it instance does not, so `bookPayload` renders the parts' subtitles and intros before it packs, and replaces each page reference with the page's index in the list. + +**Work that can run in parallel is split into lane tasks; a handler never starts a thread.** The lanes are the build's only threads ([No task starts a thread](Pipeline-Stages#no-task-starts-a-thread)). A main-thread task plans the pieces and calls `fanOut` from `fan-out.mjs` in its `submit`, with one JSON payload for each piece: + +```js +// builder/tbdocs.mjs +myPlan: { + expected: ["someTask"], + runOnMain: true, + execute() { return { payloads: planPieces() }; }, + submit(out, _state, scheduler) { + fanOut(scheduler, { + from: "myPlan", // the task whose submit this is + prefix: "myPiece", // the pieces are myPiece:0, myPiece:1, ... + handler: "myHandler", // reads its payload with fanOutPayload(taskIdx) + payloads: out.payloads, + joins: ["myJoin"], // a static main-thread task that lists "myPlan" + ganttSection: "Write", + }); + }, +}, +myJoin: { + expected: ["myPlan"], // fanOut adds every myPiece:i + runOnMain: true, + execute(inputs) { /* inputs["myPiece:0"], ... */ }, + submit() {}, +}, +``` + +The join receives each piece's output under its name. `pinTo` runs piece `i` on the lane that ran piece `i` of an earlier fan-out from the same `submit`, for work that keeps state on its lane; `after` names other main-thread tasks every piece waits for. The search index's tasks use all of these. ### 4. Define the task in `TASKS` @@ -722,7 +752,7 @@ Two shapes qualify. Most names count things `discover` already found: pages unde Then read the built page and check the number against the thing it counts. Nothing compares a derivation against reality: a name that returns the wrong number is as green as one that returns the right one. -A value that is text, or that has to appear in a raw HTML block or on a table line, is not a count: `countPlugin` cannot reach it. `{{tbdocs:size:}}` and `{{tbdocs:packageTestRows}}` are the model for one. `expandDownloadPlaceholders` expands them in the page source, between the code mask and its restore in `applyPreRenderRewrites`; `checkPlaceholders` refuses what cannot be expanded, naming the file and the line; and the values reach the render workers in the shared payload, as `counts` does. A value that depends on a file written after the pages render cannot be known in time, and is refused. +A value that is text, or that has to appear in a raw HTML block or on a table line, is not a count: `countPlugin` cannot reach it. `{{tbdocs:size:}}` and `{{tbdocs:packageTestRows}}` are the model for one. `expandDownloadPlaceholders` expands them in the page source, between the code mask and its restore in `applyPreRenderRewrites`; `checkPlaceholders` refuses what cannot be expanded, naming the file and the line; and the values reach the render workers in the shared payload, as `counts` does. A value that depends on a file written after the pages render cannot be known in time, and is refused. A value that a lane task computes while the pages render is the middle case, and the packed files' sizes are the model for it: `checkPlaceholders` names the pages that need the value, `dispatch` makes the render chunks that hold one wait for the task that has it ([`downloadSizes`](Pipeline-Stages#downloadsizes-main)), and that task broadcasts the value to the lanes. Every other page renders without waiting. --- @@ -746,8 +776,7 @@ Three surfaces, and the second is the one that gets missed. Four surfaces, none derived from `TASKS`: -- The **static-task count** in [Task DAG by section](Builder#task-dag-by-section) --- the literal number in *"The pipeline has N named static tasks plus 2N dynamic ones"*. -- The **section-membership lists** immediately below it, one line per Gantt section. +- The **section-membership lists** in [Task DAG by section](Builder#task-dag-by-section), one line per Gantt section. - The **per-task bullet** under the matching `### Seeds` / `### Spine` / `### Render` / `### Write` subsection, plus the task's row in [What runs where](Builder#what-runs-where). - The **two ASCII DAG sketches**, one under Spine and one under Render. diff --git a/docs/Documentation/Images/Tools-Groups.dot b/docs/Documentation/Images/Tools-Groups.dot index 2f9eb9722..8a3daa53d 100644 --- a/docs/Documentation/Images/Tools-Groups.dot +++ b/docs/Documentation/Images/Tools-Groups.dot @@ -137,9 +137,10 @@ digraph tools_groups { t25 [label="indexer.test"] t26 [label="check_package_tests"] t27 [label="broker.test"] t28 [label="ide-js.test"] t29 [label="shot-review.test"] t30 [label="check_callout_evidence"] + t31 [label="discover.test"] t1 -> t5 -> t9 -> t13 -> t17 -> t21 -> t25 -> t29 t2 -> t6 -> t10 -> t14 -> t18 -> t22 -> t26 -> t30 - t3 -> t7 -> t11 -> t15 -> t19 -> t23 -> t27 + t3 -> t7 -> t11 -> t15 -> t19 -> t23 -> t27 -> t31 t4 -> t8 -> t12 -> t16 -> t20 -> t24 -> t28 { rank=same; t5 t6 t7 t8 } { rank=same; t9 t10 t11 t12 } @@ -147,7 +148,7 @@ digraph tools_groups { { rank=same; t17 t18 t19 t20 } { rank=same; t21 t22 t23 t24 } { rank=same; t25 t26 t27 t28 } - { rank=same; t29 t30 } + { rank=same; t29 t30 t31 } } // ---- row 4 ---- @@ -365,6 +366,8 @@ digraph tools_groups { tooltip="Runs unit tests for ide_js.mjs: the byte-exact round trip of a minified file, how a local's name carries to another build, and a fix patched in as the smallest edit."] t29 [URL="Tools-Toolchain-Tests#shot-review-test" tooltip="Runs unit tests for the screenshot review tool: its session, its pages, its writes under docs, and its server with a stand-in run and a commit in a scratch repository."] + t31 [URL="Tools-Toolchain-Tests#discover-test" + tooltip="Runs unit tests for the source tree's inventory, which the build reads in pieces on its lanes: the same in any number of pieces, on a small tree of the tests' own."] t30 [URL="Tools-Toolchain-Tests#check-callout-evidence" tooltip="Verifies that every callout labelled with a twinBASIC build names what checks it, and that every marker names a reproducer, lane, sample, error data file or LLVM probe mode that exists."] diff --git a/docs/Documentation/Images/Tools-Groups.svg b/docs/Documentation/Images/Tools-Groups.svg index b12ee97cd..b35d963fc 100644 --- a/docs/Documentation/Images/Tools-Groups.svg +++ b/docs/Documentation/Images/Tools-Groups.svg @@ -1,8 +1,8 @@ - + tools_groups @@ -48,24 +48,24 @@ cluster_samples - -Code Samples and Attributes + +Code Samples and Attributes cluster_ide - -IDE Automation + +IDE Automation cluster_defects - -Defect Reproducers + +Defect Reproducers @@ -641,8 +641,8 @@ t29 - -shot-review.test + +shot-review.test @@ -650,179 +650,188 @@ t30 - -check_callout_evidence + +check_callout_evidence - + +t31 + + +discover.test + + + + + e1 - - -check_examples + + +check_examples - + e2 - - -gen_attribute_probes + + +gen_attribute_probes - + e3 - - -census_attributes + + +census_attributes - + e4 - - -sweep_attributes + + +sweep_attributes - + e5 - - -package_tests + + +package_tests - + i1 - - -addin_test + + +addin_test - + i2 - - -ide_test + + +ide_test - + i3 - - -try_help_addin + + +try_help_addin - + i4 - - -shoot_docs + + +shoot_docs - + i5 - - -imagestrip + + +imagestrip - + i8 - - -probe_theme_semicolon + + +probe_theme_semicolon - + i7 - - -svgshot/replay + + +svgshot/replay - + i10 - - -shot_review + + +shot_review - + i11 - - -svgshot/chromeshot + + +svgshot/chromeshot - + i12 - - -svgshot/chrome_try + + +svgshot/chrome_try - + d1 - - -bug_repro + + +bug_repro - + d2 - - -vb6run + + +vb6run - + d3 - - -recheck_callouts + + +recheck_callouts - + d4 - - -ide_js + + +ide_js @@ -886,6 +895,7 @@ + diff --git a/docs/Documentation/Pipeline-Stages.md b/docs/Documentation/Pipeline-Stages.md index e1fd8fa5a..ab79979bb 100644 --- a/docs/Documentation/Pipeline-Stages.md +++ b/docs/Documentation/Pipeline-Stages.md @@ -9,7 +9,7 @@ permalink: /Documentation/Development/Pipeline-Stages # Pipeline Stages {: .no_toc } -Interface reference for `tbdocs`. The first half covers every task in the scheduler's DAG, grouped by the five Gantt sections (Seeds / Spine / Render / Write / Check). The second half covers every module and its exports. +Interface reference for `tbdocs`. The first half covers every task in the scheduler's DAG, grouped by the Gantt sections (Seeds / Spine / Render / Write / Check); the search index's tasks, which the chart draws as Index, are under Write. The second half covers every module and its exports. For design rationale and a tour, see [tbdocs Builder](Builder). To add a task or markdown-it plugin, see [Extending the Builder](Extending). @@ -22,7 +22,7 @@ Every task shares three pieces of mutable state: the `pages[]` array, the `stati ### Page objects (`pages[]`) -`discover` creates one page object per `.md` or `.html` source file with parseable YAML frontmatter. Later tasks add fields; none removes or renames a field set earlier. Render workers receive structured-clone copies of their chunk, mutate the copies, and return a delta that the render task's `submit()` merges into the master page via `state.pageByDest`. +The inventory creates one page object per `.md` or `.html` source file with parseable YAML frontmatter: a `discoverRead:i` lane makes it, and `discover` puts it in `pages[]`. The fields below that name `discover` are set there. Later tasks add fields; none removes or renames a field set earlier. Render workers receive structured-clone copies of their chunk, mutate the copies, and return a delta that the render task's `submit()` merges into the master page via `state.pageByDest`. | Field | Added by | Type | Description | |---|---|---|---| @@ -41,6 +41,7 @@ Every task shares three pieces of mutable state: the `pages[]` array, the `stati | `breadcrumbs` | `nav` | `Page[]` | Ancestor chain from the root to the current page, nearest-first. | | `children` | `nav` | `Page[]` | Immediate child pages in nav order. | | `renderedContent` | `render:i` | `string` | HTML body produced by markdown-it. Set on the worker, merged back into the master page via the render delta. | +| `headings` | `render:i` (`headingsOf`) | `object[]\|undefined` | The page's headings, each `{ level, id, text }`, read from `renderedContent` on the worker. Set only on a page the symbol index reads (`isSymbolPage`); `symbolPlace` reads it. | | `searchIndexMarks` | `render:i` (`searchIndexMarksPlugin`) | `object[]\|undefined` | The [index entries](Authoring#index-entries-for-the-site-search) on the page's headings, each `{ id, index, index_also }` with the raw attribute values, removed from the heading before the HTML is written. Set only on a page that has any. Read by `deriveSearchEntries` on the same worker; never merged back to main. | | `seoTitle` | `render:i` (`computeChunkSeo`) | `string` | HTML-stripped, whitespace-collapsed page title for `` and `og:title`. | | `seoFullTitle` | `render:i` (`computeChunkSeo`) | `string` | `" \| "` for non-home pages; equals `seoTitle` on the home page. | @@ -74,7 +75,9 @@ Each task's `execute()` or `submit()` stores its output on `state.site`; downstr | Field | Type | Set by | Description | |---|---|---|---| | `sitePaths` | `Set` | `dispatch` | All site-relative paths reachable in the online tree (pages + statics + redirects + theme assets). Used by the offline rewrite in every render worker, by `scss` and by `writeOffline`. | -| `searchChunks` | `Array>` | `dispatch` (allocated), `render:i.submit` (filled) | Per-chunk search entries collected from the render workers. Read by `searchData`. | +| `searchChunks` | `Array>` | `dispatch` (allocated), `render:i.submit` (filled) | Per-chunk search entries collected from the render workers. Read by `searchEntries`. | +| `searchKeys` | `Array>` | `dispatch` (allocated), `render:i.submit` (filled) | For each entry of `searchChunks`, the keys `settleLabels` compares it by, and its labels (`entryKeys`). Read by `searchEntries`. | +| `searchPacked` | `Array` | `dispatch` (allocated), `render:i.submit` (filled) | Each chunk's entries as its lane packed their text (`packSearchEntries`). Read by `searchData`, and by every lane's `indexAdd:i`, which `indexSlices` sends them to. | | `checkTrees` | `object\|null` | `dispatch` | Per-tree `{ rels, baseurl }` for each tree being checked, or `null` when `--check` is off. Broadcast to the workers so each lane can build its own tree index. When non-null, the check runs everywhere downstream. | | `checkChunks` | `Array` | `dispatch` (created empty), `flush:i.submit` (appended) | Per-chunk findings, keyed by tree, in arrival order. Read by `linkJoin`. | | `checkChunkCount` | `number` | `dispatch` | How many chunks `linkJoin` must see. A short list is an error: the check examined less than the whole site. | @@ -110,9 +113,9 @@ Every task is an entry in the static `TASKS` object in [`tbdocs.mjs`](https://gi | `survives_reset` | `boolean` | no | The per-lane done flags survive an SAB reset between builds in serve mode. | | `perWorkerDeps` | `string[]` | no | Names of `unique_per_worker` tasks that must have run on the claiming lane. | | `pinnedTo` / `F_PIN_TO_PRED` | (dynamic) | no | Must run on the same lane that ran the named predecessor. Set via the `pinnedTo` array, not in the task def directly. | -| `priority` | `number` | no | When several tasks are READY, the **highest** value claims first. Default `0`; `dispatch.submit` gives each `flush:i` `priority: 1`, so a pending flush outranks a fresh render. | +| `priority` | `number` | no | When several tasks are READY, the **highest** value claims first. Default `0`; `dispatch.submit` gives each `flush:i` `priority: 1`, so a pending flush outranks a fresh render. The search index's pieces, `archiveLateDeflate:i`, `writePdf` and `checkBook` have `2`, and `archiveDeflate:i` has `1`: the first group is the path the end of the build waits for. | | `consolidate` | `boolean` | no | Combine timings across lanes into one Gantt swimlane (`render:i` / `flush:i`). | -| `ganttSection` | `string` | no | Section header for the Gantt chart row (`Seeds` / `Spine` / `Render` / `Write` / `Check`). | +| `ganttSection` | `string` | no | Section header for the Gantt chart row (`Seeds` / `Spine` / `Render` / `Write` / `Index` / `Check`). | ### Handler IDs @@ -123,8 +126,9 @@ export const HANDLERS = { warmInit: 0, renderEnvInit: 1, flush: 2, scssLight: 3, scssDark: 4, dot: 5, buildInfo: 6, render: 7, - helpArchive: 8, writePdf: 9, checkBook: 10, - searchIndex: 11, + writePdf: 9, checkBook: 10, packTests: 11, + indexAdd: 12, indexVectors: 13, archiveDeflate: 14, + discoverRead: 15, }; ``` @@ -132,13 +136,19 @@ The reverse table (`handlerById`) is built when the worker module loads. ### Static vs dynamic tasks -`TASKS` lists the **static** tasks, whose presence and edges are known before the build starts. **Dynamic** tasks (`render:i`, `flush:i`) are allocated at runtime by `dispatch.submit()` once the page count is known. Both kinds share the SAB: `sab-scheduler.mjs:allocDynamicSlots` reserves slots from the same pool, and `wireDynamicEdges` plus `appendDynamicSuccessors` extend the successor edges. +`TASKS` lists the **static** tasks, whose presence and edges are known before the build starts. **Dynamic** tasks are allocated at runtime, once a count is known: `render:i` and `flush:i` by `dispatch.submit()`, from the page count, and the pieces of the search index and of the help archive by the `submit()` of the task that plans them, through [`fanOut`](#fan-outmjs). Both kinds share the SAB: `sab-scheduler.mjs:allocDynamicSlots` reserves slots from the same pool, and `wireDynamicEdges` plus `appendDynamicSuccessors` extend the successor edges. + +### No task starts a thread + +The lanes are the build's only threads. A task whose work can run in parallel splits it into pieces and adds each piece to the graph as a lane task with [`fanOut`](#fan-outmjs). The scheduler then places the pieces on the lanes that are free, and the Gantt chart on [Build Info](BuildInfo) shows each piece on the lane that ran it. + +A task therefore never starts a worker thread or a process for its work, and never puts CPU work on Node's thread pool, which is what the functions of `node:zlib` do unless their name ends in `Sync`. File reads and writes may use the pool. The two exceptions are named in `biome.jsonc`: `worker-pool.mjs` and `cpu-worker.mjs` are the lanes, and `build-info.mjs` and `addin-project.mjs` run `git`. [`check_lint.mjs`](Tools-Toolchain-Tests#check-lint) refuses any other import of `worker_threads`, `cluster` or `child_process` in `builder/`, and any import from `node:zlib` in `builder/` or `lib/` other than a `Sync` function, `crc32` or `constants`. --- ## Section 1 --- Seed tasks -The tasks that start the build. `config`, `buildInfo`, `scssLight` and `scssDark` have no predecessors and are claimable as soon as the build starts; `highlighterInit` waits for `config`, and `loadData` for `highlighterInit`. +The tasks that start the build. `config` has no predecessor and is claimable as soon as the build starts; `highlighterInit` waits for `config`, and `loadData` for `highlighterInit`. `buildInfo`, `scssLight` and `scssDark` wait for [`discoverList`](#discoverlist-main), as `dot`, `packTests` and `warmInit` do. ### `config` (main) @@ -146,14 +156,19 @@ The tasks that start the build. `config`, `buildInfo`, `scssLight` and `scssDark config.execute({}, ctx) → { config } ``` -Reads `/_config.yml`, applies the `ctx.opts.baseurl` and `ctx.opts.url` overrides, and returns the parsed object to `discover`. +Reads `/_config.yml`, applies the `ctx.opts.baseurl` and `ctx.opts.url` overrides, and returns the parsed object to `discover`. `submit` broadcasts the config's `package_tests` entry to the lanes as the `"packageTests"` task data, for [`packTests`](#packtests-worker). ### `buildInfo` (worker) -Handler in `cpu-worker.mjs`: calls `captureBuildInfo()` from `build-info.mjs`, which runs two parallel `git` commands (`rev-parse --short HEAD` and `log -1 --format=%cs`). Falls back to `"unknown"` on failure. The result goes to `state.site.buildInfo`. +Handler in `cpu-worker.mjs`: calls `captureBuildInfo()` from `build-info.mjs`, which runs two parallel `git` commands (`rev-parse --short HEAD` and `log -1 --format=%cs`). Falls back to `"unknown"` on failure. The result goes to `state.site.buildInfo`, which the book's title page alone states: [`bookPayload`](#bookpayload-main) waits for this task, and `dispatch` does not, so no render waits for `git`. ### `scssLight` (worker), `scssDark` (worker) +```js +scssLight.expected = ["discoverList"] +scssDark.expected = ["discoverList"] +``` + Handlers call `compileLightScss(srcRoot)` and `compileDarkScss(srcRoot)`. Each compiles the vendored just-the-docs SCSS plus customisations against one palette. The CSS strings go to the `scss` task. ### `highlighterInit` (main) @@ -176,17 +191,48 @@ Calls `loadData(srcRoot)` from `data.mjs`. Writes `state.site.data` and `state.s ## Section 2 --- Spine tasks -`discover` and the main-thread tasks fed by it, with `dot` (no predecessors) running on a worker beside them. They build the `site` object, derive auxiliary data and prepare the fan-out. `deriveSitemap` and `resolveBookChapters` wait for `dispatch`, in Section 3. +The source tree's inventory and the main-thread tasks fed by it, with `dot` running on a worker beside them. They build the `site` object, derive auxiliary data and prepare the fan-out. `deriveSitemap` and `resolveBookChapters` wait for `dispatch`, in Section 3. + +The inventory is three tasks. The main thread lists the tree, two lanes open every file, and the main thread puts the results together. + +### `discoverList` (main) + +```js +discoverList.expected = ["config"] +discoverList.execute({ config: { config } }, ctx) → + { pieces, statics, pairs } +``` + +Calls `listSources(srcRoot, config.exclude ?? [])` and then `cutPieces(listing, count, config.bundle_extra ?? [])`, both from `discover.mjs`. `count` is `discoverPieces(workerCount)`: four on a machine with eight or more logical CPUs, two below that, one on a machine with one lane. Each piece is `{ pageRels, statSrcs, pairs }`: every `count`-th `.md` or `.html` file, static file and picture pair, so that each piece has its share of every folder. The `bundle_extra` files are among the static files, and a light picture is paired with its dark one wherever the two are. `statics` and `pairs` are what `discover` needs to put the results in order. + +`submit()` calls `fanOut` with the pieces as payloads, handler `discoverRead`, join `discover` and the highest priority of any lane task. + +The lane tasks that would otherwise be claimable before the pieces exist list `discoverList` in their `expected`: `buildInfo`, `scssLight`, `scssDark`, `dot`, `packTests` and `warmInit`. The first lanes to start therefore find the pieces and nothing else. + +### `discoverRead:i` (worker) + +```js +discoverRead:i.expected = ["discoverList"] +discoverRead:i → { pages, plain, warnings, sizes, pairSizes, text } +``` + +Handler in `cpu-worker.mjs`: calls `readPiece(srcRoot, piece)` from `discover-read.mjs` with its `fanOutPayload`. It reads each page file and parses its frontmatter into a [page object](#page-objects-pages), sizes each static file, and reads each picture pair's width and height from the two PNG headers. A `.md` or `.html` file with no frontmatter goes to `plain`, with its size: it is a static file. The warnings about unquoted frontmatter values that end in `#` go to `warnings`, which the main thread prints. Frontmatter that does not parse throws, naming the file, and fails the build. + +The handler then packs the text of its pages with `packPageText`, and returns it as `text`: one `SharedArrayBuffer` of UTF-8, and each page's offset and length in it. The render lanes read a page's text from there, so the render chunks' payloads hold none. + +Every call is synchronous. A lane has nothing else to do while it reads, and two lanes reading at once is what makes the inventory parallel. + +This is the one handler a lane runs after the first stage of its boot alone; see [`cpu-worker.mjs`](#cpu-workermjs). ### `discover` (main) ```js -discover.expected = ["config"] -discover.execute({ config: { config } }, ctx) → - { pages, staticFiles, config } +discover.expected = ["config", "discoverList", "discoverRead:0", ...] // the pieces, added by fanOut +discover.execute(inputs, ctx) → + { pages, staticFiles, config, pictureSizes, pageText } ``` -Calls `discover(srcRoot, config.exclude ?? [])` from `discover.mjs`, appends each `bundle_extra` entry to `staticFiles`, then runs `unpublishableSourceFiles` from `publish-policy.mjs` over the result and **throws** if anything is not a publishable type, before any write. `submit()` writes the three fields to `SharedState` and populates `state.pageByDest`. +Calls `assemble(srcRoot, plan, results)` from `discover.mjs` with `discoverList`'s plan and each piece's result; a piece that is missing throws. `assemble` sorts the pages by file name and then by path, the static files by path, and puts the `bundle_extra` files after them. The task then runs `unpublishableSourceFiles` from `publish-policy.mjs` over the static files and **throws** if anything is not a publishable type, before any write, and throws for a light picture with no dark one. `pageText` holds each piece's text buffer and, for each page's `srcRel`, the piece, offset and length of its text. `submit()` broadcasts each buffer to the lanes as the task data `"pageText:"`, keeps the places as `state.pageTextAt` for `dispatch`, writes the other four fields to `SharedState` and populates `state.pageByDest`. ### `vendorAssets` (main) @@ -213,6 +259,10 @@ Calls `computeNav(state.pages, state.site.config)` from `nav.mjs`, then `renderS ### `dot` (worker) +```js +dot.expected = ["discoverList"] +``` + Handler calls `regenerateDot(srcRoot)`. It finds `*.dot` files at any depth under `` (skipping underscore-prefixed directories, which hold build output), compares mtimes against the `.svg` siblings, calls `Graphviz.load()` once, installs Inter's width table via `applyInterMetrics()`, then runs `gv.dot(src)` per stale source. Returns `dotStats` (`processed`, `regenerated`, `failed`, `setupSkipped?`, `svgFiles[]`); `submit()` appends the new SVG descriptors to `state.staticFiles`. Rendering takes under a millisecond per diagram after a one-time `Graphviz.load()` of about 50 ms. ### `buildInit` (main) @@ -227,12 +277,12 @@ Calls `buildInitConfig(state.site)` from `template.mjs` to pre-render the config ### `markdownInit` (main) ```js -markdownInit.expected = ["discover", "vendorAssets", "deriveRedirects", "packTests"] +markdownInit.expected = ["discover", "vendorAssets", "deriveRedirects"] ``` Builds the link tables (`buildLinkTables(state.pages)`) and derives the `{{tbdocs:}}` counts registry (`deriveCounts(state, { redirectStubs: stubs.length })` from `counts.mjs`), throwing if a page names a count that does not exist. The redirect-stub count is why `deriveRedirects` is a predecessor. -It also settles the downloads that `{{tbdocs:size:}}` and `{{tbdocs:packageTestRows}}` state (`deriveDownloads`, then `checkPlaceholders`, which throws on a path the build does not publish or cannot size). `packTests`, a task of its own that follows `config`, packs the contributed packages' test projects in memory so that their sizes are known; `packageTests` writes those same bytes. Only the sizes the pages ask for travel to the workers, as `state.site.downloads`. +It also checks the downloads that `{{tbdocs:size:}}` and `{{tbdocs:packageTestRows}}` state (`deriveDownloads`, then `checkPlaceholders`, which throws on a path the build does not publish or cannot size). A static file's size is known here. The contributed packages' test projects and published tools are not packed yet: [`packTests`](#packtests-worker) packs them on a lane, and this task does not wait for it. It takes their paths from a listing of their folders (`packageTestRels`), accepts a placeholder that names one, and records each page that states such a size or lists the test projects as a **late page**, in `state.site.latePages`. Only the sizes the pages ask for travel to the workers, as `state.site.downloads`; [`downloadSizes`](#downloadsizes-main) adds the packed files' sizes for the late pages. It then instantiates the shared markdown-it (`createMarkdownIt({ highlighter: null, linkTables, baseurl, staticFiles, vendoredVideos, vendoredImages, counts })`), serializes the link tables (`serializeLinkTables(linkTables)`) for the workers, and computes site-level SEO (`computeSiteSeo(state.site.config, state.site.markdown)`). It writes `counts`, `markdown`, `linkTablesSerialized`, `seoSiteTitle` and `seoLogoUrl` to `state.site`. Per-page SEO is **not** computed here; each render worker does it via `computeChunkSeo`. @@ -268,14 +318,33 @@ Calls `resolveBookChapters(state.site.bookData, state.pages)` from `book.mjs`, w `dispatch`, the fan-out point, and the N render tasks it starts, with their barrier, the per-worker init they need, and the two tasks that prepare the destination trees. The chart draws `warmInit` and `renderEnvInit` in the worker rows as start-up bars, not in a section; they are described here. The N flush tasks and their barrier are in Section 4. +### `packTests` (worker) + +```js +packTests.expected = ["config", "discoverList"] +packTests → { packed, ms } | { failed, error } | {} +``` + +Packs each contributed package's test project, and zips each published tool, in memory (`packAllPackageTests` in `package-tests.mjs`), from the `"packageTests"` task data that `config` broadcast. The lane imports `package-tests.mjs` when it runs the task, so the other lanes do not load it. The bytes return to the main thread, where `downloadSizes` reads their sizes and `packageTests` writes them into the online tree. A config without `package_tests` packs nothing, and a failure returns as `{ failed, error }`. + +No page waits for this task except the late pages. It therefore runs at any time from the start of the build to the render of those pages, on whichever lane is free. + +### `downloadSizes` (main) + +```js +downloadSizes.expected = ["markdownInit", "packTests"] +``` + +Adds the packed files' sizes to `state.site.downloads` (`packedDownloads` in `counts.mjs`): the size of each packed file a page names, and the rows of the test projects' table. It throws when `packTests` failed. `submit` broadcasts the result to the lanes as the `"downloads"` task data, before the task is marked done. The render chunks that hold a late page wait for this task; see [`dispatch`](#dispatch-main). + ### `dispatch` (main) ```js dispatch.expected = [ - "nav", "buildInit", "buildInfo", "dot", + "nav", "buildInit", "dot", "deriveRedirects", "markdownInit", ] -dispatch.execute() → { chunks, sharedSAB } +dispatch.execute() → { chunks, sharedSAB, lateChunks } ``` `execute`: @@ -283,9 +352,11 @@ dispatch.execute() → { chunks, sharedSAB } 1. Slices `state.pages` into `workerCount × SLICES_PER_WORKER` chunks (one chunk per worker at most, for small page counts). 2. Computes the `sitePaths` set via `buildSitePathsSync` from `offline-rewrite.mjs`, using the vendored theme asset list from `enumerateVendoredThemeAssets()` rather than reading `_site/assets/`. The list also holds the path of the help add-in's project file when `_config.yml` declares one (`addinProjectOf`), since [`addinProject`](#addinproject-main) writes it only after the render. 3. Derives each output tree's inventory with `deriveTreeRels` and runs `unpublishableTreePaths` from `publish-policy.mjs` over it, **throwing** on anything that is not a publishable type. This sweep sees what `discover`'s cannot: redirect stubs, vendored theme assets, and the generated `sitemap.xml` and `search-data.json`. The inventory is shared with `checkTrees` below. -4. Builds the shared payload and packs it into one SAB via `packShared` from `sab-broadcast.mjs`: config, site-level SEO, pre-rendered chrome + sidebar, serialized link tables, static-file relative-path set, baseurl, site-paths array, offline-exclude patterns, skip-offline flag, build info, the inlined `svgContents`, the `vendoredVideos` / `vendoredImages` maps from `vendorAssets`, and `checkTrees` (per-tree `rels` + `baseurl`, or absent when `--check` is off). +4. Builds the shared payload and packs it into one SAB via `packShared` from `sab-broadcast.mjs`: config, site-level SEO, pre-rendered chrome + sidebar, serialized link tables, static-file relative-path set, baseurl, site-paths array, offline-exclude patterns, skip-offline flag, the inlined `svgContents`, the `vendoredVideos` / `vendoredImages` maps from `vendorAssets`, and `checkTrees` (per-tree `rels` + `baseurl`, or absent when `--check` is off). -`submit` allocates 2N dynamic SAB slots and writes their handler IDs. It wires `render:i → [renderJoin, flush:i]` and `flush:i → [flushJoin]`, sets the per-worker dependency `render:i → renderEnvInit`, and pins each `flush:i` to its `render:i`. It packs the per-chunk page data into a payload SAB, registers the `render:i` / `flush:i` task definitions on the scheduler (so `submit()` callbacks resolve), broadcasts the two SABs to every worker via `pool.broadcastDynamicData`, and activates the `render:i` slots. +`lateChunks` holds the index of each chunk that contains a late page (see [`markdownInit`](#markdowninit-main)). The chunks are cut as for any other page, so a late page stays in the chunk its position gives it. + +`submit` allocates 2N dynamic SAB slots and writes their handler IDs. It wires `render:i → [renderJoin, flush:i]` and `flush:i → [flushJoin]`, sets the per-worker dependency `render:i → renderEnvInit`, and pins each `flush:i` to its `render:i`. Unless `downloadSizes` is done already, it also makes each `render:i` of `lateChunks` a successor of `downloadSizes`, with a dependency count of one, so that the chunk becomes claimable when the packed files' sizes are known. Both tasks run on the main thread, so `downloadSizes` cannot finish between the check of its status and the new edge. It packs the per-chunk page data into a payload SAB: for each chunk `{ pages, texts }`, the pages without their `rawContent` and, for each, the piece, offset and length of its text in the buffers `discover` broadcast (`state.pageTextAt`). A page with no place there keeps its `rawContent` in the payload. It registers the `render:i` / `flush:i` task definitions on the scheduler (so `submit()` callbacks resolve), broadcasts the two SABs to every worker via `pool.broadcastDynamicData`, and activates the `render:i` slots. ### `prepDest` (main, deferred) @@ -305,7 +376,11 @@ Pre-creates every page output directory (online + offline), so `flush:i` can cal ### `warmInit` (worker, `on_demand` + `unique_per_worker` + `run_when_idle` + `survives_reset`) -Per-lane Shiki bootstrap (`initHighlighter()` from `highlight.mjs`). The flags: +```js +warmInit.expected = ["discoverList"] +``` + +Per-lane Shiki bootstrap (`initHighlighter()` from `highlight.mjs`). A lane does not start it before the source tree is listed, so that an idle lane takes a `discoverRead:i` first. The flags: - `unique_per_worker`: every lane that runs a render task needs its own warmup. - `on_demand`: keeps it off the auto-start list. @@ -334,15 +409,19 @@ Per-lane render environment setup. Handler: Handler (`render` in `cpu-worker.mjs`): -1. Reads the chunk JSON from `_payloadSAB` using `payloadOffset[taskIdx]` / `payloadLength[taskIdx]`. +1. Reads the chunk JSON from `_payloadSAB` using `payloadOffset[taskIdx]` / `payloadLength[taskIdx]`, and gives each page its `rawContent` with `pageText`, from the `"pageText:"` task data its place names. When the chunk holds a late page, it waits for the `"downloads"` task data from `downloadSizes` and gives it to the lane's markdown-it, which then has the packed files' sizes. 2. `await renderPhase(chunk, env.site)` --- markdown-it body render. 3. `computeChunkSeo(chunk, env.site.seoSiteTitle, env.site.config, env.site.markdown)` --- per-page SEO fields. 4. `await templatePhase(chunk, env.site, env.initData)` --- just-the-docs layout wrap. 5. When `env.offlineBase` is set: for each writable page, call `withPartialNav` to cut the page's nav down to its part of the tree, then `deriveOfflinePage`. Then, for each writable page, `withOnlineNav` cuts the online page's nav down to its part, with the "Contents" link and `nav-tree.js` after it. 6. Store `{ destPath, html, offlineHtml, offlineMisses, markdown }` on the worker's `_pendingFlush` FIFO for the matching `flush:i`, `markdown` being the page's markdown copy and its path. 7. `deriveSearchEntries(chunk, env.site)` --- per-section search entries, with any [index entries](Authoring#index-entries-for-the-site-search) the page's frontmatter or headings name. Remove `sourcePage` and the chunk-local `i` before returning (main assigns global indices). +8. For the tasks that follow the last chunk, which every lane waits for, the part of their work that one page or one entry decides: + - `headingsOf(p.renderedContent)` for each page the symbol index reads (`isSymbolPage` in `symbols.mjs`), for `symbolPlace`. + - `entryKeys(e)` for each entry --- the keys `settleLabels` compares it by, and its labels --- for `searchEntries`. The entries themselves hold no `labels`. + - `packSearchEntries(searchEntries)` --- the chunk's entries in one `SharedArrayBuffer`, each as the head and the tail of its text in `search-data.json`. `searchData` copies them into the file, and the lanes that build the search index read their entries from them. -Returns `{ pages, searchEntries }`. The `submit()` callback (registered by `dispatch.submit`) merges `renderedContent` / `offlineMisses` into the master `Page` objects via `state.pageByDest`, and writes `searchEntries` into `state.searchChunks[i]`. +Returns `{ pages, searchEntries, searchKeys, searchPacked }`. The `submit()` callback (registered by `dispatch.submit`) merges `renderedContent` / `offlineMisses` / `headings` into the master `Page` objects via `state.pageByDest`, and writes the other three into `state.searchChunks[i]`, `state.searchKeys[i]` and `state.searchPacked[i]`. ### `renderJoin` (main, `on_demand`) @@ -353,7 +432,7 @@ renderJoin.expected = ["render:0", …, "render:N-1"] // and depCount set to N renderJoin.execute() → {} ``` -Barrier over every `render:i`. Unblocks `searchData`, `symbolIndex` and `bookPayload`. +Barrier over every `render:i`. Unblocks `symbolPlace`, `searchEntries` and `bookPayload`. > [!IMPORTANT] > **A dependency count of zero does not mean the submits have run**, so the `expected` @@ -375,7 +454,7 @@ Barrier over every `render:i`. Unblocks `searchData`, `symbolIndex` and `bookPay ## Section 4 --- Write and post-write -The tasks that write the output. `scss` joins the two stylesheets after `prepDest`; each `flush:i` writes its chunk's pages after its `render:i` and `prepPageDirs`; the rest are produced by the main-thread writers, which run one at a time in the order `TASKS` declares them, and by two worker tasks, `helpArchive` and `writePdf`. All but `writeAssets` wait behind `renderJoin` or `flushJoin`. +The tasks that write the output. `scss` joins the two stylesheets after `prepDest`; each `flush:i` writes its chunk's pages after its `render:i` and `prepPageDirs`; the rest are produced by the main-thread writers, which run one at a time in the order `TASKS` declares them, and by worker tasks: `writePdf`, and the pieces of the search index and of the help archive, which their main-thread tasks add to the graph. All but `writeAssets` wait behind `renderJoin` or `flushJoin`. ### `scss` (main) @@ -407,7 +486,7 @@ flushJoin.expected = [] // populated by dispatch.submit with ["flush:0", ..., flushJoin.execute(inputs) → { written, offlineWritten, offlineMisses } ``` -Aggregates per-chunk write stats. Unblocks `writeAux`, `helpArchive`, `bookPayload` and `linkJoin`. +Aggregates per-chunk write stats. Unblocks `writeAux`, `archivePlan`, `bookPayload` and `linkJoin`. ### `writeAssets` (main) @@ -417,39 +496,69 @@ writeAssets.expected = ["dot", "vendorAssets", "prepPageDirs", "highlighterInit" Calls `writePhase(state.pages, state.staticFiles, { destRoot, dryRun, generatedAssets, baseurl, skipPages: true })` from `write.mjs`. Copies vendored theme JS and project static files, and writes generated CSS (`tb-highlight.css` from `state.site.highlightCss`). **Does not** write page HTML; the `flush:i` tasks do. The CSS baseurl rewrite (`url("/path")` → `url("/path")`) applies to copied files and generated assets. +### From the last chunk to the search index: `packageApi`, `symbolPlace`, `searchEntries` +{: #symbolplace-main } + +```js +packageApi.expected = ["dispatch"] // main +symbolPlace.expected = ["renderJoin", "packageApi"] // main +searchEntries.expected = ["renderJoin", "symbolPlace"] // main +``` + +When the last render chunk ends, every lane waits until `indexSlices` gives it a slice of the search index, and `indexSlices` waits for `symbolPlace` and `searchEntries`. The three run one after another on the main thread, so they do only the work that needs every page. The render lanes do the part that one page or one entry decides, as [`render:i`](#renderi-worker-dynamic) lists. A task that only writes a file comes after them: `symbolIndex` and `searchData`. `TASKS` declares the three before every other task that can be ready at that moment, because the main thread takes the first ready task in declaration order. + +- **`packageApi`** reads and parses `builder/package-api.json`, the package half of the symbol index, while the lanes render. The build fails, naming `node indexer/twin-index.mjs derive`, if the file is missing. +- **`symbolPlace`** makes the symbol index in memory: `symbolPages(state.pages)`, then `deriveSymbolIndex({ pages, api })` from `symbols.mjs`. It depends on `renderJoin` because an entry's anchor is the id the render gave its heading; each page's headings came back with its render chunk. Returns `{ pages, api, result }`. +- **`searchEntries`** makes the final search entries: `consolidateSearchEntries(state.searchChunks, symbolPlace.result.symbols, state.searchKeys)` from `search.mjs`. It flattens the per-chunk entry arrays, checks that no index term is the main entry (`index`) of two entries (`checkIndexTerms`, which throws naming them), drops the term entries a main term answers and gives each remaining label to its entry (`settleLabels`), renumbers the global `i` index, and joins the symbols onto the matching entries by URL (`joinSymbolsToEntries`, adding the `names` / `qualified` / `primary` fields --- see `WIP.Search.md`'s "Design" §2). Returns `{ entries, places }`: `places[n]` is entry n's chunk and its place in that chunk, by which `searchData` and `indexSlices` find the entry's packed text. + ### `searchData` (main) ```js -searchData.expected = ["renderJoin", "prepDest", "symbolIndex"] +searchData.expected = ["searchEntries", "prepDest"] ``` -Calls `writeSearchDataFromChunks(state.searchChunks, destRoot, symbolIndex.symbols)` from `search.mjs`. It flattens the per-chunk entry arrays and joins `symbolIndex`'s symbols onto the matching entries by URL (`joinSymbolsToEntries`, adding the `names` / `qualified` / `primary` fields -- see `WIP.Search.md`'s "Design" §2). It then renumbers the global `i` index, checks that no index term is the main entry (`index`) of two entries (`checkIndexTerms`, which throws naming them), and writes `assets/js/search-data.json`. Returns `{ entries, json }`. The workers did the heavy work (heading split, content sanitisation, URL encoding); this task only joins and concatenates. It depends on `symbolIndex` for the `symbols` array. +Writes `assets/js/search-data.json` with `writeSearchData` from `search.mjs`. The file's bytes are assembled, not serialised again (`searchDataBytes`): each entry's head and tail are copied from the buffer its render lane packed (`state.searchPacked`), and the main thread writes only the entry's number and the fields it got since. Returns `{ entries, json, docs }`: `json` is the file's bytes, which the link check reads, and `docs` is the entries as the file holds them (`searchDocs`), which `searchIndex` writes into `search-index.json`. The task runs while the lanes add their slices. -### `searchIndex` (worker) +### The search index: `indexSlices` to `searchIndex` +{: #searchindex-worker } ```js -searchIndex.expected = ["searchData"] -searchIndex.handler = "searchIndex" +indexSlices.expected = ["searchEntries"] // main +indexAdd:i.expected = ["indexSlices"] // worker, dynamic +indexMerge.expected = ["indexSlices", "indexAdd:0", ...] // main +indexTerms.expected = ["indexMerge"] // main +indexVectors:i.expected = ["indexSlices", "indexMerge", "indexAdd:i"] // worker, dynamic, pinned to indexAdd:i +searchIndex.expected = ["indexSlices", "indexMerge", "indexTerms", "searchData", "indexVectors:0", ...] // main ``` -Calls `writeSearchIndex(destRoot, { offline })` from `search-index.mjs`, which reads the `search-data.json` that `searchData` wrote and writes `assets/js/search-index.json` beside it: `{"docs": ..., "index": ...}`, the search entries and their lunr index, as lunr's own JSON, in one file, which the site's search box loads (`lunr.Index.load`) instead of building the index in the browser. One file, so that the page can never hold the entries of one deploy beside the index of another; `search-data.json` stays for the link check and the eval tools. Unless the build writes no offline tree, the task also writes the offline tree's `assets/js/search-index.js`, the same file as a script that sets `window.SEARCH_INDEX`, since a page under `file://` can load a script but not fetch a file. Returns `{ entries, workers, bytes }`. +These tasks build the lunr index of the search entries, and write it. The functions are in `search-index.mjs`. lunr cannot merge two indexes, but most of a build is independent for each entry, so the index is built in slices, each a run of consecutive entries: -The index is built on threads of the task's own (`search-index-worker.mjs`), up to eight, one for every 500 entries, so a small tree starts none. Each thread adds a run of the entries to a `lunr.Builder` of its own; the task merges the postings, numbering each term as one build would, works out the totals the field vectors need, and has each thread make its entries' vectors. The result is byte for byte what `lunr()` makes on one thread, which [`test/search-index.test.mjs`](Tools-Toolchain-Tests#search-index-test) checks. The task runs on a worker rather than on the main thread because the main thread runs one task at a time, and as one of them it held back `bookPayload`, `writeAux` and `writeOffline` for the second or two the index takes. `helpArchive` and `checkReport` wait for it. +1. **`indexSlices`** cuts the entries into slices of about equal text (`planIndexSegments`): two for each lane, and at most one for every 500 entries, so a small tree is one slice. The entries do not travel with the slices. Each render lane packed its chunk's entries into a `SharedArrayBuffer`, and `submit` broadcasts all of them, with the stem twins (`stemTwins`), as the task data `"indexEntries"`. A slice's payload then says where its entries are among the chunks, the number of its first entry, which entries of those runs were dropped, and the fields an entry got after its page was rendered. `submit` adds an `indexAdd:i` and an `indexVectors:i` for each slice with [`fanOut`](#fan-outmjs). +2. **`indexAdd:i`** reads its slice's entries from the chunks' buffers (`sliceDocs`, `readSearchEntries`), adds them to a `lunr.Builder` that stays on its lane (`addSlice`), and returns the slice's terms, postings and field lengths. +3. **`indexMerge`** merges the postings (`mergeSlices`). It numbers each term as one build would, and works out each term's document count and each field's average length over all the entries. It broadcasts those totals to the lanes as the task data `"indexTotals"` (`packTotals`). +4. **`indexTerms`** writes the JSON of the inverted index (`invertedIndexJson`) on the main thread, while the lanes make the vectors. +5. **`indexVectors:i`** makes its slice's field vectors with the totals (`sliceVectors`). It is pinned to the lane that ran `indexAdd:i`, which holds the slice's builder. +6. **`searchIndex`** joins the JSON (`assembleIndexJson`) and writes the files (`writeSearchIndex`), with the entries `searchData` returned as `docs`. Returns `{ entries, slices, bytes }`. + +The result is byte for byte what `lunr()` makes on one thread, for any number of slices, which [`test/search-index.test.mjs`](Tools-Toolchain-Tests#search-index-test) checks. + +`searchIndex` writes `assets/js/search-index.json`: `{"docs": ..., "index": ...}`, the search entries and their lunr index, as lunr's own JSON, in one file, which the site's search box loads (`lunr.Index.load`) instead of building the index in the browser. One file, so that the page can never hold the entries of one deploy beside the index of another; `search-data.json` stays for the link check and the eval tools. Unless the build writes no offline tree, the task also writes the offline tree's `assets/js/search-index.js`, the same file as a script that sets `window.SEARCH_INDEX`, since a page under `file://` can load a script but not fetch a file. `archiveLate` and `checkReport` wait for it. + +The index tasks are drawn in their own colour in the Gantt chart, and their main-thread tasks in the band `Index`, with `symbolPlace` and `searchEntries` before them. ### `symbolIndex` (main) ```js -symbolIndex.expected = ["renderJoin", "prepDest"] -symbolIndex.execute() → { entries, urls, gaps, unplaced, symbols } +symbolIndex.expected = ["symbolPlace", "prepDest"] +symbolIndex.execute() → { entries, urls, gaps, unplaced, json } ``` -Writes `tB/symbols.json`, the [symbol index](Building#the-symbol-index). Reads `builder/package-api.json` (the build fails, naming `node indexer/twin-index.mjs derive`, if it is missing), then calls `symbolPages(state.pages)`, `deriveSymbolIndex({ pages, api })` and `serializeSymbolIndex(...)` from `symbols.mjs`. It depends on `renderJoin` because an entry's anchor is the id the render gave its heading, read from `renderedContent`. Takes ~50 ms. With `--symbol-gaps ` it also writes `reportableGaps(...)` there as JSON. +Writes `tB/symbols.json`, the [symbol index](Building#the-symbol-index), from what [`symbolPlace`](#symbolplace-main) placed: `serializeSymbolIndex(...)` from `symbols.mjs`. With `--symbol-gaps ` it also writes `reportableGaps(...)` there as JSON. The result fields: - `urls`: every distinct URL in the index. `runBuild` passes it to `checkSymbolBaseline` from `symbol-baseline.mjs` after the check report, beside the page-count guard. - `unplaced`: the package pages that gave no entry; the summary prints them. -- `symbols`: the array `deriveSymbolIndex` returned, each `{ name, container, url, ... }`. Only `searchData` uses it. - `json`: the text of `tB/symbols.json`. `runBuild` passes it to `syncAddinIndex` from `addin-index.mjs` for the help add-in's copy, and `addinProject` packs it into the add-in's project file. `checkReport` waits for this task, since `tB/symbols.json` is in the online tree's index and `--check-audit-index` must not look for it early. @@ -486,21 +595,32 @@ writeOffline.expected = ["writeAux", "writeAssets"] Calls `writeOffline(state.staticFiles, state.site, destRoot, { auxStats, sitePaths, profileOffline })` from `offline.mjs`. `render:i` / `flush:i` have already rewritten and written the per-page HTML. This task does the rest: CSS `url()` rewriting, the `just-the-docs.js` AST patch (`deriveOfflineJtdJs`), the offline `nav.js` (the whole nav tree with its links relative to the site's root), theme assets and redirect stubs. `sitePaths` comes from `state.sitePaths`. -### `helpArchive` (worker) +### The help archive: `archivePlan` to `helpArchive` +{: #helparchive-worker } ```js -helpArchive.expected = ["flushJoin", "scss", "searchIndex", "writeOffline"] -helpArchive.handler = "helpArchive" +archivePlan.expected = ["flushJoin", "scss", "writeOffline"] // main +archiveDeflate:i.expected = ["archivePlan"] // worker, dynamic +archiveLate.expected = ["archivePlan", "searchIndex"] // main +archiveLateDeflate:i.expected = ["archiveLate"] // worker, dynamic +helpArchive.expected = ["archivePlan", "archiveLate", "archiveDeflate:0", ..., "archiveLateDeflate:0", ...] // main ``` -Writes `add-in/Resources/HELP/site.zip`, the archive of the offline tree, less the sections in `HELP_ARCHIVE_SKIP`, that the IDE help add-in embeds (see [Build and Generation Tools](Tools-Build#the-help-archive)). The four predecessors between them write the whole offline tree. The handler calls `helpArchiveStep` from `help-archive-step.mjs`, with the `skipOffline` flag it reads from `dispatch`'s shared broadcast (`sharedData()` in `cpu-worker.mjs`), and reads the offline tree from disk. It runs on a worker because it needs nothing that `dispatch` has not broadcast, and the main thread meanwhile does the work that follows `writeOffline`. +Write `add-in/Resources/HELP/site.zip`, the archive of the offline tree, less the sections in `HELP_ARCHIVE_SKIP`, that the IDE help add-in embeds (see [Build and Generation Tools](Tools-Build#the-help-archive)). The functions are in `help-archive-step.mjs`, over `lib/help-archive.mjs`. + +The deflating is split into **units**: a whole file, or one piece of 1 MB of a larger file. A large file's pieces are joined into one deflate stream. Every piece but the last ends with a sync flush, which ends it on a byte boundary without ending the stream, and each piece is primed with the 32 KB of the file before it. The bytes depend only on the piece size, never on how many lanes ran the units. -The zip comes back as a plain byte array. `submit` wraps it again as a `Buffer` over the same memory, which `addinProject` packs into the add-in's project file and `runBuild` checks the offline tree against once the Gantt chart is injected (`recheckHelpArchive`). The step writes nothing for a source root other than `docs`, a `--dest` other than `docs/_site`, and under `--serve`, `--dry-run` or `--no-help-archive`. +1. **`archivePlan`** runs once `flushJoin`, `scss` and `writeOffline` have written everything in the offline tree but `search-index.js`. `planHelpArchive` decides whether this build writes the archive, refuses one that would hold a file the Downloads page offers, lists the tree less `LATE_FILES`, and deals the units into one group for each lane. Its `submit` adds an `archiveDeflate:i` for each group with [`fanOut`](#fan-outmjs). The tree is therefore deflated while the search index is still being built. +2. **`archiveLate`** runs once `searchIndex` has written `search-index.js`, the one file in `LATE_FILES`. `planLateFiles` deals its pieces in the same way, as `archiveLateDeflate:i`. +3. **`archiveDeflate:i`** and **`archiveLateDeflate:i`** run `deflateGroup` on a lane. Each unit is read, deflated and inflated again, and the result is compared with the bytes read. A failure comes back as `{ error }`, so that it fails the build without stopping it. +4. **`helpArchive`** joins the units into entries (`finishHelpArchive`), writes the zip, reads it back and checks it against what it assembled and against the list of files. + +`helpArchive` returns the zip's bytes, which `addinProject` packs into the add-in's project file, and its path, which `runBuild` checks the offline tree against once the Gantt chart is injected (`recheckHelpArchive`). The tasks write nothing for a source root other than `docs`, a `--dest` other than `docs/_site`, and under `--serve`, `--dry-run` or `--no-help-archive`: `archivePlan` then returns a plan with no groups. ### `bookPayload` (main) ```js -bookPayload.expected = ["flushJoin", "renderJoin", "dot", "resolveBookChapters"] +bookPayload.expected = ["flushJoin", "renderJoin", "dot", "resolveBookChapters", "buildInfo"] bookPayload.execute() → SharedArrayBuffer ``` @@ -602,6 +722,15 @@ The link and integrity check over rendered pages, which the standalone [`scripts | `deriveTreeRels` | `(which, …) → string[]` | Every relative path the build believes it emitted into a given tree: pages, redirect stubs, auxiliaries, static files, theme assets, generated DOT SVGs, minus offline exclusions. The check's oracle uses it instead of the filesystem; `auditIndex` verifies it. | | `posix` | `(p) → string` | Backslash-to-slash path normalisation. | +### `fnmatch.mjs` + +The path patterns of `offline_exclude` and of the help archive's skip list: `*` stays within a folder, `**` crosses folders, `?` is one character that is not `/`. The module imports nothing, so `check-tree.mjs` can use it on the way to the first render. + +| Symbol | Signature | Description | +|---|---|---| +| `matchesAny` | `(rel, patterns) → boolean` | Returns `true` when a path matches one of the patterns. The list is compiled the first time it is seen, and again when its length has changed: a pattern with no wildcard goes into a `Set`, the others become regular expressions. `dispatch` tests every path of both trees against a list that holds each picture's SVG when the offline tree shows PNGs. | +| `fnmatchPathname` | `(pattern, path) → boolean` | The match of one pattern against one path. | + ### `link-check.mjs` The pure core shared by the build's check and the standalone [`scripts/check_links.mjs`](Tools-Site-Checks#check-links). It does no filesystem traversal and has no CLI: it takes HTML and an oracle and returns findings. **The two front ends read the tree differently, and a checker that silently checks less reports a clean pass, so run [`check_links_diff.mjs`](Tools-Site-Checks#check-links-diff) whenever this file, `check.mjs` or `check_links.mjs` changes.** @@ -640,7 +769,20 @@ The pure core shared by the build's check and the standalone [`scripts/check_lin | Symbol | Signature | Description | |---|---|---| -| `discover` | `(srcRoot, ignore) → Promise<{ pages, staticFiles }>` | Traverses the source tree, classifies pages vs static files, returns the two sorted arrays. | +| `listSources` | `(srcRoot, ignore) → Promise<{ pageRels, otherRels }>` | The files under the source root that `ignore` does not leave out, sorted: the `.md` and `.html` files, and the others. | +| `cutPieces` | `(listing, count, extra?) → { pieces, statics, pairs }` | The listing in `count` pieces for `readPiece`, with the `bundle_extra` files (`extra`) among the static files, and what `assemble` needs. | +| `assemble` | `(srcRoot, plan, results) → { pages, staticFiles, pictureSizes }` | The inventory, from `cutPieces`' plan and each piece's result: the two sorted arrays and the picture pairs' sizes. | +| `discover` | `(srcRoot, ignore) → Promise<{ pages, staticFiles }>` | The same steps in one call and one piece, without `bundle_extra`, for the tools that have no lanes. | + +### `discover-read.mjs` + +| Symbol | Signature | Description | +|---|---|---| +| `readPiece` | `(srcRoot, { pageRels, statSrcs, pairs }) → { pages, plain, warnings, sizes, pairSizes }` | Reads one piece, synchronously: the pages, the files with no frontmatter, the warnings to print, each static file's size and each pair's `[lightW, lightH, darkW, darkH]` or `null`. | +| `packPageText` | `(pages) → { sab, spans }` | The pages' `rawContent` as UTF-8 in one `SharedArrayBuffer`; `spans` holds each page's offset and length in bytes, two numbers a page. Runs on the lane that read the pages. | +| `pageText` | `(sab, offset, length) → string` | One page's text, read back. Runs on the lane that renders the page. | +| `PAGE_EXT` | `RegExp` | The extensions of a file that may be a page: `.md` and `.html`. | +| `toPosix` | `(path) → string` | A path with forward slashes. | ### `publish-policy.mjs` @@ -825,9 +967,10 @@ For **renderer rules**, order inverts. Both image plugins capture the current `m | `PLACEHOLDER_RE` | `RegExp` | Matches a `{{tbdocs:}}` or `{{tbdocs::}}` placeholder and captures the name and the argument. Used by the `substitute` helper that `countPlugin` calls, and by `findCountRefs` to locate placeholders in a page's raw markdown. | | `deriveCounts` | `(state, extra) → Record` | Derives every named count from build state: page, static-file, reference-page and documentation-page totals, folder-style reference indexes and how many of them have a permalink ending in a slash, packages (total, default, built-in), attribute anchors, enumerations, and `extra.redirectStubs`. Called by `markdownInit` to build `state.site.counts`, whose keys are the names a page may use. | | `countPlugin` | `(md, ctx) → void` | A markdown-it plugin, the last one `createMarkdownIt` applies. Substitutes each `{{tbdocs:}}` placeholder in prose and image alt text with the value `ctx.counts` holds under that name, and leaves an unknown name as written; code spans and fences are untouched. Its core rule is pushed last, so it runs after `replacements`. Does nothing when `ctx.counts` is absent. | -| `findCountRefs` | `(rawContent, md) → { name, arg, line }[]` | Finds every `{{tbdocs:...}}` reference outside code in a page's raw source, masking code with `maskCode` from `lib/markdown.mjs` and the site's markdown-it instance `md`, as the pre-render rewrites do. `line` is 1-based in `rawContent`, counted with the code put back (a masked fence is one line). Called by `validateCountNames` for each page. | -| `checkPlaceholders` | `(pages, counts, downloads, md) → { problems, sizes }` | `validateCountNames` for all placeholders: also refuses a `size` whose path the build does not publish or cannot size before render (`downloads.refused`, which names the help add-in's project, stylesheets and SVGs), a `size` without a path, an argument on a name that takes none, and either download placeholder when `downloads` is `null`. `sizes` holds the bytes of each file named, which is all the workers are sent. | -| `deriveDownloads` | `(state, { tests, addinDest }) → { files, refused, tests }` | The sizes known before render: the static files discover found (the `bundle_extra` files among them) and the packed package test projects (`tests`, from `packTests`), and the paths that are published but cannot be sized, each with its reason. | +| `findCountRefs` | `(rawContent, md) → { name, arg, line }[]` | Finds every `{{tbdocs:...}}` reference outside code in a page's raw source. Code is what `maskCode` from `lib/markdown.mjs` hides with the site's markdown-it instance `md`, as the pre-render rewrites do: every line of a fence (`blockRegions`), and the code spans of any other line (`splitCodeSpans`). Only the lines that hold a placeholder are cut into spans, since a placeholder cannot span lines. `line` is 1-based in `rawContent`. Called by `checkPlaceholders` for each page. | +| `checkPlaceholders` | `(pages, counts, downloads, md) → { problems, sizes, packedArgs, late }` | `validateCountNames` for all placeholders: also refuses a `size` whose path the build does not publish or cannot size before the page renders (`downloads.refused`, which names the help add-in's project, stylesheets and SVGs), a `size` without a path, an argument on a name that takes none, and either download placeholder when `downloads` is `null`. `sizes` holds the bytes of each file named, which is all the workers are sent. A `size` that names a file in `downloads.packed` is accepted without a size: `packedArgs` maps its argument to the file's path, and `late` names each page that states such a size or lists the test projects. | +| `deriveDownloads` | `(state, { packed, addinDest }) → { files, refused, packed }` | What is known before render: the sizes of the static files discover found (the `bundle_extra` files among them), the paths that are published but cannot be sized, each with its reason, and the paths of the files `packTests` packs (`packed`), which have no size yet. | +| `packedDownloads` | `({ sizes, packedArgs, dest, packed }) → { sizes, tests }` | The downloads as the late pages need them, once `packTests` has packed: `sizes` with each packed file a page names added, and `tests`, one row for each package test project. Throws when a file a page names was not packed. Called by `downloadSizes`. | | `expandDownloadPlaceholders` | `(src, downloads, permalink) → string` | Expands `{{tbdocs:size:}}` as `43 KB` or `1.2 MB`, and `{{tbdocs:packageTestRows}}` as one table row for each package test project, with links relative to `permalink`. `applyPreRenderRewrites` calls it on the source with code masked, using the `downloads` the page's `md` carries. | | `formatSize` | `(bytes) → string` | Whole KB (1024-based, at least 1) below a mebibyte, MB with one decimal from there. | | `validateCountNames` | `(pages, counts, md) → string[]` | Checks every page's count references against the known `counts` names via `findCountRefs`. Returns one message per unknown reference, giving the file and line (the reference's line in `rawContent`, moved down by the page's `contentLine`), the nearest known name when one is within an edit distance of three, and every known name. Empty when every reference is known. `markdownInit` throws when the result is non-empty. | @@ -911,7 +1054,13 @@ For **renderer rules**, order inverts. Both image plugins capture the current `m | Symbol | Signature | Description | |---|---|---| -| `writeSearchDataFromChunks` | `(searchChunks, destRoot, symbols) → Promise<{ entries, json }>` | Per-chunk consolidator. Flattens, joins `symbols` onto the matching entries by URL (`joinSymbolsToEntries`), renumbers global `i`, writes `assets/js/search-data.json`. Used by the `searchData` task. | +| `consolidateSearchEntries` | `(searchChunks, symbols, keyChunks?) → { entries, places }` | Per-chunk consolidator. Flattens, checks the index terms, settles the labels (`settleLabels`), renumbers global `i` and joins `symbols` onto the matching entries by URL (`joinSymbolsToEntries`). `places[n]` is entry n's `[chunk, place in the chunk]`. Used by the `searchEntries` task. | +| `settleLabels` | `(entries, keys?) → entries` | Drops a term entry that a main index term answers, and makes each label no heading, title, term entry or mark answers a secondary index term of its entry. `keys` are the entries' `entryKeys`; without them it works them out. | +| `entryKeys` / `labelKey` | `(entry, key?) → object` / `(name) → string` | What `settleLabels` compares of one entry, and a name as it compares names. The render workers call `entryKeys`. | +| `packSearchEntries` / `readSearchEntries` | `(entries) → SharedArrayBuffer` / `(sab, from?, to?) → object[]` | A chunk's entries, each as the head and the tail of its text in `search-data.json`, in one buffer; and a run of them read back, each `{ doc, title, content, url, relUrl }`. | +| `searchDataBytes` | `(entries, places, packed) → Buffer` | `search-data.json`'s bytes: each entry's number and late fields, around the head and tail copied from its chunk's buffer. | +| `searchDocs` | `(entries) → object` | The entries as `search-data.json` holds them, parsed, without a parse of the file. | +| `writeSearchData` | `({ entries, places }, packed, destRoot) → Promise<{ entries, json, docs }>` | Writes `assets/js/search-data.json`. Used by the `searchData` task. | | `joinSymbolsToEntries` | `(entries, symbols) → entries` | Attaches `names` / `qualified` / `primary` (the names that are types or language elements) to each entry whose `relUrl` matches a symbol's `url`, after normalising both (strip a trailing `/index` or `/index.html`, then a trailing slash; the `#fragment`, if any, is compared as-is). Mutates and returns `entries`. | | `deriveSearchEntries` | `(pages, site) → object[]` | Pure compute. One entry per heading-bounded section of each titled page. Each entry: `{ i, doc, title, content, url, relUrl, sourcePage }`. Called by render workers, which drop `sourcePage` and the chunk-local `i` before posting back. | | `renderEntryString` | `(entry) → string` | Per-entry JSON shape matching the upstream template output byte for byte. | @@ -923,19 +1072,31 @@ The one definition of the site search's lunr index: its fields and boosts (`FIEL | Symbol | Signature | Description | |---|---|---| -| `writeSearchIndex` | `(destRoot, { offline }) → Promise<{ entries, workers, bytes }>` | Reads `search-data.json`, writes `search-index.json` and, when `offline`, the offline tree's `search-index.js`. Used by the `searchIndex` task. | -| `buildIndexJson` | `(docs, { workers, lunrPath }) → Promise` | The index of the parsed search data as lunr's JSON, built on `workers` threads (`search-index-worker.mjs`); one builds it on the calling thread with `lunr()` itself. Every worker count gives the same bytes. | +| `writeSearchIndex` | `(destRoot, indexJson, docs, { offline }) → Promise<{ entries, bytes }>` | Writes `search-index.json` and, when `offline`, the offline tree's `search-index.js`, from the index's JSON and the entries. Used by the `searchIndex` task. | +| `indexSliceCount` | `(entries, lanes) → number` | The slices the build cuts an index into: two for each lane, at most one for every 500 entries. | +| `planIndexSlices` | `(lunr, docs, count) → { slice, docs, twins }[]` | The entries cut into `count` runs of about equal text, each with the stem twins of every entry: what one `addSlice` takes. `buildIndexJson` uses it. | +| `cutIndexSlices` | `(docs[], count) → [from, to][]` | Where those runs start and end. | +| `planIndexSegments` | `(entries, places, count) → { slice, first, segments, dropped, late }[]` | The build's slices, cut as `planIndexSlices` cuts them. Each says where its entries are among the render chunks' packed entries, and what was decided about them after the render. Used by the `indexSlices` task. | +| `sliceDocs` | `(plan, read) → docs` | One slice's entries by number, as `addSlice` takes them, from its plan and the chunks' packed entries. | +| `stemTwins` | `(lunr, docs) → Set` | The qualified names that the stemmer merges with another name's. | +| `addSlice` | `(lunr, docs, twins) → { state, added }` | One slice added to a `lunr.Builder` of its own. `state` holds the builder for `sliceVectors`; `added` is the slice's terms, postings and field lengths, for `mergeSlices`. | +| `mergeSlices` | `(added[]) → { merged, totals }` | The slices' postings merged, each term numbered as one build numbers it, and the totals the vectors need: each slice's term numbers, each term's idf, the document count and each field's average length. | +| `sliceVectors` | `(lunr, state, totals) → string` | lunr's `createFieldVectors` over one slice's builder, as `toJSON` writes the vectors. | +| `invertedIndexJson` | `(merged) → string` | lunr's `toJSON` of the inverted index, from the merged postings. | +| `assembleIndexJson` | `(lunr, vectors[], invertedIndex) → string` | The index's JSON, from every slice's vectors and the inverted index. | +| `packTotals` / `unpackTotals` | `(totals) → SharedArrayBuffer` / `(sab, slice) → totals` | `mergeSlices`' totals for the lanes, which read them in place. | +| `buildIndexJson` | `(docs, { slices, lunrPath }) → string` | The index of the parsed search data as lunr's JSON, every step on the calling thread. Every slice count gives the same bytes. The tests use it. | | `buildIndex` | `(lunr, docs) → lunr.Index` | The index built by `lunr()` on the calling thread: what the split build must equal. `eval/site_search.mjs` uses it for a site with no `search-index.json`. | | `loadSearchLunr` | `(lunrPath?) → lunr` | The vendored lunr with the site's patches installed, once per copy. | | `searchIndexFile` | `(indexJson, docs) → string` | `search-index.json`'s text: `{"docs": ..., "index": ...}`, the entries minified and the index as given. | | `offlineSearchIndexJs` | `(fileText) → string` | Wraps `search-index.json` as `window.SEARCH_INDEX = JSON.parse('…')` for the offline tree. | -| `defaultIndexWorkers` | `(entries) → number` | The threads the build gives an index: half the machine, at most eight, one per 500 entries. | ### `symbols.mjs` | Symbol | Signature | Description | |---|---|---| -| `symbolPages` | `(pages) → object[]` | The pages under `/tB/`, each as `{ src, url, title, parent, symbols, excludeFromDocs, headings }`, `headings` read from `renderedContent`. | +| `symbolPages` | `(pages) → object[]` | The pages under `/tB/`, each as `{ src, url, title, parent, symbols, excludeFromDocs, headings }`. `headings` is the page's own when its render worker set it, and is read from `renderedContent` otherwise. | +| `isSymbolPage` | `(page) → boolean` | Whether `symbolPages` reads a page: one under `/tB/`, or a summary page. | | `headingsOf` | `(html) → { level, id, text }[]` | Every heading of a rendered page, in order, with the id the render gave it. A scan for `` tags from the offline tree only. A font preload is a CORS-mode fetch; under `file://` there is no origin to match, so Chrome fails it with `ERR_FAILED` while the `@font-face` fetch succeeds. The preload gains nothing offline and adds two red lines to the console. | | `posixDirname` | `(rel) → string` | POSIX directory component of a relative path. | | `fileDirSegsFromRel` | `(rel) → string[]` | Splits a destination path into directory segments. | -| `fnmatchPathname` | `(pattern, path) → boolean` | Glob-style pathname match. | | `computeRelative`, `resolveRaw`, `computeRelUrl`, `buildSegs`, `decode`, `getPageCache`, `stripSeo`, `rewriteHtml`, `rewriteCss`, `injectSearchSetup` | various | Internal helpers; see [`offline-rewrite.mjs`](https://github.com/twinbasic/documentation/blob/main/builder/offline-rewrite.mjs) for the per-symbol descriptions. | ### `pdf.mjs` @@ -1021,6 +1181,14 @@ Pure-compute rewrite helpers, split from `offline.mjs` so `cpu-worker.mjs` can i | `SharedState` | class | `pages[]`, `staticFiles[]`, `site`, `pageByDest`, `searchChunks`. Created by the `Scheduler` constructor. | | `Scheduler` | class | Main-thread side of the pull scheduler. Constructor: `{ pool, tasks, views, idMapping, ganttSections }`. Methods: `start(ctx)` (returns the results promise), `addDynamicTasks(count)`, `summary()`. The orchestrator sets the event hooks (`_onWorkerDone`, `_onWorkerError`, `_onPerWorkerTiming`, `_onMainTaskReady`). | +### `fan-out.mjs` + +| Symbol | Signature | Description | +|---|---|---| +| `fanOut` | `(scheduler, { from, prefix, handler, payloads, after?, pinTo?, joins?, ganttSection?, priority?, describe? }) → string[]` | Adds one lane task `:` for each payload, from the `submit` of the main-thread task `from`. Every piece waits for `from`, and for each task in `after` that is not done yet. `pinTo` names an earlier fan-out of the same `submit`: piece `i` then runs on the lane that ran its piece `i`. Each static task in `joins` waits for every piece, and receives each one's output under its name; it must list `from` in its `expected`. The payloads are packed into one `SharedArrayBuffer`, broadcast as the task data `fan::`, which a handler reads with `fanOutPayload(taskIdx)` in `cpu-worker.mjs`. Returns the pieces' names. | + +A piece cannot become READY while its edges are being written, because `from` is still CLAIMED until its `submit` returns. For the same reason a task in `after` must be a main-thread task or a piece made in the same `submit`: a lane task could finish between the check of its status and the writing of its edge. + ### `worker-pool.mjs` | Symbol | Signature | Description | @@ -1031,18 +1199,24 @@ Pure-compute rewrite helpers, split from `offline.mjs` so `cpu-worker.mjs` can i Worker harness; no exports. Runs the pull loop in module scope. +The module's static imports are the first stage of a lane's boot: the scheduler, `sab-broadcast.mjs` and `discover-read.mjs`. Every other module a handler needs is loaded by `loadRest`, the second stage, which the pull loop awaits before a lane's first task that is not a `discoverRead`. Each stage posts a `coldBoot` message with its times, for the Gantt chart. + The handler table is built from the imported `HANDLERS` constant: | Handler | Source | Description | |---|---|---| +| `discoverRead` | `discover-read.mjs` | `readPiece` over the piece in its `fanOutPayload`, then `packPageText` over its pages. Runs after the first boot stage alone. | | `warmInit` | inline | Awaits `initHighlighter()`. | | `renderEnvInit` | inline | Unpacks shared SAB, awaits highlighter, reconstructs link tables, builds markdown-it, stores `_renderEnv`. | | `flush` | inline | Drains the next `_pendingFlush` batch to disk. | | `scssLight` / `scssDark` | `scss.mjs` | Light/dark palette compile. | | `dot` | `dot.mjs` | `regenerateDot` over `srcRoot`. | | `buildInfo` | `build-info.mjs` | `captureBuildInfo`. | +| `packTests` | `package-tests.mjs` | `packAllPackageTests` over the `"packageTests"` task data; imports the module when it runs. | | `render` | inline | Five-stage chunk render: `renderPhase` → `computeChunkSeo` → `templatePhase` → offline → `deriveSearchEntries`. | -| `helpArchive` | `help-archive-step.mjs` | `helpArchiveStep` over the offline tree; reads `skipOffline` from the shared payload through `sharedData()`. | +| `indexAdd` | `search-index.mjs` | `addSlice` over its slice's entries, which `sliceDocs` reads from the `"indexEntries"` task data as the plan in its `fanOutPayload` says; keeps the builder in `_indexSlices` for `indexVectors`. | +| `indexVectors` | `search-index.mjs` | `sliceVectors` over the builder `indexAdd` kept on this lane, with the `"indexTotals"` task data. | +| `archiveDeflate` | `help-archive-step.mjs` | `deflateGroup` over the units in its `fanOutPayload`. Runs `archiveDeflate:i` and `archiveLateDeflate:i`. | | `writePdf` | `pdf.mjs` | Waits for the `"book"` task data, unpacks it with `unpackBookPayload`, writes the PDF tree and keeps the book for `checkBook`. | | `checkBook` | inline | `checkChunk` over the book `writePdf` kept on this lane; `null` without `--check`. | diff --git a/docs/Documentation/Tools-Build.md b/docs/Documentation/Tools-Build.md index 4b35e7689..9f142c930 100644 --- a/docs/Documentation/Tools-Build.md +++ b/docs/Documentation/Tools-Build.md @@ -116,7 +116,9 @@ The zip is too large to commit; `add-in/Resources/HELP/` is in `.gitignore`. Only a build of the documentation tree into `docs/_site-offline` writes the archive. Builds of another source tree or `--dest`, `--serve`, `--dry-run` and builds without an offline tree skip it, and so does `--no-help-archive`. CI must not pass `--no-help-archive`, or the project file it publishes would hold no archive; `check_ci_workflows.mjs` fails when one does. -A file the build cannot write, or an archive that does not match the tree, fails the build with exit code 1. The build ends by checking the offline tree on disk against the archive again, now that the chart is in: the same files must be listed, less the ones the archive leaves out, and only `BuildInfo.html` and `assets/images/gantt.svg` may differ in content. +A file the build cannot write, or an archive that does not match the tree, fails the build with exit code 1. The build ends by checking the offline tree on disk against the archive again, now that the chart is in: the same files must be listed, less the ones the archive leaves out, and only `BuildInfo.html` and `assets/images/gantt.svg` may differ in size or CRC-32 from the archive's entry. + +The build's lanes deflate the files, as tasks of its graph: the [Pipeline Stages](Pipeline-Stages#helparchive-worker) page lists them. The offline tree is deflated while the search index is built, and the index's own file, `assets/js/search-index.js`, once it is written. The reader on the twinBASIC side does no inflating of its own, so the zip format is fixed: @@ -125,8 +127,9 @@ The reader on the twinBASIC side does no inflating of its own, so the zip format - No extra fields, comments or data descriptors: the CRC-32 and both sizes are in the local header and in the central directory. - No zip64, so a tree of more than 65,535 files, or an archive of 4 GB, is refused. - Files that are compressed already (`.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, `.ico`, `.woff2`, `.woff`, `.mp4`, `.zip`, `.pdf`) are stored. Every other file is deflated at level 9, and stored instead when the deflated data is not smaller than the file. +- A deflated file larger than 1 MB is deflated in pieces of 1 MB, which are joined into one deflate stream. Every piece but the last ends with a sync flush, and each piece is primed with the 32 KB of the file before it, so the stream is about the size of one made in a single pass. The bytes depend only on the piece size, not on how many pieces were deflated at a time. -The build reads the file back, checks every entry against its source file, and names any that differ. The writer is `lib/help-archive.mjs`. +Each file, or piece, is inflated again after it is deflated and compared with the bytes read. The build then reads the zip back, compares it with what it assembled, and checks every entry's headers against the list of files; it names any that differ. The writer is `lib/help-archive.mjs`. ## build_fonts.py {: #build-fonts } diff --git a/docs/Documentation/Tools-Toolchain-Tests.md b/docs/Documentation/Tools-Toolchain-Tests.md index 296a8d686..ec7245962 100644 --- a/docs/Documentation/Tools-Toolchain-Tests.md +++ b/docs/Documentation/Tools-Toolchain-Tests.md @@ -83,7 +83,7 @@ The gate also covers `lib/markdown.mjs` and `lib/frontmatter.mjs`, the modules t - the rewrite chain leaves alone a fence that only the site's parser finds, and an admonition written inside one; - the build's check of `{{tbdocs:}}` count names skips names in code and gives an unknown one's line in its file; -- the `{{tbdocs:size:}}` and `{{tbdocs:packageTestRows}}` placeholders are expanded outside code, in a raw HTML block and on a table line, and refused, at their line, for a path the build does not publish or cannot size; +- the `{{tbdocs:size:}}` and `{{tbdocs:packageTestRows}}` placeholders are expanded outside code, in a raw HTML block and on a table line, and refused, at their line, for a path the build does not publish or cannot size; a file the build packs while the pages render is accepted without a size, and its page is named as one that renders once the size is known; - `discover` names the page and line of `title: Input #`, and says nothing about a quoted value; - [`convert_em_dash_separators.mjs`](Tools-Build#convert-em-dash-separators), which rewrites page source by hand, converts prose and nothing else. @@ -170,7 +170,7 @@ Exit codes: **0** Biome found nothing (with `--staged`, also when no script is s node --test test/search.test.mjs -Unit tests for the site search, run by Node's own test runner. The first group builds search entries from small synthetic pages through `builder/search.mjs` and checks what each entry holds: the split at headings, the folding of generic sections such as See Also into the member they belong to, index marks, the join with the symbol index, and identical output from one build to the next. The build's own check sees only which URLs the index covers. +Unit tests for the site search, run by Node's own test runner. The first group builds search entries from small synthetic pages through `builder/search.mjs` and checks what each entry holds: the split at headings, the folding of generic sections such as See Also into the member they belong to, index marks, the join with the symbol index, and identical output from one build to the next. The build's own check sees only which URLs the index covers. A render worker packs its entries' text once, for `search-data.json` and for the workers that build the search index, so the group also checks that the file assembled from the packed text is each entry as `renderEntryString` writes it, that a worker reads back the fields it packed, and that the labels settle the same with the keys a worker worked out. The rest guard that the search page agrees with the build. The build writes the index (`builder/search-index.mjs`), and the page under `builder/vendor/just-the-docs/` and its offline copy in `builder/offline.mjs` only load and query it. So the tests check: @@ -187,7 +187,7 @@ Exit codes: **0** every test passed, **1** a test failed. node --test test/search-index.test.mjs -Verifies the search index the build writes. The build makes the index on several threads, merges what they make and writes it as lunr's own JSON (`builder/search-index.mjs`). lunr has no way to merge two indexes, so this test builds a fixture on one thread with lunr itself and on two, three, seven and more threads than entries, and requires the same bytes each time. The fixture holds what the merge has to get right: words that look like numbers, words only a later thread meets, empty fields, HTML entities and hand-marked index terms. It also checks that an index loaded from the file answers as lunr's does, that a thread that fails fails the build, that `search-index.json` holds the search entries and their index and nothing else, and that the offline tree's `search-index.js` holds the same. +Verifies the search index the build writes. The build makes the index in slices on its lanes, merges what they make and writes it as lunr's own JSON (`builder/search-index.mjs`). lunr has no way to merge two indexes, so this test builds a fixture with lunr itself and in one, two, three, seven and more slices than entries, and requires the same bytes each time. It also runs the steps as the build runs them: each slice's entries read from the chunks the render workers packed, some of whose entries were dropped since, and the totals read from the `SharedArrayBuffer` the lanes are sent. The fixture holds what the merge has to get right: words that look like numbers, words only a later slice meets, empty fields, HTML entities and hand-marked index terms. It also checks that the slices hold every entry once and in order, that an index loaded from the file answers as lunr's does, that `search-index.json` holds the search entries and their index and nothing else, and that the offline tree's `search-index.js` holds the same. No browser, no built tree, about a second. @@ -362,7 +362,7 @@ The others pack fixture folders, each a git repository of its own: - a CRLF checkout packs to the same bytes as an LF one, and two packs are identical; - the file is written into exactly the trees it is given. -A second group writes small archives with `lib/help-archive.mjs` and checks them against their tree, as the build does at its end. A tree as it was archived has no differences, only the files named may differ in content, and any other changed, added or removed file is named. +A second group writes small archives with `lib/help-archive.mjs` and checks them against their tree, as the build does at its end. A tree as it was archived has no differences, only the files named may differ in content, and any other changed, added or removed file is named. A file larger than the archive's piece size is deflated in pieces: its entry inflates in one pass to the file, with the file's CRC-32, and the archive's bytes are the same however the pieces are grouped and ordered. Needs git; no browser, no built tree, no twinBASIC, about 1 s. @@ -386,6 +386,23 @@ Unit tests for [`ide_js.mjs`](Tools-Defects#ide-js) and its library, `scripts/id Exit codes: **0** every test passed, **1** a test failed. +## discover.test.mjs +{: #discover-test } + + node --test test/discover.test.mjs + +Unit tests for `builder/discover.mjs` and `builder/discover-read.mjs`, which make the source tree's inventory: the pages, the static files and the sizes of the pictures that come in two themes. The build reads the tree in pieces on its lanes and compares its output with the last commit's, on the site's own tree and its own piece count. A fault that those do not reach passes it. These tests read a small tree of their own, under the temp folder: + +- the inventory is the same in any number of pieces, and from `discover()`, which the other tools call; +- the pages are sorted by file name and then by path, the static files by path, with the `bundle_extra` files after them; +- a `.md` file with no frontmatter is a static file, and an excluded file is in neither list; +- a picture pair's sizes are read, including a pair whose dark picture is a `bundle_extra` file, and a file that is not a PNG gives no entry; +- an unquoted frontmatter value that ends in `#` is reported by the piece that read it, and frontmatter that does not parse names its file. + +No build, no lanes, well under a second. + +Exit codes: **0** every test passed, **1** a test failed. + ## check_page_baseline.mjs {: #check-page-baseline } diff --git a/docs/Documentation/Tools.md b/docs/Documentation/Tools.md index e2effc204..af0ebc7af 100644 --- a/docs/Documentation/Tools.md +++ b/docs/Documentation/Tools.md @@ -115,7 +115,7 @@ A local pass of [`check_a11y.mjs`](Tools-Site-Checks#check-a11y) does not predic test.bat -The tests the toolchain has to pass. Thirty-two steps, each stopping the run if it fails: +The tests the toolchain has to pass. Thirty-three steps, each stopping the run if it fails: 1. [`scripts/check_publish_policy.mjs`](Tools-Toolchain-Tests#check-publish-policy) --- verifies the publish allowlist still refuses the types it should. Needs neither a browser nor a built tree. 2. [`scripts/check_gate_lists.mjs`](Tools-Toolchain-Tests#check-gate-lists) --- verifies the two gate lists on this page still match the wrappers that run them. @@ -135,20 +135,21 @@ The tests the toolchain has to pass. Thirty-two steps, each stopping the run if 16. [`test/addin-project.test.mjs`](Tools-Toolchain-Tests#addin-project-test) --- unit tests for how the build packs the help add-in's project file: exactly the files git tracks in `add-in/`, never `Resources/HELP/`, the same bytes from any checkout. 17. [`test/indexer.test.mjs`](Tools-Toolchain-Tests#indexer-test) --- unit tests for the package indexer: the VB6 preprocessing, the files of a package, the `api.json` built from them (sorted by code unit, nested types by their path, values and fields in declaration order, the same bytes from the same files) and the differ that compares two of them. 18. [`test/ide-js.test.mjs`](Tools-Toolchain-Tests#ide-js-test) --- unit tests for [`ide_js.mjs`](Tools-Defects#ide-js), which reads, names and patches the IDE's minified `main.js`: the byte-exact round trip, how a name carries to another build, and a fix patched in as the smallest edit, on a few lines written in the test. -19. [`scripts/check_regex_safety.mjs`](Tools-Toolchain-Tests#check-regex-safety) --- refuses a regex that can backtrack exponentially, written as a literal or built from constants. -20. [`scripts/check_code_regions.mjs`](Tools-Toolchain-Tests#check-code-regions) --- verifies no pre-render rewrite alters the contents of a code fence or code span, that the rewrites over rendered HTML leave a raw `
` or `` alone, and that `lib/markdown.mjs` and `lib/frontmatter.mjs` pass their probes.
-21. [`scripts/check_page_baseline.mjs`](Tools-Toolchain-Tests#check-page-baseline) --- verifies the page-count drift guard still refuses a fall.
-22. [`scripts/check_book_coverage.mjs`](Tools-Toolchain-Tests#check-book-coverage) --- verifies the build still warns about a page `docs/_book.yml` does not mention.
-23. [`scripts/check_package_tests.mjs`](Tools-Toolchain-Tests#check-package-tests) --- verifies every NOTE and WARNING of a contributed package's section names the test cases behind it, and that each package test project is in order.
-24. [`scripts/check_callout_evidence.mjs`](Tools-Toolchain-Tests#check-callout-evidence) --- verifies every callout labelled with a twinBASIC build names what checks it, and that every marker names a reproducer, lane, sample, error data file or LLVM probe mode that exists.
-25. [`scripts/check_errors.mjs`](Tools-Toolchain-Tests#check-errors) --- verifies every page's Common Errors section is what the run-time error data under `errors/` writes, and that the data is in order.
-26. [`scripts/check_symbol_index.mjs`](Tools-Toolchain-Tests#check-symbol-index) --- verifies the symbol index still places each kind of symbol, and its drift guard still refuses a lost URL.
-27. [`scripts/check_twin_parsers.mjs`](Tools-Toolchain-Tests#check-twin-parsers) --- verifies the scanners of twinBASIC source and of the attribute reference still read the shapes each once misread.
-28. [`scripts/check_attribute_sweep.mjs`](Tools-Toolchain-Tests#check-attribute-sweep) --- verifies the logic of the attribute sweep: its site skeletons, how it reads a probe's diagnostics, how it batches probes, and how it compares the answers with `Attributes.md`.
-29. [`scripts/check_cli.mjs`](Tools-Toolchain-Tests#check-cli) --- verifies `lib/cli.mjs`, the command-line parser, and each tool's recorded command-line errors.
-30. [`scripts/check_pdf_shims_equiv.mjs`](Tools-Toolchain-Tests#check-pdf-shims-equiv) --- verifies the book's pdf-lib shims write what stock pdf-lib writes, patch the members of pdf-lib it lists, have each of them in their shim's table of targets, and run.
-31. [`scripts/check_impexp_parity.mjs`](Tools-Toolchain-Tests#check-impexp-parity) --- verifies the editions of the impexp tool pass the same built-in tests, and exit, print and write the same for one sequence of commands. Without Python it reports itself skipped and passes, except in CI. It compares the twinBASIC edition too, when `IMPEXP_EXE` names its built exe.
-32. [`scripts/check_axe_patch_equiv.mjs`](Tools-Toolchain-Tests#check-axe-patch-equiv) --- verifies the vendored axe source patch still produces identical colour values.
+19. [`test/discover.test.mjs`](Tools-Toolchain-Tests#discover-test) --- unit tests for the source tree's inventory, which the build reads in pieces on its lanes: the same in any number of pieces, on a small tree of the tests' own.
+20. [`scripts/check_regex_safety.mjs`](Tools-Toolchain-Tests#check-regex-safety) --- refuses a regex that can backtrack exponentially, written as a literal or built from constants.
+21. [`scripts/check_code_regions.mjs`](Tools-Toolchain-Tests#check-code-regions) --- verifies no pre-render rewrite alters the contents of a code fence or code span, that the rewrites over rendered HTML leave a raw `
` or `` alone, and that `lib/markdown.mjs` and `lib/frontmatter.mjs` pass their probes.
+22. [`scripts/check_page_baseline.mjs`](Tools-Toolchain-Tests#check-page-baseline) --- verifies the page-count drift guard still refuses a fall.
+23. [`scripts/check_book_coverage.mjs`](Tools-Toolchain-Tests#check-book-coverage) --- verifies the build still warns about a page `docs/_book.yml` does not mention.
+24. [`scripts/check_package_tests.mjs`](Tools-Toolchain-Tests#check-package-tests) --- verifies every NOTE and WARNING of a contributed package's section names the test cases behind it, and that each package test project is in order.
+25. [`scripts/check_callout_evidence.mjs`](Tools-Toolchain-Tests#check-callout-evidence) --- verifies every callout labelled with a twinBASIC build names what checks it, and that every marker names a reproducer, lane, sample, error data file or LLVM probe mode that exists.
+26. [`scripts/check_errors.mjs`](Tools-Toolchain-Tests#check-errors) --- verifies every page's Common Errors section is what the run-time error data under `errors/` writes, and that the data is in order.
+27. [`scripts/check_symbol_index.mjs`](Tools-Toolchain-Tests#check-symbol-index) --- verifies the symbol index still places each kind of symbol, and its drift guard still refuses a lost URL.
+28. [`scripts/check_twin_parsers.mjs`](Tools-Toolchain-Tests#check-twin-parsers) --- verifies the scanners of twinBASIC source and of the attribute reference still read the shapes each once misread.
+29. [`scripts/check_attribute_sweep.mjs`](Tools-Toolchain-Tests#check-attribute-sweep) --- verifies the logic of the attribute sweep: its site skeletons, how it reads a probe's diagnostics, how it batches probes, and how it compares the answers with `Attributes.md`.
+30. [`scripts/check_cli.mjs`](Tools-Toolchain-Tests#check-cli) --- verifies `lib/cli.mjs`, the command-line parser, and each tool's recorded command-line errors.
+31. [`scripts/check_pdf_shims_equiv.mjs`](Tools-Toolchain-Tests#check-pdf-shims-equiv) --- verifies the book's pdf-lib shims write what stock pdf-lib writes, patch the members of pdf-lib it lists, have each of them in their shim's table of targets, and run.
+32. [`scripts/check_impexp_parity.mjs`](Tools-Toolchain-Tests#check-impexp-parity) --- verifies the editions of the impexp tool pass the same built-in tests, and exit, print and write the same for one sequence of commands. Without Python it reports itself skipped and passes, except in CI. It compares the twinBASIC edition too, when `IMPEXP_EXE` names its built exe.
+33. [`scripts/check_axe_patch_equiv.mjs`](Tools-Toolchain-Tests#check-axe-patch-equiv) --- verifies the vendored axe source patch still produces identical colour values.
 
 POSIX:
 
@@ -170,6 +171,7 @@ POSIX:
       && node --test test/addin-project.test.mjs \
       && node --test test/indexer.test.mjs \
       && node --test test/ide-js.test.mjs \
+      && node --test test/discover.test.mjs \
       && node scripts/check_regex_safety.mjs \
       && node scripts/check_code_regions.mjs \
       && node scripts/check_page_baseline.mjs \
diff --git a/docs/assets/images/dot/scheduler-dag.dot b/docs/assets/images/dot/scheduler-dag.dot
index dc79a0cf6..3c05a9f8d 100644
--- a/docs/assets/images/dot/scheduler-dag.dot
+++ b/docs/assets/images/dot/scheduler-dag.dot
@@ -38,6 +38,8 @@ digraph scheduler {
     LD  [label=[M]>,           fillcolor="#fef7e0", color="#f9ab00"]
     WI  [label=[W] per-lane
on_demand, idle
>, fillcolor="#e8f0fe", color="#4285f4"] + DL [label=[M]>, fillcolor="#fef7e0", color="#f9ab00"] + DRi [label=[W]>, fillcolor="#e8f0fe", color="#4285f4"] DI [label=[M]>, fillcolor="#fef7e0", color="#f9ab00"] VA [label=[M]>, fillcolor="#fef7e0", color="#f9ab00"] NV [label=[M]>, fillcolor="#fef7e0", color="#f9ab00"] @@ -59,12 +61,25 @@ digraph scheduler { Fi [label=[W] pinned>, fillcolor="#e8f0fe", color="#4285f4"] FJ [label=[M]>, fillcolor="#fef7e0", color="#f9ab00"] WA [label=[M]>, fillcolor="#fef7e0", color="#f9ab00"] + PA [label=[M]>, fillcolor="#fef7e0", color="#f9ab00"] + SP [label=[M]>, fillcolor="#fef7e0", color="#f9ab00"] + SE [label=[M]>, fillcolor="#fef7e0", color="#f9ab00"] SDt [label=[M]>, fillcolor="#fef7e0", color="#f9ab00"] SYM [label=[M]>, fillcolor="#fef7e0", color="#f9ab00"] AP [label=[M]>, fillcolor="#fef7e0", color="#f9ab00"] WX [label=[M]>, fillcolor="#fef7e0", color="#f9ab00"] WO [label=[M]>, fillcolor="#fef7e0", color="#f9ab00"] - HA [label=[W]>, fillcolor="#e8f0fe", color="#4285f4"] + IS [label=[M]>, fillcolor="#fef7e0", color="#f9ab00"] + IAi [label=[W]>, fillcolor="#e8f0fe", color="#4285f4"] + IM [label=[M]>, fillcolor="#fef7e0", color="#f9ab00"] + IT [label=[M]>, fillcolor="#fef7e0", color="#f9ab00"] + IVi [label=[W] pinned>, fillcolor="#e8f0fe", color="#4285f4"] + SI [label=[M]>, fillcolor="#fef7e0", color="#f9ab00"] + APl [label=[M]>, fillcolor="#fef7e0", color="#f9ab00"] + ADi [label=[W]>, fillcolor="#e8f0fe", color="#4285f4"] + AL [label=[M]>, fillcolor="#fef7e0", color="#f9ab00"] + ALi [label=[W]>, fillcolor="#e8f0fe", color="#4285f4"] + HA [label=[M]>, fillcolor="#fef7e0", color="#f9ab00"] BP [label=[M]>, fillcolor="#fef7e0", color="#f9ab00"] WP [label=[W]>, fillcolor="#e8f0fe", color="#4285f4"] @@ -74,7 +89,15 @@ digraph scheduler { // ── Edges ─────────────────────────────────────────────────────────── - CF -> DI + CF -> DL + DL -> DRi + DRi -> DI + // The lane tasks that wait for the listing, so that the first lanes up + // are free for the pieces. + DL -> SL + DL -> SD + DL -> DT + DL -> WI CF -> HI HI -> LD DI -> NV @@ -117,12 +140,18 @@ digraph scheduler { HI -> WA VA -> WA - RJ -> SDt + DP -> PA + PA -> SP + RJ -> SP + + RJ -> SE + SP -> SE + + SE -> SDt PD -> SDt - RJ -> SYM + SP -> SYM PD -> SYM - SYM -> SDt SYM -> AP PD -> AP @@ -137,9 +166,25 @@ digraph scheduler { WX -> WO WA -> WO - FJ -> HA - SCSS -> HA - WO -> HA + SE -> IS + IS -> IAi + IAi -> IM + IAi -> IVi + IM -> IT + IM -> IVi + IT -> SI + IVi -> SI + SDt -> SI + + FJ -> APl + SCSS -> APl + WO -> APl + APl -> ADi + APl -> AL + SI -> AL + AL -> ALi + ADi -> HA + ALi -> HA FJ -> BP RJ -> BP @@ -158,5 +203,6 @@ digraph scheduler { CB -> CR SCSS -> CR SYM -> CR + SI -> CR AP -> CR } diff --git a/docs/assets/images/dot/scheduler-dag.svg b/docs/assets/images/dot/scheduler-dag.svg index 4925cb8be..4acbec31a 100644 --- a/docs/assets/images/dot/scheduler-dag.svg +++ b/docs/assets/images/dot/scheduler-dag.svg @@ -1,677 +1,938 @@ - - + + scheduler CF - -config -[M] + +config +[M] HI - -highlighterInit -[M] + +highlighterInit +[M] - + CF->HI - - + + - + -DI - -discover -[M] +DL + +discoverList +[M] - + -CF->DI - - +CF->DL + + BI - -buildInfo -[W] + +buildInfo +[W] - + DP - -dispatch -[M] + +dispatch +[M] - + BI->DP - - + + SL - -scssLight -[W] + +scssLight +[W] - + SCSS - -scss -[M] + +scss +[M] - + SL->SCSS - - + + SD - -scssDark -[W] + +scssDark +[W] - + SD->SCSS - - + + LD - -loadData -[M] + +loadData +[M] - + HI->LD - - + + - + WA - -writeAssets -[M] + +writeAssets +[M] - + HI->WA - - + + - + BP - -bookPayload -[M] + +bookPayload +[M] - + HI->BP - - + + - + RBC - -resolveBookChapters -[M] + +resolveBookChapters +[M] - + LD->RBC - - + + WI - -warmInit -[W] per-lane -on_demand, idle + +warmInit +[W] per-lane +on_demand, idle - + REI - -renderEnvInit -[W] per-lane + +renderEnvInit +[W] per-lane - + WI->REI - - + + - + + +DL->SL + + + + + +DL->SD + + + + + +DL->WI + + + + +DRi + +discoverRead:i +[W] + + + +DL->DRi + + + + + +DT + +dot +[W] + + + +DL->DT + + + + + +DI + +discover +[M] + + + +DRi->DI + + + + + VA - -vendorAssets -[M] + +vendorAssets +[M] - + DI->VA - - + + - + NV - -nav -[M] + +nav +[M] - + DI->NV - - + + - + BU - -buildInit -[M] + +buildInit +[M] - + DI->BU - - + + - + MI - -markdownInit -[M] + +markdownInit +[M] - + DI->MI - - + + - + DR - -deriveRedirects -[M] + +deriveRedirects +[M] - + DI->DR - - + + - + VA->MI - - + + - + VA->WA - - + + - + NV->DP - - + + - + BU->DP - - + + - + MI->DP - - + + - + DR->DP - - + + - + WX - -writeAux -[M] + +writeAux +[M] - + DR->WX - - - - - -DT - -dot -[W] + + - + DT->DP - - + + - + DT->WA - - + + - + DT->BP - - + + - + DSi - -deriveSitemap -[M] + +deriveSitemap +[M] - + DSi->RBC - - + + - + DSi->WX - - + + - + RBC->BP - - + + - + DP->DSi - - + + - + PD - -prepDest -[M] + +prepDest +[M] - + DP->PD - - + + - + DP->REI - - + + - + Ri - -render:i -[W] + +render:i +[W] - + DP->Ri - - + + + + + +PA + +packageApi +[M] + + + +DP->PA + + - + PPD - -prepPageDirs -[M] + +prepPageDirs +[M] - + PD->PPD - - + + - + PD->SCSS - - + + - + SDt - -searchData -[M] + +searchData +[M] - + PD->SDt - - + + - + SYM - -symbolIndex -[M] + +symbolIndex +[M] - + PD->SYM - - + + - + AP - -addinProject -[M] + +addinProject +[M] - + PD->AP - - + + - + Fi - -flush:i -[W] pinned + +flush:i +[W] pinned - + PPD->Fi - - + + - + PPD->WA - - + + - + REI->Ri - - + + - + RJ - -renderJoin -[M] + +renderJoin +[M] - + Ri->RJ - - + + - + Ri->Fi - - + + - - -RJ->SDt - - + + +SP + +symbolPlace +[M] - - -RJ->SYM - - + + +RJ->SP + + - - -RJ->BP - - + + +SE + +searchEntries +[M] - - -HA - -helpArchive -[W] + + +RJ->SE + + - - -SCSS->HA - - + + +RJ->BP + + + + + +APl + +archivePlan +[M] + + + +SCSS->APl + + - + CR - -checkReport -[M] + +checkReport +[M] - + SCSS->CR - - + + - + FJ - -flushJoin -[M] + +flushJoin +[M] - + Fi->FJ - - + + - + FJ->WX - - + + - - -FJ->HA - - + + +FJ->APl + + - + FJ->BP - - + + - + LJ - -linkJoin -[M] + +linkJoin +[M] - + FJ->LJ - - + + - + WA->WX - - + + - + WO - -writeOffline -[M] + +writeOffline +[M] - + WA->WO - - + + + + + +PA->SP + + + + + +SP->SE + + + + + +SP->SYM + + + + + +SE->SDt + + + + + +IS + +indexSlices +[M] + + + +SE->IS + + - + SDt->WX - - - - - -SYM->SDt - - + + + + + +SI + +searchIndex +[M] + + + +SDt->SI + + - + SYM->AP - - + + - + SYM->CR - - + + - + AP->CR - - + + - + WX->WO - - + + - + WX->LJ - - + + - - -WO->HA - - + + +WO->APl + + - + WO->LJ - - + + + + + +IAi + +indexAdd:i +[W] + + + +IS->IAi + + + + + +IM + +indexMerge +[M] + + + +IAi->IM + + + + + +IVi + +indexVectors:i +[W] pinned + + + +IAi->IVi + + + + + +IT + +indexTerms +[M] + + + +IM->IT + + + + + +IM->IVi + + + + + +IT->SI + + + + + +IVi->SI + + + + + +AL + +archiveLate +[M] + + + +SI->AL + + + + + +SI->CR + + + + + +ADi + +archiveDeflate:i +[W] + + + +APl->ADi + + + + + +APl->AL + + + + + +HA + +helpArchive +[M] + + + +ADi->HA + + + + + +ALi + +archiveLateDeflate:i +[W] + + + +AL->ALi + + + + + +ALi->HA + + - + HA->AP - - + + - + WP - -writePdf -[W] + +writePdf +[W] - + BP->WP - - + + - + CB - -checkBook -[W] pinned + +checkBook +[W] pinned - + WP->CB - - + + - + LJ->CR - - + + - + CB->CR - - + + diff --git a/lib/help-archive.mjs b/lib/help-archive.mjs index 12e7d36f3..205c62864 100644 --- a/lib/help-archive.mjs +++ b/lib/help-archive.mjs @@ -4,9 +4,9 @@ // const problems = await checkHelpArchive({ src, zip, mayDiffer, skip }); // // checkHelpArchive reads an archive written earlier against the tree as it is now: -// the same files, the same bytes, except in the files named in `mayDiffer`. -// `skip(name)` leaves a file of the tree out of the archive, and out of the -// comparison; pass both functions the same one. +// the same files, and the same size and CRC-32 in each, except in the files named +// in `mayDiffer`. `skip(name)` leaves a file of the tree out of the archive, and +// out of the comparison; pass both functions the same one. // // The IDE help add-in serves the documentation offline from this zip, embedded in // its DLL as the resource HELP/site.zip (a twinBASIC project embeds @@ -28,35 +28,44 @@ // lib/zip.mjs deflates everything and is shared with other tools, so this // writes its own. // -// The files are deflated, and later inflated for the check, a few at a time on -// Node's thread pool. The bytes written do not depend on that: the entries are -// assembled in name order, each from its own file. +// ── Units ── // -// Nothing here trusts what it wrote. After the rename, the file is read back: the -// end record, every central-directory entry and every local header are parsed and -// compared with each other and with the tree, and each entry is inflated, when it -// is deflated, and compared, with its CRC-32, with the source file's bytes. That -// always runs. +// The deflating is split into units, each of which runs on its own, so that the +// build can run them on its lanes (builder/help-archive-step.mjs): a unit is a +// whole file, or one piece of a file larger than PIECE_BYTES. A large file's +// pieces are joined into one deflate stream, as pigz makes one: every piece but +// the last ends with a sync flush, which ends it on a byte boundary without ending +// the stream, and each piece is primed with the 32 KB of the file before it, so +// that a match can reach back across the join as it would in one stream. The +// bytes depend only on PIECE_BYTES, never on how many units ran at once, and are +// within a few bytes of one stream's size. The piece CRC-32s are combined +// (crc32Combine) into the file's. +// +// Nothing here starts a thread or puts work on Node's thread pool: everything is +// synchronous, on the thread that calls it. Parallelism is the caller's, by +// running units on threads of its own (WIP.Build.md, "No task starts a thread"). +// +// Nothing here trusts what it wrote. Each unit inflates what it deflated and +// compares it with the bytes it read. The archive is read back after the rename, +// compared byte for byte with what was assembled, and parsed: the end record, +// every central-directory entry and every local header are compared with each +// other and with the tree's list of files. // // The module has no side effects at import and never exits the process. A problem -// is an Error thrown by writeHelpArchive: +// is an Error thrown by writeArchive and writeHelpArchive: // // - verifyFailed: the file was written and the read-back found differences; // `problems` lists them, each naming its entry, and `stats` is what the // summary of a successful run would hold; // - tooLarge: the tree needs zip64 (more than 65,535 files, a name over 65,535 // bytes, or 4 GB); -// - anything else (an unreadable or empty tree, a write that failed) carries -// the system's own message. +// - anything else (an unreadable or empty tree, a unit whose deflate does not +// inflate back, a write that failed) carries its own message. -import { mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises"; -import os from "node:os"; +import { closeSync, fstatSync, openSync, readdirSync, readFileSync, readSync, statSync } from "node:fs"; +import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; -import { promisify } from "node:util"; -import zlib from "node:zlib"; - -const deflateRaw = promisify(zlib.deflateRaw); -const inflateRaw = promisify(zlib.inflateRaw); +import { constants, crc32, deflateRawSync, inflateRawSync } from "node:zlib"; // Files that are compressed already; deflating them costs time and gains nothing. const STORED_EXTENSIONS = new Set([ @@ -73,6 +82,12 @@ const STORED_EXTENSIONS = new Set([ ".pdf", ]); +// A file deflated whole is at most this big; a larger one is deflated in pieces +// of this size. The archive's bytes depend on it: changing it changes them. +export const PIECE_BYTES = 1 << 20; +// What a piece is primed with: deflate's whole window. +const WINDOW = 32768; + const MAX_ENTRIES = 0xffff; const MAX_BYTES = 0xffffffff; @@ -90,65 +105,249 @@ function tooLarge(message) { return Object.assign(new Error(message), { tooLarge: true }); } -/** Runs `task(item, index)` over `items`, at most `limit` at a time, and returns the results in order. */ -async function mapLimit(items, limit, task) { - const results = new Array(items.length); - let next = 0; - const lane = async () => { - while (next < items.length) { - const i = next++; - results[i] = await task(items[i], i); - } - }; - await Promise.all(Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, lane)); - return results; -} +const isStoredType = (name) => STORED_EXTENSIONS.has(path.extname(name).toLowerCase()); /** - * Every file under `dir` that `skip` keeps, as { name, file }, `name` relative - * with forward slashes, in code-unit order. + * Every file under `dir` that `skip` keeps, as { name, file, size }, `name` + * relative with forward slashes, in code-unit order. */ -async function listFiles(dir, skip = () => false) { +export function listFiles(dir, skip = () => false) { const found = []; - const walk = async (d, prefix) => { - for (const e of await readdir(d, { withFileTypes: true })) { + const walk = (d, prefix) => { + for (const e of readdirSync(d, { withFileTypes: true })) { const file = path.join(d, e.name); const name = prefix + e.name; - if (e.isDirectory()) await walk(file, `${name}/`); + if (e.isDirectory()) walk(file, `${name}/`); else if (e.isFile() && !skip(name)) found.push({ name, file }); } }; - await walk(dir, ""); + walk(dir, ""); + for (const f of found) f.size = statSync(f.file).size; return found.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); } -const isStoredType = (name) => STORED_EXTENSIONS.has(path.extname(name).toLowerCase()); +function fstatSize(file) { + const fd = openSync(file, "r"); + try { + return fstatSync(fd).size; + } finally { + closeSync(fd); + } +} + +/** Refuses a tree a zip without zip64 cannot hold. */ +export function checkZipLimits(files) { + if (files.length > MAX_ENTRIES) { + throw tooLarge(`${files.length} files is more than a zip without zip64 holds (${MAX_ENTRIES}).`); + } + for (const { name } of files) { + if (Buffer.byteLength(name, "utf8") > 0xffff) throw tooLarge(`the name is too long for a zip entry: ${name}`); + } +} + +// ── Units ────────────────────────────────────────────────────────────────── -/** Reads and, where it pays, deflates one file: what its entry needs apart from the headers. */ -async function prepareEntry({ name, file }) { - const data = await readFile(file); - const crc = zlib.crc32(data); - let method = 0; - let body = data; - if (!isStoredType(name) && data.length > 0) { - const deflated = await deflateRaw(data, { level: 9 }); - if (deflated.length < data.length) { - method = 8; - body = deflated; +/** + * The units that deflate `files` ({ name, size }): one per file, or one per + * piece of a file that is deflated and larger than PIECE_BYTES, as + * { name, size, piece: [index, count] }. Each unit's `cost` is the bytes it + * deflates; a stored file is only read and checksummed, which costs about a + * sixteenth as much. + */ +export function planUnits(files) { + const units = []; + for (const { name, size } of files) { + if (isStoredType(name)) { + units.push({ name, size, cost: Math.ceil(size / 16) }); + continue; + } + if (size <= PIECE_BYTES) { + units.push({ name, size, cost: size }); + continue; + } + const count = Math.ceil(size / PIECE_BYTES); + for (let index = 0; index < count; index++) { + units.push({ name, size, piece: [index, count], cost: Math.min(PIECE_BYTES, size - index * PIECE_BYTES) }); } } - return { crc, method, body, size: data.length }; + return units; } -/** Builds the archive from the prepared entries, and returns it with the counts the summary reports. */ -function assembleArchive(files, prepared) { +/** + * `units` dealt into at most `groups` lists of about equal cost, the costliest + * first, each to the list with the least so far. Which unit goes where changes + * only which thread deflates it, never the archive's bytes. + */ +export function groupUnits(units, groups) { + const n = Math.max(1, Math.min(groups, units.length)); + const lists = Array.from({ length: n }, () => ({ cost: 0, units: [] })); + const order = [...units.keys()].sort((a, b) => units[b].cost - units[a].cost || a - b); + for (const i of order) { + let least = lists[0]; + for (const l of lists) if (l.cost < least.cost) least = l; + least.units.push(units[i]); + least.cost += units[i].cost; + } + return lists.map((l) => l.units).filter((l) => l.length > 0); +} + +/** Reads `length` bytes of `file` at `position`; throws if the file holds fewer. */ +function readRange(file, position, length) { + const buf = Buffer.allocUnsafe(length); + const fd = openSync(file, "r"); + try { + let done = 0; + while (done < length) { + const n = readSync(fd, buf, done, length - done, position + done); + if (n === 0) throw new Error(`${file} is shorter than the archive's plan of it`); + done += n; + } + } finally { + closeSync(fd); + } + return buf; +} + +/** + * Deflates one unit of the tree under `root`, and checks that what it deflated + * inflates to the bytes it read. Returns { name, crc, size, method, body }, with + * `piece` as well for a piece; `body` is a Uint8Array of its own, so that it can + * cross to another thread without the memory around it. + */ +export function deflateUnit(root, unit) { + const file = path.join(root, ...unit.name.split("/")); + if (!unit.piece) { + const data = readFileSync(file); + if (data.length !== unit.size) throw new Error(`${unit.name} changed size while the archive was made`); + const crc = crc32(data); + let method = 0; + let body = data; + if (!isStoredType(unit.name) && data.length > 0) { + const deflated = deflateRawSync(data, { level: 9 }); + if (deflated.length < data.length) { + if (!inflateRawSync(deflated).equals(data)) { + throw new Error(`${unit.name}: the deflated data does not inflate to the file`); + } + method = 8; + body = deflated; + } + } + return { name: unit.name, crc, size: data.length, method, body: new Uint8Array(body) }; + } + + const [index, count] = unit.piece; + const start = index * PIECE_BYTES; + const end = Math.min(unit.size, start + PIECE_BYTES); + const primed = Math.min(WINDOW, start); + const read = readRange(file, start - primed, end - start + primed); + const dictionary = primed > 0 ? read.subarray(0, primed) : undefined; + const data = read.subarray(primed); + const last = index === count - 1; + if (last && fstatSize(file) !== unit.size) throw new Error(`${unit.name} changed size while the archive was made`); + const flush = last ? constants.Z_FINISH : constants.Z_SYNC_FLUSH; + const body = deflateRawSync(data, { level: 9, finishFlush: flush, ...(dictionary && { dictionary }) }); + const back = inflateRawSync(body, { + finishFlush: constants.Z_SYNC_FLUSH, + ...(dictionary && { dictionary }), + }); + if (!back.equals(data)) throw new Error(`${unit.name}: piece ${index + 1} of ${count} does not inflate to the file`); + return { + name: unit.name, + piece: index, + crc: crc32(data), + size: data.length, + method: 8, + body: new Uint8Array(body), + }; +} + +// ── CRC-32 of joined pieces ──────────────────────────────────────────────── + +// zlib's crc32_combine: the CRC-32 of A followed by B, from the CRC-32 of each +// and B's length, by applying B's length of zero bytes to A's CRC as an +// operator over GF(2). Node does not expose zlib's. +function gf2Times(mat, vec) { + let sum = 0; + for (let i = 0; vec; vec >>>= 1, i++) if (vec & 1) sum ^= mat[i]; + return sum >>> 0; +} + +function gf2Square(square, mat) { + for (let n = 0; n < 32; n++) square[n] = gf2Times(mat, mat[n]); +} + +export function crc32Combine(crc1, crc2, len2) { + if (len2 <= 0) return crc1 >>> 0; + const even = new Array(32); + const odd = new Array(32); + odd[0] = 0xedb88320; // the CRC-32 polynomial, reflected + let row = 1; + for (let n = 1; n < 32; n++) { + odd[n] = row; + row <<= 1; + } + gf2Square(even, odd); // two zero bits + gf2Square(odd, even); // four + let c = crc1 >>> 0; + let len = len2; + do { + gf2Square(even, odd); + if (len & 1) c = gf2Times(even, c); + len = Math.floor(len / 2); + if (len === 0) break; + gf2Square(odd, even); + if (len & 1) c = gf2Times(odd, c); + len = Math.floor(len / 2); + } while (len !== 0); + return (c ^ crc2) >>> 0; +} + +/** + * Each file's entry from the units' results: a whole file's as it is, a large + * file's from its pieces, joined in order with their CRC-32s combined. Throws + * when a file has no result, or a piece is missing. Returns them in `files` order. + */ +export function collectEntries(files, results) { + const whole = new Map(); + const pieces = new Map(); + for (const r of results) { + if (r.piece === undefined) whole.set(r.name, r); + else { + if (!pieces.has(r.name)) pieces.set(r.name, []); + pieces.get(r.name)[r.piece] = r; + } + } + return files.map(({ name, file, size }) => { + if (whole.has(name)) return whole.get(name); + const parts = pieces.get(name); + if (!parts) throw new Error(`${name}: no unit deflated it`); + const count = Math.ceil(size / PIECE_BYTES); + let crc = 0; + let total = 0; + for (let i = 0; i < count; i++) { + const p = parts[i]; + if (!p) throw new Error(`${name}: piece ${i + 1} of ${count} was never deflated`); + crc = i === 0 ? p.crc : crc32Combine(crc, p.crc, p.size); + total += p.size; + } + if (parts.length !== count || total !== size) throw new Error(`${name}: its pieces do not add up to the file`); + const body = Buffer.concat(parts.map((p) => p.body)); + // A file that deflated no smaller is stored, as a whole one would be. + if (body.length >= size) return { name, crc, size, method: 0, body: readFileSync(file) }; + return { name, crc, size, method: 8, body }; + }); +} + +// ── The zip ──────────────────────────────────────────────────────────────── + +/** Builds the archive from the entries, and returns it with the counts the summary reports. */ +function assembleArchive(entries) { const parts = []; const central = []; let offset = 0; let rawBytes = 0; let storedBytes = 0; - files.forEach(({ name }, i) => { - const { crc, method, body, size } = prepared[i]; + for (const { name, crc, method, body, size } of entries) { const nameBytes = Buffer.from(name, "utf8"); if (method === 0) storedBytes += body.length; rawBytes += size; @@ -185,33 +384,32 @@ function assembleArchive(files, prepared) { parts.push(local, nameBytes, body); offset += local.length + nameBytes.length + body.length; if (offset > MAX_BYTES) throw tooLarge("the archive passes 4 GB, which needs zip64."); - }); + } const centralBytes = Buffer.concat(central); if (offset + centralBytes.length + 22 > MAX_BYTES) throw tooLarge("the archive passes 4 GB, which needs zip64."); const end = Buffer.alloc(22); end.writeUInt32LE(SIG_END, 0); - end.writeUInt16LE(files.length, 8); - end.writeUInt16LE(files.length, 10); + end.writeUInt16LE(entries.length, 8); + end.writeUInt16LE(entries.length, 10); end.writeUInt32LE(centralBytes.length, 12); end.writeUInt32LE(offset, 16); return { zip: Buffer.concat([...parts, centralBytes, end]), rawBytes, storedBytes }; } /** - * Reads the file back and returns the differences found, each naming its entry, - * and the size of the file. + * Parses `zip` against the tree's list of files: the end record, every + * central-directory entry and every local header, with each other and with the + * list. Returns the differences found, each naming its entry, and each entry's + * { name, method, crc, csize, usize, dataAt }, in order. */ -async function verifyArchive(zipFile, files, limit, mayDiffer = new Set()) { - const zip = await readFile(zipFile); +function parseArchive(zip, files) { const head = []; const tail = []; + const entries = []; const bad = (list, name, text) => list.push(`${name}: ${text}`); if (zip.length < 22 || zip.readUInt32LE(zip.length - 22) !== SIG_END) { - return { - problems: ["(archive): the end-of-central-directory record is not where it should be"], - zipBytes: zip.length, - }; + return { problems: ["(archive): the end-of-central-directory record is not where it should be"], entries }; } const endAt = zip.length - 22; const total = zip.readUInt16LE(endAt + 10); @@ -224,16 +422,11 @@ async function verifyArchive(zipFile, files, limit, mayDiffer = new Set()) { bad(head, "(archive)", `the archive holds ${total} entries, the tree ${files.length} files`); if (cdOffset + cdSize !== endAt) bad(head, "(archive)", "the central directory does not end at the end record"); - // One list of problems per entry, kept in entry order; the content checks of the - // entries run afterwards, in parallel, and fill their own entry's list. - const perEntry = []; - const contentChecks = []; + const mine = []; let at = cdOffset; let expectLocal = 0; let previous = null; for (let i = 0; i < total; i++) { - const mine = []; - perEntry.push(mine); if (at + 46 > endAt || zip.readUInt32LE(at) !== SIG_CENTRAL) { bad(mine, `(entry ${i})`, "the central-directory record is missing or malformed"); break; @@ -267,6 +460,7 @@ async function verifyArchive(zipFile, files, limit, mayDiffer = new Set()) { if (zip.readUInt16LE(rec + 14) !== DOS_DATE) bad(mine, name, "the DOS date is not 1980-01-01"); if (method !== 0 && method !== 8) bad(mine, name, `the method is ${method}`); if (method === 0 && csize !== usize) bad(mine, name, "a stored entry's sizes differ"); + if (method === 8 && csize >= usize) bad(mine, name, "the entry is deflated and not smaller than the file"); // The local header must agree with the central record. if (localAt !== expectLocal) @@ -295,74 +489,30 @@ async function verifyArchive(zipFile, files, limit, mayDiffer = new Set()) { bad(mine, name, "the data runs past the central directory"); continue; } - - // And with the file in the tree; this part reads and inflates, so it is deferred. - const stored = zip.subarray(dataAt, dataAt + csize); - const differs = mayDiffer.has(name); - contentChecks.push(async () => { - const source = await readFile(listed.file); - let content = null; - if (method === 0) content = stored; - else if (method === 8) { - try { - content = await inflateRaw(stored); - } catch (err) { - bad(mine, name, `the data does not inflate: ${err.message}`); - return; - } - if (csize >= source.length && !differs) { - bad(mine, name, "the entry is deflated and not smaller than the file"); - } - } - if (content === null) return; - if (content.length !== usize) bad(mine, name, `the data is ${content.length} bytes, the record says ${usize}`); - if (zlib.crc32(content) !== crc) bad(mine, name, "the CRC-32 differs from the data's"); - if (differs) return; - if (!content.equals(source)) bad(mine, name, "the content differs from the file in the tree"); - if (zlib.crc32(source) !== crc) bad(mine, name, "the CRC-32 differs from the file's"); - }); + entries.push({ name, method, crc, csize, usize, dataAt, file: listed.file }); } - await mapLimit(contentChecks, limit, (check) => check()); - const problems = [...head, ...perEntry.flat()]; + const problems = [...head, ...mine]; if (problems.length === 0 && expectLocal !== cdOffset) bad(tail, "(archive)", "the entries do not fill the space before the central directory"); - return { problems: [...problems, ...tail], zipBytes: zip.length }; + return { problems: [...problems, ...tail], entries }; } /** - * Writes `src` as the help archive `out`, reads it back and checks it. + * Writes the entries (collectEntries' result, in the order of `files`) as the + * help archive `out`, reads it back and checks it. * * @param {object} o - * @param {string} o.src the tree to archive, an absolute path * @param {string} o.out the zip to write, an absolute path; written under a * temporary name and renamed, so a reader never sees half of it - * @param {(name: string) => boolean} [o.skip] true for a file (relative, forward - * slashes) the archive leaves out - * @returns {Promise<{entries: number, rawBytes: number, zipBytes: number, storedBytes: number, ms: number}>} - * @throws {Error} as the header describes: `verifyFailed` (with `problems` and - * `stats`), `tooLarge`, or the system's error + * @param {{name: string}[]} o.files the tree's files, in name order + * @param {object[]} o.entries one per file, in the same order + * @returns {Promise<{entries: number, rawBytes: number, zipBytes: number, storedBytes: number, zip: Buffer}>} + * @throws {Error} as the header describes */ -export async function writeHelpArchive({ src, out, skip }) { - const started = Date.now(); - const limit = os.availableParallelism(); - - let files; - try { - files = await listFiles(src, skip); - } catch (err) { - throw new Error(`cannot read ${src}: ${err.message}`, { cause: err }); - } - if (files.length === 0) throw new Error(`${src} holds no files.`); - if (files.length > MAX_ENTRIES) { - throw tooLarge(`${files.length} files is more than a zip without zip64 holds (${MAX_ENTRIES}).`); - } - for (const { name } of files) { - if (Buffer.byteLength(name, "utf8") > 0xffff) throw tooLarge(`the name is too long for a zip entry: ${name}`); - } - - const prepared = await mapLimit(files, limit, prepareEntry); - const { zip, rawBytes, storedBytes } = assembleArchive(files, prepared); +export async function writeArchive({ out, files, entries }) { + checkZipLimits(files); + const { zip, rawBytes, storedBytes } = assembleArchive(entries); await mkdir(path.dirname(out), { recursive: true }); const temp = `${out}.${process.pid}.tmp`; @@ -374,8 +524,10 @@ export async function writeHelpArchive({ src, out, skip }) { throw err; } - const { problems, zipBytes } = await verifyArchive(out, files, limit); - const stats = { entries: files.length, rawBytes, zipBytes, storedBytes, ms: Date.now() - started }; + const back = await readFile(out); + const problems = back.equals(zip) ? [] : ["(archive): the file read back is not what was written"]; + problems.push(...parseArchive(back, files).problems); + const stats = { entries: files.length, rawBytes, zipBytes: back.length, storedBytes }; if (problems.length > 0) { throw Object.assign(new Error(`the archive does not match the tree: ${problems.length} problem(s)`), { verifyFailed: true, @@ -386,11 +538,40 @@ export async function writeHelpArchive({ src, out, skip }) { return { ...stats, zip }; } +/** + * Writes `src` as the help archive `out`, every unit on this thread, reads it + * back and checks it. The build does the same on its lanes + * (builder/help-archive-step.mjs). + * + * @param {object} o + * @param {string} o.src the tree to archive, an absolute path + * @param {string} o.out the zip to write, an absolute path + * @param {(name: string) => boolean} [o.skip] true for a file (relative, forward + * slashes) the archive leaves out + * @returns {Promise<{entries: number, rawBytes: number, zipBytes: number, storedBytes: number, ms: number, zip: Buffer}>} + * @throws {Error} as the header describes: `verifyFailed` (with `problems` and + * `stats`), `tooLarge`, or the system's error + */ +export async function writeHelpArchive({ src, out, skip }) { + const started = Date.now(); + let files; + try { + files = listFiles(src, skip); + } catch (err) { + throw new Error(`cannot read ${src}: ${err.message}`, { cause: err }); + } + if (files.length === 0) throw new Error(`${src} holds no files.`); + checkZipLimits(files); + const results = planUnits(files).map((unit) => deflateUnit(src, unit)); + const written = await writeArchive({ out, files, entries: collectEntries(files, results) }); + return { ...written, ms: Date.now() - started }; +} + /** * Checks an archive written earlier against the tree as it is now: the same - * file names, and the same bytes in each file, except in the named files, which - * may differ in content (the archive's copy of each must still be intact). It - * reads the archive and the tree and writes nothing. + * file names, and the same size and CRC-32 in each file, except in the named + * files, which may differ in content. It reads the archive and the tree and + * writes nothing. * * @param {object} o * @param {string} o.src the tree, an absolute path @@ -400,16 +581,49 @@ export async function writeHelpArchive({ src, out, skip }) { * @returns {Promise} the differences found, each naming its entry; empty when none */ export async function checkHelpArchive({ src, zip, mayDiffer = [], skip }) { - const files = await listFiles(src, skip); + const files = listFiles(src, skip); const inTree = new Set(files.map((f) => f.name)); - const entries = archiveNames(await readFile(zip)); - if (entries === null) return ["(archive): the end-of-central-directory record is not where it should be"]; - const inZip = new Set(entries); + const bytes = await readFile(zip); + const names = archiveNames(bytes); + if (names === null) return ["(archive): the end-of-central-directory record is not where it should be"]; + const inZip = new Set(names); const problems = []; for (const name of inTree) if (!inZip.has(name)) problems.push(`${name}: in the tree, not in the archive`); for (const name of inZip) if (!inTree.has(name)) problems.push(`${name}: in the archive, not in the tree`); if (problems.length > 0) return problems; - return (await verifyArchive(zip, files, os.availableParallelism(), new Set(mayDiffer))).problems; + + const parsed = parseArchive(bytes, files); + const differs = new Set(mayDiffer); + // The reads overlap, which is file I/O on Node's thread pool; the CRC-32s are + // taken here, on this thread, as each file arrives. + const changed = new Set(); + const compared = parsed.entries.filter((e) => !differs.has(e.name)); + await readEach( + compared.map((e) => e.file), + READS_AT_ONCE, + (source, i) => { + const e = compared[i]; + if (source.length !== e.usize || crc32(source) !== e.crc) changed.add(e.name); + }, + ); + for (const e of compared) { + if (changed.has(e.name)) parsed.problems.push(`${e.name}: the content differs from the file in the tree`); + } + return parsed.problems; +} + +const READS_AT_ONCE = 32; + +/** Reads `files`, at most `limit` at a time, and calls `each(bytes, index)` for each as it arrives. */ +async function readEach(files, limit, each) { + let next = 0; + const lane = async () => { + while (next < files.length) { + const i = next++; + each(await readFile(files[i]), i); + } + }; + await Promise.all(Array.from({ length: Math.max(1, Math.min(limit, files.length)) }, lane)); } /** The entry names in an archive's central directory, or null when it has no end record. */ diff --git a/lib/markdown.mjs b/lib/markdown.mjs index f103d3c3c..91c4e3d18 100644 --- a/lib/markdown.mjs +++ b/lib/markdown.mjs @@ -76,13 +76,20 @@ export function blockRegions(src, { md = bareParser() } = {}) { // Each line's text and the ending that followed it, which is "" only for a // last line with none. An empty source has no lines, and a final line ending // starts no line after it: markdown-it counts the same way. +// +// The line ends are found by a regular expression and the backticks below by +// `indexOf`, never one character at a time: `maskCode` goes over every page's +// whole source on the render lanes, and over the pages with a placeholder on +// the main thread before the first render. function splitLines(src) { const lines = []; + const lineEnd = /\r\n?|\n/g; let i = 0; while (i < src.length) { - let j = i; - while (j < src.length && src[j] !== "\n" && src[j] !== "\r") j++; - const eol = src[j] === "\r" && src[j + 1] === "\n" ? "\r\n" : src.slice(j, j + 1); + lineEnd.lastIndex = i; + const m = lineEnd.exec(src); + const j = m ? m.index : src.length; + const eol = m ? m[0] : ""; lines.push({ text: src.slice(i, j), eol }); i = j + eol.length; } @@ -111,28 +118,31 @@ export function mapLines(src, fn) { * `` \`a `b` `` the scan pairs the escaped backtick with the one before `b`. */ export function splitCodeSpans(line) { + // Most lines hold no backtick, and are one segment of prose. + if (!line.includes("`")) return line ? [{ code: false, text: line }] : []; const parts = []; let buf = ""; let k = 0; while (k < line.length) { if (line[k] !== "`") { - buf += line[k++]; + const tick = line.indexOf("`", k); + const end = tick < 0 ? line.length : tick; + buf += line.slice(k, end); + k = end; continue; } let n = 0; while (line[k + n] === "`") n++; - let p = k + n; + let p = line.indexOf("`", k + n); let found = -1; - while (p < line.length) { - if (line[p] === "`") { - let m = 0; - while (line[p + m] === "`") m++; - if (m === n) { - found = p; - break; - } - p += m; - } else p++; + while (p >= 0) { + let m = 0; + while (line[p + m] === "`") m++; + if (m === n) { + found = p; + break; + } + p = line.indexOf("`", p + m); } if (found < 0) { buf += line.slice(k, k + n); diff --git a/lib/zip.mjs b/lib/zip.mjs index c821c9bca..faf76dfa9 100644 --- a/lib/zip.mjs +++ b/lib/zip.mjs @@ -10,7 +10,7 @@ // unchanged set of files twice writes the same bytes. import { readFileSync, statSync } from "node:fs"; -import zlib from "node:zlib"; +import { crc32, deflateRawSync, inflateRawSync } from "node:zlib"; /** * A zip file, as the bytes: for each file a local header and the deflated data, @@ -23,8 +23,8 @@ export function zipFiles(files) { const centrals = []; let offset = 0; for (const { name, data, mtime } of files) { - const compressed = zlib.deflateRawSync(data, { level: 9 }); - const crc = zlib.crc32(data); + const compressed = deflateRawSync(data, { level: 9 }); + const crc = crc32(data); const nameBytes = Buffer.from(name, "utf8"); const time = (mtime.getHours() << 11) | (mtime.getMinutes() << 5) | (mtime.getSeconds() >> 1); const date = ((Math.max(mtime.getFullYear(), 1980) - 1980) << 9) | ((mtime.getMonth() + 1) << 5) | mtime.getDate(); @@ -94,7 +94,7 @@ export function readZip(buf) { const local = buf.readUInt32LE(at + 42); const name = buf.toString("utf8", at + 46, at + 46 + nameLength); const start = local + 30 + buf.readUInt16LE(local + 26) + buf.readUInt16LE(local + 28); - files.push({ name, data: zlib.inflateRawSync(buf.subarray(start, start + size)) }); + files.push({ name, data: inflateRawSync(buf.subarray(start, start + size)) }); at += 46 + nameLength; } return files; diff --git a/scripts/check_code_regions.mjs b/scripts/check_code_regions.mjs index cfeed8987..4c7775dac 100644 --- a/scripts/check_code_regions.mjs +++ b/scripts/check_code_regions.mjs @@ -83,7 +83,7 @@ import path from "node:path"; import MarkdownIt from "markdown-it"; import deflist from "markdown-it-deflist"; -import { checkPlaceholders, formatSize, validateCountNames } from "../builder/counts.mjs"; +import { checkPlaceholders, formatSize, packedDownloads, validateCountNames } from "../builder/counts.mjs"; import { discover } from "../builder/discover.mjs"; import { applyPostRenderRewrites, applyPreRenderRewrites, createMarkdownIt } from "../builder/render.mjs"; import { markdownCopy } from "../builder/markdown-copy.mjs"; @@ -622,6 +622,48 @@ function downloadProbe() { assert.match(check("{{tbdocs:size:tB/add-in.twinproj}}")[0], /embeds the offline tree/); assert.match(check("{{tbdocs:size:s.css}}")[0], /rewritten/); assert.deepEqual(check("`{{tbdocs:size:nope}}`\n\n```\n{{tbdocs:size:nope}}\n```"), []); + + // A file the build packs while the pages render has no size yet: its placeholder is accepted, + // and so is the table, and each page that holds one is named as late. packedDownloads then + // has the sizes and the rows; a tool is sized and is no row. + const withPacked = { ...downloads, packed: new Set(["t/P/P-tests.twinproj", "t/P/tool.zip"]) }; + const checked = checkPlaceholders( + [ + { srcRel: "early.md", rawContent: "{{tbdocs:size:a/x.bin}} `{{tbdocs:packageTestRows}}`" }, + { srcRel: "size.md", rawContent: "{{tbdocs:size:/t/P/tool.zip}} {{tbdocs:size:a/x.bin}}" }, + { srcRel: "rows.md", rawContent: "{{tbdocs:packageTestRows}}" }, + ], + { pages: 1 }, + withPacked, + md, + ); + assert.deepEqual(checked.problems, []); + assert.deepEqual(checked.late, ["size.md", "rows.md"]); + assert.deepEqual(checked.sizes, { "a/x.bin": 1 }); + assert.deepEqual(checked.packedArgs, { "/t/P/tool.zip": "t/P/tool.zip" }); + const packed = [ + { pkg: "P", rel: "t/P/P-tests.twinproj", bytes: new Uint8Array(2048), kind: "tests" }, + { pkg: "P", rel: "t/P/tool.zip", bytes: new Uint8Array(3072), kind: "tool" }, + ]; + assert.deepEqual(packedDownloads({ ...checked, dest: "t", packed }), { + sizes: { "a/x.bin": 1, "/t/P/tool.zip": 3072 }, + tests: { dest: "t", packages: [{ pkg: "P", rel: "t/P/P-tests.twinproj", bytes: 2048 }] }, + }); + assert.throws(() => packedDownloads({ ...checked, dest: "t", packed: [] }), /was to be packed, and was not/); + // Before the files are packed a parser has the static sizes alone, and refuses the rest. + const early = createMarkdownIt({ + highlighter: null, + linkTables: null, + baseurl: "", + staticFiles: new Set(), + downloads: { sizes: checked.sizes, tests: null }, + }); + assert.equal(applyPreRenderRewrites("{{tbdocs:size:a/x.bin}}", early, { permalink: "/" }), "1 KB"); + assert.throws( + () => applyPreRenderRewrites("{{tbdocs:packageTestRows}}", early, { permalink: "/" }), + /before the test projects were packed/, + ); + assert.throws(() => applyPreRenderRewrites("{{tbdocs:size:/t/P/tool.zip}}", early, { permalink: "/" }), /waits/); assert.deepEqual([1, 1023, 1024, 44000, 1048000, 1048576, 1.25 * 1048576].map(formatSize), [ "1 KB", "1 KB", diff --git a/test.bat b/test.bat index 1fad77548..bec639e70 100644 --- a/test.bat +++ b/test.bat @@ -144,6 +144,14 @@ node --test test/indexer.test.mjs @rem No tree, no install, about 1 s. node --test test/ide-js.test.mjs @if errorlevel 1 goto :fail +@rem Unit tests for builder/discover.mjs and discover-read.mjs: the source +@rem tree's inventory, which the build reads in pieces on its lanes. The +@rem build compares its output on the site's own tree and piece count, so +@rem these read a small tree of their own in any number of pieces, with +@rem a picture pair that has a file from outside the tree. No build, no +@rem lanes, well under a second. +node --test test/discover.test.mjs +@if errorlevel 1 goto :fail @rem A regex that backtracks exponentially is a hang waiting for the @rem right input, and nothing that reads the site can see it: the corpus @rem passes until some page happens to contain the trigger, and then the diff --git a/test/addin-project.test.mjs b/test/addin-project.test.mjs index 0dcc870d0..e11141de0 100644 --- a/test/addin-project.test.mjs +++ b/test/addin-project.test.mjs @@ -25,9 +25,21 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync import { tmpdir } from "node:os"; import path from "node:path"; import { after, describe, test } from "node:test"; +import { crc32, inflateRawSync } from "node:zlib"; import { addinProjectOf, formatAddinProject, packAddinProject, writeAddinProject } from "../builder/addin-project.mjs"; import { downloadsKept, helpArchiveSkips } from "../builder/help-archive-step.mjs"; -import { checkHelpArchive, writeHelpArchive } from "../lib/help-archive.mjs"; +import { + checkHelpArchive, + collectEntries, + crc32Combine, + deflateUnit, + groupUnits, + listFiles, + PIECE_BYTES, + planUnits, + writeArchive, + writeHelpArchive, +} from "../lib/help-archive.mjs"; import { REPO_ROOT } from "../lib/repo-paths.mjs"; import { importProject, packFiles, readProject } from "../scripts/impexp.mjs"; @@ -295,6 +307,103 @@ describe("the help archive checked against the offline tree", () => { ]); }); + // An archive's entries, read through its central directory: each name with + // its method, its CRC-32 and its bytes, a deflated entry inflated in one pass. + function entriesOf(zipFile) { + const buf = readFileSync(zipFile); + const endAt = buf.length - 22; + const out = new Map(); + let at = buf.readUInt32LE(endAt + 16); + for (let i = 0; i < buf.readUInt16LE(endAt + 10); i++) { + const method = buf.readUInt16LE(at + 10); + const size = buf.readUInt32LE(at + 20); + const nameLength = buf.readUInt16LE(at + 28); + const local = buf.readUInt32LE(at + 42); + const start = local + 30 + buf.readUInt16LE(local + 26) + buf.readUInt16LE(local + 28); + const body = buf.subarray(start, start + size); + out.set(buf.toString("utf8", at + 46, at + 46 + nameLength), { + method, + crc: buf.readUInt32LE(at + 16), + data: method === 8 ? inflateRawSync(body) : body, + }); + at += 46 + nameLength; + } + return out; + } + + // Text that deflates, and differs all along: a counter in a sentence. + const longText = (bytes) => { + let s = ""; + for (let i = 0; s.length < bytes; i++) s += `Line ${i} of a page that the help archive holds, ${i * 7919}.\n`; + return s.slice(0, bytes); + }; + + test("deflates a large file in pieces that are one stream, with the file's CRC-32", async () => { + // Three pieces and a part of one; a file of exactly two; one at the limit, + // which is deflated whole; a stored type over the limit, which is not cut. + const files = { + "big.js": longText(3 * PIECE_BYTES + 12345), + "two.html": longText(2 * PIECE_BYTES), + "whole.html": longText(PIECE_BYTES), + "small.css": longText(300), + "picture.png": Buffer.from(longText(PIECE_BYTES + 99)), + }; + const { src, zip } = await written("h-pieces", files); + const entries = entriesOf(zip); + for (const [name, text] of Object.entries(files)) { + const e = entries.get(name); + const source = Buffer.from(text); + assert.ok(e.data.equals(source), `${name} does not inflate to the file`); + assert.equal(e.crc, crc32(source), `${name}'s CRC-32`); + assert.equal(e.method, name.endsWith(".png") ? 0 : 8, `${name}'s method`); + } + assert.deepEqual( + planUnits(listFiles(src)).map((u) => (u.piece ? `${u.name} ${u.piece[0] + 1}/${u.piece[1]}` : u.name)), + [ + "big.js 1/4", + "big.js 2/4", + "big.js 3/4", + "big.js 4/4", + "picture.png", + "small.css", + "two.html 1/2", + "two.html 2/2", + "whole.html", + ], + ); + assert.deepEqual(await checkHelpArchive({ src, zip }), []); + }); + + test("gives the same archive however the units are grouped and ordered", async () => { + const { src, zip } = await written("h-groups", { + "a.html": longText(2 * PIECE_BYTES + 5), + "b.html": longText(700), + "c/d.html": longText(PIECE_BYTES + 1), + }); + const files = listFiles(src); + const units = planUnits(files); + for (const groups of [1, 2, 5]) { + const dealt = groupUnits(units, groups); + assert.equal(dealt.flat().length, units.length); + const results = dealt.reverse().flatMap((group) => group.map((u) => deflateUnit(src, u))); + const again = path.join(tmp, `h-groups-${groups}.zip`); + await writeArchive({ out: again, files, entries: collectEntries(files, results) }); + assert.ok(readFileSync(again).equals(readFileSync(zip)), `${groups} group(s) give other bytes`); + } + // A piece that never arrived is named, not left out. + const short = units.filter((u) => !(u.name === "a.html" && u.piece[0] === 1)).map((u) => deflateUnit(src, u)); + assert.throws(() => collectEntries(files, short), /a\.html: piece 2 of 3 was never deflated/); + }); + + test("combines the CRC-32s of two runs of bytes into that of both", () => { + const data = Buffer.from(longText(50000)); + for (const cut of [0, 1, 255, 256, 32768, 49999, 50000]) { + const a = data.subarray(0, cut); + const b = data.subarray(cut); + assert.equal(crc32Combine(crc32(a), crc32(b), b.length), crc32(data), `cut at ${cut}`); + } + }); + test("names a file the Downloads page offers that the archive would hold", async () => { const src = tree("h-downloads", { "Downloads.html": [ diff --git a/test/discover.test.mjs b/test/discover.test.mjs new file mode 100644 index 000000000..3c2d5973d --- /dev/null +++ b/test/discover.test.mjs @@ -0,0 +1,347 @@ +// Unit tests for builder/discover.mjs and builder/discover-read.mjs: the +// source tree's inventory, which the build reads in pieces on its lanes, and +// for builder/fnmatch.mjs, the patterns the output trees' inventories leave +// files out by, and for builder/nav.mjs, the nav the pages' frontmatter gives. +// +// The build compares its output with the last commit's, so a fault that the +// site's own tree and its piece count do not reach passes it: an inventory +// that depends on how many pieces it was read in, a picture pair with a file +// from outside the tree. These read a small tree of their own in any number +// of pieces. +// +// Runs with a bare `node --test test/discover.test.mjs`: no build, no lanes. + +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { after, describe, test } from "node:test"; +import { assemble, cutPieces, discover, listSources } from "../builder/discover.mjs"; +import { packPageText, pageText, readPiece } from "../builder/discover-read.mjs"; +import { deriveTreeRels } from "../builder/check-tree.mjs"; +import { fnmatchPathname, matchesAny } from "../builder/fnmatch.mjs"; +import { computeNav } from "../builder/nav.mjs"; + +// A PNG's first 24 bytes, which is all the build reads of one. +function pngHeader(width, height) { + const b = Buffer.alloc(24); + Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(b, 0); + b.writeUInt32BE(13, 8); + b.write("IHDR", 12, "latin1"); + b.writeUInt32BE(width, 16); + b.writeUInt32BE(height, 20); + return b; +} + +const top = mkdtempSync(path.join(os.tmpdir(), "tbdocs-discover-")); +after(() => rmSync(top, { recursive: true, force: true })); +const srcRoot = path.join(top, "docs"); +const put = (rel, content) => { + const file = path.join(top, rel); + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, content); +}; +const page = (title, extra = "") => `---\ntitle: ${title}\n${extra}---\n\nThe ${title} page.\n`; + +for (const folder of ["A", "B", "C", "D", "E"]) { + put(`docs/${folder}/index.md`, page(folder, `permalink: /x/${folder}/\n`)); + put(`docs/${folder}/Other.md`, page(`${folder} other`)); + put(`docs/${folder}/Images/shot.png`, pngHeader(800, 600)); + put(`docs/${folder}/Images/shot.light.png`, pngHeader(804, 600)); + put(`docs/${folder}/notes.txt`, `notes of ${folder}\n`); +} +put("docs/index.md", page("Home", "permalink: /\n")); +put("docs/Hash.md", page("Input #")); +put("docs/raw.md", "No frontmatter here.\n"); +put("docs/A/Images/broken.png", pngHeader(10, 10)); +put("docs/A/Images/broken.light.png", "not a PNG, though longer than a header"); +put("docs/_out/skipped.md", page("Skipped")); +// Outside the tree, as _config.yml's bundle_extra names them: a file of its own, +// and the dark picture of a light picture that is inside the tree. +put("extra/tool.mjs", "export {};\n"); +put("extra/dark.png", pngHeader(640, 480)); +put("docs/A/Images/outside.light.png", pngHeader(644, 480)); +const EXTRA = [ + { src: "../extra/tool.mjs", dest: "downloads/tool.mjs" }, + { src: "../extra/dark.png", dest: "A/Images/outside.png" }, +]; +const IGNORE = ["_*", "_*/**"]; + +async function inventory(count, extra = EXTRA) { + const plan = cutPieces(await listSources(srcRoot, IGNORE), count, extra); + const results = plan.pieces.map((piece) => readPiece(srcRoot, piece)); + return { plan, results, ...assemble(srcRoot, plan, results) }; +} + +describe("the source tree's inventory", () => { + test("is the same in any number of pieces", async () => { + const one = await inventory(1); + assert.equal(one.plan.pieces.length, 1); + for (const count of [2, 3, 4, 7, 50]) { + const many = await inventory(count); + assert.equal(many.plan.pieces.length, count); + assert.deepEqual(many.pages, one.pages, `${count} pieces: the pages`); + assert.deepEqual(many.staticFiles, one.staticFiles, `${count} pieces: the static files`); + assert.deepEqual( + Object.entries(many.pictureSizes), + Object.entries(one.pictureSizes), + `${count} pieces: the pairs`, + ); + } + }); + + test("a count below one is one piece", async () => { + assert.equal((await inventory(0)).plan.pieces.length, 1); + }); + + test("the pages are sorted by file name, then by path", async () => { + const { pages } = await inventory(3); + assert.deepEqual( + pages.map((p) => p.srcRel), + [ + "Hash.md", + ...["A", "B", "C", "D", "E"].map((f) => `${f}/Other.md`), + ...["A", "B", "C", "D", "E"].map((f) => `${f}/index.md`), + "index.md", + ], + ); + const a = pages.find((p) => p.srcRel === "A/index.md"); + assert.equal(a.permalink, "/x/A/"); + assert.equal(a.destPath, "x/A/index.html"); + assert.equal(a.rawContent, "\nThe A page.\n"); + assert.equal(a.contentLine, 5); + assert.equal(a.srcPath, path.join(srcRoot, "A/index.md")); + assert.equal(pages.find((p) => p.srcRel === "A/Other.md").permalink, "/A/Other.html"); + }); + + test("a file with no frontmatter is a static file, and an excluded one is nowhere", async () => { + const { pages, staticFiles } = await inventory(2); + const raw = staticFiles.find((s) => s.srcRel === "raw.md"); + assert.deepEqual(raw, { srcPath: path.join(srcRoot, "raw.md"), srcRel: "raw.md", destRel: "raw.md", size: 21 }); + assert.ok(![...pages, ...staticFiles].some((f) => f.srcRel.startsWith("_out"))); + }); + + test("the static files are sorted by path, with the files from outside the tree after them", async () => { + const { staticFiles } = await inventory(4); + const rels = staticFiles.map((s) => s.srcRel); + const inside = rels.slice(0, -EXTRA.length); + assert.deepEqual(inside, [...inside].sort()); + assert.deepEqual(rels.slice(-EXTRA.length), ["downloads/tool.mjs", "A/Images/outside.png"]); + const tool = staticFiles.at(-2); + assert.equal(tool.srcPath, path.join(top, "extra", "tool.mjs")); + assert.equal(tool.size, 11); + }); + + test("a pair's sizes are read, one with its dark picture outside the tree too", async () => { + const { pictureSizes } = await inventory(3); + assert.deepEqual(pictureSizes["B/Images/shot.light.png"], [804, 600, 800, 600]); + assert.deepEqual(pictureSizes["A/Images/outside.light.png"], [644, 480, 640, 480]); + // No entry for a pair with a file that is no PNG, or for a light picture with no dark one. + assert.ok(!("A/Images/broken.light.png" in pictureSizes)); + assert.equal((await inventory(3, [])).pictureSizes["A/Images/outside.light.png"], undefined); + // In the static files' order. + const lights = Object.keys(pictureSizes); + assert.deepEqual(lights, [...lights].sort()); + }); + + test("an unquoted value that ends in # is a warning from its piece", async () => { + const { results } = await inventory(2); + const warnings = results.flatMap((r) => r.warnings); + assert.equal(warnings.length, 1); + assert.match(warnings[0], /^discover: Hash\.md:2: an unquoted value ends in #/); + }); + + test("frontmatter that does not parse names its file", async () => { + put("bad/docs/Bad.md", "---\ntitle: [unclosed\n---\n"); + const bad = path.join(top, "bad", "docs"); + const plan = cutPieces(await listSources(bad), 2); + assert.throws(() => plan.pieces.map((p) => readPiece(bad, p)), /Failed to parse frontmatter in Bad\.md/); + }); + + test("discover() is the same inventory in one call, without the files from outside", async () => { + const warn = console.warn; + const warned = []; + console.warn = (line) => warned.push(line); + let found; + try { + found = await discover(srcRoot, IGNORE); + } finally { + console.warn = warn; + } + const pieces = await inventory(3, []); + assert.deepEqual(found.pages, pieces.pages); + assert.deepEqual(found.staticFiles, pieces.staticFiles); + assert.equal(warned.length, 1); + }); +}); + +// The nav tree, each page's levels in it and each page's list of children all +// come from one sorted list of children for each page (builder/nav.mjs). The +// site has few pages with nav_exclude and few parents that reverse their +// children, and the build's comparison sees only the site. +describe("the nav the pages' frontmatter gives", () => { + const page = (title, frontmatter = {}) => { + const permalink = frontmatter.permalink ?? `/${title}`; + return { srcRel: `${permalink.slice(1)}.md`, permalink, frontmatter: { title, ...frontmatter, permalink } }; + }; + const build = (pages) => { + const { navTree } = computeNav(pages, {}); + return { navTree, by: Object.fromEntries(pages.map((p) => [p.frontmatter.title, p])) }; + }; + const shape = (nodes) => nodes.map((n) => (n.children.length ? [n.title, shape(n.children)] : n.title)); + + test("children are ordered by nav_order, then by title, and a page's levels are its positions", () => { + const { navTree, by } = build([ + page("Zeta", { nav_order: 1 }), + page("Alpha", { nav_order: 2 }), + page("b", { parent: "Alpha" }), + page("a", { parent: "Alpha" }), + page("c", { parent: "Alpha", nav_order: 1 }), + page("leaf", { parent: "a", grand_parent: "Alpha" }), + ]); + assert.deepEqual(shape(navTree), ["Zeta", ["Alpha", ["c", ["a", ["leaf"]], "b"]]]); + assert.deepEqual(by.Zeta.navLevels, [1, 1]); + assert.deepEqual(by.c.navLevels, [1, 2, 1]); + assert.deepEqual(by.leaf.navLevels, [1, 2, 2, 1]); + assert.deepEqual(by.leaf.breadcrumbs, [ + { title: "Alpha", url: "/Alpha" }, + { title: "a", url: "/a" }, + ]); + assert.deepEqual( + by.Alpha.children.map((c) => c.title), + ["c", "a", "b"], + ); + assert.deepEqual(by.Zeta.children, []); + }); + + test("a nav_exclude page is listed among the children, and is not in the tree or counted in the levels", () => { + const { navTree, by } = build([ + page("Top"), + page("a", { parent: "Top" }), + page("b", { parent: "Top", nav_exclude: true }), + page("c", { parent: "Top" }), + ]); + assert.deepEqual(shape(navTree), [["Top", ["a", "c"]]]); + assert.deepEqual( + by.Top.children.map((c) => c.title), + ["a", "b", "c"], + ); + assert.deepEqual(by.c.navLevels, [1, 1, 2]); + assert.equal(by.b.navLevels, undefined); + }); + + test("child_nav_order reverses both lists", () => { + const { navTree, by } = build([ + page("Top", { child_nav_order: "desc" }), + page("a", { parent: "Top" }), + page("b", { parent: "Top", nav_exclude: true }), + page("c", { parent: "Top" }), + ]); + assert.deepEqual(shape(navTree), [["Top", ["c", "a"]]]); + assert.deepEqual( + by.Top.children.map((c) => c.title), + ["c", "b", "a"], + ); + assert.deepEqual(by.a.navLevels, [1, 1, 2]); + }); + + test("a child whose grand_parent names another page's parent is not that page's child", () => { + const { navTree, by } = build([ + page("One"), + page("Two"), + page("Shared", { parent: "One", permalink: "/One/Shared" }), + page("Shared", { parent: "Two", permalink: "/Two/Shared" }), + page("x", { parent: "Shared", grand_parent: "Two" }), + ]); + assert.deepEqual(shape(navTree), [ + ["One", ["Shared"]], + ["Two", [["Shared", ["x"]]]], + ]); + assert.deepEqual(by.x.navLevels, [1, 2, 1, 1]); + }); +}); + +// A render chunk's payload names where each page's text is in the buffer the +// lane that read the page packed (packPageText). The site's own pages are +// nearly all ASCII, where a length in characters and one in bytes agree. +describe("the pages' text, packed for the render lanes", () => { + test("each page's text is read back as it was, whatever its characters", () => { + const pages = [ + "plain\r\ntext\n", + "", + "za\u{17C}\u{F3}\u{142}\u{107} \u{2014} \u{1F600} \u{65E5}\u{672C}", + "after", + ].map((rawContent) => ({ rawContent })); + const { sab, spans } = packPageText(pages); + assert.equal(spans.length, 2 * pages.length); + assert.equal(sab.byteLength, Buffer.byteLength(pages.map((p) => p.rawContent).join(""), "utf8")); + for (const [i, page] of pages.entries()) { + assert.equal(pageText(sab, spans[2 * i], spans[2 * i + 1]), page.rawContent); + } + }); + + test("no pages pack into an empty buffer", () => { + const { sab, spans } = packPageText([]); + assert.equal(sab.byteLength, 0); + assert.deepEqual(spans, []); + }); +}); + +// The output trees' inventories leave out what offline_exclude names +// (builder/fnmatch.mjs). The site's own list has few wildcards, and the build's +// comparison sees only that list. +describe("the patterns a tree's inventory leaves files out by", () => { + test("* stays within a folder, ** crosses folders, ? is one character", () => { + assert.equal(fnmatchPathname("a/*.svg", "a/b.svg"), true); + assert.equal(fnmatchPathname("a/*.svg", "a/c/b.svg"), false); + assert.equal(fnmatchPathname("a/**", "a/c/b.svg"), true); + assert.equal(fnmatchPathname("a/?.svg", "a/b.svg"), true); + assert.equal(fnmatchPathname("a/?.svg", "a//.svg"), false); + assert.equal(fnmatchPathname("a.b", "axb"), false); + }); + + test("a list matches as its patterns do one by one", () => { + const patterns = ["Images/x.svg", "book/**", "*.tmp", "a+b(1).png"]; + const rels = [ + "Images/x.svg", + "Images/x.svg2", + "book/a/b.html", + "book", + "x.tmp", + "d/x.tmp", + "a+b(1).png", + "aab1.png", + ]; + for (const rel of rels) { + const one = patterns.some((pat) => fnmatchPathname(pat, rel)); + assert.equal(matchesAny(rel, patterns), one, rel); + } + assert.equal(matchesAny("x", []), false); + assert.equal(matchesAny("x", undefined), false); + }); + + test("a pattern added to a list that was already used is honoured", () => { + const patterns = ["a.svg"]; + assert.equal(matchesAny("b.svg", patterns), false); + patterns.push("b.svg"); + assert.equal(matchesAny("b.svg", patterns), true); + }); + + test("the offline tree's inventory leaves out what the list names", () => { + const common = { + pages: [{ destPath: "a\\index.html" }, { destPath: "book\\b.html" }], + staticFiles: [{ destRel: "Images\\x.svg" }, { destRel: "Images\\x.png" }], + stubs: [], + themeAssetRels: [], + excludePatterns: ["Images/x.svg", "book/**"], + }; + const offline = deriveTreeRels("offline", common); + assert.equal(offline.includes("a/index.html"), true); + assert.equal(offline.includes("Images/x.png"), true); + assert.equal(offline.includes("Images/x.svg"), false); + assert.equal(offline.includes("book/b.html"), false); + const online = deriveTreeRels("online", common); + assert.equal(online.includes("Images/x.svg"), true); + assert.equal(online.includes("book/b.html"), true); + }); +}); diff --git a/test/render.test.mjs b/test/render.test.mjs index aefd056d9..dbfca629c 100644 --- a/test/render.test.mjs +++ b/test/render.test.mjs @@ -27,6 +27,7 @@ import { Graphviz } from "@hpcc-js/wasm-graphviz"; import { stripXmlPrologue } from "../builder/dot.mjs"; import { inlineDiagram } from "../builder/inline-diagram.mjs"; import { markdownCopy } from "../builder/markdown-copy.mjs"; +import { readPiece } from "../builder/discover-read.mjs"; import { isWebsiteOnlyLink, rewriteHtml, websiteOf } from "../builder/offline-rewrite.mjs"; import { permalinkToDestPath } from "../builder/paths.mjs"; import { assignPackageVersions, calloutLabelsOf, parseCalloutLabel } from "../lib/callout-labels.mjs"; @@ -39,7 +40,7 @@ import { } from "../builder/render.mjs"; import { lightOnly, - pairSizes, + picturePairs, pictureSvgOutputs, pngPictures, unpairedLightPictures, @@ -491,18 +492,20 @@ describe("themePairPlugin and lightOnly", () => { assert.match(render("`![x](Images/A.light.png)`"), /]*>!\[x\]\(Images\/A\.light\.png\)<\/code>/); }); - test("the two pictures' sizes are read from their headers", async () => { + test("the two pictures' sizes are read from their headers, a real PNG's", async () => { const dir = mkdtempSync(path.join(tmpdir(), "theme-pictures-")); try { const png = (w, h) => encodePng({ width: w, height: h, rgba: new Uint8Array(w * h * 4) }); writeFileSync(path.join(dir, "A.png"), png(6, 4)); writeFileSync(path.join(dir, "A.light.png"), png(5, 3)); writeFileSync(path.join(dir, "B.light.png"), png(1, 1)); - const files = ["A.png", "A.light.png", "B.light.png"].map((f) => ({ - srcRel: `x/${f}`, - srcPath: path.join(dir, f), - })); - assert.deepEqual({ ...(await pairSizes(files)) }, { "x/A.light.png": [5, 3, 6, 4] }); + const files = ["A.png", "A.light.png", "B.light.png"].map((f) => ({ srcRel: `x/${f}`, src: f })); + // The pairs, each with where its two files are; a light picture alone is no pair. + const pairs = picturePairs(files); + assert.deepEqual(pairs, [["x/A.light.png", "A.light.png", "A.png"]]); + // And their sizes, as a lane reads them (discover-read.mjs). + const { pairSizes } = readPiece(dir, { pageRels: [], statSrcs: [], pairs: pairs.map(([, l, d]) => [l, d]) }); + assert.deepEqual(pairSizes, [[5, 3, 6, 4]]); } finally { rmSync(dir, { recursive: true, force: true }); } diff --git a/test/search-index.test.mjs b/test/search-index.test.mjs index 93c34faab..8ca626e47 100644 --- a/test/search-index.test.mjs +++ b/test/search-index.test.mjs @@ -1,16 +1,16 @@ // The gate on builder/search-index.mjs's split build: the search index the -// build writes on several threads must be, byte for byte, the index lunr -// itself makes on one (lunr(config) and JSON.stringify), for any number of -// threads. lunr has no way to merge two indexes, so the build merges what -// each thread's lunr.Builder holds and makes the vectors from totals of its +// build writes in slices on its lanes must be, byte for byte, the index lunr +// itself makes in one (lunr(config) and JSON.stringify), for any number of +// slices. lunr has no way to merge two indexes, so the build merges what +// each slice's lunr.Builder holds and makes the vectors from totals of its // own (WIP.Search.md, "The pre-built index"); a change to how it does that, // or a lunr whose builder keeps its state otherwise, gives a slightly // different ranking that nothing else would notice. // // The fixture is made to reach the merge's corners: terms that look like -// numbers (which JavaScript orders before other keys), terms a later thread -// meets first, terms only one thread has, empty fields, HTML entities, stem -// twins, hand-marked index terms and a thread with a single entry. +// numbers (which JavaScript orders before other keys), terms a later slice +// meets first, terms only one slice has, empty fields, HTML entities, stem +// twins, hand-marked index terms and a slice with a single entry. // // Runs with a bare `node --test test/search-index.test.mjs`; no build needed. @@ -19,13 +19,25 @@ import vm from "node:vm"; import { describe, test } from "node:test"; import { + addSlice, + assembleIndexJson, buildIndex, buildIndexJson, - defaultIndexWorkers, + indexSliceCount, + invertedIndexJson, loadSearchLunr, + mergeSlices, offlineSearchIndexJs, + packTotals, + planIndexSegments, + planIndexSlices, searchIndexFile, + sliceDocs, + sliceVectors, + stemTwins, + unpackTotals, } from "../builder/search-index.mjs"; +import { packSearchEntries, readSearchEntries } from "../builder/search.mjs"; // A deterministic fixture of `count` entries. function fixture(count) { @@ -85,23 +97,109 @@ describe("the split build is lunr()'s", () => { const docs = fixture(120); const reference = JSON.stringify(buildIndex(lunr, docs)); - test("on one thread it is lunr()'s own", async () => { - assert.equal(await buildIndexJson(docs, { workers: 1 }), reference); + test("in one slice it is lunr()'s own", () => { + assert.equal(buildIndexJson(docs, { slices: 1 }), reference); }); - for (const workers of [2, 3, 7, 119]) { - test(`on ${workers} threads it is lunr()'s, byte for byte`, async () => { - assert.equal(await buildIndexJson(docs, { workers }), reference); + for (const slices of [2, 3, 7, 119]) { + test(`in ${slices} slices it is lunr()'s, byte for byte`, () => { + assert.equal(buildIndexJson(docs, { slices }), reference); }); } - test("more threads than entries gives one entry each", async () => { + test("more slices than entries gives one entry each", () => { const few = fixture(4); - assert.equal(await buildIndexJson(few, { workers: 16 }), JSON.stringify(buildIndex(lunr, few))); + assert.equal(buildIndexJson(few, { slices: 16 }), JSON.stringify(buildIndex(lunr, few))); }); - test("an index loaded from it answers as lunr()'s does", async () => { - const loaded = lunr.Index.load(JSON.parse(await buildIndexJson(docs, { workers: 3 }))); + // As the build runs it: each slice's builder kept for its vectors, and the + // totals read back from the SharedArrayBuffer the lanes are sent. + test("through the totals the lanes are sent it is lunr()'s, byte for byte", () => { + const plan = planIndexSlices(lunr, JSON.parse(JSON.stringify(docs)), 5); + // Each slice's payload as JSON, as fanOut packs it. + const lanes = plan.map((p) => JSON.parse(JSON.stringify(p))).map((p) => addSlice(lunr, p.docs, p.twins)); + const { merged, totals } = mergeSlices(lanes.map((l) => l.added)); + const sab = packTotals(totals); + const vectors = lanes.map((l, s) => sliceVectors(lunr, l.state, unpackTotals(sab, s))); + assert.equal(assembleIndexJson(lunr, vectors, invertedIndexJson(merged)), reference); + }); + + // As the build plans it: the entries stay where the render lanes packed + // them, chunk by chunk, and a slice says where its entries are and what the + // main thread decided about them since (planIndexSegments, sliceDocs). Some + // entries the lanes sent were dropped, so a run of a chunk skips them. + test("from the chunks the render lanes packed it is lunr()'s, byte for byte", () => { + const entries = Object.entries(docs).map(([id, doc]) => ({ ...doc, i: Number(id), url: `/base${doc.relUrl}` })); + // Chunks of uneven sizes, one of them empty, with an entry that was + // dropped after every third kept one and at both ends of a chunk. + const dropped = { doc: "Dropped", title: "gone", content: "never indexed", url: "/base/gone", relUrl: "/gone" }; + const sizes = [1, 0, 17, 40, 2, 60]; + const sent = []; + const places = []; + let n = 0; + for (const size of sizes) { + const chunk = [dropped]; + for (let k = 0; k < size; k++, n++) { + places.push([sent.length, chunk.length]); + chunk.push(entries[n]); + if (n % 3 === 2) chunk.push(dropped); + } + chunk.push(dropped); + sent.push(chunk); + } + assert.equal(n, entries.length); + const packed = sent.map(packSearchEntries); + const read = (chunk, from, to) => readSearchEntries(packed[chunk], from, to); + const twins = [...stemTwins(lunr, entries)]; + assert.deepEqual(twins, [...stemTwins(lunr, docs)]); + + for (const count of [1, 4, 9, 119]) { + const plan = planIndexSegments(entries, places, count).map((p) => JSON.parse(JSON.stringify(p))); + assert.equal(plan.length, count); + // Every entry once, in order, under its own number, as the file holds it. + const readBack = Object.assign({}, ...plan.map((p) => sliceDocs(p, read))); + assert.deepEqual(Object.keys(readBack), Object.keys(docs)); + for (const id of Object.keys(docs)) assert.deepEqual(readBack[id], { ...docs[id], url: entries[id].url }); + const lanes = plan.map((p) => addSlice(lunr, sliceDocs(p, read), twins)); + const { merged, totals } = mergeSlices(lanes.map((l) => l.added)); + const sab = packTotals(totals); + const vectors = lanes.map((l, s) => sliceVectors(lunr, l.state, unpackTotals(sab, s))); + assert.equal(assembleIndexJson(lunr, vectors, invertedIndexJson(merged)), reference, `${count} slices`); + } + }); + + test("the build's slices are cut where planIndexSlices cuts them", () => { + const entries = Object.values(docs); + const places = entries.map((_, k) => [0, k]); + for (const count of [1, 2, 5, 37, 119, 120, 500]) { + const whole = planIndexSlices(lunr, docs, count); + const segments = planIndexSegments(entries, places, count); + assert.deepEqual( + segments.map((p) => [p.first, p.segments]), + whole.map((p) => { + const ids = Object.keys(p.docs).map(Number); + return [ids[0], [[0, ids[0], ids.at(-1) + 1]]]; + }), + ); + } + assert.deepEqual(planIndexSegments([], [], 4), [{ slice: 0, first: 0, segments: [], dropped: [], late: {} }]); + }); + + test("the slices hold every entry once, in order, none of them empty", () => { + const ids = Object.keys(docs); + for (const count of [1, 2, 5, 37, 119, 120, 500]) { + const plan = planIndexSlices(lunr, docs, count); + assert.equal(plan.length, Math.min(count, ids.length)); + assert.deepEqual( + plan.flatMap((p) => Object.keys(p.docs)), + ids, + ); + assert.ok(plan.every((p) => Object.keys(p.docs).length > 0)); + } + }); + + test("an index loaded from it answers as lunr()'s does", () => { + const loaded = lunr.Index.load(JSON.parse(buildIndexJson(docs, { slices: 3 }))); const built = buildIndex(lunr, docs); for (const q of ["form", "f*", "window print", "1", "h80004005", "loop", "printer.font", "onlylast119"]) { assert.deepEqual( @@ -111,12 +209,6 @@ describe("the split build is lunr()'s", () => { ); } }); - - test("a thread that fails fails the build", async () => { - // Only a thread reads `index` (indexField()), and a string has no map(). - const broken = { ...docs, 119: { ...docs[119], index: "not a list" } }; - await assert.rejects(buildIndexJson(broken, { workers: 2 }), /search index worker: TypeError/); - }); }); describe("the files the build writes", () => { @@ -139,9 +231,11 @@ describe("the files the build writes", () => { assert.deepEqual(window.SEARCH_INDEX, JSON.parse(text)); }); - test("a site of a few hundred entries starts no thread", () => { - assert.equal(defaultIndexWorkers(10), 1); - assert.equal(defaultIndexWorkers(499), 1); - assert.ok(defaultIndexWorkers(12000) >= 1 && defaultIndexWorkers(12000) <= 8); + test("a site of a few hundred entries is one slice, a larger one a few for each lane", () => { + assert.equal(indexSliceCount(10, 16), 1); + assert.equal(indexSliceCount(499, 4), 1); + assert.equal(indexSliceCount(1500, 4), 3); + assert.equal(indexSliceCount(13000, 4), 8); + assert.equal(indexSliceCount(13000, 64), 26); }); }); diff --git a/test/search.test.mjs b/test/search.test.mjs index 91de7d900..57775bf39 100644 --- a/test/search.test.mjs +++ b/test/search.test.mjs @@ -21,12 +21,19 @@ import path from "node:path"; import os from "node:os"; import { checkIndexTerms, + consolidateSearchEntries, deriveSearchEntries, + entryKeys, joinSymbolsToEntries, + labelKey, + packSearchEntries, parseIndexTerms, + readSearchEntries, renderEntryString, + searchDataBytes, + searchDocs, settleLabels, - writeSearchDataFromChunks, + writeSearchData, } from "../builder/search.mjs"; import { createMarkdownIt } from "../builder/render.mjs"; import { parseFrontmatter } from "../lib/frontmatter.mjs"; @@ -1910,24 +1917,155 @@ describe("settleLabels: what the bold labels come to", () => { { ...e("Add Reference", "/p#term:add-reference"), i: 1 }, { ...e("B", "/p#b"), i: 2, labels: ["New Thing"] }, ]; - const { json, entries } = await writeSearchDataFromChunks([chunk], dir, []); + const packed = [packSearchEntries(chunk)]; + const settled = consolidateSearchEntries([chunk], []); + const { json, entries } = await writeSearchData(settled, packed, dir); assert.equal(entries, 2); - assert.doesNotMatch(json, /labels/); - assert.deepEqual(Object.keys(JSON.parse(json)), ["0", "1"]); + assert.doesNotMatch(String(json), /labels/); + assert.deepEqual(Object.keys(JSON.parse(String(json))), ["0", "1"]); + assert.equal(fs.readFileSync(path.join(dir, "assets/js/search-data.json"), "utf8"), String(json)); const plain = [ { ...e("A", "/p#a"), i: 0 }, { ...e("B", "/p#b"), i: 1 }, ]; const before = plain.map(renderEntryString).join(","); - const after = await writeSearchDataFromChunks([plain.map((x) => ({ ...x }))], dir, []); - assert.equal(after.json, `{${before}\n}\n`); + const copy = plain.map((x) => ({ ...x })); + const after = await writeSearchData(consolidateSearchEntries([copy], []), [packSearchEntries(copy)], dir); + assert.equal(String(after.json), `{${before}\n}\n`); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); + // The labels reach the main thread in the keys (entryKeys' `written`), beside + // the entries, which hold none. test("the worker sends the labels to the main thread", () => { - assert.match(read("builder/cpu-worker.mjs"), /labels: e\.labels,/); + const worker = read("builder/cpu-worker.mjs"); + assert.match(worker, /const searchKeys = derived\.map\(\(e\) => entryKeys\(e, key\)\);/); + assert.match(worker, /searchEntries,\r?\n\s+searchKeys,/); + assert.deepEqual(entryKeys(e("T", "/p", { labels: ["Copy Path"] })).written, ["Copy Path"]); + }); + + // The render lanes work the keys out (entryKeys) and the main thread only + // compares them: the outcome must be what settleLabels makes on its own. + test("with the keys a lane worked out, the outcome is the same", () => { + const make = () => [ + e("Find & Replace", "/p#find", { index: ["Debug-Console"], index_also: ["call stack"] }), + e("Debug Console", "/p#term:debug-console"), + e("Menu Item", "/p#term:menu-item", { labels: ["Sub Item"] }), + e("Holder", "/p#h", { + doc: "Status Bar", + labels: ["find replace", "Call Stack", "Sub Item", "Status bar", "New"], + }), + e("Other", "/p#o", { labels: ["Menu item", "Straße Neu"], index_also: ["kept"] }), + ]; + const alone = settleLabels(make()); + // As a lane sends them: the keys apart, and no `labels` on an entry. + const sent = make().map(({ labels: _labels, ...x }) => x); + const keyed = settleLabels( + sent, + make().map((x) => entryKeys(x)), + ); + assert.deepEqual(keyed, alone); + assert.ok(alone.every((x) => !("labels" in x))); + assert.deepEqual(alone.find((x) => x.title === "Holder").index_also, ["New"]); + assert.deepEqual(alone.find((x) => x.title === "Other").index_also, ["kept", "Straße Neu"]); + assert.equal(labelKey("Find & Replace"), "find replace"); + // Through consolidateSearchEntries, chunk by chunk. + const chunked = consolidateSearchEntries( + [sent.slice(0, 2), sent.slice(2)], + [], + [ + make() + .slice(0, 2) + .map((x) => entryKeys(x)), + make() + .slice(2) + .map((x) => entryKeys(x)), + ], + ); + assert.deepEqual( + chunked.entries.map(({ i: _i, ...x }) => x), + alone, + ); + assert.throws(() => consolidateSearchEntries([sent], [], [[]]), /5 entries came with the settle keys of 0/); + }); +}); + +// The entries between the threads (search.mjs, "Between the lanes"): the lane +// that renders a chunk packs its entries' text once, the main thread copies it +// into search-data.json around what it decided since, and the search index's +// lanes read their entries from it. All three must hold what the entries hold. +describe("packed entries: one text for the file and for the index's lanes", () => { + const entry = (n, extra = {}) => ({ + doc: `Page ${n % 3} \u{2014} "quoted"`, + title: n % 4 === 0 ? "" : `Title ${n} \u{df}`, + content: n % 5 === 0 ? "" : `Text ${n} \\ back\u{2028}slash & \u{1F600} `, + url: `/base/P%20${n}#s`, + relUrl: `/P ${n}#s${n % 7 === 3 ? "term:x" : ""}`, + ...extra, + }); + // Three chunks, one of them empty, with index terms, labels and a term entry + // that a main term drops. + const chunks = () => [ + [entry(0, { index: ["Alpha Beta"] }), entry(1), entry(2, { labels: ["New Thing"], index_also: ["gamma"] })], + [], + [ + { ...entry(3), title: "alpha beta", relUrl: "/P 3#term:alpha-beta" }, + entry(4, { labels: ["Other One"] }), + entry(5), + entry(6), + ], + ]; + const symbols = [ + { name: "Left", container: "Strings", kind: "function", url: "/P 1#s" }, + { name: "Strings", container: null, kind: "module", url: "/P 1#s" }, + { name: "Caf\u{e9}", container: "T", kind: "property", url: "/P 5#s" }, + ]; + + test("search-data.json is each entry as renderEntryString writes it", () => { + const sent = chunks(); + const packed = sent.map(packSearchEntries); + const { entries, places } = consolidateSearchEntries(sent, symbols); + assert.equal(entries.length, 6, "the term entry a main term answers is dropped"); + assert.deepEqual(places, [ + [0, 0], + [0, 1], + [0, 2], + [2, 1], + [2, 2], + [2, 3], + ]); + const text = String(searchDataBytes(entries, places, packed)); + assert.equal(text, `{${entries.map(renderEntryString).join(",")}\n}\n`); + assert.match(text, /"names": "Left Strings"/); + assert.match(text, /"index_also": \["gamma","New Thing"\]/); + // And the entries the index's file holds are the file's, in its order. + assert.equal(JSON.stringify(searchDocs(entries)), JSON.stringify(JSON.parse(text))); + }); + + test("no entry at all is an empty object", () => { + const { entries, places } = consolidateSearchEntries([[]], []); + assert.equal(String(searchDataBytes(entries, places, [packSearchEntries([])])), "{\n}\n"); + }); + + test("a lane reads back the fields a page's render knows, for any run of a chunk", () => { + const sent = chunks()[2]; + const sab = packSearchEntries(sent); + assert.ok(sab instanceof SharedArrayBuffer); + const fields = ({ doc, title, content, url, relUrl }) => ({ doc, title, content, url, relUrl }); + assert.deepEqual(readSearchEntries(sab), sent.map(fields)); + assert.deepEqual(readSearchEntries(sab, 1, 3), sent.slice(1, 3).map(fields)); + assert.deepEqual(readSearchEntries(sab, 3, 4), sent.slice(3).map(fields)); + assert.deepEqual(readSearchEntries(sab, 2, 2), []); + assert.deepEqual(readSearchEntries(packSearchEntries([])), []); + assert.throws(() => readSearchEntries(sab, 2, 5), /not within the chunk's 4/); + }); + + test("a chunk that never arrived is refused, not left out", () => { + const holes = new Array(2); + holes[0] = chunks()[0]; + assert.throws(() => consolidateSearchEntries(holes, []), /1 of 2 chunks never arrived/); }); });