-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.ts
409 lines (336 loc) · 12.4 KB
/
server.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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
import { WebSocketServer, ServerOptions } from 'ws';
import { IncomingMessage, Server } from 'node:http';
import express from 'express';
import { URL } from 'node:url';
import { Socket } from 'node:net';
import { IWebSocket, WebSocketMessageReader, WebSocketMessageWriter } from 'vscode-ws-jsonrpc';
import { createConnection, createServerProcess, forward } from 'vscode-ws-jsonrpc/server';
import { Message, InitializeRequest, InitializeParams, DiagnosticRelatedInformation, Diagnostic, PublishDiagnosticsNotification, PublishDiagnosticsParams } from 'vscode-languageserver';
import * as cp from 'child_process';
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
import path from 'node:path';
import cookie from "cookie";
import * as crypto from "node:crypto";
import "dotenv/config";
enum RunMode {
development = "development",
production = "production"
}
const mode: RunMode | string = process.env.MODE || RunMode.production;
function isProduction() : boolean
{
return mode == RunMode.production;
}
function isDevelopment() : boolean
{
return !isProduction();
}
interface LanguageServerRunConfig {
serverName: string;
pathName: string;
serverPort: number;
wsServerOptions: ServerOptions,
spawnOptions?: cp.SpawnOptions;
}
function log(...args: any[])
{
if(isDevelopment())
{
console.log(...args);
}
}
function filterLink(link: string)
{
[
"/opt/emsdk/upstream/emscripten/cache/sysroot",
].forEach((value) =>
{
link = link.replace(value, "/***");
});
return link;
}
/**
* start the language server inside the current process
*/
const launchLanguageServer = (runconfig: LanguageServerRunConfig, socket: IWebSocket, libraries: any) => {
if(!libraries)
return;
/**
* Process the libraries and break it out into their version directories
*/
let baseLibraryDirectory = process.env.PGETINKER_LIBS_DIRECTORY || "/opt/PGEtinker-libs";
baseLibraryDirectory += "/olcPixelGameEngine/" + libraries["olcPixelGameEngine"];
const libraryDirectories: any = {};
libraryDirectories["olcPixelGameEngine"] = baseLibraryDirectory + "/olcPixelGameEngine";
const libraryKeys = Object.keys(libraries);
libraryKeys.forEach((library) =>
{
if(library == "olcPixelGameEngine")
return;
libraryDirectories[library] = baseLibraryDirectory + "/" + library + "/" + libraries[library];
});
// create a sha256 of the libraryDirectories object
const libraryHash = crypto.createHash("sha256");
libraryHash.update(JSON.stringify(libraryDirectories));
// use the hash to derive a workspace
const workspacePath = path.join(process.cwd(), "workspaces", libraryHash.digest("base64url"));
const { serverName, spawnOptions } = runconfig;
const errors: string[] = [];
let nsJailArgs = [
"--config",
path.join(process.cwd(), process.env.COMPILER_NSJAIL_CFG || "nsjail-emscripten-ci.cfg"),
"-B",
`${workspacePath}:/workspace`,
];
libraryKeys.forEach((library) =>
{
if(!existsSync(libraryDirectories[library]))
{
errors.push(`${libraryDirectories[library]} does not exist.`);
return;
}
nsJailArgs.push("-R");
nsJailArgs.push(`${libraryDirectories[library]}:/workspace/${library}`);
});
nsJailArgs.push("--");
// begin clangd specifics
nsJailArgs.push("/usr/bin/clangd");
nsJailArgs.push("--compile-commands-dir=/workspace");
nsJailArgs.push("--header-insertion=never");
// if we make it here, and have errors, quit
if(errors.length > 0)
{
console.error(errors);
return;
}
// if workspace doesn't exist, let's create it
if(!existsSync(path.join(workspacePath, "compile_commands.json")))
{
if(!existsSync(path.join(process.cwd(), "workspaces")))
mkdirSync(path.join(process.cwd(), "workspaces"));
if(!existsSync(workspacePath))
mkdirSync(workspacePath);
let compileCommandsTemplate: string = readFileSync(path.join(process.cwd(), "compile_commands.template"), "utf-8");
writeFileSync(path.join(workspacePath, "compile_commands.json"), compileCommandsTemplate);
}
log(libraryDirectories);
log(libraries);
log(workspacePath, existsSync(workspacePath));
log(nsJailArgs);
const reader = new WebSocketMessageReader(socket);
const writer = new WebSocketMessageWriter(socket);
// start the language server as an external process
const socketConnection = createConnection(reader, writer, () => socket.dispose());
const serverConnection = createServerProcess(serverName, "nsjail", nsJailArgs, spawnOptions);
if (serverConnection)
{
forward(socketConnection, serverConnection, (message: Message) =>
{
if (Message.isRequest(message))
{
log(`${serverName} Server received:`);
log(message);
if(message.method === InitializeRequest.type.method)
{
const initializeParams = message.params as InitializeParams;
initializeParams.processId = process.pid;
}
}
if(Message.isNotification(message))
{
log(`${serverName} Sending Notification:`);
if(message.method === PublishDiagnosticsNotification.method)
{
const publishParams = message.params as PublishDiagnosticsParams;
log("-- BEGIN DIAGNOSTICS --");
if(publishParams.diagnostics.length > 0)
{
publishParams.uri = filterLink(publishParams.uri);
log(publishParams.uri);
publishParams.diagnostics.forEach((diagnostic: Diagnostic) =>
{
log(diagnostic);
if(diagnostic?.relatedInformation && diagnostic.relatedInformation.length > 0)
{
diagnostic.relatedInformation.forEach((relatedInformation: DiagnosticRelatedInformation) =>
{
relatedInformation.location.uri = filterLink(relatedInformation.location.uri)
})
}
});
}
log("-- END DIAGNOSTICS --");
}
}
if(Message.isResponse(message))
{
if(message.result)
{
log(`${serverName} Server sent:`);
if((message.result as []).length > 0)
{
(message.result as []).forEach((item) =>
{
let keys = Object.keys(item);
if(keys.includes("target"))
{
(item as any).target = `unavailable`;
}
return undefined;
});
}
if((message.result as any).contents?.value)
{
// @ts-ignore
message.result.contents.value = filterLink(message.result.contents.value);
}
log(message);
}
}
return message;
});
}
};
const upgradeWsServer = (runconfig: LanguageServerRunConfig,
config: {
server: Server,
wss: WebSocketServer
}) =>
{
config.server.on('upgrade', (request: IncomingMessage, socket: Socket, head: Buffer) =>
{
const baseURL = `http://${request.headers.host}/`;
const pathName = request.url ? new URL(request.url, baseURL).pathname : undefined;
if(pathName !== runconfig.pathName)
return;
config.wss.handleUpgrade(request, socket, head, webSocket =>
{
let libraries = null;
try
{
let cookies = cookie.parse(request.headers["cookie"] as string);
libraries = JSON.parse(decodeURIComponent(cookies.pgetinker_libraries));
}
catch(e)
{
}
let keepAliveInterval: NodeJS.Timeout;
const socket: IWebSocket = {
send: content => webSocket.send(content, error => {
if (error) {
throw error;
}
}),
onMessage: cb => webSocket.on('message', (data) => {
log(data.toString());
cb(data);
}),
onError: cb => webSocket.on('error', cb),
onClose: cb => webSocket.on('close', cb),
dispose: () =>
{
clearInterval(keepAliveInterval);
webSocket.close();
}
};
// launch the server when the web socket is opened
if (webSocket.readyState === webSocket.OPEN)
{
launchLanguageServer(runconfig, socket, libraries);
}
else
{
webSocket.on('open', () =>
{
launchLanguageServer(runconfig, socket, libraries);
});
}
keepAliveInterval = setInterval(() =>
{
webSocket.send(JSON.stringify({
jsonrpc: "2.0",
method: "telemetry/event",
params: {
message: "Number Five Alive",
},
}));
}, 30000);
});
});
};
/** LSP server runner */
const runLanguageServer = (
languageServerRunConfig: LanguageServerRunConfig
) => {
process.on('uncaughtException', (error) =>
{
console.error('Uncaught Exception: ', error.toString());
if (error.stack) {
console.error(error.stack);
}
});
// create the express application
const app = express();
// start the http server
const httpServer: Server = app.listen(languageServerRunConfig.serverPort);
const wss = new WebSocketServer(languageServerRunConfig.wsServerOptions);
// create the web socket
upgradeWsServer(languageServerRunConfig, {
server: httpServer,
wss
});
app.get("/trigger-close-clients", (_, response) =>
{
wss.clients.forEach((ws) =>
{
if(ws.OPEN)
{
ws.close();
}
});
response.json({ message: "clients have been closed." });
});
process.on("SIGINT", () =>
{
wss.clients.forEach((ws) =>
{
ws.close();
});
wss.close();
process.exit();
});
};
runLanguageServer({
serverName: 'CLANGD',
pathName: '/clangd',
serverPort: 3000,
wsServerOptions: {
noServer: true,
perMessageDeflate: false,
clientTracking: true,
verifyClient: (clientInfo: { origin: string; secure: boolean; req: IncomingMessage }, callback) =>
{
try
{
let cookies = cookie.parse(clientInfo.req.headers["cookie"] as string);
let appKey = Buffer.from(process.env.APP_KEY?.replace("base64:", "") as string, 'base64');
let session = JSON.parse(Buffer.from(cookies.pgetinker_session, "base64").toString());
// @ts-ignore
const decipher = crypto.createDecipheriv(
"aes-256-cbc",
appKey,
Buffer.from(session.iv, 'base64')
);
let plaintext = decipher.update(session.value, "base64", "utf8");
plaintext += decipher.final("utf8");
}
catch(e)
{
callback(false);
return;
}
callback(true);
return;
}
}
});