# parallel-executor

<a href="https://www.npmjs.com/package/parallel-executor"><img src="https://img.shields.io/npm/v/parallel-executor.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/package/parallel-executor"><img src="https://img.shields.io/npm/l/parallel-executor.svg" alt="Package License" /></a>

Runs a function over an array using all CPU cores. The array is split into
batches, each batch is processed in parallel, and the results are returned
in the same order as the input.

It works in Node.js (with child processes) and in the browser (with Web
Workers). Both versions have the same API.

## Installation

```console
npm i parallel-executor
```

Node.js 18.14 or newer is required for the server version. Works with both
`import` and `require`.

| Import path                | Runs the task in                  |
| -------------------------- | --------------------------------- |
| `parallel-executor/server` | child processes (Node.js)         |
| `parallel-executor/client` | Web Workers (browser)             |
| `parallel-executor`        | picks one of the above, see below |

`parallel-executor` gives you the client version when your bundler targets
the browser (it uses the `browser` export condition, which Vite, webpack,
esbuild and Rollup support), and the server version everywhere else. Import
`/server` or `/client` directly if you want to be explicit.

## Usage

### Node.js

```js
import { parallelExecute } from 'parallel-executor/server'

const tasks = Array.from({ length: 15 }, (_, i) => i + 1)

const results = await parallelExecute(tasks, (batch) =>
  batch.map((id) => {
    let sum = 0
    for (let i = 0; i < 500_000_000; i++) sum += i % 10
    return `Task ${id} result: ${sum}`
  })
)

console.log(results[0]) // 'Task 1 result: 2250000000'
```

The heavy loop runs in child processes, one per CPU core. With all cores in
use it finishes several times faster than running it in a single process.

### Browser

```js
import { parallelExecute } from 'parallel-executor/client'

const tasks = Array.from({ length: 15 }, (_, i) => i + 1)

const results = await parallelExecute(tasks, (batch) =>
  batch.map((id) => {
    let sum = 0
    for (let i = 0; i < 500_000_000; i++) sum += i % 10
    return `Task ${id} result: ${sum}`
  })
)
```

The heavy loop runs in Web Workers, so the page stays responsive while it
runs. With all cores in use it finishes several times faster than running
it on the main thread.

## How it works

1. `data` is split into one batch per worker. Items are handed out in
   turn, so with 8 workers the batches of the examples above are
   `[1, 9], [2, 10], [3, 11], [4, 12], [5, 13], [6, 14], [7, 15], [8]`.
2. A worker is started for each batch. In Node.js a worker is a child
   process started with `child_process.fork`. In the browser it is a Web
   Worker created from an inline script, so no extra file has to be
   served.
3. The source code of the task, the batch and `params` are sent to the
   worker. The worker runs the task and sends the result back.
4. When all batches are done, the results are put back in the original
   order and the workers are stopped.

## Writing the task

The task is converted to a string and recreated in the worker, so:

- It can't use variables from outside its own body. Pass the values it
  needs through `params`.
- It has to be an arrow function or a function expression. Class methods
  and bound functions don't work.
- `params`, the data and the results are copied between workers with the
  [structured clone algorithm](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm).
  `Map`, `Set`, `Date`, `BigInt` and similar values are supported.
  Functions and class instances are not.
- In Node.js the task can load modules with `require()` or `await import()`
  inside its body. Use absolute paths for your own files, for example by
  passing `import.meta.dirname` or `__dirname` in `params`.
- In the browser the task can load scripts with `await import(url)` using
  a full URL. It has no access to the DOM, the same as any Web Worker.
- In the browser the task is recreated with `new Function`, so a Content
  Security Policy has to allow `'unsafe-eval'` and `blob:` workers.

```js
import { parallelExecute } from 'parallel-executor/server'

const results = await parallelExecute(
  files,
  async (batch, params) => {
    const { readFile } = require('node:fs/promises')
    const { join } = require('node:path')
    const { parse } = require(join(params.dir, 'parser.js'))

    return Promise.all(
      batch.map(async (file) => parse(await readFile(file, 'utf8')))
    )
  },
  { params: { dir: import.meta.dirname } }
)
```

## API

### `parallelExecute(data, task, options?)`

The same function is exported from `parallel-executor/server` and
`parallel-executor/client`.

Returns a promise with an array of results, one for each item of `data`, in
the same order.

- `data` - the array to process.
- `task(batch, params, workerIndex)` - called once in each worker.
  - `batch` - the part of `data` given to this worker.
  - `params` - the `params` option.
  - `workerIndex` - the index of this worker, starting from `0`.

  It has to return (or resolve to) an array with one result for each item
  of `batch`, in the same order. If it returns nothing, every result is
  `undefined`.

- `options`
  - `params` - a value passed to the task.
  - `workers` - number of workers. Defaults to the number of CPU cores
    (`os.availableParallelism()` in Node.js,
    `navigator.hardwareConcurrency` in the browser). It is never more than
    `data.length`.
  - `maxOldSpaceSize` - server only. Sets `--max-old-space-size` (in MB)
    for each child process.

The promise is rejected and all workers are stopped if:

- the task throws in any worker (the promise is rejected with that error),
- a worker stops before sending its result (a child process exits, or a
  Web Worker has an uncaught error),
- the result can't be copied back (for example it contains a function),
- the task returns an array of the wrong length.

### TypeScript

Types are included:

```ts
import {
  parallelExecute,
  type ExecuteOptions,
  type Task
} from 'parallel-executor/client'

const results = await parallelExecute<number, string>([1, 2, 3], (batch) =>
  batch.map(String)
)
```

The compiled code of the task is what gets sent to the worker. If your
compiler adds helper functions to it (for example when targeting old
JavaScript versions), the task will fail in the worker.

## License

ISC
