Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .changeset/stream-input.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
6 changes: 6 additions & 0 deletions .changeset/stream-metadata.md
Original file line number Diff line number Diff line change
@@ -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.
4 changes: 3 additions & 1 deletion docs/creating-generators.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
24 changes: 19 additions & 5 deletions packages/core/src/__tests__/generators.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
},
},
};

Expand Down Expand Up @@ -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,
Expand All @@ -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 () => {
Expand Down
12 changes: 1 addition & 11 deletions packages/core/src/caching.mjs
Original file line number Diff line number Diff line change
@@ -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';

Expand Down Expand Up @@ -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<T>}
*/
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.
Expand Down
27 changes: 21 additions & 6 deletions packages/core/src/generators.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand All @@ -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<unknown>}
*/
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);
};

/**
Expand Down Expand Up @@ -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}"`);
Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/generators/metadata/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ export default {

hasParallelProcessor: true,

streamsInput: true,

markdown: {
remarkPlugins: [
'remark-parse',
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/generators/metadata/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { Position } from 'unist';

export type Generator = GeneratorMetadata<
{},
Generate<Array<Root>, AsyncGenerator<MetadataEntry>>,
Generate<AsyncIterable<Array<Root>>, AsyncGenerator<MetadataEntry>>,
ProcessChunk<Root, MetadataEntry, Record<string, string>>
>;

Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/generators/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
9 changes: 9 additions & 0 deletions packages/core/src/utils/__tests__/generators.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
getVersionFromSemVer,
coerceSemVer,
getCompatibleVersions,
once,
} from '../generators.mjs';

describe('getEntryDescription', () => {
Expand Down Expand Up @@ -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]]);
});
});
11 changes: 11 additions & 0 deletions packages/core/src/utils/generators.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>}
*/
export async function* once(value) {
yield value;
}

/**
* Parses the SemVer string into a Node.js-alike version
*
Expand Down
9 changes: 7 additions & 2 deletions packages/react/src/html/__tests__/generate.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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]))
);
Expand Down
Loading
Loading