486d92e77a73e8f3ac003b655b34e1a4b4615574
[poolifier.git] / src / worker / utils.ts
1 import { checkValidWorkerChoiceStrategy } from '../pools/utils.js'
2 import { isPlainObject } from '../utils.js'
3 import type { TaskFunctionObject } from './task-functions.js'
4 import { KillBehaviors, type WorkerOptions } from './worker-options.js'
5
6 export const checkValidWorkerOptions = (
7 opts: WorkerOptions | undefined
8 ): void => {
9 if (opts != null && !isPlainObject(opts)) {
10 throw new TypeError('opts worker options parameter is not a plain object')
11 }
12 if (
13 opts?.killBehavior != null &&
14 !Object.values(KillBehaviors).includes(opts.killBehavior)
15 ) {
16 throw new TypeError(
17 `killBehavior option '${opts.killBehavior}' is not valid`
18 )
19 }
20 if (
21 opts?.maxInactiveTime != null &&
22 !Number.isSafeInteger(opts.maxInactiveTime)
23 ) {
24 throw new TypeError('maxInactiveTime option is not an integer')
25 }
26 if (opts?.maxInactiveTime != null && opts.maxInactiveTime < 5) {
27 throw new TypeError(
28 'maxInactiveTime option is not a positive integer greater or equal than 5'
29 )
30 }
31 if (opts?.killHandler != null && typeof opts.killHandler !== 'function') {
32 throw new TypeError('killHandler option is not a function')
33 }
34 }
35
36 export const checkValidTaskFunctionEntry = <Data = unknown, Response = unknown>(
37 name: string,
38 fnObj: TaskFunctionObject<Data, Response>
39 ): void => {
40 if (typeof name !== 'string') {
41 throw new TypeError('A taskFunctions parameter object key is not a string')
42 }
43 if (typeof name === 'string' && name.trim().length === 0) {
44 throw new TypeError(
45 'A taskFunctions parameter object key is an empty string'
46 )
47 }
48 if (typeof fnObj.taskFunction !== 'function') {
49 throw new TypeError(
50 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
51 `taskFunction object 'taskFunction' property '${fnObj.taskFunction}' is not a function`
52 )
53 }
54 if (fnObj.priority != null && !Number.isSafeInteger(fnObj.priority)) {
55 throw new TypeError(
56 `taskFunction object 'priority' property '${fnObj.priority}' is not an integer`
57 )
58 }
59 checkValidWorkerChoiceStrategy(fnObj.strategy)
60 }
61
62 export const checkTaskFunctionName = (name: string): void => {
63 if (typeof name !== 'string') {
64 throw new TypeError('name parameter is not a string')
65 }
66 if (typeof name === 'string' && name.trim().length === 0) {
67 throw new TypeError('name parameter is an empty string')
68 }
69 }