-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathnode-env-manager.ts
More file actions
236 lines (210 loc) · 8.79 KB
/
node-env-manager.ts
File metadata and controls
236 lines (210 loc) · 8.79 KB
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
import {
AnyEnvironment,
Communication,
IRunOptions,
Message,
MultiCounter,
socketClientInitializer,
} from '@dazl/engine-core';
import { IDisposable, SetMultiMap } from '@dazl/patterns';
import { fileURLToPath } from 'node:url';
import { parseArgs } from 'node:util';
import { extname } from 'node:path';
import { ConnectionHandlers, WsServerHost } from './ws-node-host.js';
import { ILaunchHttpServerOptions, launchEngineHttpServer } from './launch-http-server.js';
import { workerThreadInitializer2 } from './worker-thread-initializer2.js';
import { bindMetricsListener, type PerformanceMetrics } from './metrics-utils.js';
export interface RunningNodeEnvironment {
id: string;
dispose(): Promise<void>;
getMetrics(): Promise<PerformanceMetrics>;
activate?(value?: unknown): Promise<void>;
}
export interface NodeEnvConfig extends Pick<AnyEnvironment, 'env' | 'endpointType'> {
envType: AnyEnvironment['envType'] | 'remote';
remoteUrl?: string;
}
export type NodeEnvsFeatureMapping = {
featureToEnvironments: Record<string, string[]>;
availableEnvironments: Record<string, NodeEnvConfig>;
};
export class NodeEnvManager implements IDisposable {
private disposables = new Set<() => Promise<void>>();
isDisposed = () => false;
dispose = async () => {
this.isDisposed = () => true;
for (const disposable of this.disposables) {
await disposable();
}
};
envInstanceIdCounter = new MultiCounter();
id = 'node-environment-manager';
openEnvironments = new SetMultiMap<string, RunningNodeEnvironment>();
constructor(
private importMeta: { url: string },
private featureEnvironmentsMapping: NodeEnvsFeatureMapping,
) {}
public async autoLaunch(
runtimeOptions: Map<string, string | boolean | undefined>,
{
connectionHandlers,
...serverOptions
}: ILaunchHttpServerOptions & {
connectionHandlers?: ConnectionHandlers;
} = {},
lazy = false,
) {
process.env.ENGINE_FLOW_V2_DIST_URL = this.importMeta.url;
const disposeMetricsListener = bindMetricsListener(() => this.collectMetricsFromAllOpenEnvironments());
const verbose = Boolean(runtimeOptions.get('verbose'));
const staticDirPath = fileURLToPath(new URL('../web', this.importMeta.url));
const { port, socketServer, app, close } = await launchEngineHttpServer({ staticDirPath, ...serverOptions });
runtimeOptions.set('enginePort', port.toString());
const clientsHost = new WsServerHost(socketServer);
const disposeOnConnectionOpen = connectionHandlers?.onConnectionOpen
? clientsHost.registerConnectionHandler(connectionHandlers.onConnectionOpen)
: undefined;
const disposeOnConnectionClose = connectionHandlers?.onConnectionClose
? clientsHost.registerDisconnectionHandler(connectionHandlers.onConnectionClose)
: undefined;
const disposeOnReconnection = connectionHandlers?.onConnectionReconnect
? clientsHost.registerReconnectionHandler(connectionHandlers.onConnectionReconnect)
: undefined;
const disposeConnectionHandlers = () => {
disposeOnConnectionOpen?.();
disposeOnConnectionClose?.();
disposeOnReconnection?.();
};
clientsHost.addEventListener('message', handleRegistrationOnMessage);
const forwardingCom = new Communication(clientsHost, 'clients-host-com');
function handleRegistrationOnMessage({ data }: { data: Message }) {
const knownClientHost = forwardingCom.getEnvironmentHost(data.from);
if (knownClientHost === undefined) {
forwardingCom.registerEnv(data.from, clientsHost);
} else if (knownClientHost !== clientsHost) {
console.warn(
`[ENGINE]: environment ${data.from} is already registered to a different host, reregistering`,
);
forwardingCom.clearEnvironment(data.from);
forwardingCom.registerEnv(data.from, knownClientHost);
}
}
await this.runFeatureEnvironments(verbose, runtimeOptions, forwardingCom);
if (!lazy) {
await this.activateEnvs();
}
app.get('/health', (_req, res) => {
res.status(200).end();
});
const disposeAutoLaunch = async () => {
disposeMetricsListener();
await this.closeAll();
clientsHost.removeEventListener('message', handleRegistrationOnMessage);
disposeConnectionHandlers();
await clientsHost.dispose();
await close();
};
if (this.isDisposed()) {
await disposeAutoLaunch();
} else {
this.disposables.add(disposeAutoLaunch);
}
if (process.send) {
process.send({ port });
}
return { port };
}
async activateEnvs(value?: unknown) {
const activatedEnvs: Promise<void>[] = [];
for (const env of this.openEnvironments.values()) {
if (!env.activate) continue;
activatedEnvs.push(env.activate(value));
}
await Promise.all(activatedEnvs);
}
async closeAll() {
await Promise.all([...this.openEnvironments.values()].map((env) => this.closeEnv(env)));
}
private closeEnv(env: RunningNodeEnvironment) {
this.openEnvironments.delete(env.id, env);
return env.dispose();
}
private async runFeatureEnvironments(
verbose: boolean,
runtimeOptions: Map<string, string | boolean | undefined>,
forwardingCom: Communication,
) {
const featureName = runtimeOptions.get('feature');
if (!featureName || typeof featureName !== 'string') {
throw new Error('feature is a required for autoLaunch');
}
const hasFeatureDef = Object.hasOwn(this.featureEnvironmentsMapping.featureToEnvironments, featureName);
if (!hasFeatureDef) {
throw new Error(`[ENGINE]: no environments found for feature ${featureName}`);
}
const envNames = this.featureEnvironmentsMapping.featureToEnvironments[featureName] || [];
if (verbose) {
console.log(`[ENGINE]: found the following environments for feature ${featureName}:\n${envNames}`);
}
await Promise.all(
envNames.map((envName) => this.initializeEnvironment(envName, runtimeOptions, forwardingCom, verbose)),
);
}
private createEnvironmentFileUrl(envName: string) {
const env = this.featureEnvironmentsMapping.availableEnvironments[envName];
if (!env) {
throw new Error(`environment ${envName} not found`);
}
return new URL(`${env.env}.${env.envType}${extname(this.importMeta.url)}`, this.importMeta.url);
}
async initializeEnvironment(
envName: string,
runtimeOptions: IRunOptions,
forwardingCom: Communication,
verbose: boolean,
) {
const env = this.featureEnvironmentsMapping.availableEnvironments[envName];
if (!env) {
throw new Error(`environment ${envName} not found`);
}
let runningEnv: RunningNodeEnvironment;
if (env.envType === 'remote') {
if (!env.remoteUrl) {
throw new Error(`Remote URL for environment ${envName} is not defined`);
}
runningEnv = await socketClientInitializer({ communication: forwardingCom, env, envUrl: env.remoteUrl });
} else {
const envWithInit = workerThreadInitializer2({
communication: forwardingCom,
env: env,
workerURL: this.createEnvironmentFileUrl(envName),
runtimeOptions: runtimeOptions,
});
envWithInit.preLoad();
runningEnv = envWithInit;
}
this.openEnvironments.add(envName, runningEnv);
if (verbose) {
console.log(`[ENGINE]: Environment ${runningEnv.id} is ready`);
}
}
async collectMetricsFromAllOpenEnvironments() {
const metrics = {
marks: [] as PerformanceEntry[],
measures: [] as PerformanceEntry[],
};
for (const runningEnv of this.openEnvironments.values()) {
const { marks, measures } = await runningEnv.getMetrics();
metrics.marks.push(...marks.map((m) => ({ ...m, debugInfo: `${runningEnv.id}:${m.name}` })));
metrics.measures.push(...measures.map((m) => ({ ...m, debugInfo: `${runningEnv.id}:${m.name}` })));
}
return metrics;
}
}
export function parseRuntimeOptions() {
const { values: args } = parseArgs({
strict: false,
allowPositionals: false,
});
return new Map(Object.entries(args));
}