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, | |
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, | |
21 | maxWorkers: availableParallelism() | |
22 | }, | |
23 | ...options | |
24 | } | |
30369cc0 | 25 | const { workerFile, minWorkers, maxWorkers, ...poolOptions } = options |
3b311539 | 26 | const pool = new DynamicThreadPool<ThreadWorkerData, ThreadWorkerResponse>( |
67f3f2d6 JB |
27 | minWorkers!, |
28 | maxWorkers!, | |
30369cc0 JB |
29 | workerFile, |
30 | poolOptions | |
3b311539 JB |
31 | ) |
32 | if (!fastify.hasDecorator('pool')) { | |
33 | fastify.decorate('pool', pool) | |
34 | } | |
35 | if (!fastify.hasDecorator('execute')) { | |
36 | fastify.decorate( | |
37 | 'execute', | |
38 | async ( | |
39 | data?: ThreadWorkerData, | |
40 | name?: string, | |
6a3ecc50 | 41 | transferList?: readonly TransferListItem[] |
3b311539 JB |
42 | ): Promise<ThreadWorkerResponse> => |
43 | await pool.execute(data, name, transferList) | |
44 | ) | |
45 | } | |
46 | done() | |
47 | } | |
48 | ||
49 | export const fastifyPoolifier = fp(fastifyPoolifierPlugin, { | |
50 | fastify: '4.x', | |
51 | name: 'fastify-poolifier' | |
52 | }) |