79d24dc61fe0a3f47a25d4e5fb5ddeb5880e2a2a
[poolifier.git] / examples / typescript / http-server-pool / fastify-hybrid / src / fastify-poolifier.ts
1 import type { TransferListItem } from 'node:worker_threads'
2
3 import type { FastifyPluginCallback } from 'fastify'
4 import fp from 'fastify-plugin'
5 import { availableParallelism, DynamicThreadPool } from 'poolifier'
6
7 import {
8 type FastifyPoolifierOptions,
9 type ThreadWorkerData,
10 type ThreadWorkerResponse
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 }
25 const { workerFile, minWorkers, maxWorkers, ...poolOptions } = options
26 const pool = new DynamicThreadPool<ThreadWorkerData, ThreadWorkerResponse>(
27 minWorkers!,
28 maxWorkers!,
29 workerFile,
30 poolOptions
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,
41 transferList?: TransferListItem[]
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 })