diff --git a/.changeset/stream-input.md b/.changeset/stream-input.md index bd84fc1de..aa0322881 100644 --- a/.changeset/stream-input.md +++ b/.changeset/stream-input.md @@ -2,4 +2,4 @@ '@doc-kit/core': minor --- -Generators can set `streamsInput: true` to receive their dependency's output as an async iterable of chunks as they are produced, instead of waiting for all of it. The cache runs a streamed generator once for every reader, and lets a chunk go once all of them have read it. +Generators can set `streamsInput: true` to receive their dependency's output as an async iterable of chunks as they are produced, instead of waiting for all of it. With one thread, the input is collected first and arrives as its only chunk. The cache runs a streamed generator once for every reader, and lets a chunk go once all of them have read it. diff --git a/.changeset/stream-metadata.md b/.changeset/stream-metadata.md new file mode 100644 index 000000000..98156e0c1 --- /dev/null +++ b/.changeset/stream-metadata.md @@ -0,0 +1,6 @@ +--- +'@doc-kit/core': minor +'@doc-kit/generator-react': minor +--- + +`metadata` and `section-pages` stream their input: with more than one thread, they start on their dependency's first chunk, so parsing, metadata and section pages overlap. The generated files are unchanged. diff --git a/docs/creating-generators.md b/docs/creating-generators.md index b22a225f7..6de55a95c 100644 --- a/docs/creating-generators.md +++ b/docs/creating-generators.md @@ -342,8 +342,10 @@ export default { ``` - A dependency that doesn't stream arrives as a single chunk. -- With one thread, `input` is still the collected array, so accept both. +- With one thread, `input` is collected first and arrives as its only chunk. - `input` can be iterated only once. +- `metadata`'s chunks hold whole files, and a file is one module, so a chunk + holds all the entries of each module in it. ## Declaring a dependent diff --git a/packages/core/src/__tests__/generators.test.mjs b/packages/core/src/__tests__/generators.test.mjs index f4060c9ca..eeb08418d 100644 --- a/packages/core/src/__tests__/generators.test.mjs +++ b/packages/core/src/__tests__/generators.test.mjs @@ -142,11 +142,25 @@ const syntheticGenerators = { yield* input; }, }, + // A source of two chunks, and a reader that tells which it got + 'two-chunks': { + name: 'two-chunks', + hasParallelProcessor: true, + generate: async () => + (async function* () { + yield [1]; + yield [2]; + })(), + }, 'shape-reader': { name: 'shape-reader', - dependsOn: 'metadata', + dependsOn: 'two-chunks', streamsInput: true, - generate: async input => ({ array: Array.isArray(input) }), + generate: async input => { + const chunks = await Array.fromAsync(input); + + return { chunks }; + }, }, }; @@ -339,7 +353,7 @@ describe('createGenerator orchestration', () => { assert.deepStrictEqual(unhandled, []); }); - it('gives a generator that streams its input the whole input with one thread', async () => { + it('gives a generator that streams its input the whole input as one chunk with one thread', async () => { const one = await createGenerator().runGenerators({ target: ['shape-reader'], threads: 1, @@ -349,8 +363,8 @@ describe('createGenerator orchestration', () => { threads: 2, }); - assert.deepStrictEqual(one, [{ array: true }]); - assert.deepStrictEqual(two, [{ array: false }]); + assert.deepStrictEqual(one, [{ chunks: [[1, 2]] }]); + assert.deepStrictEqual(two, [{ chunks: [[1], [2]] }]); }); it('returns no results with discardResults', async () => { diff --git a/packages/core/src/caching.mjs b/packages/core/src/caching.mjs index eabf4c3ea..4beeb431e 100644 --- a/packages/core/src/caching.mjs +++ b/packages/core/src/caching.mjs @@ -1,6 +1,7 @@ 'use strict'; import logger from './logger/index.mjs'; +import { once } from './utils/generators.mjs'; import { isAsyncIterable } from './utils/misc.mjs'; import { createTee } from './utils/tee.mjs'; @@ -37,17 +38,6 @@ export const collectAsyncGenerator = async generator => { return results; }; -/** - * Gives a value as the single chunk of an async generator. - * - * @template T - * @param {T} value - * @returns {AsyncGenerator} - */ -async function* once(value) { - yield value; -} - /** * Creates the cache that backs the generator pipeline. It is the single owner * of every piece of caching the orchestrator needs. diff --git a/packages/core/src/generators.mjs b/packages/core/src/generators.mjs index e374b923f..bc4242afc 100644 --- a/packages/core/src/generators.mjs +++ b/packages/core/src/generators.mjs @@ -9,6 +9,7 @@ import { resolvePipeline } from './generators/pipeline.mjs'; import logger from './logger/index.mjs'; import createWorkerPool from './threading/index.mjs'; import createParallelWorker from './threading/parallel.mjs'; +import { once } from './utils/generators.mjs'; import { loadMarkdownPlugins } from './utils/markdown/plugins.mjs'; import { isAsyncIterable } from './utils/misc.mjs'; @@ -31,15 +32,30 @@ const createGenerator = () => { * Gets the input from a dependency generator, collected or streamed. * * @param {string | undefined} dependsOn - Resolved dependency specifier - * @param {boolean} [streamed] - Whether to stream its chunks + * @param {boolean} [streamsInput] - Whether to give it as an async iterable + * of its chunks + * @param {number} threads - The number of threads the run uses * @returns {Promise} */ - const getDependencyInput = async (dependsOn, streamed) => { + const getDependencyInput = async (dependsOn, streamsInput, threads) => { if (!dependsOn) { return undefined; } - return streamed ? cache.stream(dependsOn) : cache.consume(dependsOn); + if (!streamsInput) { + return cache.consume(dependsOn); + } + + if (threads > 1) { + return cache.stream(dependsOn); + } + + // With one thread nothing runs alongside, so streaming would only keep + // every stage's data alive at once: the input is collected whole first, + // and given as its only chunk + const whole = await cache.consume(dependsOn); + + return once(whole); }; /** @@ -76,11 +92,10 @@ const createGenerator = () => { cache.store( specifier, (async () => { - // With one thread nothing runs alongside, so streaming would only keep - // every stage's data alive at once: each stage takes its input whole const dependencyInput = await getDependencyInput( dependsOn, - streamsInput && configuration.threads > 1 + streamsInput, + configuration.threads ); generatorsLogger.debug(`Starting "${name}"`); diff --git a/packages/core/src/generators/metadata/index.mjs b/packages/core/src/generators/metadata/index.mjs index fcdd965b7..64747e682 100644 --- a/packages/core/src/generators/metadata/index.mjs +++ b/packages/core/src/generators/metadata/index.mjs @@ -16,6 +16,8 @@ export default { hasParallelProcessor: true, + streamsInput: true, + markdown: { remarkPlugins: [ 'remark-parse', diff --git a/packages/core/src/generators/metadata/types.d.ts b/packages/core/src/generators/metadata/types.d.ts index c84305c37..966912e2c 100644 --- a/packages/core/src/generators/metadata/types.d.ts +++ b/packages/core/src/generators/metadata/types.d.ts @@ -3,7 +3,7 @@ import type { Position } from 'unist'; export type Generator = GeneratorMetadata< {}, - Generate, AsyncGenerator>, + Generate>, AsyncGenerator>, ProcessChunk> >; diff --git a/packages/core/src/generators/types.d.ts b/packages/core/src/generators/types.d.ts index 7bac2a412..f158e1ec0 100644 --- a/packages/core/src/generators/types.d.ts +++ b/packages/core/src/generators/types.d.ts @@ -73,7 +73,7 @@ declare global { /** * Receive the dependency's output as an async iterable of its chunks, as * they are produced, instead of one collected array. With one thread, the - * input is still a collected array, so accept both. + * input is collected first and arrives as its only chunk. */ streamsInput?: boolean; diff --git a/packages/core/src/utils/__tests__/generators.test.mjs b/packages/core/src/utils/__tests__/generators.test.mjs index 6fe290dba..b33d46fce 100644 --- a/packages/core/src/utils/__tests__/generators.test.mjs +++ b/packages/core/src/utils/__tests__/generators.test.mjs @@ -7,6 +7,7 @@ import { getVersionFromSemVer, coerceSemVer, getCompatibleVersions, + once, } from '../generators.mjs'; describe('getEntryDescription', () => { @@ -138,3 +139,11 @@ describe('getCompatibleVersions', () => { assert.equal(result.length, 2); }); }); + +describe('once', () => { + it('gives a value as the only chunk', async () => { + const chunks = await Array.fromAsync(once([1, 2])); + + assert.deepEqual(chunks, [[1, 2]]); + }); +}); diff --git a/packages/core/src/utils/generators.mjs b/packages/core/src/utils/generators.mjs index 516113bca..df5c3e99e 100644 --- a/packages/core/src/utils/generators.mjs +++ b/packages/core/src/utils/generators.mjs @@ -42,6 +42,17 @@ export const groupNodesByModule = nodes => { return Map.groupBy(nodes, node => node.api); }; +/** + * Gives a value as the single chunk of an async generator. + * + * @template T + * @param {T} value + * @returns {AsyncGenerator} + */ +export async function* once(value) { + yield value; +} + /** * Parses the SemVer string into a Node.js-alike version * diff --git a/packages/react/src/html/__tests__/generate.test.mjs b/packages/react/src/html/__tests__/generate.test.mjs index a2198925b..c1437ff17 100644 --- a/packages/react/src/html/__tests__/generate.test.mjs +++ b/packages/react/src/html/__tests__/generate.test.mjs @@ -5,14 +5,16 @@ import { join } from 'node:path'; import { describe, it } from 'node:test'; import { pathToFileURL } from 'node:url'; +import { collectAsyncGenerator } from '@doc-kit/core/caching.mjs'; import { loadGenerator } from '@doc-kit/core/generators/loader.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'; import { jsx, toJs } from 'estree-util-to-js'; import buildContent from '../../jsx-ast/utils/buildContent.mjs'; import { buildNotFoundPage } from '../../jsx-ast/utils/synthetic/404.mjs'; -import { generate as chunk } from '../../section-pages/generate.mjs'; +import { generate as sectionPages } from '../../section-pages/generate.mjs'; import { compile, createViteBundler } from '../bundlers/vite.mjs'; import { FONTS } from '../constants.mjs'; import { generate } from '../generate.mjs'; @@ -196,7 +198,10 @@ describe('web generate', () => { ], }); - const pages = Map.groupBy(await chunk(entries), entry => entry.api); + const pages = Map.groupBy( + await collectAsyncGenerator(sectionPages(once(entries))), + entry => entry.api + ); const contents = await Promise.all( [...pages.values()].map(group => buildContent(group, group[0])) ); diff --git a/packages/react/src/section-pages/__tests__/generate.test.mjs b/packages/react/src/section-pages/__tests__/generate.test.mjs index 8605ba1c4..e00bed549 100644 --- a/packages/react/src/section-pages/__tests__/generate.test.mjs +++ b/packages/react/src/section-pages/__tests__/generate.test.mjs @@ -1,12 +1,31 @@ import assert from 'node:assert/strict'; import { before, describe, it } from 'node:test'; +import { collectAsyncGenerator } from '@doc-kit/core/caching.mjs'; import getConfig, { setConfig, } from '@doc-kit/core/utils/configuration/index.mjs'; import { generate } from '../generate.mjs'; +/** + * Runs the generator over the given batches of entries, streamed in as + * `metadata` yields them, and collects what it yields. + * + * @param {...Array} batches + * @returns {Promise>} + */ +const run = (...batches) => collectAsyncGenerator(generate(streamOf(batches))); + +/** + * Yields each batch in turn, as a streamed input. + * + * @param {Array>} batches + */ +async function* streamOf(batches) { + yield* batches; +} + /** * Builds a metadata-shaped entry whose heading node is shared between * `heading` and `content`, exactly like the metadata generator produces. @@ -72,7 +91,7 @@ describe('section-pages generate', () => { it('keeps every original entry and appends the chunk pages', async () => { const input = createModule(); - const output = await generate(input); + const output = await run(input); assert.deepEqual(output.slice(0, input.length), input); @@ -97,7 +116,7 @@ describe('section-pages generate', () => { }); it('describes where each chunk came from', async () => { - const output = await generate(createModule()); + const output = await run(createModule()); const readFile = output.find(e => e.path === '/fs/readFile'); assert.deepEqual(readFile.chunk, { @@ -111,7 +130,7 @@ describe('section-pages generate', () => { }); it('promotes headings so the chunk reads as its own page', async () => { - const output = await generate(createModule()); + const output = await run(createModule()); const dir = output.filter(e => e.api === 'fs-Dir'); assert.deepEqual( @@ -134,13 +153,13 @@ describe('section-pages generate', () => { const input = createModule(); const snapshot = structuredClone(input); - await generate(input); + await run(input); assert.deepEqual(input, snapshot); }); it('leaves modules with a single section alone', async () => { - const output = await generate([ + const output = await run([ createEntry('tiny', 1, 'Tiny'), createEntry('tiny', 2, '`tiny.only()`', { name: 'only', type: 'method' }), ]); @@ -149,7 +168,7 @@ describe('section-pages generate', () => { }); it('leaves modules that document no API entry alone', async () => { - const output = await generate([ + const output = await run([ createEntry('guide', 1, 'About this documentation'), createEntry('guide', 2, 'Contributing'), createEntry('guide', 2, 'Stability index'), @@ -172,7 +191,7 @@ describe('section-pages generate', () => { link('https://example.com') ); - const output = await generate(input); + const output = await run(input); const chunk = output.find(e => e.path === '/fs/readFile'); assert.deepEqual( @@ -206,7 +225,7 @@ describe('section-pages generate', () => { }, }); - const output = await generate(input); + const output = await run(input); const chunk = output.find(e => e.path === '/fs/readFile'); assert.deepEqual( @@ -225,7 +244,9 @@ describe('section-pages generate', () => { getConfig('section-pages').exclude = ['fs']; try { - assert.equal((await generate(createModule())).length, 6); + const output = await run(createModule()); + + assert.equal(output.length, 6); } finally { getConfig('section-pages').exclude = []; } @@ -235,7 +256,7 @@ describe('section-pages generate', () => { getConfig('section-pages').maxDepth = 2; try { - const output = await generate(createModule()); + const output = await run(createModule()); assert.deepEqual( output.filter(e => e.chunk && e.heading.depth === 1).map(e => e.path), @@ -245,4 +266,53 @@ describe('section-pages generate', () => { getConfig('section-pages').maxDepth = 3; } }); + + it('builds the same output from several batches as from its whole input', async () => { + const tiny = [ + createEntry('tiny', 1, 'Tiny'), + createEntry('tiny', 2, '`tiny.only()`', { name: 'only', type: 'method' }), + ]; + + const batched = await run(createModule(), tiny); + + // The whole input as one batch, as it comes with one thread + const whole = await run([...createModule(), ...tiny]); + + assert.deepEqual(batched, whole); + }); + + it( + 'passes each batch on before the next one arrives', + // The next batch waits for the test, so a batch held back until it + // arrives would never be passed on + { timeout: 10_000 }, + async () => { + const gate = Promise.withResolvers(); + const first = [...createModule(), createEntry('tiny', 1, 'Tiny')]; + + async function* batches() { + yield first; + await gate.promise; + yield [createEntry('zlib', 1, 'Zlib')]; + } + + const output = generate(batches()); + const { value } = await output.next(); + + assert.deepEqual(value, first); + + gate.resolve(); + + const rest = await collectAsyncGenerator(output); + + assert.deepEqual( + rest.filter(e => !e.chunk).map(e => e.api), + ['zlib'] + ); + assert.equal( + rest.filter(e => e.chunk && e.heading.depth === 1).length, + 3 + ); + } + ); }); diff --git a/packages/react/src/section-pages/generate.mjs b/packages/react/src/section-pages/generate.mjs index 12e134cd5..7a506bbcb 100644 --- a/packages/react/src/section-pages/generate.mjs +++ b/packages/react/src/section-pages/generate.mjs @@ -100,14 +100,14 @@ const buildChunkEntries = (module, chunk, index, anchors) => { }; /** - * Adds per-section chunk pages for every module, next to the full pages. + * Builds the chunk pages of every module among the given entries. * - * @type {import('./types').Generator['generate']} + * @param {Array} input - Whole modules' entries + * @param {import('./types').Configuration} config + * @returns {Array} */ -export async function generate(input) { - const { maxDepth, exclude } = getConfig('section-pages'); - - const output = [...input]; +const buildChunkPages = (input, { maxDepth, exclude }) => { + const pages = []; for (const entries of groupNodesByModule(input).values()) { const module = entries.find(entry => entry.heading.depth === 1); @@ -135,9 +135,37 @@ export async function generate(input) { const anchors = buildAnchorMap(chunks); chunks.forEach((chunk, index) => { - output.push(...buildChunkEntries(module, chunk, index, anchors)); + pages.push(...buildChunkEntries(module, chunk, index, anchors)); }); } - return output; + return pages; +}; + +/** + * Adds per-section chunk pages for every module, next to the full pages. + * + * The entries are passed on as their modules arrive, so the pages built from + * them can start while `metadata` still runs, and the chunk pages follow them + * all, in module order, as if built from the whole input at once. + * + * @type {import('./types').Generator['generate']} + */ +export async function* generate(input) { + const config = getConfig('section-pages'); + + const chunkPages = []; + + // A module's chunk pages need all of its entries, which arrive in the same + // batch: each batch `metadata` yields holds whole files, and a file is one + // module + for await (const entries of input) { + yield entries; + + chunkPages.push(...buildChunkPages(entries, config)); + } + + if (chunkPages.length > 0) { + yield chunkPages; + } } diff --git a/packages/react/src/section-pages/index.mjs b/packages/react/src/section-pages/index.mjs index b1043d110..380d1883c 100644 --- a/packages/react/src/section-pages/index.mjs +++ b/packages/react/src/section-pages/index.mjs @@ -29,6 +29,8 @@ export default { dependsOn: '@doc-kit/core/metadata', + streamsInput: true, + dependent: [ '@doc-kit/generator-react/html', '@doc-kit/generator-react/sitemap', diff --git a/packages/react/src/section-pages/types.d.ts b/packages/react/src/section-pages/types.d.ts index bf57e1ee2..cccbf59c3 100644 --- a/packages/react/src/section-pages/types.d.ts +++ b/packages/react/src/section-pages/types.d.ts @@ -24,5 +24,8 @@ export type Chunk = { export type Generator = GeneratorMetadata< Configuration, - Generate, Promise>> + Generate< + AsyncIterable>, + AsyncGenerator> + > >;