Commit | Line | Data |
---|---|---|
a449b585 | 1 | import type { TransferListItem } from 'node:worker_threads' |
ded253e2 | 2 | |
ef083f7b | 3 | import type { FastifyPluginCallback } from 'fastify' |
a8706532 | 4 | import fp from 'fastify-plugin' |
ded253e2 JB |
5 | import { availableParallelism, DynamicThreadPool } from 'poolifier' |
6 | ||
80115618 JB |
7 | import type { |
8 | FastifyPoolifierOptions, | |
9 | WorkerData, | |
3a502712 | 10 | WorkerResponse, |
a8706532 JB |
11 | } from './types.js' |
12 | ||
13 | const fastifyPoolifierPlugin: FastifyPluginCallback<FastifyPoolifierOptions> = ( | |
14 | fastify, | |
15 | options, | |
16 | done | |
e18b3556 | 17 | ) => { |
6ff35e73 JB |
18 | options = { |
19 | ...{ | |
20 | minWorkers: 1, | |
3a502712 | 21 | maxWorkers: availableParallelism(), |
6ff35e73 | 22 | }, |
3a502712 | 23 | ...options, |
6ff35e73 | 24 | } |
30369cc0 | 25 | const { workerFile, minWorkers, maxWorkers, ...poolOptions } = options |
a8706532 | 26 | const pool = new DynamicThreadPool<WorkerData, WorkerResponse>( |
3a502712 | 27 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
67f3f2d6 | 28 | minWorkers!, |
3a502712 | 29 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
67f3f2d6 | 30 | maxWorkers!, |
30369cc0 JB |
31 | workerFile, |
32 | poolOptions | |
a8706532 JB |
33 | ) |
34 | if (!fastify.hasDecorator('pool')) { | |
35 | fastify.decorate('pool', pool) | |
36 | } | |
37 | if (!fastify.hasDecorator('execute')) { | |
38 | fastify.decorate( | |
39 | 'execute', | |
d2bc8d80 JB |
40 | async ( |
41 | data?: WorkerData, | |
42 | name?: string, | |
6a3ecc50 | 43 | transferList?: readonly TransferListItem[] |
d2bc8d80 | 44 | ): Promise<WorkerResponse> => await pool.execute(data, name, transferList) |
a8706532 JB |
45 | ) |
46 | } | |
b6dbd509 | 47 | done() |
a8706532 JB |
48 | } |
49 | ||
50 | export const fastifyPoolifier = fp(fastifyPoolifierPlugin, { | |
51 | fastify: '4.x', | |
3a502712 | 52 | name: 'fastify-poolifier', |
a8706532 | 53 | }) |