This repository has been archived by the owner on Aug 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 659
/
ServerClient.ts
371 lines (322 loc) · 9.85 KB
/
ServerClient.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
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
import {IS_ROME_DEV_ENV} from "@internal/cli-environment";
import {Reporter} from "@internal/cli-reporter";
import {BridgeServer} from "@internal/events";
import {markup} from "@internal/markup";
import {Resource, createResourceFromCallback} from "@internal/resources";
import ServerRequest, {EMPTY_SUCCESS_RESPONSE} from "./ServerRequest";
import ServerBridge, {
PartialServerQueryRequest,
ServerProfileWorker,
ServerQueryRequest,
ServerQueryResponse,
} from "../common/bridges/ServerBridge";
import Server, {partialServerQueryRequestToFull} from "./Server";
import {
ClientFlags,
ClientRequestFlags,
DEFAULT_CLIENT_FLAGS,
} from "../common/types/client";
import {VERSION} from "../common/constants";
import {DurationMeasurer} from "@internal/numbers";
import {DIAGNOSTIC_CATEGORIES, descriptions} from "@internal/diagnostics";
import {ConsumePath, consume} from "@internal/consume";
import {createUIDPath} from "@internal/path";
import {Dict} from "@internal/typescript-helpers";
import {ServerCommand, serverCommands} from "./commands";
import {toKebabCase} from "@internal/string-utils";
export default class ServerClient {
constructor(
server: Server,
id: number,
bridge: BridgeServer<typeof ServerBridge>,
) {
this.server = server;
this.id = id;
this.bridge = bridge;
this.env = {};
this.requestsInFlight = new Set();
this.reporter = new Reporter(
"ServerClient",
{
wrapperFactory: server.fatalErrorHandler.wrapBound,
markupOptions: server.logger.markupOptions,
},
);
this.resources = server.resources.createContainer(
`ServerClient<${id}>`,
[bridge, this.reporter],
);
this.flags = DEFAULT_CLIENT_FLAGS;
}
private server: Server;
public id: number;
public env: Dict<undefined | string>;
public bridge: BridgeServer<typeof ServerBridge>;
public resources: Resource;
public requestsInFlight: Set<ServerRequest>;
public flags: ClientFlags;
public reporter: Reporter;
public async init(): Promise<void> {
const {bridge, server} = this;
bridge.events.profilingGetWorkers.subscribe(async () => {
const workers: ServerProfileWorker[] = [];
for (const {id, displayName} of server.workerManager.getExternalWorkers()) {
workers.push({id, displayName});
}
return workers;
});
bridge.events.profilingStopWorker.subscribe(async (id) => {
const worker = server.workerManager.getWorkerAssert(id);
return await worker.bridge.events.profilingStop.call();
});
bridge.resources.add(
createResourceFromCallback(
"BridgeEndServerRequestCancellationHandler",
async () => {
for (const req of this.requestsInFlight) {
await req.cancel("client disconnected");
}
},
),
);
await bridge.handshake();
const client = await this.setup();
bridge.events.query.subscribe(async (request) => {
return await this.handleRequest(request);
});
bridge.events.cancelQuery.subscribe(async (token) => {
for (const req of this.requestsInFlight) {
if (req.query.cancelToken === token) {
await req.cancel("user requested");
}
}
});
bridge.events.endServer.subscribe(() => server.end());
return client;
}
private async setup(): Promise<void> {
const {bridge, server, reporter} = this;
const {
flags,
streamState,
outputFormat,
outputSupport,
version,
env,
} = await bridge.events.getClientInfo.call();
const stream = reporter.addStream(
{
format: outputFormat,
features: outputSupport,
write(chunk: string, error: boolean) {
if (flags.silent && !error) {
return;
}
bridge.events.write.send([chunk, error]);
},
},
streamState,
);
if (version !== VERSION) {
reporter.error(
markup`Client version ${version} does not match server version ${VERSION}. Goodbye lol.`,
);
await this.bridge.end();
return;
}
bridge.events.updateFeatures.subscribe((features) => {
return stream.updateFeatures(features);
});
// Update ServerClient props
this.flags = flags;
this.env = env;
reporter.updateMarkupOptions({
cwd: flags.cwd,
});
// Add reporter to connected set, important logs may be output to these
server.connectedReporters.addAttachedStream(stream);
// Warn about disabled disk caching. Don't bother if it's only been set due to ROME_DEV. We don't care to see it in development.
if (server.cache.writeDisabled && !IS_ROME_DEV_ENV) {
reporter.warn(
markup`Disk caching has been disabled due to the <emphasis>ROME_CACHE=0</emphasis> environment variable`,
);
}
bridge.endEvent.subscribe(() => {
// Cancel any requests still in flight
for (const req of this.requestsInFlight) {
req.cancel("bridge died");
}
});
}
public async handleRequest(
partialQuery: PartialServerQueryRequest,
): Promise<ServerQueryResponse> {
const {server} = this;
const query: ServerQueryRequest = partialServerQueryRequestToFull(
partialQuery,
);
const req = new ServerRequest({
client: this,
query,
server,
});
await req.init();
try {
let res: ServerQueryResponse = await this.dispatchRequest(req, []);
res = await req.teardown(res);
return res;
} catch (err) {
await server.fatalErrorHandler.handle(err);
throw new Error("Process should have quit already");
}
}
private async dispatchBenchmarkRequest(
req: ServerRequest,
): Promise<ServerQueryResponse> {
const {client} = req;
const {reporter} = client;
const {benchmarkIterations} = req.query.requestFlags;
// Warmup
const warmupStart = new DurationMeasurer();
const result = await this.dispatchRequest(req, ["benchmark"]);
const warmupTook = warmupStart.since();
// Benchmark
const progress = req.reporter.progress({title: markup`Running benchmark`});
progress.setTotal(benchmarkIterations);
const benchmarkStart = new DurationMeasurer();
for (let i = 0; i < benchmarkIterations; i++) {
await this.dispatchRequest(req, ["benchmark"]);
progress.tick();
}
progress.end();
const benchmarkTook = benchmarkStart.since();
await reporter.section(
markup`Benchmark results`,
() => {
reporter.info(
markup`Request artifacts may have been cached after the first run, artificially decreasing subsequent run time`,
);
reporter.heading(markup`Query`);
reporter.inspect(req.query);
reporter.heading(markup`Stats`);
reporter.list([
markup`Warmup took <emphasis>${warmupTook}</emphasis>`,
markup`<number emphasis>${String(benchmarkIterations)}</number> runs`,
markup`<emphasis>${benchmarkTook}</emphasis> total`,
markup`<emphasis>${benchmarkTook.divide(benchmarkIterations, true)}</emphasis> per run`,
]);
},
);
return result;
}
private async dispatchRequest(
req: ServerRequest,
origins: string[],
): Promise<ServerQueryResponse> {
const {query} = req;
const {requestFlags} = query;
if (requestFlags.benchmark && !origins.includes("benchmark")) {
return this.dispatchBenchmarkRequest(req);
}
try {
const defaultCommandFlags: Dict<unknown> = {};
// A type-safe wrapper for retrieving command flags
// TODO perhaps present this as JSON or something if this isn't a request from the CLI?
const flagsConsumer = consume({
path: createUIDPath("argv"),
parent: undefined,
value: query.commandFlags,
onDefinition(def) {
// objectPath should only have a depth of 1
defaultCommandFlags[def.objectPath[0]] = def.default;
},
objectPath: [],
context: {
category: DIAGNOSTIC_CATEGORIES["flags/invalid"],
getOriginalValue: () => {
return undefined;
},
normalizeKey: (key) => {
return toKebabCase(key);
},
getDiagnosticLocation: (keys: ConsumePath) => {
return req.getDiagnosticLocationFromFlags({
type: "flag",
key: String(keys[0]),
target: "value",
});
},
},
});
// Get command
const serverCommand: undefined | ServerCommand<Dict<unknown>> = serverCommands.get(
query.commandName,
);
if (serverCommand) {
await validateRequestFlags(req, serverCommand);
let commandFlags;
if (serverCommand.defineFlags !== undefined) {
commandFlags = serverCommand.defineFlags(flagsConsumer);
}
req.setNormalizedCommandFlags({
flags: commandFlags,
defaultFlags: defaultCommandFlags,
});
// @ts-expect-error
const data = await serverCommand.callback(req, commandFlags);
return {
...EMPTY_SUCCESS_RESPONSE,
hasData: data !== undefined,
data,
};
} else {
req.throwDiagnosticFlagError({
target: {
type: "arg",
key: 0,
},
description: descriptions.FLAGS.UNKNOWN_COMMAND({
programName: "rome",
commandName: query.commandName,
}),
});
}
} catch (err) {
return await req.buildResponseFromError(err);
}
}
}
const disallowedFlagsWhenReviewing: Array<keyof ClientRequestFlags> = ["watch"];
async function validateRequestFlags(
req: ServerRequest,
serverCommand: ServerCommand<Dict<unknown>>,
) {
const {requestFlags} = req.query;
// Commands need to explicitly allow these flags
validateAllowedRequestFlag(req, "watch", serverCommand);
validateAllowedRequestFlag(req, "review", serverCommand);
// Don't allow review in combination with other flags
if (requestFlags.review) {
for (const key of disallowedFlagsWhenReviewing) {
if (requestFlags[key]) {
throw req.throwDiagnosticFlagError({
description: descriptions.FLAGS.DISALLOWED_REVIEW_FLAG(key),
target: {type: "flag", key},
});
}
}
}
}
function validateAllowedRequestFlag(
req: ServerRequest,
flagKey: NonNullable<ServerCommand<Dict<unknown>>["allowRequestFlags"]>[number],
serverCommand: ServerCommand<Dict<unknown>>,
) {
const allowRequestFlags = serverCommand.allowRequestFlags || [];
if (req.query.requestFlags[flagKey] && !allowRequestFlags.includes(flagKey)) {
throw req.throwDiagnosticFlagError({
description: descriptions.FLAGS.DISALLOWED_REQUEST_FLAG(flagKey),
target: {type: "flag", key: flagKey},
});
}
}