Skip to content
Open
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
6 changes: 6 additions & 0 deletions .changeset/cloneable-worker-config.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@doc-kit/core': patch
'@doc-kit/generator-react': patch
---

Leave values that can't be cloned, such as functions, out of the configuration sent to worker threads. A configured `html.bundler`, the Vite adapter included, no longer needs `threads: 1`.
6 changes: 4 additions & 2 deletions docs/creating-generators.md
Original file line number Diff line number Diff line change
Expand Up @@ -261,8 +261,10 @@ Filtering entries is light work, but heavier work takes the same shape.
- The items, `deps`, the results, and the generator's configuration section
are copied between threads with the
[structured clone algorithm](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm).
Functions can't be copied (passing one throws a `DataCloneError`), and class
instances arrive as plain objects.
Functions can't be copied (passing one in the items or `deps` throws a
`DataCloneError`), and class instances arrive as plain objects. Values in the
configuration that can't be copied, such as functions and `URL`s, are left
out of the copy a worker gets.
- Each worker imports your module on its own, so `processChunk` sees nothing
`generate` set up: pass what it needs in `deps`. A module only
`processChunk` uses can be imported inside it, as the `metadata` generator
Expand Down
1 change: 1 addition & 0 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
"remark-stringify": "^11.0.0",
"semver": "^7.8.5",
"shiki": "^4.5.0",
"to-cloneable": "^1.0.0",
"unified": "^11.0.5",
"unist-builder": "^4.0.0",
"unist-util-find-after": "^5.0.0",
Expand Down
26 changes: 26 additions & 0 deletions packages/core/src/threading/__tests__/parallel.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,32 @@ describe('createParallelWorker', () => {
deepStrictEqual(await result, [0, 1, 2, 3, 4]);
});

it('sends workers only what can be cloned of the configuration', async () => {
const configurations = [];
const pool = {
run: async task => {
configurations.push(structuredClone(task.configuration));

return task.input;
},
};
const worker = createParallelWorker('ast-js', astJsGenerator, pool, {
threads: 2,
chunkSize: 1,
'ast-js': {
minify: true,
bundler: { compile: () => {}, name: 'custom' },
},
other: { minify: false },
});

await collectStream(worker.stream([0, 1, 2], {}));

deepStrictEqual(configurations[0], {
'ast-js': { minify: true, bundler: { name: 'custom' } },
});
});

it('propagates a later worker failure without an unhandled rejection', async () => {
const tasks = [];
const pool = {
Expand Down
19 changes: 10 additions & 9 deletions packages/core/src/threading/parallel.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
'use strict';

import { toCloneable } from 'to-cloneable';

import logger from '#logger/index.mjs';
import { isAsyncIterable } from '#utils/misc.mjs';

Expand Down Expand Up @@ -32,18 +34,16 @@ const createChunks = (count, size) => {
* @param {unknown[]} fullInput - Full input array
* @param {number[]} indices - Indices to process
* @param {Object} extra - Stuff to pass to the worker
* @param {import('../utils/configuration/types').Configuration} configuration - Serialized options
* @param {Partial<import('../utils/configuration/types').Configuration>} configuration - The configuration the worker gets
* @param {string} generatorSpecifier - Resolved specifier of the generator
* @param {string} generatorName - Name of the generator
* @returns {ParallelTaskOptions} Task data for Piscina
*/
const createTask = (
fullInput,
indices,
extra,
configuration,
generatorSpecifier,
generatorName
generatorSpecifier
) => {
return {
generatorSpecifier,
Expand All @@ -52,10 +52,7 @@ const createTask = (
// Remap indices to 0-based for the sliced array
itemIndices: indices.map((_, i) => i),
extra,
// Only pass the needed configuration to this generator
configuration: {
[generatorName]: configuration[generatorName],
},
configuration,
};
};

Expand All @@ -78,6 +75,10 @@ export default function createParallelWorker(

const { name } = generator;

// Only this generator's configuration, without what can't be sent to a
// worker, such as a bundler's functions, which only this thread uses
const workerConfiguration = { [name]: toCloneable(configuration[name]) };

return {
/**
* Processes items in parallel, yielding results in submission order.
Expand Down Expand Up @@ -165,7 +166,7 @@ export default function createParallelWorker(
running++;

const task = pool.run(
createTask(batch, indices, extra, configuration, specifier, name)
createTask(batch, indices, extra, workerConfiguration, specifier)
);

tasks.push(
Expand Down
10 changes: 1 addition & 9 deletions packages/react/src/html/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -534,12 +534,6 @@ When you customize the site, keep in mind that:
The `bundler` option takes a small adapter, so the site can be built with Vite
(the default) or any other bundler.

> [!WARNING]
> Worker threads receive a copy of the configuration, and functions can't be
> copied. A configuration that sets `bundler`, the Vite adapter included, must
> build with `threads: 1` (or `--threads 1`). With more threads, the build
> fails with a `DataCloneError`.

### Writing an adapter

An adapter is an object with three methods. The generator calls `buildServer`
Expand Down Expand Up @@ -584,7 +578,7 @@ CSS modules, resolve the `config.imports` aliases, and serve the
indefinitely.

An adapter can live in your project, without changes to doc-kit. Pass it as
`bundler`, with `threads: 1`:
`bundler`:

```js displayName="webpack-bundler.mjs"
export const createWebpackBundler = webpackOptions => ({
Expand Down Expand Up @@ -617,8 +611,6 @@ import { createViteBundler } from '@doc-kit/generator-react/html/bundlers/vite';
import myVitePlugin from './my-vite-plugin.mjs';

export default {
threads: 1,

html: {
bundler: createViteBundler({
plugins: [myVitePlugin()],
Expand Down
9 changes: 9 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading