/
process.ts
113 lines (96 loc) 路 2.97 KB
/
process.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import { stderr, stdout } from 'src/utils'
import {
ReadyMessage,
RequestMessage,
ResponseMessage,
StartupMessage,
TinypoolWorkerMessage,
} from '../common'
import { getHandler, throwInNextTick } from './utils'
type IncomingMessage =
| (StartupMessage & TinypoolWorkerMessage<'pool'>)
| (RequestMessage & TinypoolWorkerMessage<'port'>)
type OutgoingMessage =
| (ReadyMessage & TinypoolWorkerMessage<'pool'>)
| (ResponseMessage & TinypoolWorkerMessage<'port'>)
process.__tinypool_state__ = {
isChildProcess: true,
isTinypoolWorker: true,
workerData: null,
workerId: Number(process.env.TINYPOOL_WORKER_ID),
}
const memoryUsage = process.memoryUsage.bind(process)
const send = process.send!.bind(process)
process.on('message', (message: IncomingMessage) => {
// Message was not for port or pool
// It's likely end-users own communication between main and worker
if (!message || !message.__tinypool_worker_message__) return
if (message.source === 'pool') {
const { filename, name } = message
;(async function () {
if (filename !== null) {
await getHandler(filename, name)
}
send!(<OutgoingMessage>{
ready: true,
source: 'pool',
__tinypool_worker_message__: true,
})
})().catch(throwInNextTick)
return
}
if (message.source === 'port') {
return onMessage(message).catch(throwInNextTick)
}
throw new Error(`Unexpected TinypoolWorkerMessage ${JSON.stringify(message)}`)
})
async function onMessage(message: IncomingMessage & { source: 'port' }) {
const { taskId, task, filename, name } = message
let response: OutgoingMessage & Pick<typeof message, 'source'>
try {
const handler = await getHandler(filename, name)
if (handler === null) {
throw new Error(`No handler function exported from ${filename}`)
}
const result = await handler(task)
response = {
source: 'port',
__tinypool_worker_message__: true,
taskId,
result,
error: null,
usedMemory: memoryUsage().heapUsed,
}
// If the task used e.g. console.log(), wait for the stream to drain
// before potentially entering the `Atomics.wait()` loop, and before
// returning the result so that messages will always be printed even
// if the process would otherwise be ready to exit.
if (stdout()?.writableLength! > 0) {
await new Promise((resolve) => process.stdout.write('', resolve))
}
if (stderr()?.writableLength! > 0) {
await new Promise((resolve) => process.stderr.write('', resolve))
}
} catch (error) {
response = {
source: 'port',
__tinypool_worker_message__: true,
taskId,
result: null,
error: serializeError(error),
usedMemory: memoryUsage().heapUsed,
}
}
send!(response)
}
function serializeError(error: unknown) {
if (error instanceof Error) {
return {
...error,
name: error.name,
stack: error.stack,
message: error.message,
}
}
return String(error)
}