Commit | Line | Data |
---|---|---|
3b311539 JB |
1 | import type { TransferListItem } from 'worker_threads' |
2 | import { DynamicThreadPool, availableParallelism } from 'poolifier' | |
3 | import { type FastifyPluginCallback } from 'fastify' | |
4 | import fp from 'fastify-plugin' | |
5 | import { | |
6 | type FastifyPoolifierOptions, | |
7 | type ThreadWorkerData, | |
8 | type ThreadWorkerResponse | |
9 | } from './types.js' | |
10 | ||
11 | const fastifyPoolifierPlugin: FastifyPluginCallback<FastifyPoolifierOptions> = ( | |
12 | fastify, | |
13 | options, | |
14 | done | |
15 | ) => { | |
16 | options = { | |
17 | ...{ | |
18 | minWorkers: 1, | |
19 | maxWorkers: availableParallelism() | |
20 | }, | |
21 | ...options | |
22 | } | |
23 | const pool = new DynamicThreadPool<ThreadWorkerData, ThreadWorkerResponse>( | |
24 | options.minWorkers as number, | |
25 | options.maxWorkers as number, | |
26 | options.workerFile, | |
27 | options | |
28 | ) | |
29 | if (!fastify.hasDecorator('pool')) { | |
30 | fastify.decorate('pool', pool) | |
31 | } | |
32 | if (!fastify.hasDecorator('execute')) { | |
33 | fastify.decorate( | |
34 | 'execute', | |
35 | async ( | |
36 | data?: ThreadWorkerData, | |
37 | name?: string, | |
38 | transferList?: TransferListItem[] | |
39 | ): Promise<ThreadWorkerResponse> => | |
40 | await pool.execute(data, name, transferList) | |
41 | ) | |
42 | } | |
43 | done() | |
44 | } | |
45 | ||
46 | export const fastifyPoolifier = fp(fastifyPoolifierPlugin, { | |
47 | fastify: '4.x', | |
48 | name: 'fastify-poolifier' | |
49 | }) |