Commit | Line | Data |
---|---|---|
a449b585 | 1 | import type { TransferListItem } from 'node:worker_threads' |
ded253e2 | 2 | |
ef083f7b | 3 | import type { FastifyPluginCallback } from 'fastify' |
3b311539 | 4 | import fp from 'fastify-plugin' |
ded253e2 JB |
5 | import { availableParallelism, DynamicThreadPool } from 'poolifier' |
6 | ||
80115618 JB |
7 | import type { |
8 | FastifyPoolifierOptions, | |
9 | ThreadWorkerData, | |
3a502712 | 10 | ThreadWorkerResponse, |
3b311539 JB |
11 | } from './types.js' |
12 | ||
13 | const fastifyPoolifierPlugin: FastifyPluginCallback<FastifyPoolifierOptions> = ( | |
14 | fastify, | |
15 | options, | |
16 | done | |
17 | ) => { | |
18 | options = { | |
19 | ...{ | |
20 | minWorkers: 1, | |
3a502712 | 21 | maxWorkers: availableParallelism(), |
3b311539 | 22 | }, |
3a502712 | 23 | ...options, |
3b311539 | 24 | } |
30369cc0 | 25 | const { workerFile, minWorkers, maxWorkers, ...poolOptions } = options |
3b311539 | 26 | const pool = new DynamicThreadPool<ThreadWorkerData, ThreadWorkerResponse>( |
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 | |
3b311539 JB |
33 | ) |
34 | if (!fastify.hasDecorator('pool')) { | |
35 | fastify.decorate('pool', pool) | |
36 | } | |
37 | if (!fastify.hasDecorator('execute')) { | |
38 | fastify.decorate( | |
39 | 'execute', | |
40 | async ( | |
41 | data?: ThreadWorkerData, | |
42 | name?: string, | |
6a3ecc50 | 43 | transferList?: readonly TransferListItem[] |
3b311539 JB |
44 | ): Promise<ThreadWorkerResponse> => |
45 | await pool.execute(data, name, transferList) | |
46 | ) | |
47 | } | |
48 | done() | |
49 | } | |
50 | ||
51 | export const fastifyPoolifier = fp(fastifyPoolifierPlugin, { | |
52 | fastify: '4.x', | |
3a502712 | 53 | name: 'fastify-poolifier', |
3b311539 | 54 | }) |