feat: add per task function strategy support
[poolifier.git] / src / worker / utils.ts
CommitLineData
31847469 1import { checkValidWorkerChoiceStrategy } from '../pools/utils.js'
d35e5717 2import { isPlainObject } from '../utils.js'
31847469 3import type { TaskFunctionObject } from './task-functions.js'
d35e5717 4import { KillBehaviors, type WorkerOptions } from './worker-options.js'
9a38f99e 5
c63a35a0
JB
6export const checkValidWorkerOptions = (
7 opts: WorkerOptions | undefined
8): void => {
9a38f99e
JB
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 }
9a38f99e
JB
34}
35
bcfb06ce
JB
36export const checkValidTaskFunctionObjectEntry = <
37 Data = unknown,
38 Response = unknown
39>(
40 name: string,
41 fnObj: TaskFunctionObject<Data, Response>
42 ): void => {
9a38f99e
JB
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 }
31847469 51 if (typeof fnObj.taskFunction !== 'function') {
9a38f99e 52 throw new TypeError(
31847469
JB
53 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
54 `taskFunction object 'taskFunction' property '${fnObj.taskFunction}' is not a function`
9a38f99e
JB
55 )
56 }
31847469
JB
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)
9a38f99e
JB
63}
64
65export 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}