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