b5c1725a776572116cef3e51a0c9e477d43c45d6
[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 checkValidTaskFunctionObjectEntry = <
37 Data = unknown,
38 Response = unknown
39 >(
40 name: string,
41 fnObj: TaskFunctionObject<Data, Response>
42 ): void => {
43 if (typeof name !== 'string') {
44 throw new TypeError('A taskFunctions parameter object key is not a string')
45 }
46 if (typeof name === 'string' && name.trim().length === 0) {
47 throw new TypeError(
48 'A taskFunctions parameter object key is an empty string'
49 )
50 }
51 if (typeof fnObj.taskFunction !== 'function') {
52 throw new TypeError(
53 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
54 `taskFunction object 'taskFunction' property '${fnObj.taskFunction}' is not a function`
55 )
56 }
57 if (fnObj.priority != null && !Number.isSafeInteger(fnObj.priority)) {
58 throw new TypeError(
59 `taskFunction object 'priority' property '${fnObj.priority}' is not an integer`
60 )
61 }
62 checkValidWorkerChoiceStrategy(fnObj.strategy)
63 }
64
65 export const checkTaskFunctionName = (name: string): void => {
66 if (typeof name !== 'string') {
67 throw new TypeError('name parameter is not a string')
68 }
69 if (typeof name === 'string' && name.trim().length === 0) {
70 throw new TypeError('name parameter is an empty string')
71 }
72 }