-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathnodeWorker.ts
190 lines (169 loc) · 4.66 KB
/
nodeWorker.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import { Worker } from 'node:worker_threads';
import { FuctionRequest } from './ioTService.js';
import * as path from 'path';
import { Configuration } from './configuration.js';
import { getModuleDirname, getProjectDirname } from './getDirname.js';
import { Logger } from './logger.js';
interface MyWorker extends Worker {
used?: boolean;
toKill?: boolean;
onMessage?: (msg: any) => void;
onError?: (err: any) => void;
}
const workers = new Map<string, MyWorker>();
/**
* Run the function in a Node.js Worker Thread
* @param input
* @returns
*/
async function runInWorker(input: {
artifactFile: string;
environment: {
[key: string]: string | undefined;
};
fuctionRequest: FuctionRequest;
}) {
const func = await Configuration.getLambda(input.fuctionRequest.functionId);
return new Promise<void>((resolve, reject) => {
let worker: MyWorker | undefined = workers.get(
input.fuctionRequest.workerId,
);
if (!worker) {
const environment = input.environment;
addEnableSourceMapsToEnv(environment);
worker = startWorker({
handler: func.handler ?? 'handler',
artifactFile: input.artifactFile,
workerId: input.fuctionRequest.workerId,
functionId: input.fuctionRequest.functionId,
environment,
verbose: Configuration.config.verbose,
});
worker.used = false;
worker.toKill = false;
} else {
Logger.verbose(
`[Function ${input.fuctionRequest.functionId}] [Worker ${input.fuctionRequest.workerId}] Reusing worker`,
);
}
worker.onMessage = (msg) => {
Logger.verbose(
`[Function ${input.fuctionRequest.functionId}] [Worker ${input.fuctionRequest.workerId}] Worker message`,
JSON.stringify(msg),
);
worker.used = false;
if (msg?.errorType) {
reject(msg);
} else {
resolve(msg);
}
if (worker.toKill) {
worker.toKill = false;
void worker.terminate();
}
};
worker.onError = (err) => {
Logger.error(
`[Function ${input.fuctionRequest.functionId}] [Worker ${input.fuctionRequest.workerId}] Error`,
err,
);
reject(err);
};
worker.used = true;
worker.postMessage({
env: input.fuctionRequest.env,
event: input.fuctionRequest.event,
context: input.fuctionRequest.context,
});
});
}
/**
* Add NODE_OPTIONS: --enable-source-maps to the environment variables
* @param environment
*/
function addEnableSourceMapsToEnv(environment: {
[key: string]: string | undefined;
}) {
const nodeOptions = environment.NODE_OPTIONS || '';
if (!nodeOptions.includes('--enable-source-maps')) {
environment.NODE_OPTIONS =
nodeOptions + (nodeOptions ? ' ' : '') + '--enable-source-maps';
}
}
type WorkerRequest = {
handler: string;
artifactFile: string;
workerId: string;
functionId: string;
environment: {
[key: string]: string | undefined;
};
verbose?: boolean;
};
/**
* Start a new Node.js Worker Thread
* @param input
* @returns
*/
function startWorker(input: WorkerRequest) {
Logger.verbose(
`[Function ${input.functionId}] [Worker ${input.workerId}] Starting worker. Artifact: ${input.artifactFile}`,
);
const localProjectDir = getProjectDirname();
const worker: MyWorker = new Worker(
path.resolve(path.join(getModuleDirname(), `./nodeWorkerRunner.mjs`)),
{
env: {
...input.environment,
IS_LOCAL: 'true',
LOCAL_PROJECT_DIR: localProjectDir,
},
execArgv: ['--enable-source-maps'],
workerData: input,
stderr: true,
stdin: true,
stdout: true,
//type: "module",
},
);
worker.stdout.on('data', (data: Buffer) => {
Logger.log(`[Function ${input.functionId}]`, data.toString());
});
worker.stderr.on('data', (data: Buffer) => {
Logger.error(`[Function ${input.functionId}]`, data.toString());
});
worker.on('exit', () => {
Logger.verbose(
`[Function ${input.functionId}] [Worker ${input.workerId}] Worker exited`,
);
workers.delete(input.workerId);
});
workers.set(input.workerId, worker);
worker.on('message', (msg) => {
worker?.onMessage?.(msg);
});
worker.on('error', (err) => {
worker?.onError?.(err);
});
return worker;
}
/**
* Stop all Node.js Worker Threads
*/
async function stopAllWorkers() {
Logger.verbose('Stopping all workers');
const promises: Promise<any>[] = [];
for (const worker of workers.values()) {
if (worker.used) {
worker.toKill = true;
} else {
promises.push(worker.terminate());
}
}
workers.clear();
await Promise.all(promises);
}
export const NodeWorker = {
runInWorker,
stopAllWorkers,
};