81a57698f5fa6a7dc5e631cbdec844ee68c44c2c
[poolifier.git] / src / utility-types.ts
1 import type { Worker as ClusterWorker } from 'node:cluster'
2 import type { MessagePort } from 'node:worker_threads'
3 import type { KillBehavior } from './worker/worker-options'
4 import type { IWorker, Task } from './pools/worker'
5
6 /**
7 * Make all properties in T non-readonly.
8 *
9 * @typeParam T - Type in which properties will be non-readonly.
10 */
11 export type Draft<T> = { -readonly [P in keyof T]?: T[P] }
12
13 /**
14 * Message object that is passed between main worker and worker.
15 *
16 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
17 * @typeParam MainWorker - Type of main worker.
18 * @internal
19 */
20 export interface MessageValue<
21 Data = unknown,
22 MainWorker extends ClusterWorker | MessagePort | unknown = unknown
23 > extends Task<Data> {
24 /**
25 * Kill code.
26 */
27 readonly kill?: KillBehavior | 1
28 /**
29 * Error.
30 */
31 readonly error?: string
32 /**
33 * Runtime.
34 */
35 readonly runTime?: number
36 /**
37 * Reference to main worker.
38 */
39 readonly parent?: MainWorker
40 }
41
42 /**
43 * Worker function that can be executed types.
44 */
45 export type WorkerSyncFunction<Data = unknown, Response = unknown> = (
46 data?: Data
47 ) => Response
48 export type WorkerAsyncFunction<Data = unknown, Response = unknown> = (
49 data?: Data
50 ) => Promise<Response>
51 export type WorkerFunction<Data = unknown, Response = unknown> =
52 | WorkerSyncFunction<Data, Response>
53 | WorkerAsyncFunction<Data, Response>
54
55 /**
56 * An object holding the execution response promise resolve/reject callbacks.
57 *
58 * @typeParam Worker - Type of worker.
59 * @typeParam Response - Type of execution response. This can only be serializable data.
60 * @internal
61 */
62 export interface PromiseResponseWrapper<
63 Worker extends IWorker,
64 Response = unknown
65 > {
66 /**
67 * Resolve callback to fulfill the promise.
68 */
69 readonly resolve: (value: Response) => void
70 /**
71 * Reject callback to reject the promise.
72 */
73 readonly reject: (reason?: string) => void
74 /**
75 * The worker handling the execution.
76 */
77 readonly worker: Worker
78 }