From defddab41957a97e123bb7cde4f6c55f312f6e00 Mon Sep 17 00:00:00 2001 From: avivkeller Date: Sat, 28 Nov 2026 11:31:43 -0700 Subject: [PATCH] feat: incremental building --- .changeset/experimental-incremental.md | 7 + docs/cli.md | 3 + docs/configuration.md | 7 + docs/creating-generators.md | 84 ++++ e2e/incremental-build.spec.js | 166 +++++++ packages/cli/bin/commands/generate.mjs | 5 + packages/core/package.json | 1 + .../core/src/__tests__/generators.test.mjs | 86 ++++ packages/core/src/generators.mjs | 17 +- packages/core/src/generators/ast/generate.mjs | 18 +- .../json/__tests__/generate.test.mjs | 99 ++++- .../core/src/generators/json/generate.mjs | 51 ++- packages/core/src/generators/json/index.mjs | 4 +- .../core/src/generators/metadata/generate.mjs | 21 +- .../core/src/generators/metadata/types.d.ts | 3 +- packages/core/src/generators/types.d.ts | 13 +- .../src/incremental/__tests__/hash.test.mjs | 62 +++ .../src/incremental/__tests__/index.test.mjs | 408 +++++++++++++++++ .../incremental/__tests__/manifest.test.mjs | 109 +++++ packages/core/src/incremental/constants.mjs | 15 + packages/core/src/incremental/hash.mjs | 95 ++++ packages/core/src/incremental/index.mjs | 96 ++++ packages/core/src/incremental/manifest.mjs | 127 ++++++ packages/core/src/incremental/section.mjs | 416 ++++++++++++++++++ packages/core/src/incremental/types.d.ts | 89 ++++ .../src}/utils/__tests__/channel.test.mjs | 0 .../jsx-ast => core/src}/utils/channel.mjs | 0 .../configuration/__tests__/index.test.mjs | 2 + .../core/src/utils/configuration/index.mjs | 2 + .../core/src/utils/configuration/types.d.ts | 3 + packages/core/src/utils/file.mjs | 7 + packages/react/src/html/README.md | 25 +- .../src/html/__tests__/generate.test.mjs | 247 ++++++++++- packages/react/src/html/bundlers/vite.mjs | 7 +- packages/react/src/html/generate.mjs | 95 +++- packages/react/src/html/index.mjs | 12 + packages/react/src/html/types.d.ts | 3 + packages/react/src/jsx-ast/generate.mjs | 16 +- packages/react/src/jsx-ast/utils/merge.mjs | 2 +- scripts/benchmark-incremental.mjs | 121 +++++ scripts/comparators/files.mjs | 4 +- 41 files changed, 2487 insertions(+), 61 deletions(-) create mode 100644 .changeset/experimental-incremental.md create mode 100644 e2e/incremental-build.spec.js create mode 100644 packages/core/src/incremental/__tests__/hash.test.mjs create mode 100644 packages/core/src/incremental/__tests__/index.test.mjs create mode 100644 packages/core/src/incremental/__tests__/manifest.test.mjs create mode 100644 packages/core/src/incremental/constants.mjs create mode 100644 packages/core/src/incremental/hash.mjs create mode 100644 packages/core/src/incremental/index.mjs create mode 100644 packages/core/src/incremental/manifest.mjs create mode 100644 packages/core/src/incremental/section.mjs create mode 100644 packages/core/src/incremental/types.d.ts rename packages/{react/src/jsx-ast => core/src}/utils/__tests__/channel.test.mjs (100%) rename packages/{react/src/jsx-ast => core/src}/utils/channel.mjs (100%) create mode 100644 scripts/benchmark-incremental.mjs diff --git a/.changeset/experimental-incremental.md b/.changeset/experimental-incremental.md new file mode 100644 index 000000000..9309da3de --- /dev/null +++ b/.changeset/experimental-incremental.md @@ -0,0 +1,7 @@ +--- +'@doc-kit/cli': minor +'@doc-kit/core': minor +'@doc-kit/generator-react': minor +--- + +Add `doc-kit generate --experimental-incremental` diff --git a/docs/cli.md b/docs/cli.md index 36b76e280..f378f2f97 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -62,6 +62,9 @@ parentheses. **Default:** the number of CPUs, up to 6 (`1` on riscv64). - `--chunk-size ` {number} Items each worker processes per task, at least 1 (`chunkSize`). **Default:** `10`. +- `--experimental-incremental` {boolean} Reuse the previous build's output, + rebuilding only what changed (`experimentalIncremental`). **Default:** + `false`. **Experimental.** ```bash # Build everything the configuration file describes diff --git a/docs/configuration.md b/docs/configuration.md index 7b52af6db..ba31e429d 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -186,6 +186,13 @@ These sit at the top level, next to `target` and `global`: - `discardResults` {boolean} Keep none of the requested generators' results, so each can be let go as soon as it's produced. `doc-kit generate` and `doc-kit preview` set it. **Default:** `false`. +- `experimentalIncremental` {boolean} Reuse the previous build's output: the + generators that support it only rebuild what changed, leave the other files + untouched, and remove the files whose sources are gone. The state is stored + in `/.doc-kit/`, which is about as large as the output and + shouldn't be deployed. After an interrupted build, every file is written + again. **Default:** `false`. **Experimental:** the option and the + directory's format may change. Each worker's heap is limited to 512 MB. If a build runs out of memory, lower `threads`, or raise the limit by running Node.js with `--max-old-space-size`, diff --git a/docs/creating-generators.md b/docs/creating-generators.md index 6de55a95c..4bdb0d7e6 100644 --- a/docs/creating-generators.md +++ b/docs/creating-generators.md @@ -203,6 +203,90 @@ await cp(new URL('./assets', import.meta.url), join(output, 'assets'), { }); ``` +### Incremental builds + +With [`experimentalIncremental`](./configuration.md#execution-options) on, a +generator can skip the items that haven't changed since the previous build. +`generate` receives a third argument for this, with an `incremental` property. + +A generator that produces one result per item, for other generators to read, +uses `reuse`: + +```mjs displayName="generate.mjs" +export async function* generate(entries, worker, { incremental }) { + // `stale` holds the entries that changed. Results for the others are + // loaded from the previous build, and all results are yielded in order + yield* incremental.reuse(entries, stale => worker.stream(stale)); +} +``` + +A generator that only writes files uses `partition`: + +```mjs displayName="generate.mjs" +import { join } from 'node:path'; + +import getConfig from '@doc-kit/core/utils/configuration/index.mjs'; +import { writeFile } from '@doc-kit/core/utils/file.mjs'; + +export async function generate(entries, worker, { incremental }) { + const { output } = getConfig('my-format'); + + // `files` returns the file, or files, an entry is written to + const { stale } = incremental.partition(entries, { + files: entry => `${entry.api}.txt`, + }); + + for (const entry of stale) { + await writeFile(join(output, `${entry.api}.txt`), render(entry)); + } +} +``` + +In both cases, files and results from the previous build that this build +doesn't use are removed when it finishes. + +Each item has a key: a hash of its JSON and of the generator's configuration, +so changing the configuration rebuilds everything. A result of `reuse` is +hashed by the key it was stored under instead of by its content, so whatever +is built from it is rebuilt whenever it is. The generator object can adjust +the key under `incremental`: + +- `key` {Function} Returns what to hash for an item instead of the item + itself: one value or an array. Strings and bytes are hashed as they are, + other values as JSON. +- `omit` {string[]} Configuration keys that don't affect the output, such as + paths. `input`, `output`, `ignore` and `pathsToCopy` are always omitted. +- `salt` {Array} Extra values to hash into every key, such as a format + version. + +`incremental` has these methods: + +- `reuse(items, make[, options])` yields one result per item, in order, as + arrays. `items` is an array, or an async iterable of arrays. `make` receives + the stale items as an async iterable of arrays and yields one result for + each, in order. Results are stored in `/.doc-kit/`, so they must be + [structured-cloneable](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm). + `options.key` overrides the declared `key`. A generator that already writes + each result to its own file can pass `options.file`, which returns that + file for an item, and `options.read`, which reads a result from it, so the + result isn't stored twice. +- `partition(items, options)` splits the items into `{ fresh, stale }`. + `options.files` returns the file or files an item is written to, and + `options.key` overrides the declared `key`. +- `record(label, ...files)` tracks files that don't belong to an item, such as + assets, so they aren't removed. +- `salt(compute)` hashes values computed at run time into every key, such as + the hash of a built bundle. Call it before the first `reuse` or `partition`. +- `digest(...parts)` hashes values into a string that a `key` function can + return later, without holding on to the values. + +When the option is off, or the generator has no `output`, every item is stale +and nothing is stored or removed, so a generator doesn't need a separate code +path. + +Keys don't cover code. After changing a generator or a plugin, or upgrading +doc-kit, delete `/.doc-kit/` to rebuild everything. + ## Worker threads For heavy work on many independent items, give the generator a diff --git a/e2e/incremental-build.spec.js b/e2e/incremental-build.spec.js new file mode 100644 index 000000000..a504a9304 --- /dev/null +++ b/e2e/incremental-build.spec.js @@ -0,0 +1,166 @@ +import { execFile } from 'node:child_process'; +import { + appendFile, + mkdir, + mkdtemp, + readdir, + readFile, + rm, + stat, + writeFile, +} from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { dirname, join, relative } from 'node:path'; +import { promisify } from 'node:util'; + +import { expect, test } from '@playwright/test'; + +const CLI = join(import.meta.dirname, '../packages/cli/bin/cli.mjs'); + +const DOCUMENTS = { + fs: '# File system\n\nReads and writes files.\n', + path: '# Path\n\nWorks with file paths.\n', + zlib: '# Zlib\n\nCompresses and decompresses.\n', +}; + +// Each test runs the real CLI, worker threads included, against the output +// the previous test left +test.describe.configure({ mode: 'serial' }); + +test.describe('Incremental builds', () => { + let root; + let input; + let output; + + /** + * Runs an incremental build of the site, with `all.html`, and its JSON. + */ + const build = () => + promisify(execFile)(process.execPath, [ + CLI, + 'generate', + ...['-t', 'html', '-t', 'html-all', '-t', 'json'], + ...['-i', join(input, '*.md')], + ...['-o', output], + '--experimental-incremental', + ]); + + /** + * The modification time of every page and JSON document, by path. Client + * assets are excluded, as they are written on every build. + */ + const builtFiles = async () => { + const entries = await readdir(output, { + recursive: true, + withFileTypes: true, + }); + + const files = entries + .filter(entry => entry.isFile()) + .map(entry => relative(output, join(entry.parentPath, entry.name))) + .filter(file => /^[^./][^/]*\.(html|json)$/.test(file)); + + return Object.fromEntries( + await Promise.all( + files + .toSorted() + .map(async file => [file, (await stat(join(output, file))).mtimeMs]) + ) + ); + }; + + /** + * The files whose modification time differs between two builds. + */ + const changedBetween = (before, after) => + Object.keys(after).filter(file => after[file] !== before[file]); + + test.beforeAll(async () => { + root = await mkdtemp(join(tmpdir(), 'doc-kit-incremental-e2e-')); + input = join(root, 'docs'); + output = join(root, 'out'); + + await mkdir(input); + + for (const [name, content] of Object.entries(DOCUMENTS)) { + await writeFile(join(input, `${name}.md`), content); + } + + await build(); + }); + + test.afterAll(() => rm(root, { recursive: true, force: true })); + + test('leaves every file alone when nothing changed', async () => { + const before = await builtFiles(); + + expect(Object.keys(before)).toEqual([ + '404.html', + 'all.html', + 'fs.html', + 'fs.json', + 'path.html', + 'path.json', + 'zlib.html', + 'zlib.json', + ]); + + await build(); + + expect(await builtFiles()).toEqual(before); + }); + + test('rewrites only the files an edited document is part of', async () => { + const before = await builtFiles(); + + await appendFile(join(input, 'fs.md'), '\nWatches them, too.\n'); + await build(); + + const after = await builtFiles(); + + expect(changedBetween(before, after)).toEqual([ + 'all.html', + 'fs.html', + 'fs.json', + ]); + expect(await readFile(join(output, 'fs.html'), 'utf-8')).toContain( + 'Watches them, too.' + ); + }); + + test('removes the files of a deleted document, and nothing the pages need', async () => { + await writeFile(join(output, 'mine.txt'), 'not doc-kit’s'); + + await rm(join(input, 'zlib.md')); + await build(); + + const after = await builtFiles(); + + expect(Object.keys(after)).toEqual([ + '404.html', + 'all.html', + 'fs.html', + 'fs.json', + 'path.html', + 'path.json', + ]); + await expect(stat(join(output, 'mine.txt'))).resolves.toBeDefined(); + + // Every asset a page loads still exists + for (const page of Object.keys(after).filter(file => + file.endsWith('.html') + )) { + const html = await readFile(join(output, page), 'utf-8'); + const assets = html.matchAll(/(?:src|href)="([^"]*assets\/[^"]+)"/g); + + for (const [, asset] of assets) { + const path = join(output, dirname(page), asset); + + await expect( + stat(path), + `${page} loads ${asset}` + ).resolves.toBeDefined(); + } + } + }); +}); diff --git a/packages/cli/bin/commands/generate.mjs b/packages/cli/bin/commands/generate.mjs index d58a4facf..53701d9e2 100644 --- a/packages/cli/bin/commands/generate.mjs +++ b/packages/cli/bin/commands/generate.mjs @@ -25,6 +25,7 @@ const { runGenerators } = createGenerator(); * @property {string} index * @property {boolean} minify * @property {string} typeMap + * @property {boolean} experimentalIncremental */ /** @@ -53,6 +54,10 @@ export const generateOptions = [ new Option('--index ', 'index.md URL or path'), new Option('--minify', 'Minify?'), new Option('--type-map ', 'Type map URL or path'), + new Option( + '--experimental-incremental', + 'Rebuild only what changed since the previous build (experimental)' + ), ]; const generate = new Command('generate').description('Generate API docs'); diff --git a/packages/core/package.json b/packages/core/package.json index 8da82c45e..9f82fe501 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -34,6 +34,7 @@ }, "imports": { "#generators/*": "./src/generators/*", + "#incremental/*": "./src/incremental/*", "#logger/*": "./src/logger/*", "#parsers/*": [ "./src/parsers/*", diff --git a/packages/core/src/__tests__/generators.test.mjs b/packages/core/src/__tests__/generators.test.mjs index eeb08418d..2ad720a31 100644 --- a/packages/core/src/__tests__/generators.test.mjs +++ b/packages/core/src/__tests__/generators.test.mjs @@ -1,6 +1,13 @@ import assert from 'node:assert/strict'; +import { existsSync } from 'node:fs'; +import { mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; import { describe, it, mock, beforeEach } from 'node:test'; +import { loadManifest, manifestPath } from '../incremental/manifest.mjs'; +import { DISABLED_SECTION } from '../incremental/section.mjs'; + // Tracks how many times each synthetic generator actually executed so we can // assert that a shared dependency runs exactly once even after its result is // evicted from the cache once its last consumer has read it. @@ -162,6 +169,25 @@ const syntheticGenerators = { return { chunks }; }, }, + // A generator recording an output through the incremental section it is + // handed, and one failing after it + 'gen-record': { + name: 'gen-record', + dependsOn: 'metadata', + generate: async (input, worker, { incremental }) => { + record('gen-record'); + incremental.record('recorded', 'recorded.txt'); + return { disabled: incremental === DISABLED_SECTION }; + }, + }, + 'gen-fail': { + name: 'gen-fail', + dependsOn: 'metadata', + generate: async () => { + record('gen-fail'); + throw new Error('boom'); + }, + }, }; mock.module('../generators/loader.mjs', { @@ -376,4 +402,64 @@ describe('createGenerator orchestration', () => { assert.equal(results, undefined); }); + + describe('incremental building', () => { + const createOutput = async context => { + const output = await mkdtemp(join(tmpdir(), 'doc-kit-orchestrator-')); + context.after(() => rm(output, { recursive: true, force: true })); + + return output; + }; + + it('gives each generator its section and saves the manifest after every target finishes', async context => { + const output = await createOutput(context); + const { runGenerators } = createGenerator(); + + const results = await runGenerators({ + target: ['gen-record'], + threads: 1, + experimentalIncremental: true, + 'gen-record': { output }, + }); + + assert.deepStrictEqual(results, [{ disabled: false }]); + + const { manifest } = await loadManifest(output); + assert.deepStrictEqual(manifest.generators['gen-record'], { + recorded: ['recorded.txt'], + }); + }); + + it('writes no manifest when a generator fails', async context => { + const output = await createOutput(context); + const { runGenerators } = createGenerator(); + + await assert.rejects( + runGenerators({ + target: ['gen-record', 'gen-fail'], + threads: 1, + experimentalIncremental: true, + 'gen-record': { output }, + 'gen-fail': { output }, + }), + /boom/ + ); + + assert.equal(existsSync(manifestPath(output)), false); + }); + + it('gives disabled sections and writes nothing without the flag', async context => { + const output = await createOutput(context); + const { runGenerators } = createGenerator(); + + const results = await runGenerators({ + target: ['gen-record'], + threads: 1, + 'gen-record': { output }, + }); + + assert.deepStrictEqual(results, [{ disabled: true }]); + assert.equal(existsSync(manifestPath(output)), false); + }); + }); }); diff --git a/packages/core/src/generators.mjs b/packages/core/src/generators.mjs index bc4242afc..4b2582850 100644 --- a/packages/core/src/generators.mjs +++ b/packages/core/src/generators.mjs @@ -6,6 +6,7 @@ import { resolveGeneratorSpecifier, } from './generators/loader.mjs'; import { resolvePipeline } from './generators/pipeline.mjs'; +import { createIncrementalStore } from './incremental/index.mjs'; import logger from './logger/index.mjs'; import createWorkerPool from './threading/index.mjs'; import createParallelWorker from './threading/parallel.mjs'; @@ -28,6 +29,9 @@ const createGenerator = () => { /** @type {import('piscina').Piscina} */ let pool; + /** @type {import('./incremental/types').IncrementalStore} */ + let incremental; + /** * Gets the input from a dependency generator, collected or streamed. * @@ -110,7 +114,12 @@ const createGenerator = () => { // Returned rather than awaited, so this function doesn't hold on to the // input while the generator runs, and the generator can let it go - return generate(dependencyInput, await worker); + return generate(dependencyInput, await worker, { + incremental: await incremental.section( + generator, + configuration[name] + ), + }); })().then(result => { // A streaming generator returns before it has produced anything, so // it isn't complete here @@ -159,6 +168,10 @@ const createGenerator = () => { // Create worker pool pool = createWorkerPool(threads); + incremental = createIncrementalStore({ + enabled: configuration.experimentalIncremental === true, + }); + // Schedule all generators for (const specifier of targets) { scheduleGenerator(specifier, generators, inputOf, configuration); @@ -169,6 +182,8 @@ const createGenerator = () => { const read = discardResults ? cache.drain : cache.consume; const collected = await Promise.all(targets.map(read)); + await incremental.save(); + await pool.destroy(); return discardResults ? undefined : collected; diff --git a/packages/core/src/generators/ast/generate.mjs b/packages/core/src/generators/ast/generate.mjs index 1044e3488..12e948334 100644 --- a/packages/core/src/generators/ast/generate.mjs +++ b/packages/core/src/generators/ast/generate.mjs @@ -1,10 +1,12 @@ 'use strict'; +import { readFileSync } from 'node:fs'; import { readFile } from 'node:fs/promises'; import { relative, sep } from 'node:path/posix'; import { parse as parseYaml } from 'yaml'; +import { DISABLED_SECTION } from '#incremental/section.mjs'; import getConfig from '#utils/configuration/index.mjs'; import { withExt } from '#utils/file.mjs'; import { findFiles, globParent } from '#utils/glob.mjs'; @@ -106,11 +108,16 @@ export async function processChunk(inputSlice, itemIndices) { } /** - * Generates AST trees from markdown input files. + * Generates AST trees from markdown input files. An incremental build only + * parses the files that changed. * * @type {import('./types').Generator['generate']} */ -export async function* generate(_, worker) { +export async function* generate( + _, + worker, + { incremental = DISABLED_SECTION } = {} +) { const { ast: config } = getConfig(); const files = config.input.flatMap(input => { @@ -122,7 +129,8 @@ export async function* generate(_, worker) { }); // Parse markdown files in parallel using worker threads - for await (const chunkResult of worker.stream(files)) { - yield chunkResult; - } + yield* incremental.reuse(files, stale => worker.stream(stale), { + /** @param {[string, string]} file */ + key: ([path, parent]) => [path, parent, readFileSync(path)], + }); } diff --git a/packages/core/src/generators/json/__tests__/generate.test.mjs b/packages/core/src/generators/json/__tests__/generate.test.mjs index 935e747aa..cbbdb2433 100644 --- a/packages/core/src/generators/json/__tests__/generate.test.mjs +++ b/packages/core/src/generators/json/__tests__/generate.test.mjs @@ -1,6 +1,8 @@ import assert from 'node:assert/strict'; -import { readFile } from 'node:fs/promises'; -import { basename } from 'node:path'; +import { existsSync } from 'node:fs'; +import { mkdtemp, readFile, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { basename, join } from 'node:path'; import { describe, it } from 'node:test'; import { fileURLToPath } from 'node:url'; @@ -8,11 +10,15 @@ import Ajv from 'ajv'; import { loadGenerator } from '#generators/loader.mjs'; import { parseApiDoc } from '#generators/metadata/utils/parse.mjs'; +import { createIncrementalStore } from '#incremental/index.mjs'; +import { setConfig } from '#utils/configuration/index.mjs'; import { findFiles } from '#utils/glob.mjs'; import { loadMarkdownPlugins } from '#utils/markdown/plugins.mjs'; import { getProcessor } from '#utils/markdown/processor.mjs'; import { QUERIES } from '#utils/queries/index.mjs'; +import { generate, processChunk } from '../generate.mjs'; +import json from '../index.mjs'; import schema from '../schema.json' with { type: 'json' }; import { buildDocument } from '../utils/document.mjs'; @@ -41,21 +47,30 @@ const dependencies = { const validate = new Ajv({ allErrors: true, strict: true }).compile(schema); /** - * Runs a fixture through the metadata stage and builds its document. + * The metadata entries of a fixture, as the `metadata` generator yields them. */ -const buildFixture = async name => { +const parseFixture = async (name, transform = source => source) => { const content = await readFile(new URL(name, fixtures), 'utf-8'); - // The AST stage links the stability prefix; mirror that - const source = content.replace( - QUERIES.stabilityIndexPrefix, - match => `[${match}](documentation.html#stability-index)` + return parseApiDoc( + { + path: `/${basename(name, '.md')}`, + tree: getProcessor('ast').parse(transform(content)), + }, + typeMap ); +}; - const path = `/${basename(name, '.md')}`; - const entries = parseApiDoc( - { path, tree: getProcessor('ast').parse(source) }, - typeMap +/** + * Runs a fixture through the metadata stage and builds its document. + */ +const buildFixture = async name => { + // The AST stage links the stability prefix; mirror that + const entries = await parseFixture(name, source => + source.replace( + QUERIES.stabilityIndexPrefix, + match => `[${match}](documentation.html#stability-index)` + ) ); return buildDocument(entries[0], entries, dependencies); @@ -284,4 +299,64 @@ describe('json', () => { ); }); }); + + describe('incremental building', () => { + /** + * Runs an incremental build of the fixtures into the output, through a + * worker that builds on this thread and notes which modules it was given. + */ + const build = async (names, output) => { + const built = []; + + const worker = { + async *stream(batches, dependencies) { + for await (const items of batches) { + built.push(...items.map(({ head }) => head.api)); + + yield await processChunk(items, [...items.keys()], dependencies); + } + }, + }; + + const store = createIncrementalStore({ enabled: true }); + const incremental = await store.section(json, { output }); + const entries = ( + await Promise.all(names.map(name => parseFixture(name))) + ).flat(); + + const documents = []; + + for await (const chunk of generate(entries, worker, { incremental })) { + documents.push(...chunk); + } + + await store.save(); + + return { documents: documents.map(({ id }) => id), built }; + }; + + it('builds only the changed modules, yields every document, and removes those of dropped modules', async context => { + const output = await mkdtemp(join(tmpdir(), 'doc-kit-json-')); + context.after(() => rm(output, { recursive: true, force: true })); + + await setConfig({ target: ['json'], output }); + + const first = await build(['module.md', 'misc.md'], output); + + assert.deepEqual(first, { + documents: ['module', 'misc'], + built: ['module', 'misc'], + }); + + // Nothing changed: the documents are read back, in the same order + const second = await build(['module.md', 'misc.md'], output); + + assert.deepEqual(second, { documents: ['module', 'misc'], built: [] }); + + const third = await build(['module.md'], output); + + assert.deepEqual(third, { documents: ['module'], built: [] }); + assert.equal(existsSync(join(output, 'misc.json')), false); + }); + }); }); diff --git a/packages/core/src/generators/json/generate.mjs b/packages/core/src/generators/json/generate.mjs index 6ce545eb8..f572632a5 100644 --- a/packages/core/src/generators/json/generate.mjs +++ b/packages/core/src/generators/json/generate.mjs @@ -2,9 +2,10 @@ import { join } from 'node:path'; +import { DISABLED_SECTION } from '#incremental/section.mjs'; import getConfig from '#utils/configuration/index.mjs'; import { GITHUB_BLOB_URL, populate } from '#utils/configuration/templates.mjs'; -import { withExt, writeJSON } from '#utils/file.mjs'; +import { readJSON, withExt, writeJSON } from '#utils/file.mjs'; import { groupNodesByModule } from '#utils/generators.mjs'; import { buildDocument } from './utils/document.mjs'; @@ -24,11 +25,17 @@ export async function processChunk(slicedInput, itemIndices, dependencies) { } /** - * Generates one JSON document per input file. + * Generates one JSON document per input file. An incremental build only + * builds the modules that changed, and reads the other documents from the + * files the previous build wrote. * * @type {import('./types').Generator['generate']} */ -export async function* generate(input, worker) { +export async function* generate( + input, + worker, + { incremental = DISABLED_SECTION } = {} +) { const config = getConfig('json'); /** @type {import('./types').Dependencies} */ @@ -47,19 +54,33 @@ export async function* generate(input, worker) { entries: nodes, })); - for await (const chunk of worker.stream(modules, dependencies)) { - if (config.output) { - await Promise.all( - chunk.map(document => - writeJSON( - join(config.output, withExt(document.path, 'json')), - document, - config.minify + /** + * Builds the modules' documents and writes each to its file. + * + * @param {AsyncIterable | typeof modules} stale + * @yields {Array} + */ + async function* build(stale) { + for await (const chunk of worker.stream(stale, dependencies)) { + if (config.output) { + await Promise.all( + chunk.map(document => + writeJSON( + join(config.output, withExt(document.path, 'json')), + document, + config.minify + ) ) - ) - ); - } + ); + } - yield chunk; + yield chunk; + } } + + yield* incremental.reuse(modules, build, { + /** @param {(typeof modules)[number]} module */ + file: ({ head }) => withExt(head.path, 'json'), + read: readJSON, + }); } diff --git a/packages/core/src/generators/json/index.mjs b/packages/core/src/generators/json/index.mjs index 129869796..ab3a879d6 100644 --- a/packages/core/src/generators/json/index.mjs +++ b/packages/core/src/generators/json/index.mjs @@ -1,6 +1,6 @@ 'use strict'; -import { SCHEMA_URL } from './constants.mjs'; +import { SCHEMA_URL, SCHEMA_VERSION } from './constants.mjs'; import { generate, processChunk } from './generate.mjs'; /** @@ -22,6 +22,8 @@ export default { hasParallelProcessor: true, + incremental: { salt: [SCHEMA_VERSION] }, + markdown: { remarkPlugins: [ '#plugins/type-annotations/remark.mjs', diff --git a/packages/core/src/generators/metadata/generate.mjs b/packages/core/src/generators/metadata/generate.mjs index 7e7619c60..e744d73a0 100644 --- a/packages/core/src/generators/metadata/generate.mjs +++ b/packages/core/src/generators/metadata/generate.mjs @@ -1,5 +1,6 @@ 'use strict'; +import { DISABLED_SECTION } from '#incremental/section.mjs'; import getConfig from '#utils/configuration/index.mjs'; import { loadFromURL } from '#utils/loaders.mjs'; @@ -16,28 +17,40 @@ export async function processChunk(fullInput, itemIndices, typeMap) { const results = []; + // One list of entries per file, so each file's result can be stored for (const idx of itemIndices) { - results.push(...parseApiDoc(fullInput[idx], typeMap)); + results.push(parseApiDoc(fullInput[idx], typeMap)); } return results; } /** - * Generates a flattened list of metadata entries from API docs. + * Generates a flattened list of metadata entries from API docs. An + * incremental build only parses the trees that changed. * * @type {import('./types').Generator['generate']} */ -export async function* generate(inputs, worker) { +export async function* generate( + inputs, + worker, + { incremental = DISABLED_SECTION } = {} +) { const { metadata: config } = getConfig(); const typeMap = config.typeMap ? JSON.parse(await loadFromURL(config.typeMap)) : {}; + await incremental.salt(() => [typeMap]); + // Stream chunks as they complete - allows dependent generators // to start collecting/preparing while we're still processing - for await (const chunkResult of worker.stream(inputs, typeMap)) { + const entries = incremental.reuse(inputs, stale => + worker.stream(stale, typeMap) + ); + + for await (const chunkResult of entries) { yield chunkResult.flat(); } } diff --git a/packages/core/src/generators/metadata/types.d.ts b/packages/core/src/generators/metadata/types.d.ts index 966912e2c..4cc364f7b 100644 --- a/packages/core/src/generators/metadata/types.d.ts +++ b/packages/core/src/generators/metadata/types.d.ts @@ -4,7 +4,8 @@ import type { Position } from 'unist'; export type Generator = GeneratorMetadata< {}, Generate>, AsyncGenerator>, - ProcessChunk> + // One list of entries per file + ProcessChunk>, Record> >; /** diff --git a/packages/core/src/generators/types.d.ts b/packages/core/src/generators/types.d.ts index f158e1ec0..aee9257ef 100644 --- a/packages/core/src/generators/types.d.ts +++ b/packages/core/src/generators/types.d.ts @@ -41,9 +41,15 @@ declare global { */ export type Generate = ( input: I, - worker: ParallelWorker + worker: ParallelWorker, + context: GeneratorContext ) => O extends AsyncGenerator ? O : Promise; + // What the orchestrator passes to `generate` as its third argument + export type GeneratorContext = { + incremental: import('../incremental/types').IncrementalSection; + }; + /** * Type for the optional processChunk function of a generator * @template I - Input type @@ -77,6 +83,11 @@ declare global { */ streamsInput?: boolean; + /** + * How this generator's items are keyed in an incremental build + */ + incremental?: import('../incremental/types').IncrementalOptions; + /** * The unified plugins this generator processes Markdown with, listed as * in the `markdown` option, with paths relative to its module. Each list diff --git a/packages/core/src/incremental/__tests__/hash.test.mjs b/packages/core/src/incremental/__tests__/hash.test.mjs new file mode 100644 index 000000000..f20b4518c --- /dev/null +++ b/packages/core/src/incremental/__tests__/hash.test.mjs @@ -0,0 +1,62 @@ +'use strict'; + +import assert from 'node:assert/strict'; +import { mkdir, mkdtempDisposable, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { describe, it } from 'node:test'; + +import { hash, hashDirectory, trace } from '../hash.mjs'; + +describe('hash', () => { + it('gives a different hash when the same text is split differently', () => { + assert.notEqual(hash('ab', 'c'), hash('a', 'bc')); + assert.equal(hash('ab', 'c'), hash('ab', 'c')); + }); + + it('hashes bytes as they are, and other values as JSON', () => { + assert.equal(hash(Buffer.from('a')), hash('a')); + assert.equal(hash({ a: [1] }), hash('{"a":[1]}')); + assert.notEqual(hash({ a: 1 }), hash({ a: 2 })); + }); + + it('hashes a stored result, and the elements of a stored array, by key', () => { + const result = { content: 'a' }; + const list = [{ content: 'b' }]; + + trace(result, 'key'); + trace(list, 'list'); + + assert.equal(hash(result), hash('"key"')); + assert.equal(hash({ page: result }), hash('{"page":"key"}')); + assert.equal(hash(list[0]), hash('"list/0"')); + + // A copy is not the stored result + assert.notEqual(hash({ ...result }), hash(result)); + }); +}); + +describe('hashDirectory', () => { + it('depends on every path and byte', async () => { + await using directory = await mkdtempDisposable( + join(tmpdir(), 'doc-kit-hash-') + ); + + const { path } = directory; + + await mkdir(join(path, 'assets')); + await writeFile(join(path, 'library.mjs'), 'export {}'); + await writeFile(join(path, 'assets/chunk.mjs'), 'a'); + + const first = await hashDirectory(path); + + assert.equal(await hashDirectory(path), first); + + await writeFile(join(path, 'assets/chunk.mjs'), 'b'); + assert.notEqual(await hashDirectory(path), first); + + await writeFile(join(path, 'assets/chunk.mjs'), 'a'); + await writeFile(join(path, 'assets/other.mjs'), ''); + assert.notEqual(await hashDirectory(path), first); + }); +}); diff --git a/packages/core/src/incremental/__tests__/index.test.mjs b/packages/core/src/incremental/__tests__/index.test.mjs new file mode 100644 index 000000000..d232a51c7 --- /dev/null +++ b/packages/core/src/incremental/__tests__/index.test.mjs @@ -0,0 +1,408 @@ +'use strict'; + +import assert from 'node:assert/strict'; +import { existsSync } from 'node:fs'; +import { mkdtemp, readdir, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { describe, it } from 'node:test'; + +import { readJSON, writeFile, writeJSON } from '#utils/file.mjs'; + +import { SCHEMA, STATE_DIRECTORY } from '../constants.mjs'; +import { createIncrementalStore } from '../index.mjs'; +import { loadManifest, manifestPath, saveManifest } from '../manifest.mjs'; +import { DISABLED_SECTION } from '../section.mjs'; + +const createOutput = async context => { + const output = await mkdtemp(join(tmpdir(), 'doc-kit-incremental-')); + context.after(() => rm(output, { recursive: true, force: true })); + + return output; +}; + +const html = { name: 'html' }; + +const open = async (output, config = {}, generator = html) => { + const store = createIncrementalStore({ enabled: true }); + + return { + store, + section: await store.section(generator, { output, ...config }), + }; +}; + +const files = item => `${item.id}.html`; + +const write = async (output, items) => { + for (const item of items) { + await writeFile(join(output, files(item)), item.id); + } +}; + +/** + * Runs a build whose `reuse` makes an upper-cased copy of each item, and + * returns the items it was asked to make. + */ +const build = async (output, items, { generator = html, ...options } = {}) => { + const { store, section } = await open(output, {}, generator); + const made = []; + + const results = await Array.fromAsync( + section.reuse( + items, + async function* (stale) { + for await (const batch of stale) { + made.push(...batch); + + yield batch.map(item => ({ id: item.id.toUpperCase() })); + } + }, + options + ) + ); + + await store.save(); + + return { results: results.flat(), made, section }; +}; + +describe('createIncrementalStore', () => { + it('returns the disabled section when off or without an output', async context => { + const output = await createOutput(context); + const disabled = createIncrementalStore({ enabled: false }); + + assert.equal(await disabled.section(html, { output }), DISABLED_SECTION); + assert.equal( + await createIncrementalStore({ enabled: true }).section(html, {}), + DISABLED_SECTION + ); + + await disabled.save(); + assert.equal(existsSync(manifestPath(output)), false); + }); + + it('keeps the entries of generators that did not run, one manifest per output', async context => { + const output = await createOutput(context); + const other = await createOutput(context); + + await saveManifest(output, { + schema: SCHEMA, + generators: { json: { j: ['a.json'] }, html: { h: ['a.html'] } }, + }); + + const store = createIncrementalStore({ enabled: true }); + + (await store.section(html, { output })).record('x', 'b.html'); + (await store.section({ name: 'sitemap' }, { output })).record('x', 's.xml'); + (await store.section(html, { output: other })).record('x', 'c.html'); + + assert.equal( + await store.section(html, { output }), + await store.section(html, { output }) + ); + + await store.save(); + + assert.deepEqual((await loadManifest(output)).manifest.generators, { + json: { j: ['a.json'] }, + html: { x: ['b.html'] }, + sitemap: { x: ['s.xml'] }, + }); + assert.deepEqual((await loadManifest(other)).manifest.generators, { + html: { x: ['c.html'] }, + }); + assert.deepEqual(await readdir(join(output, STATE_DIRECTORY)), [ + 'manifest.json', + ]); + }); +}); + +describe('partition', () => { + it('treats an item as fresh when its key wrote files that still exist', async context => { + const output = await createOutput(context); + const a = { id: 'a' }; + const b = { id: 'b' }; + + const first = await open(output); + + assert.deepEqual(first.section.partition([a, b], { files }).stale, [a, b]); + await write(output, [a]); + await first.store.save(); + + const recorded = (await loadManifest(output)).manifest.generators.html; + + assert.deepEqual(Object.values(recorded).toSorted(), [ + ['a.html'], + ['b.html'], + ]); + assert.match(Object.keys(recorded)[0], /^[0-9a-f]{32}$/); + + // `b`'s file was recorded but never written + const second = await open(output); + + assert.deepEqual(second.section.partition([{ id: 'a' }, b], { files }), { + fresh: [{ id: 'a' }], + stale: [b], + }); + + // The same item keyed differently, or with its file gone, is stale + const third = await open(output); + + assert.deepEqual( + third.section.partition([a], { files, key: () => 'other' }).stale, + [a] + ); + + await rm(join(output, 'a.html')); + + const fourth = await open(output); + + assert.deepEqual(fourth.section.partition([a], { files }).stale, [a]); + }); + + it('salts keys with the configuration, minus omitted keys, and the computed parts', async context => { + const output = await createOutput(context); + const a = { id: 'a' }; + + const first = await open(output, { title: 'A', input: 'x' }); + await first.section.salt(() => ['run']); + first.section.partition([a], { files }); + await write(output, [a]); + await first.store.save(); + + /** + * Whether `a` is fresh under a configuration and a computed part. + */ + const isFresh = async (config, part) => { + const { section } = await open(output, config); + + await section.salt(() => [part]); + + return section.partition([a], { files }).fresh.length === 1; + }; + + assert.equal(await isFresh({ title: 'A', input: 'y' }, 'run'), true); + assert.equal(await isFresh({ title: 'B', input: 'x' }, 'run'), false); + assert.equal(await isFresh({ title: 'A', input: 'x' }, 'other'), false); + + await assert.rejects( + first.section.salt(() => []), + /salted after/ + ); + await DISABLED_SECTION.salt(() => assert.fail('computed')); + }); + + it('removes the files the previous build recorded and this one did not', async context => { + const output = await createOutput(context); + + for (const file of ['kept.html', 'stale.html', 'api/fs/old.html']) { + await writeFile(join(output, file), file); + } + + await writeFile(join(output, 'mine.txt'), 'not doc-kit’s'); + + await saveManifest(output, { + schema: SCHEMA, + generators: { + html: { + k: ['kept.html', 'stale.html'], + o: ['api/fs/old.html', 'missing.html'], + }, + }, + }); + + const { store, section } = await open(output); + + section.record('label', 'kept.html'); + await store.save(); + + assert.equal(existsSync(join(output, 'kept.html')), true); + assert.equal(existsSync(join(output, 'mine.txt')), true); + assert.equal(existsSync(join(output, 'stale.html')), false); + // The emptied directory is removed too + assert.equal(existsSync(join(output, 'api')), false); + + assert.deepEqual((await loadManifest(output)).manifest.generators.html, { + label: ['kept.html'], + }); + }); + + it('reuses no file from an interrupted build, but still removes them', async context => { + const output = await createOutput(context); + const a = { id: 'a' }; + const b = { id: 'b' }; + + const first = await open(output); + first.section.partition([a, b], { files }); + await write(output, [a, b]); + await first.store.save(); + + // Opened, and never saved + const interrupted = await open(output); + + assert.deepEqual(interrupted.section.partition([a, b], { files }).fresh, [ + a, + b, + ]); + + const next = await open(output); + + assert.deepEqual(next.section.partition([a], { files }).stale, [a]); + await next.store.save(); + + assert.equal(existsSync(join(output, 'a.html')), true); + assert.equal(existsSync(join(output, 'b.html')), false); + + // Once a build has finished, its output is reused again + const last = await open(output); + + assert.deepEqual(last.section.partition([a], { files }).fresh, [a]); + }); +}); + +describe('reuse', () => { + const a = { id: 'a' }; + const b = { id: 'b' }; + const c = { id: 'c' }; + + it('makes only what the previous build did not store, in input order', async context => { + const output = await createOutput(context); + + const first = await build(output, [a, c]); + + assert.deepEqual(first.made, [a, c]); + assert.deepEqual(first.results, [{ id: 'A' }, { id: 'C' }]); + + // As batches, a stale item between two fresh ones + const second = await build( + output, + (async function* () { + yield [a]; + yield [b, c]; + })() + ); + + assert.deepEqual(second.made, [b]); + assert.deepEqual(second.results, [{ id: 'A' }, { id: 'B' }, { id: 'C' }]); + }); + + it('removes stored results that are no longer used', async context => { + const output = await createOutput(context); + const stored = join(output, STATE_DIRECTORY, 'html'); + + await build(output, [a, b]); + assert.equal((await readdir(stored)).length, 2); + + await build(output, [a]); + assert.equal((await readdir(stored)).length, 1); + + await build(output, []); + assert.equal(existsSync(stored), false); + }); + + it('reuses the results an interrupted build stored', async context => { + const output = await createOutput(context); + + await build(output, [a]); + + // Makes `b`, and is never saved + const { section } = await open(output); + + await Array.fromAsync( + section.reuse([a, b], async function* (stale) { + for await (const batch of stale) { + yield batch.map(() => ({ id: 'B' })); + } + }) + ); + + assert.deepEqual((await build(output, [a, b])).made, []); + }); + + it('keys an item made from a result by the key the result was stored under', async context => { + const output = await createOutput(context); + const pages = { name: 'pages' }; + + /** + * Makes results from the items, then pages from the results, and returns + * the results that pages were made from. + */ + const run = async items => { + const { results } = await build(output, items); + + return (await build(output, results, { generator: pages })).made; + }; + + assert.deepEqual(await run([a, b]), [{ id: 'A' }, { id: 'B' }]); + assert.deepEqual(await run([a, b]), []); + + // A different item giving the same result: the page is still made again + assert.deepEqual(await run([a, { id: 'b', edited: true }]), [{ id: 'B' }]); + }); + + it('reads results from the files the generator wrote', async context => { + const output = await createOutput(context); + + /** + * Makes a document of each item, written to a file of its own. + */ + const run = async items => { + const { store, section } = await open(output); + const made = []; + + const documents = await Array.fromAsync( + section.reuse( + items, + async function* (stale) { + for await (const batch of stale) { + made.push(...batch); + + for (const { id } of batch) { + await writeJSON(join(output, `${id}.json`), { id }); + } + + yield batch.map(({ id }) => ({ id })); + } + }, + { file: item => `${item.id}.json`, read: readJSON } + ) + ); + + await store.save(); + + return { documents: documents.flat(), made }; + }; + + await run([a, b]); + + assert.deepEqual(await run([a, b]), { documents: [a, b], made: [] }); + assert.equal(existsSync(join(output, STATE_DIRECTORY, 'html')), false); + + // A file that is no longer made is removed + assert.deepEqual(await run([b]), { documents: [b], made: [] }); + assert.equal(existsSync(join(output, 'a.json')), false); + }); + + it('rethrows a failure in `make` after yielding the earlier results', async context => { + const output = await createOutput(context); + const { section } = await open(output); + const results = []; + + await assert.rejects(async () => { + const reused = section.reuse([a, b], async function* (stale) { + await Array.fromAsync(stale); + + yield [{ id: 'A' }]; + + throw new Error('boom'); + }); + + for await (const batch of reused) { + results.push(...batch); + } + }, /boom/); + + assert.deepEqual(results, [{ id: 'A' }]); + }); +}); diff --git a/packages/core/src/incremental/__tests__/manifest.test.mjs b/packages/core/src/incremental/__tests__/manifest.test.mjs new file mode 100644 index 000000000..fff4f18d7 --- /dev/null +++ b/packages/core/src/incremental/__tests__/manifest.test.mjs @@ -0,0 +1,109 @@ +'use strict'; + +import assert from 'node:assert/strict'; +import { mkdtemp, readdir, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { describe, it } from 'node:test'; + +import { writeFile } from '#utils/file.mjs'; + +import { SCHEMA } from '../constants.mjs'; +import { loadManifest, manifestPath, saveManifest } from '../manifest.mjs'; + +const createOutput = async context => { + const output = await mkdtemp(join(tmpdir(), 'doc-kit-manifest-')); + context.after(() => rm(output, { recursive: true, force: true })); + + return output; +}; + +const writeManifest = (output, content) => + writeFile(manifestPath(output), content); + +describe('loadManifest', () => { + it('treats a missing manifest as empty, with a reason', async context => { + const output = await createOutput(context); + const { manifest, reason } = await loadManifest(output); + + assert.deepEqual(manifest, { schema: SCHEMA, generators: {} }); + assert.match(reason, /no manifest/); + }); + + it('treats invalid JSON as empty', async context => { + const output = await createOutput(context); + await writeManifest(output, '{ not json'); + + const { manifest, reason } = await loadManifest(output); + + assert.deepEqual(manifest.generators, {}); + assert.match(reason, /cannot be read/); + }); + + it('treats a manifest listing files outside the output as empty', async context => { + const output = await createOutput(context); + + for (const outputs of [ + { k: ['../outside.html'] }, + { k: [join(tmpdir(), 'absolute.html')] }, + { k: ['.'] }, + { k: 'a.html' }, + ['a.html'], + ]) { + await writeManifest( + output, + JSON.stringify({ schema: SCHEMA, generators: { html: outputs } }) + ); + + const { manifest, reason } = await loadManifest(output); + + assert.deepEqual(manifest.generators, {}); + assert.match(reason, /malformed/); + } + }); + + it('keeps the files, not the keys, of an interrupted build', async context => { + const output = await createOutput(context); + + await saveManifest(output, { + schema: SCHEMA, + building: true, + generators: { html: { k: ['a.html'], o: ['b.html'] } }, + }); + + const { manifest, reason } = await loadManifest(output); + + assert.deepEqual(manifest.generators, { + html: { '': ['a.html', 'b.html'] }, + }); + assert.match(reason, /did not finish/); + }); + + it('treats another schema as empty', async context => { + const output = await createOutput(context); + await writeManifest(output, JSON.stringify({ schema: 0, generators: {} })); + + const { manifest, reason } = await loadManifest(output); + + assert.deepEqual(manifest.generators, {}); + assert.match(reason, /schema 0/); + }); + + it('reads back what was saved, leaving no temporary file', async context => { + const output = await createOutput(context); + const saved = { + schema: SCHEMA, + generators: { html: { k: ['a.html'] } }, + }; + + await saveManifest(output, saved); + + const { manifest, reason } = await loadManifest(output); + + assert.equal(reason, undefined); + assert.deepEqual(manifest, saved); + assert.deepEqual(await readdir(dirname(manifestPath(output))), [ + 'manifest.json', + ]); + }); +}); diff --git a/packages/core/src/incremental/constants.mjs b/packages/core/src/incremental/constants.mjs new file mode 100644 index 000000000..0fd510aa3 --- /dev/null +++ b/packages/core/src/incremental/constants.mjs @@ -0,0 +1,15 @@ +'use strict'; + +// Bump whenever the shape of what is stored changes +export const SCHEMA = 1; + +// Inside the output directory. Holds the manifest and each generator's +// stored results +export const STATE_DIRECTORY = '.doc-kit'; +export const MANIFEST_FILE = 'manifest.json'; + +// Hex characters kept from each sha256 digest (128 bits) +export const KEY_LENGTH = 32; + +// Global configuration keys that hold paths, excluded from every salt +export const SALT_CONFIG_OMIT = ['input', 'ignore', 'output', 'pathsToCopy']; diff --git a/packages/core/src/incremental/hash.mjs b/packages/core/src/incremental/hash.mjs new file mode 100644 index 000000000..fd780f3d1 --- /dev/null +++ b/packages/core/src/incremental/hash.mjs @@ -0,0 +1,95 @@ +'use strict'; + +import { createHash } from 'node:crypto'; +import { readFile } from 'node:fs/promises'; +import { join } from 'node:path'; + +import { findFiles } from '#utils/glob.mjs'; + +import { KEY_LENGTH } from './constants.mjs'; + +/** + * The key each stored result was stored under. That key already covers + * everything the result was built from, so it is hashed in place of the + * result's content. + * + * @type {WeakMap} + */ +const origins = new WeakMap(); + +/** + * @param {unknown} value + * @returns {value is object} + */ +const isObject = value => typeof value === 'object' && value !== null; + +/** + * Registers the key a result was stored under. Array elements are registered + * too, since generators often flatten their results. + * + * @param {unknown} result + * @param {string} key + */ +export const trace = (result, key) => { + if (!isObject(result)) { + return; + } + + origins.set(result, key); + + if (Array.isArray(result)) { + for (const [index, item] of result.entries()) { + if (isObject(item)) { + origins.set(item, `${key}/${index}`); + } + } + } +}; + +/** + * Serializes a value to JSON, replacing each stored result with its key. + * + * @param {unknown} value + * @returns {string} + */ +const stringify = value => + JSON.stringify(value, (_, nested) => origins.get(nested) ?? nested) ?? ''; + +/** + * Hashes strings and bytes as they are, and other values as JSON. + * + * @param {...unknown} parts + * @returns {string} The hex digest, {@link KEY_LENGTH} characters long + */ +export const hash = (...parts) => { + const hasher = createHash('sha256'); + + for (const part of parts) { + const data = + typeof part === 'string' || ArrayBuffer.isView(part) + ? part + : stringify(part); + + // Length-prefixed, so ('ab', 'c') and ('a', 'bc') hash differently + hasher.update(`${data.length}:`); + hasher.update(data); + } + + return hasher.digest('hex').slice(0, KEY_LENGTH); +}; + +/** + * Hashes every file under a directory, by relative path and content. + * + * @param {string} directory + * @returns {Promise} + */ +export const hashDirectory = async directory => { + const files = findFiles('**/*', { cwd: directory }).sort(); + + const contents = await Promise.all( + files.map(file => readFile(join(directory, file))) + ); + + return hash(...files.flatMap((file, index) => [file, contents[index]])); +}; diff --git a/packages/core/src/incremental/index.mjs b/packages/core/src/incremental/index.mjs new file mode 100644 index 000000000..229483daa --- /dev/null +++ b/packages/core/src/incremental/index.mjs @@ -0,0 +1,96 @@ +'use strict'; + +import { resolve } from 'node:path'; + +import logger from '#logger/index.mjs'; + +import { SCHEMA } from './constants.mjs'; +import { loadManifest, saveManifest } from './manifest.mjs'; +import { createSection, DISABLED_SECTION } from './section.mjs'; + +const incrementalLogger = logger.child('incremental'); + +/** + * Opens an output directory's manifest for a build. + * + * @param {string} output - The absolute output directory + * @returns {Promise<{ previous: import('./types').Manifest, sections: Map> }>} + */ +const openManifest = async output => { + const { manifest: previous, reason } = await loadManifest(output); + + if (reason) { + incrementalLogger.info(`${reason}; writing every file again`); + } else { + // Marked until this build saves its own manifest, because output files + // are about to be overwritten + await saveManifest(output, { ...previous, building: true }); + } + + return { previous, sections: new Map() }; +}; + +/** + * Creates the incremental state for a run: one manifest per output directory. + * + * @param {{ enabled: boolean }} options + * @returns {import('./types').IncrementalStore} + */ +export const createIncrementalStore = ({ enabled }) => { + /** @type {Map>} */ + const directories = new Map(); + + return { + /** @type {import('./types').IncrementalStore['section']} */ + async section(generator, config) { + if (!enabled || !config?.output) { + return DISABLED_SECTION; + } + + const { name } = generator; + const output = resolve(config.output); + + if (!directories.has(output)) { + directories.set(output, openManifest(output)); + } + + const { previous, sections } = await directories.get(output); + + if (!sections.has(name)) { + sections.set( + name, + createSection(generator, config, output, previous.generators[name]) + ); + } + + return (await sections.get(name)).section; + }, + + /** @type {import('./types').IncrementalStore['save']} */ + async save() { + for (const [output, opened] of directories) { + const { previous, sections } = await opened; + + // Generators that did not run keep their entries + const generators = { ...previous.generators }; + + for (const [name, section] of sections) { + const outputs = await (await section).close(); + + if (Object.keys(outputs).length > 0) { + generators[name] = outputs; + } else { + delete generators[name]; + } + } + + await saveManifest(output, { schema: SCHEMA, generators }); + + incrementalLogger.debug(`Saved manifest`, { + output, + generators: Object.keys(generators), + }); + } + }, + }; +}; diff --git a/packages/core/src/incremental/manifest.mjs b/packages/core/src/incremental/manifest.mjs new file mode 100644 index 000000000..60f792d10 --- /dev/null +++ b/packages/core/src/incremental/manifest.mjs @@ -0,0 +1,127 @@ +'use strict'; + +import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'; +import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'; + +import { isPlainObject } from '#utils/misc.mjs'; + +import { MANIFEST_FILE, SCHEMA, STATE_DIRECTORY } from './constants.mjs'; + +// Files from an interrupted build are listed under this key. No item hashes +// to it, so they can be removed but never reused +const UNKNOWN_KEY = ''; + +/** + * @param {string} output + * @returns {string} + */ +export const manifestPath = output => + join(resolve(output), STATE_DIRECTORY, MANIFEST_FILE); + +/** + * Whether a recorded file is inside the output directory. Files listed in the + * manifest can be deleted, so it must not list anything else. + * + * @param {string} output + * @param {unknown} file + * @returns {boolean} + */ +const isInside = (output, file) => { + if (typeof file !== 'string') { + return false; + } + + const path = relative(output, resolve(output, file)); + + return path !== '' && !isAbsolute(path) && path.split(sep)[0] !== '..'; +}; + +/** + * @param {string} output + * @param {unknown} manifest + * @returns {string | undefined} Why the manifest cannot be used + */ +const validate = (output, manifest) => { + if (manifest?.schema !== SCHEMA) { + return `has schema ${manifest?.schema}, expected ${SCHEMA}`; + } + + const wellFormed = + isPlainObject(manifest.generators) && + Object.values(manifest.generators).every( + outputs => + isPlainObject(outputs) && + Object.values(outputs).every( + files => + Array.isArray(files) && files.every(file => isInside(output, file)) + ) + ); + + return wellFormed ? undefined : 'is malformed'; +}; + +/** + * Reads a manifest. An unusable one is returned empty, with a `reason`. One + * from an interrupted build keeps its files, so they can be removed, but not + * their keys. + * + * @param {string} output + * @returns {Promise<{ manifest: import('./types').Manifest, reason?: string }>} + */ +export const loadManifest = async output => { + const path = manifestPath(output); + const empty = { schema: SCHEMA, generators: {} }; + + let manifest; + + try { + manifest = JSON.parse(await readFile(path, 'utf-8')); + } catch (error) { + return { + manifest: empty, + reason: + error.code === 'ENOENT' + ? `no manifest at ${path}` + : `${path} cannot be read (${error.message})`, + }; + } + + const invalid = validate(resolve(output), manifest); + + if (invalid) { + return { manifest: empty, reason: `${path} ${invalid}` }; + } + + if (manifest.building) { + const generators = Object.fromEntries( + Object.entries(manifest.generators).map(([name, outputs]) => [ + name, + { [UNKNOWN_KEY]: Object.values(outputs).flat() }, + ]) + ); + + return { + manifest: { schema: SCHEMA, generators }, + reason: `${path} is from a build that did not finish`, + }; + } + + return { manifest }; +}; + +/** + * Writes a manifest atomically: to a temporary file, flushed, then renamed. + * + * @param {string} output + * @param {import('./types').Manifest} manifest + */ +export const saveManifest = async (output, manifest) => { + const path = manifestPath(output); + const temporary = `${path}.tmp`; + + await mkdir(dirname(path), { recursive: true }); + await writeFile(temporary, JSON.stringify(manifest, null, 2), { + flush: true, + }); + await rename(temporary, path); +}; diff --git a/packages/core/src/incremental/section.mjs b/packages/core/src/incremental/section.mjs new file mode 100644 index 000000000..99c243f59 --- /dev/null +++ b/packages/core/src/incremental/section.mjs @@ -0,0 +1,416 @@ +'use strict'; + +import { + mkdir, + readdir, + readFile, + rename, + rm, + rmdir, + stat, + writeFile, +} from 'node:fs/promises'; +import { join, posix } from 'node:path'; +import { deserialize, serialize } from 'node:v8'; + +import logger from '#logger/index.mjs'; +import { enforceArray } from '#utils/array.mjs'; +import { createChannel } from '#utils/channel.mjs'; +import { isAsyncIterable, omitKeys } from '#utils/misc.mjs'; + +import { SALT_CONFIG_OMIT, STATE_DIRECTORY } from './constants.mjs'; +import { hash, trace } from './hash.mjs'; + +const incrementalLogger = logger.child('incremental'); + +/** + * The section used when incremental building is off: every item is stale, and + * nothing is stored or removed. + * + * @type {import('./types').IncrementalSection} + */ +export const DISABLED_SECTION = Object.freeze({ + /** @returns {AsyncIterable>} */ + reuse: (items, make) => make(items), + /** @returns {{ fresh: [], stale: Array }} */ + partition: items => ({ fresh: [], stale: items }), + /** @returns {void} */ + record: () => {}, + /** @returns {Promise} */ + salt: async () => {}, + /** @returns {string} */ + digest: () => '', +}); + +/** + * Converts an output path to the form the manifest uses: POSIX, relative. + * + * @param {string} path + * @returns {string} + */ +const normalizePath = path => + posix.normalize(path.replaceAll('\\', '/')).replace(/^\/+/, ''); + +/** + * Finds the keys whose files all still exist. + * + * @param {string} output - The absolute output directory + * @param {import('./types').Outputs} outputs + * @returns {Promise>} + */ +const findIntact = async (output, outputs) => { + const intact = new Set(); + + await Promise.all( + Object.entries(outputs).map(async ([key, files]) => { + const stats = await Promise.all( + files.map(file => stat(join(output, file)).catch(() => undefined)) + ); + + if (stats.every(entry => entry?.isFile())) { + intact.add(key); + } + }) + ); + + return intact; +}; + +/** + * Removes files, then any directories left empty. + * + * @param {string} output - The absolute output directory + * @param {Iterable} files - Relative to the output directory + */ +const removeFiles = async (output, files) => { + await Promise.all( + Array.from(files, file => rm(join(output, file), { force: true })) + ); + + for (const file of files) { + for ( + let directory = posix.dirname(file); + directory !== '.'; + directory = posix.dirname(directory) + ) { + try { + await rmdir(join(output, directory)); + } catch { + // Not empty, or already removed + break; + } + } + } +}; + +/** + * Creates a generator's section of the incremental state. + * + * Results are stored in the generator's own directory, one file per key, + * written to a temporary name and then renamed. A stored result is therefore + * always complete, even after an interrupted build. Output files are written + * in place, so they are only trusted when the manifest says the build + * finished. + * + * @param {import('./types').IncrementalGenerator} generator + * @param {Record} config - The generator's configuration + * @param {string} output - The absolute output directory + * @param {import('./types').Outputs} [previous] - What the previous build recorded + * @returns {Promise<{ section: import('./types').IncrementalSection, close(): Promise }>} + */ +export const createSection = async ( + generator, + config, + output, + previous = {} +) => { + const { name, incremental: options = {} } = generator; + + const resultsDirectory = join(output, STATE_DIRECTORY, name); + + // Read once, up front, so checking an item never touches the disk + const [intact, storedBefore] = await Promise.all([ + findIntact(output, previous), + readdir(resultsDirectory).then( + files => new Set(files), + () => new Set() + ), + ]); + + /** @type {Map>} The files this build recorded, by key */ + const outputs = new Map(); + + /** @type {Set} Keys of the results this build uses */ + const used = new Set(); + + /** @type {Set} Keys of the results this build wrote */ + const written = new Set(); + + let salt; + let directory; + let reused = 0; + let total = 0; + + /** + * @param {Array} [parts] - Computed at run time + * @returns {string} + */ + const seal = (parts = []) => + (salt = hash( + name, + omitKeys(config, [...SALT_CONFIG_OMIT, ...(options.omit ?? [])]), + ...(options.salt ?? []), + ...parts + )); + + /** + * @param {unknown} item + * @param {import('./types').KeyOptions['key']} key + * @returns {string} + */ + const keyOf = (item, key = options.key) => + hash((salt ??= seal()), ...enforceArray(key ? key(item) : item)); + + /** + * Counts an item for the summary. + * + * @param {boolean} fresh + * @returns {boolean} `fresh` + */ + const count = fresh => { + total++; + + if (fresh) { + reused++; + } + + return fresh; + }; + + /** + * Stores a result under its key, unless this build already has. + * + * @param {string} key + * @param {unknown} result + */ + const store = async (key, result) => { + if (written.has(key)) { + return; + } + + written.add(key); + + const file = join(resultsDirectory, key); + + await (directory ??= mkdir(resultsDirectory, { recursive: true })); + await writeFile(`${file}.tmp`, serialize(result)); + await rename(`${file}.tmp`, file); + }; + + /** + * Loads the result stored under a key. + * + * @param {string} key + * @returns {Promise} + */ + const load = async key => { + const file = join(resultsDirectory, key); + + try { + return deserialize(await readFile(file)); + } catch (cause) { + throw new Error(`Cannot read ${file}; delete it and build again`, { + cause, + }); + } + }; + + /** @type {import('./types').IncrementalSection} */ + const section = { + /** @type {import('./types').IncrementalSection['reuse']} */ + async *reuse(items, make, { key, file, read } = {}) { + /** + * One slot per item, in input order, until its result is yielded. + * `path` is set when the result is read from the generator's own file. + * + * @type {Array<{ key: string, path?: string, result?: unknown }>} + */ + const slots = []; + + // Slots waiting for a result from `make`, in order + const making = []; + + // Runs of leading slots whose results are ready to yield + const ready = createChannel(); + + /** + * Queues every slot ahead of the first one still waiting. + */ + const flush = () => { + const waiting = slots.indexOf(making[0]); + const run = slots.splice(0, waiting === -1 ? slots.length : waiting); + + if (run.length > 0) { + ready.push(run); + } + }; + + /** + * Creates a slot for each item, and yields the stale items. + * + * @yields {Array} Each batch's stale items + */ + async function* staleItems() { + for await (const batch of isAsyncIterable(items) ? items : [items]) { + const stale = []; + + for (const item of batch) { + const slot = { key: keyOf(item, key) }; + + slots.push(slot); + + if (file) { + slot.path = normalizePath(file(item)); + outputs.set(slot.key, [slot.path]); + } else { + used.add(slot.key); + } + + if (!count((file ? intact : storedBefore).has(slot.key))) { + making.push(slot); + stale.push(item); + } + } + + flush(); + + if (stale.length > 0) { + yield stale; + } + } + } + + /** + * Assigns the results from `make` to their slots. + */ + const fill = async () => { + try { + for await (const results of make(staleItems())) { + await Promise.all( + results.map(result => { + const slot = making.shift(); + + if (!slot) { + throw new Error( + `"${name}" made more results than it was given items` + ); + } + + slot.result = result; + + return file ? undefined : store(slot.key, result); + }) + ); + + flush(); + } + } finally { + ready.end(); + } + }; + + const filling = fill(); + + // Rethrown below, after the results that preceded the failure + filling.catch(() => {}); + + for await (const run of ready) { + const results = await Promise.all( + run.map(slot => { + if ('result' in slot) { + return slot.result; + } + + return file ? read(join(output, slot.path)) : load(slot.key); + }) + ); + + for (const [index, result] of results.entries()) { + trace(result, run[index].key); + } + + yield results; + } + + await filling; + }, + + /** @type {import('./types').IncrementalSection['partition']} */ + partition(items, { key, files }) { + const fresh = []; + const stale = []; + + for (const item of items) { + const itemKey = keyOf(item, key); + + outputs.set(itemKey, enforceArray(files(item)).map(normalizePath)); + + (count(intact.has(itemKey)) ? fresh : stale).push(item); + } + + return { fresh, stale }; + }, + + /** @type {import('./types').IncrementalSection['record']} */ + record(label, ...files) { + outputs.set(label, files.map(normalizePath)); + }, + + /** @type {import('./types').IncrementalSection['salt']} */ + async salt(compute) { + if (salt !== undefined) { + throw new Error(`"${name}" salted after its keys were derived`); + } + + seal(await compute()); + }, + + digest: hash, + }; + + return { + section, + + /** + * Removes the previous build's files and results that this build did not + * use, and returns the files it recorded. + * + * @returns {Promise} + */ + async close() { + const recorded = new Set([...outputs.values()].flat()); + const removed = new Set(Object.values(previous).flat()).difference( + recorded + ); + + await removeFiles(output, removed); + + // Includes temporary files left by an interrupted build + const unused = storedBefore.difference(used); + + await removeFiles( + output, + Array.from(unused, file => posix.join(STATE_DIRECTORY, name, file)) + ); + + if (total > 0 || removed.size > 0 || unused.size > 0) { + incrementalLogger.info( + `Reused ${reused} of ${total} items, removed ${removed.size} files and ${unused.size} stored results`, + { generator: name } + ); + } + + return Object.fromEntries(outputs); + }, + }; +}; diff --git a/packages/core/src/incremental/types.d.ts b/packages/core/src/incremental/types.d.ts new file mode 100644 index 000000000..1f20f078e --- /dev/null +++ b/packages/core/src/incremental/types.d.ts @@ -0,0 +1,89 @@ +// Files by the key that produced them, relative to the output directory +// (POSIX, no leading slash). The key is an item's hash, or a label for files +// that don't belong to an item +export type Outputs = Record>; + +// The manifest at `/.doc-kit/manifest.json` +export type Manifest = { + schema: number; + // Set while a build is running, to detect one that did not finish + building?: true; + generators: Record; +}; + +// Strings and bytes are hashed as they are, other values as JSON. In that +// JSON, a result of `reuse` is replaced by the key it was stored under +export type KeyPart = unknown; + +export type KeyOptions = { + // Overrides the generator's declared `key` + key?: (item: T) => KeyPart | Array; +}; + +export type PartitionOptions = KeyOptions & { + // The file or files an item is written to, relative to the output directory + files: (item: T) => string | Array; +}; + +export type Partition = { + // Items whose files the previous build wrote from the same key + fresh: Array; + // Items to write again + stale: Array; +}; + +export type ReuseOptions = KeyOptions & { + // For a generator that already writes each result to its own file: the + // file, relative to the output directory. The result is then read from it + // with `read` instead of being stored twice + file?: (item: T) => string; + read?: (path: string) => Promise; +}; + +// A generator's section of the incremental state +export type IncrementalSection = { + // Yields one result per item, in order. Results the previous build stored + // under the same key are loaded; `make` receives only the other items, and + // must yield one result for each, in order. New results are stored under + // `/.doc-kit` for the next build + reuse( + items: Array | AsyncIterable>, + make: (stale: AsyncIterable>) => AsyncIterable>, + options?: ReuseOptions + ): AsyncIterable>; + // For a generator that only writes files: splits the items by whether the + // previous build wrote their files from the same key + partition(items: Array, options: PartitionOptions): Partition; + // Tracks files that don't belong to an item, such as assets + record(label: string, ...files: Array): void; + // Hashes values computed at run time into every key. Must be called before + // the first `reuse` or `partition`; `compute` only runs when enabled + salt(compute: () => Array | Promise>): Promise; + // Hashes values into a string a `key` function can return later + digest(...parts: Array): string; +}; + +// A generator's `incremental` property +export type IncrementalOptions = { + // Configuration keys that don't affect the output, excluded from the salt + omit?: Array; + // Extra values for the salt + salt?: Array; + // What to hash for an item. Defaults to the item itself + key?: (item: I) => KeyPart | Array; +}; + +export type IncrementalGenerator = Pick< + GeneratorMetadata, + 'name' | 'incremental' +>; + +// The incremental state for a run: one manifest per output directory +export type IncrementalStore = { + section( + generator: IncrementalGenerator, + config: Record | undefined + ): Promise; + // Removes what this run did not use, and saves the manifests + save(): Promise; +}; diff --git a/packages/react/src/jsx-ast/utils/__tests__/channel.test.mjs b/packages/core/src/utils/__tests__/channel.test.mjs similarity index 100% rename from packages/react/src/jsx-ast/utils/__tests__/channel.test.mjs rename to packages/core/src/utils/__tests__/channel.test.mjs diff --git a/packages/react/src/jsx-ast/utils/channel.mjs b/packages/core/src/utils/channel.mjs similarity index 100% rename from packages/react/src/jsx-ast/utils/channel.mjs rename to packages/core/src/utils/channel.mjs diff --git a/packages/core/src/utils/configuration/__tests__/index.test.mjs b/packages/core/src/utils/configuration/__tests__/index.test.mjs index 9af97147d..5a09804aa 100644 --- a/packages/core/src/utils/configuration/__tests__/index.test.mjs +++ b/packages/core/src/utils/configuration/__tests__/index.test.mjs @@ -209,6 +209,7 @@ describe('config.mjs', () => { target: 'json', threads: 4, chunkSize: 5, + experimentalIncremental: true, }; const config = createConfigFromCLIOptions(options); @@ -228,6 +229,7 @@ describe('config.mjs', () => { target: 'json', threads: 4, chunkSize: 5, + experimentalIncremental: true, }); }); diff --git a/packages/core/src/utils/configuration/index.mjs b/packages/core/src/utils/configuration/index.mjs index e66d3ed42..52e8e8595 100644 --- a/packages/core/src/utils/configuration/index.mjs +++ b/packages/core/src/utils/configuration/index.mjs @@ -82,6 +82,7 @@ export const getDefaultConfig = (generators, config) => ? 1 : Math.min(availableParallelism(), DEFAULT_MAX_THREADS), chunkSize: DEFAULT_CHUNK_SIZE, + experimentalIncremental: false, }) ); @@ -229,6 +230,7 @@ export const createConfigFromCLIOptions = options => ({ target: options.target, threads: options.threads, chunkSize: options.chunkSize, + experimentalIncremental: options.experimentalIncremental, }); /** diff --git a/packages/core/src/utils/configuration/types.d.ts b/packages/core/src/utils/configuration/types.d.ts index d29b3b2a0..d6f10fc76 100644 --- a/packages/core/src/utils/configuration/types.d.ts +++ b/packages/core/src/utils/configuration/types.d.ts @@ -20,6 +20,9 @@ export type Configuration = { // Keeps none of the requested generators' results, for runs that only need // what the generators write discardResults?: boolean; + + // Enable incremental building? + experimentalIncremental: boolean; } & { [K in keyof AllGenerators]: GlobalConfiguration & AllGenerators[K]['defaultConfiguration']; diff --git a/packages/core/src/utils/file.mjs b/packages/core/src/utils/file.mjs index 314d39743..c98be323d 100644 --- a/packages/core/src/utils/file.mjs +++ b/packages/core/src/utils/file.mjs @@ -19,6 +19,13 @@ export const writeFile = (file, ...args) => .mkdir(dirname(file), { recursive: true }) .then(() => fs.writeFile(file, ...args)); +/** + * @param {string} file + * @returns {Promise} + */ +export const readJSON = async file => + JSON.parse(await fs.readFile(file, 'utf-8')); + /** * Writes a value as JSON * diff --git a/packages/react/src/html/README.md b/packages/react/src/html/README.md index b6a5ca8da..e64bbae83 100644 --- a/packages/react/src/html/README.md +++ b/packages/react/src/html/README.md @@ -33,6 +33,22 @@ pages whose content it shows, which come before it in the input, and its `headings`. Its program imports theirs, so they are not built again. Node.js's `html-all` generator (`@node-core/doc-kit`) adds `all.html` this way. +### Incremental builds + +With [`experimentalIncremental`](https://doc-kit.nodejs.org/configuration#execution-options) +on, a page is only rendered again when one of these changes: + +- The page itself, as built by `jsx-ast`. A composed page depends on its + parts. +- What all pages share: the component library, the client assets, the + template and the `html` configuration. The library contains every component + and the `#theme/config` module, so editing a component, upgrading a + dependency, or adding or removing a page renders every page again. + +The library and the client assets are still bundled on every build, and every +page is still compiled. Pages and client files that a build no longer +produces are removed. + ## Configuring Several options are @@ -565,9 +581,12 @@ module's imports as they are, as the library they point to may not exist yet. share one Preact. - `buildClient(options)` {Function} Bundles the client entry into `config.output` and returns a promise of the assets every page loads: - `{ scripts, preloads, stylesheets, fonts }`, as paths relative to the output - directory. `preloads` are the chunks the scripts import statically, rendered - as `modulepreload` hints, and `fonts` (optional) are fonts to preload. + `{ scripts, preloads, stylesheets, fonts, emitted }`, as paths relative to + the output directory. `preloads` are the chunks the scripts import + statically, rendered as `modulepreload` hints, and `fonts` (optional) are + fonts to preload. `emitted` (optional) is every file the build wrote, so an + [incremental build](#incremental-builds) can remove the ones a later build + doesn't write. Without it, only the files every page loads are tracked. - `entry` {string} The client program every page shares. - `virtualImports` {Object} In-memory modules to make available, by module ID, `#theme/config` included. diff --git a/packages/react/src/html/__tests__/generate.test.mjs b/packages/react/src/html/__tests__/generate.test.mjs index 8b530c1bf..684483734 100644 --- a/packages/react/src/html/__tests__/generate.test.mjs +++ b/packages/react/src/html/__tests__/generate.test.mjs @@ -1,12 +1,23 @@ import assert from 'node:assert/strict'; -import { mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'; +import { existsSync } from 'node:fs'; +import { + mkdtemp, + readdir, + readFile, + rm, + stat, + writeFile, +} from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { before, describe, it } from 'node:test'; +import { setTimeout } from 'node:timers/promises'; import { pathToFileURL } from 'node:url'; import { collectAsyncGenerator } from '@doc-kit/core/caching.mjs'; import { loadGenerator } from '@doc-kit/core/generators/loader.mjs'; +import { createIncrementalStore } from '@doc-kit/core/incremental/index.mjs'; +import { loadManifest } from '@doc-kit/core/incremental/manifest.mjs'; import { setConfig } from '@doc-kit/core/utils/configuration/index.mjs'; import { once } from '@doc-kit/core/utils/generators.mjs'; import { loadMarkdownPlugins } from '@doc-kit/core/utils/markdown/plugins.mjs'; @@ -19,6 +30,8 @@ import { generate as sectionPages } from '../../section-pages/generate.mjs'; import { compile, createViteBundler } from '../bundlers/vite.mjs'; import { FONTS } from '../constants.mjs'; import { generate as generatePages } from '../generate.mjs'; +import html from '../index.mjs'; +import { pageFileName } from '../utils/processing.mjs'; import { processChunk } from '../utils/render.mjs'; /** @@ -40,6 +53,14 @@ await loadMarkdownPlugins( await loadGenerator(import.meta.resolve('../../jsx-ast/index.mjs')) ); +/** + * Builds the pages of module entries, one page per module. + */ +const buildPages = async entries => + Promise.all(entries.map(entry => buildContent([entry], entry))).then( + contents => contents.map(toPage) + ); + /** * Converts a page's JSX AST into the `{ data, headings, readingTime, content }` * shape `html` consumes, mirroring the conversion the jsx-ast worker performs. @@ -656,4 +677,228 @@ describe('web generate', () => { } ); }); + + describe('incremental', () => { + /** + * Runs an incremental build of the pages into the output, through a + * worker that renders on this thread and notes which pages it rendered. + * + * @returns {Promise<{ rendered: Array, manifest: import('@doc-kit/core/incremental/types').Manifest }>} + */ + const build = async (pages, output) => { + const rendered = []; + + const worker = { + async *stream(batches, extra) { + for await (const tasks of batches) { + rendered.push(...tasks.map(task => pageFileName(task.data))); + + yield await processChunk(tasks, [...tasks.keys()], extra); + } + }, + }; + + const store = createIncrementalStore({ enabled: true }); + const incremental = await store.section(html, { output }); + + await generatePages([pages], worker, { incremental }); + await store.save(); + + // Let the clock move, so an unchanged mtime means no write happened + await setTimeout(20); + + return { rendered, manifest: (await loadManifest(output)).manifest }; + }; + + /** + * The modification times of the given files, by file. + */ + const mtimes = async (output, files) => + Object.fromEntries( + await Promise.all( + files.map(async file => [ + file, + (await stat(join(output, file))).mtimeMs, + ]) + ) + ); + + it('renders nothing the second time and leaves every file alone', async context => { + const { output } = await createTestConfiguration(context); + + const parts = await buildPages([ + createEntry('fs', 'File system'), + createEntry('zlib', 'Zlib'), + ]); + const pages = [...parts, createComposedPage(parts)]; + + const first = await build(pages, output); + + assert.deepEqual(first.rendered.toSorted(), [ + 'combined.html', + 'fs.html', + 'zlib.html', + ]); + + const files = Object.values(first.manifest.generators.html).flat(); + const pageFiles = files.filter(file => !file.startsWith('assets/')); + const before = await mtimes(output, pageFiles); + + const second = await build(pages, output); + + // The client is bundled again (into the same files); the pages are not + assert.deepEqual(second.rendered, []); + assert.deepEqual(await mtimes(output, pageFiles), before); + + // Building the same library twice gives the same bytes: the salt holds + assert.deepEqual(second.manifest, first.manifest); + + // The pages and the client's files are all recorded + assert.ok(files.includes('fs.html')); + assert.ok(files.some(file => file.startsWith('assets/'))); + }); + + it('renders an edited page again, and a composed page with it, but nothing else', async context => { + const { output } = await createTestConfiguration(context); + + const fs = createEntry('fs', 'File system'); + const zlib = createEntry('zlib', 'Zlib'); + const files = ['fs.html', 'zlib.html', 'combined.html']; + + /** + * The module pages, and a composed page of them. + */ + const buildSite = async () => { + const parts = await buildPages([fs, zlib]); + + return [...parts, createComposedPage(parts)]; + }; + + await build(await buildSite(), output); + const before = await mtimes(output, files); + + // A change after the first paragraph: the description every page's + // documentation index shows stays the same, so the library does too + zlib.content.children.push({ + type: 'paragraph', + children: [{ type: 'text', value: 'More about zlib' }], + }); + + const { rendered } = await build(await buildSite(), output); + const after = await mtimes(output, files); + + assert.deepEqual(rendered, ['zlib.html', 'combined.html']); + assert.equal(after['fs.html'], before['fs.html']); + assert.notEqual(after['zlib.html'], before['zlib.html']); + assert.notEqual(after['combined.html'], before['combined.html']); + assert.match( + await readFile(join(output, 'combined.html'), 'utf8'), + /More about zlib/ + ); + }); + + it('renders every page again when the page set changes', async context => { + const { output } = await createTestConfiguration(context); + + const fs = createEntry('fs', 'File system'); + const zlib = createEntry('zlib', 'Zlib'); + + await build(await buildPages([fs, zlib]), output); + + // A new module is on every page's sidebar + const { rendered } = await build( + await buildPages([fs, zlib, createEntry('net', 'Net')]), + output + ); + + assert.deepEqual(rendered.toSorted(), [ + 'fs.html', + 'net.html', + 'zlib.html', + ]); + }); + + it('removes the pages of a dropped module, and nothing else', async context => { + const { config, output } = await createTestConfiguration(context, [ + 'section-pages', + ]); + config['section-pages'].maxDepth = 2; + + const fs = [ + createEntry('fs', 'File system'), + createEntry('fs', '`fs.readFile()`', { + depth: 2, + slug: 'fsreadfile', + type: 'method', + name: 'readFile', + }), + createEntry('fs', '`fs.watch()`', { + depth: 2, + slug: 'fswatch', + type: 'method', + name: 'watch', + }), + ]; + const zlib = createEntry('zlib', 'Zlib'); + + const toPages = async entries => { + const groups = Map.groupBy( + await collectAsyncGenerator(sectionPages(once(entries))), + entry => entry.api + ); + + return Promise.all( + [...groups.values()].map(group => buildContent(group, group[0])) + ).then(contents => contents.map(toPage)); + }; + + await build(await toPages([...fs, zlib]), output); + + assert.ok(existsSync(join(output, 'fs/readFile.html'))); + await writeFile(join(output, 'mine.txt'), 'not doc-kit’s'); + + const { rendered, manifest } = await build(await toPages([zlib]), output); + + // The sidebar lost a module, so the remaining page is rendered again + assert.deepEqual(rendered, ['zlib.html']); + assert.equal(existsSync(join(output, 'fs.html')), false); + assert.equal(existsSync(join(output, 'fs')), false); + assert.ok(existsSync(join(output, 'zlib.html'))); + assert.ok(existsSync(join(output, 'mine.txt'))); + assert.deepEqual( + Object.values(manifest.generators.html) + .flat() + .filter(file => !file.startsWith('assets/')), + ['zlib.html'] + ); + }); + + it('removes the client files a previous build wrote and this one did not', async context => { + const { config, output } = await createTestConfiguration(context); + + const pages = await buildPages([createEntry('fs', 'File system')]); + + await build(pages, output); + + const stylesheets = async () => + (await readdir(join(output, 'assets'))).filter(file => + file.endsWith('.css') + ); + + const [before] = await stylesheets(); + + const stylesheet = join(output, '..', `doc-kit-test-${Date.now()}.css`); + context.after(() => rm(stylesheet, { force: true })); + await writeFile(stylesheet, '.extra { color: red }'); + config.html.stylesheets = [stylesheet]; + + const { rendered } = await build(pages, output); + + // The assets changed, so the page did, and the old stylesheet is gone + assert.deepEqual(rendered, ['fs.html']); + const after = await stylesheets(); + assert.equal(after.length, 1); + assert.notEqual(after[0], before); + }); + }); }); diff --git a/packages/react/src/html/bundlers/vite.mjs b/packages/react/src/html/bundlers/vite.mjs index aae767da1..cda6648d9 100644 --- a/packages/react/src/html/bundlers/vite.mjs +++ b/packages/react/src/html/bundlers/vite.mjs @@ -396,7 +396,7 @@ export const buildClient = async ({ const outDir = resolve(config.output); - await viteBuild( + const result = await viteBuild( createViteConfig({ sources, input: { [CLIENT_NAME]: CLIENT_ENTRY_ID }, @@ -418,9 +418,13 @@ export const buildClient = async ({ const manifest = JSON.parse(await readFile(manifestPath, 'utf8')); + let emitted = result.output.map(({ fileName }) => fileName); + if (!configuredManifest) { await rm(manifestPath); await rmdir(dirname(manifestPath)).catch(() => {}); + + emitted = emitted.filter(file => file !== MANIFEST_NAME); } const entries = Object.values(manifest); @@ -443,6 +447,7 @@ export const buildClient = async ({ preloads: collectImports(manifest, chunk), stylesheets: [...new Set(stylesheets)], fonts, + emitted, }; }; diff --git a/packages/react/src/html/generate.mjs b/packages/react/src/html/generate.mjs index f57701556..af60852d3 100644 --- a/packages/react/src/html/generate.mjs +++ b/packages/react/src/html/generate.mjs @@ -6,13 +6,16 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; +import { hashDirectory } from '@doc-kit/core/incremental/hash.mjs'; +import { DISABLED_SECTION } from '@doc-kit/core/incremental/section.mjs'; import logger from '@doc-kit/core/logger/index.mjs'; +import { createChannel } from '@doc-kit/core/utils/channel.mjs'; import getConfig from '@doc-kit/core/utils/configuration/index.mjs'; -import { createChannel } from '../jsx-ast/utils/channel.mjs'; import { resolveBundler } from './bundlers/index.mjs'; import { copyStaticAssets } from './utils/copying.mjs'; import createProgramBuilder, { moduleFileName } from './utils/generate.mjs'; +import { pageFileName } from './utils/processing.mjs'; import { createPageWriter } from './utils/render.mjs'; const htmlLogger = logger.child('html'); @@ -32,11 +35,16 @@ const htmlLogger = logger.child('html'); * 3. A composed page (with `parts`, which come before it) imports their * compiled programs, so nothing is built twice. * 4. The worker pool imports, renders, templates, minifies and writes the - * pages as they are compiled, one page in memory per worker. + * pages as they are compiled, one page in memory per worker. An incremental + * build only renders the pages that changed. * * @type {import('./types').Generator['generate']} */ -export async function generate(input, worker) { +export async function generate( + input, + worker, + { incremental = DISABLED_SECTION } = {} +) { const config = getConfig('html'); const template = await readFile(config.templatePath, 'utf-8'); @@ -54,7 +62,13 @@ export async function generate(input, worker) { process.once('exit', removeOnExit); try { - const building = buildSite(input, { worker, outDir, config, template }); + const building = buildSite(input, { + worker, + outDir, + config, + template, + incremental, + }); input = undefined; @@ -79,12 +93,13 @@ export async function generate(input, worker) { * @param {string} options.outDir - Where the library and the programs are written * @param {import('./types').ResolvedWebConfiguration} options.config * @param {string} options.template - The page template + * @param {import('@doc-kit/core/incremental/types').IncrementalSection} options.incremental * @returns {Promise} */ const buildSite = async (input, options) => { // Not destructured in the parameters, so that clearing `input` below lets // go of it - const { worker, outDir, config, template } = options; + const { worker, outDir, config, template, incremental } = options; // Loaded here rather than with the generator, so the threads rendering // pages, which load this module too, never load what only this needs @@ -101,6 +116,17 @@ const buildSite = async (input, options) => { // this module, which re-exports it once it is const libraryURL = pathToFileURL(join(outDir, 'page-library.mjs')).href; + // Adapters expect an empty directory, and `outDir` holds the pages + const libraryDir = join(outDir, 'library'); + + /** + * A hash of each compiled page's source, by `api`, so the source itself can + * be freed. A composed page's covers its parts', which come before it + * + * @type {Map} + */ + const sources = new Map(); + /** * Compiles a page's program to disk and describes it for the workers. * @@ -120,6 +146,14 @@ const buildSite = async (input, options) => { const { data, headings, readingTime } = page; + sources.set( + data.api, + incremental.digest( + page, + ...(page.parts ?? []).map(api => sources.get(api)) + ) + ); + return { moduleURL: pathToFileURL(file).href, data, @@ -135,8 +169,6 @@ const buildSite = async (input, options) => { * @returns {Promise} */ const bundle = async heads => { - // Adapters expect an empty directory, and `outDir` holds the pages - const libraryDir = join(outDir, 'library'); await mkdir(libraryDir); const builtLibraryURL = await bundler.buildServer({ @@ -167,6 +199,27 @@ const buildSite = async (input, options) => { // The compiled pages, rendered once the bundles are built const rendering = createChannel(); + /** + * Filters out the pages that haven't changed since the previous build. + * + * @param {AsyncIterable>} batches + * @yields {Array} Each batch's pages to render + */ + async function* stalePages(batches) { + for await (const tasks of batches) { + const { stale } = incremental.partition(tasks, { + /** @param {import('./types').PageTask} task */ + key: task => sources.get(task.data.api), + /** @param {import('./types').PageTask} task */ + files: task => pageFileName(task.data), + }); + + if (stale.length > 0) { + yield stale; + } + } + } + let writing; /** @@ -175,9 +228,31 @@ const buildSite = async (input, options) => { * @param {Array} heads - Every page's metadata */ const startWriting = heads => { - writing = bundle(heads).then(assets => - createPageWriter(worker)(rendering, { template, assets }) - ); + writing = bundle(heads).then(async assets => { + // What every page depends on. The built library covers the components, + // their dependencies and the list of pages + await incremental.salt(async () => [ + await hashDirectory(libraryDir), + assets, + template, + ]); + + // Without `emitted`, only the files every page loads are tracked + incremental.record( + 'client', + ...(assets.emitted ?? [ + ...assets.scripts, + ...assets.preloads, + ...assets.stylesheets, + ...(assets.fonts ?? []), + ]) + ); + + return createPageWriter(worker)(stalePages(rendering), { + template, + assets, + }); + }); // Awaited once every page is compiled writing.catch(() => {}); diff --git a/packages/react/src/html/index.mjs b/packages/react/src/html/index.mjs index f9537e417..ce8829b09 100644 --- a/packages/react/src/html/index.mjs +++ b/packages/react/src/html/index.mjs @@ -91,6 +91,18 @@ export default { generate, + incremental: { + // Functions and paths. Their effect is covered by the built library's hash + omit: [ + 'bundler', + 'templatePath', + 'imports', + 'virtualImports', + 'stylesheets', + 'components', + ], + }, + // Rendering, templating, minifying and writing the pages scales with the // page count, so it is farmed out to the worker pool. hasParallelProcessor: true, diff --git a/packages/react/src/html/types.d.ts b/packages/react/src/html/types.d.ts index fa742b29a..313a0fd2a 100644 --- a/packages/react/src/html/types.d.ts +++ b/packages/react/src/html/types.d.ts @@ -58,6 +58,9 @@ export type ClientAssets = { stylesheets: Array; // Fonts to preload, so text does not wait on the stylesheet to request them. fonts?: Array; + // Every file the build wrote, so an incremental build can remove the ones a + // later build doesn't write. Without it, only the files above are tracked. + emitted?: Array; }; export type ServerBundleOptions = { diff --git a/packages/react/src/jsx-ast/generate.mjs b/packages/react/src/jsx-ast/generate.mjs index 99b97db7f..efdf61231 100644 --- a/packages/react/src/jsx-ast/generate.mjs +++ b/packages/react/src/jsx-ast/generate.mjs @@ -1,10 +1,11 @@ import { isMainThread } from 'node:worker_threads'; +import { DISABLED_SECTION } from '@doc-kit/core/incremental/section.mjs'; +import { createChannel } from '@doc-kit/core/utils/channel.mjs'; import getConfig from '@doc-kit/core/utils/configuration/index.mjs'; import { groupNodesByModule } from '@doc-kit/core/utils/generators.mjs'; import { jsx, toJs } from 'estree-util-to-js'; -import { createChannel } from './utils/channel.mjs'; import { getSortedHeadNodes } from './utils/getSortedHeadNodes.mjs'; import { merge } from './utils/merge.mjs'; import { buildNotFoundPage } from './utils/synthetic/404.mjs'; @@ -47,11 +48,16 @@ export async function processChunk(slicedInput, itemIndices) { * * Pages are emitted as they are built, in the order they arrive, the synthetic * pages last. Once the input ends, `{ manifest }` lists every page's head in - * the site's order, without waiting for the pages still being built. + * the site's order, without waiting for the pages still being built. An + * incremental build only builds the pages whose entries changed. * * @type {import('./types').Generator['generate']} */ -export async function* generate(input, worker) { +export async function* generate( + input, + worker, + { incremental = DISABLED_SECTION } = {} +) { // Composed pages are not built here: the `html` generator assembles them // from their parts' content. const synthetic = getConfig('jsx-ast').generateNotFoundPage @@ -110,5 +116,7 @@ export async function* generate(input, worker) { // The input's failure reaches the output through the manifest describe().catch(error => manifest.reject(error)); - yield* merge(worker.stream(described), announce()); + const pages = incremental.reuse(described, stale => worker.stream(stale)); + + yield* merge(pages, announce()); } diff --git a/packages/react/src/jsx-ast/utils/merge.mjs b/packages/react/src/jsx-ast/utils/merge.mjs index ee555b940..27c7fccc7 100644 --- a/packages/react/src/jsx-ast/utils/merge.mjs +++ b/packages/react/src/jsx-ast/utils/merge.mjs @@ -1,6 +1,6 @@ 'use strict'; -import { createChannel } from './channel.mjs'; +import { createChannel } from '@doc-kit/core/utils/channel.mjs'; /** * Yields the items of several async iterables as they arrive. A failure is diff --git a/scripts/benchmark-incremental.mjs b/scripts/benchmark-incremental.mjs new file mode 100644 index 000000000..c098adaf1 --- /dev/null +++ b/scripts/benchmark-incremental.mjs @@ -0,0 +1,121 @@ +// Measures what `--experimental-incremental` saves. Each run builds a copy of +// the input four times: without the option, with it into an empty directory, +// again with nothing changed, and again after editing one document. Prints the +// median of each. +// +// node scripts/benchmark-incremental.mjs -i "node/doc/api/*.md" \ +// [-t html -t json] [--runs 3] [-- ] + +import { spawnSync } from 'node:child_process'; +import { appendFile, cp, glob, mkdtempDisposable, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { basename, join } from 'node:path'; +import { parseArgs } from 'node:util'; + +const CLI = join( + import.meta.dirname, + '..', + 'packages', + 'cli', + 'bin', + 'cli.mjs' +); + +const { values, positionals } = parseArgs({ + allowPositionals: true, + options: { + input: { type: 'string', short: 'i' }, + target: { type: 'string', short: 't', multiple: true, default: ['html'] }, + runs: { type: 'string', default: '3' }, + }, +}); + +if (!values.input) { + throw new Error('Pass the documents to build with -i ""'); +} + +const median = numbers => { + const sorted = numbers.toSorted((a, b) => a - b); + const middle = sorted.length >> 1; + + return sorted.length % 2 + ? sorted[middle] + : (sorted[middle - 1] + sorted[middle]) / 2; +}; + +// Removed when the script exits +await using temporary = await mkdtempDisposable( + join(tmpdir(), 'doc-kit-benchmark-incremental-') +); + +const root = temporary.path; +const docs = join(root, 'docs'); + +// Copied, so editing a document doesn't touch the input +const documents = []; + +for await (const file of glob(values.input)) { + documents.push(join(docs, basename(file))); + + await cp(file, documents.at(-1)); +} + +/** + * Times one build into the output, in seconds. + * + * @param {string} output + * @param {Array} [flags] + */ +const build = (output, flags = []) => { + const start = performance.now(); + + const { status, stderr } = spawnSync( + process.execPath, + [ + CLI, + 'generate', + ...values.target.flatMap(target => ['-t', target]), + ...['-i', join(docs, '*.md')], + ...['-o', output], + ...['--log-level', 'error'], + ...flags, + ...positionals, + ], + { encoding: 'utf-8' } + ); + + if (status !== 0) { + throw new Error(`generate failed:\n${stderr}`); + } + + return (performance.now() - start) / 1000; +}; + +const times = { full: [], first: [], unchanged: [], edited: [] }; + +for (let run = 0; run < Number(values.runs); run++) { + const full = join(root, `full-${run}`); + const incremental = join(root, `incremental-${run}`); + + times.full.push(build(full)); + times.first.push(build(incremental, ['--experimental-incremental'])); + times.unchanged.push(build(incremental, ['--experimental-incremental'])); + + await appendFile(documents[0], `\nBenchmark edit ${run}.\n`); + + times.edited.push(build(incremental, ['--experimental-incremental'])); + + await rm(full, { recursive: true }); + await rm(incremental, { recursive: true }); +} + +console.log( + `${documents.length} documents, -t ${values.target.join(' -t ')}, median of ${values.runs} runs` +); + +console.table({ + 'without the option': { seconds: median(times.full).toFixed(2) }, + 'first incremental build': { seconds: median(times.first).toFixed(2) }, + 'nothing changed': { seconds: median(times.unchanged).toFixed(2) }, + 'one document edited': { seconds: median(times.edited).toFixed(2) }, +}); diff --git a/scripts/comparators/files.mjs b/scripts/comparators/files.mjs index 7e7d1035c..0ecd9b621 100644 --- a/scripts/comparators/files.mjs +++ b/scripts/comparators/files.mjs @@ -1,6 +1,7 @@ import { glob } from 'node:fs/promises'; import path from 'node:path'; +import { STATE_DIRECTORY } from '../../packages/core/src/incremental/constants.mjs'; import { BENCHMARK_FILE, COMPARISON_FILE } from '../constants.mjs'; const METADATA_FILES = new Set([BENCHMARK_FILE, COMPARISON_FILE]); @@ -9,7 +10,8 @@ export const listOutputFiles = async directory => { const entries = glob('**/*', { cwd: directory, withFileTypes: true, - exclude: entry => METADATA_FILES.has(entry.name), + exclude: entry => + METADATA_FILES.has(entry.name) || entry.name === STATE_DIRECTORY, }); return (await Array.fromAsync(entries))