-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
462 lines (380 loc) · 15.9 KB
/
server.js
File metadata and controls
462 lines (380 loc) · 15.9 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
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
const net = require('net');
const { spawn } = require('child_process');
const express = require('express');
const bodyParser = require('body-parser');
const chalk = require('chalk');
const app = express();
app.use(bodyParser.json());
app.use((req, res, next) => {
console.log("mid", req.method, req.path);
res.header("Access-Control-Allow-Origin", "*"); // restrict it to the required domain
res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
// Set custom headers for CORS
res.header("Access-Control-Allow-Headers", "Content-type,Accept,X-Custom-Header");
if (req.method === "OPTIONS") {
return res.status(200).end();
}
next()
})
// Debug logging utility with colors
const debug = {
log: (...args) => console.log(chalk.blue('[DEBUG]'), ...args),
error: (...args) => console.error(chalk.red('[ERROR]'), ...args),
info: (...args) => console.info(chalk.green('[INFO]'), ...args),
warn: (...args) => console.warn(chalk.yellow('[WARN]'), ...args),
// Special loggers for DAP server communication
dapRequest: (pid, data) => console.log(
chalk.blue('[DEBUG]'),
chalk.cyan(`[DAP Request PID ${pid}]`),
chalk.white(JSON.stringify(data, null, 2))
),
dapResponse: (pid, data) => console.log(
chalk.blue('[DEBUG]'),
chalk.magenta(`[DAP Response PID ${pid}]`),
chalk.white(JSON.stringify(data, null, 2))
),
dapServer: (pid, message) => console.log(
chalk.blue('[DEBUG]'),
chalk.green(`[DAP Server PID ${pid}]`),
chalk.white(message)
),
dapError: (pid, error) => console.error(
chalk.red('[ERROR]'),
chalk.red(`[DAP Server PID ${pid}]`),
chalk.white(error)
)
};
// Store multiple DAP server instances and their clients
const dapInstances = new Map();
// Function to start DAP server
async function startDAPServer(port = 8123) {
return new Promise((resolve, reject) => {
debug.log(chalk.cyan('Starting new DAP server instance'));
const dapServer = spawn('node', ['../js-debug/src/dapDebugServer.js', port], {
stdio: ['pipe', 'pipe', 'pipe']
});
let serverPort = null;
const pid = dapServer.pid;
debug.dapServer(pid, chalk.yellow(`Server spawned with PID: ${pid}`));
dapServer.stdout.on('data', (data) => {
const output = data.toString();
debug.dapServer(pid, chalk.cyan(`stdout: ${output}`));
// Look for port number in DAP server output - handle both formats
const portMatch = output.match(/(?:port: (\d+)|\d+:(\d+))/);
if (portMatch) {
serverPort = parseInt(portMatch[1] || portMatch[2]);
debug.dapServer(pid, chalk.green(`Listening on port: ${serverPort}`));
dapInstances.set(pid, {
server: dapServer,
client: null,
port: serverPort,
pid: pid,
isInitialized: false,
responses: [],
childEvents: [],
child: null,
});
resolve({ port: serverPort, pid: pid });
}
});
dapServer.stderr.on('data', (data) => {
debug.dapError(pid, `stderr: ${data.toString()}`);
});
dapServer.on('error', (error) => {
debug.dapError(pid, `error: ${error}`);
reject(error);
});
dapServer.on('close', (code) => {
debug.dapServer(pid, chalk.yellow(`Server exited with code ${code}`));
dapInstances.delete(pid);
});
});
}
// Function to connect to DAP server
async function connectToDAPServer(pid, port, child = false) {
return new Promise((resolve, reject) => {
debug.dapServer(pid, chalk.cyan(`Connecting to port ${port}`));
const dapClient = new net.Socket();
const instance = dapInstances.get(pid);
dapClient.connect(port, 'localhost', () => {
debug.dapServer(pid, chalk.green('Connected successfully'));
instance[child ? "child" : "client"] = dapClient;
instance.isInitialized = true;
resolve();
});
dapClient.on('error', (error) => {
debug.dapError(pid, `Connection error: ${error}`);
reject(error);
});
dapClient.on("data", (data) => {
console.log(child ? "[child]" : "" + "net socket - data pid: " + pid + " ", data.toString())
// if mutiple payload/json are present in one, returns Array.
const jsonContent = processMessage(data)
console.log("jsonContent", data.toString(), "\t\n ->> ", jsonContent)
let responsesArr = !child ? instance.responses : instance.childEvents;
if (!responsesArr) responsesArr = []
try {
if(Array.isArray((jsonContent))) {
for (json of jsonContent) {
responsesArr.push(json)
}
return;
}
responsesArr.push(jsonContent)
} catch (e) { console.log(e) }
//console.log("res", pid, responsesArr)
})
});
}
// Function to get or create DAP server instance
async function getOrCreateDAPInstance(pid) {
debug.log(chalk.cyan(`Getting or creating DAP instance for PID: ${pid}`));
let instance = dapInstances.get(pid);
if (!instance) {
debug.log(chalk.yellow(`No existing instance found for PID ${pid}, creating new one`));
// Create new instance if none exists
const { port, pid: newPid } = await startDAPServer();
await connectToDAPServer(newPid, port);
instance = dapInstances.get(newPid);
} else if (!instance.isInitialized) {
debug.log(chalk.yellow(`Instance found for PID ${pid} but not initialized, reconnecting`));
// Reconnect if instance exists but not initialized
await connectToDAPServer(pid, instance.port);
}
return instance;
}
// Handle incoming requests from client
app.post('/debug', async (req, res) => {
try {
debug.log(chalk.cyan('Received new debug session request'));
const portInc = dapInstances.size;
// Create new instance for initial request
const { port, pid: newPid } = await startDAPServer(8123 + portInc);
await connectToDAPServer(newPid, port);
const instance = dapInstances.get(newPid);
debug.dapRequest(newPid, req.body);
// Forward request to DAP server
const request = JSON.stringify({
type: "request",
...(req.body)
});
instance.client.write(`Content-Length: ${Buffer.byteLength(request, "utf8")}\r\n\r\n${request}`);
// Handle response from DAP server
const response = await new Promise((resolve, reject) => {
let responseData = '';
const responseHandler = (data) => {
responseData += data.toString();
if (responseData.includes('\n')) {
instance.client.removeListener('data', responseHandler);
// Extract the JSON content after header with processMessage function.
const processedJsonContent = processMessage(responseData);
console.log("j", processedJsonContent)
const jsonContent = (Array.isArray(processedJsonContent) && processedJsonContent.find(e => e.type === "response")) || processedJsonContent
debug.dapResponse(newPid, responseData);
resolve(jsonContent);
}
};
instance.client.on('data', responseHandler);
});
res.json({ ...response, pid: newPid });
} catch (error) {
debug.error(chalk.red('Error handling debug request:'), error);
res.status(500).json({ error: error.message });
}
});
// Handle subsequent requests to existing DAP server
app.post('/debug/:pid', async (req, res) => {
try {
const pid = parseInt(req.params.pid);
debug.dapRequest(pid, req.body);
console.log("req - query", req.query)
const child = req.query.child === 'true';
const instance = await getOrCreateDAPInstance(pid);
if (!instance || !instance.client) {
throw new Error('DAP server connection not available');
}
let client = instance.client;
console.log(`found instance for pid: ${pid}, IsChild: ${child} (${req.query.child})`)
if (child) {
if (!instance.child) {
console.log("connecting again for child instance")
await connectToDAPServer(pid, instance.port, child)
}
client = instance.child;
}
// Forward request to DAP server
//const request = JSON.stringify(req.body);
//instance.client.write(request + '\n');
const request = JSON.stringify({
type: "request",
...(req.body)
});
client.write(`Content-Length: ${Buffer.byteLength(request, "utf8")}\r\n\r\n${request}`);
// Handle response from DAP server
const response = await new Promise((resolve, reject) => {
let responseData = Buffer.from([]);
const responseHandler = (data) => {
console.log("responseHandler", data.toString(), responseData)
responseData = Buffer.concat([responseData, data]);
if (responseData.includes('\n')) {
debug.dapResponse(pid, responseData.toString());
const processedJsonContent = processMessage(responseData);
const jsonContent = (Array.isArray(processedJsonContent) && processedJsonContent.find(e => e.type === "response" && e.request_seq === request.seq)) || processedJsonContent
console.log("res - json", jsonContent, request)
if (jsonContent.request_seq === req.body.seq) {
client.removeListener('data', responseHandler);
resolve(jsonContent);
}
}
};
client.on('data', responseHandler);
});
res.json(response);
} catch (error) {
debug.error(chalk.red('Error handling debug request:'), error);
res.status(500).json({ error: error.message });
}
});
// Get DAP server status by PID
app.get('/status/:pid', (req, res) => {
const pid = parseInt(req.params.pid);
debug.log(chalk.cyan(`Checking status for DAP server (PID ${pid})`));
const instance = dapInstances.get(pid);
if (instance) {
res.json({
status: 'running',
pid: instance.pid,
port: instance.port,
hasClient: !!instance.client,
isInitialized: instance.isInitialized
});
} else {
debug.warn(chalk.yellow(`No DAP server found with PID ${pid}`));
res.json({
status: 'not_found',
message: 'No DAP server running with this PID'
});
}
});
app.get('/debug/:pid/polling', (req, res) => {
const pid = parseInt(req.params.pid);
const instance = dapInstances.get(pid);
if (instance) {
console.log("polling", instance.responses, instance.childEvents)
res.json(instance.child ? ({
events: instance.responses || [],
childEvents: instance.childEvents || []
}) : ({
events: instance.responses || []
})
);
if (instance.responses?.length) instance.responses.length = 0
if (instance?.childEvents?.length) instance.childEvents.length = 0
} else {
res.json({
status: 'not_found',
message: 'No DAP server running with this PID'
});
}
})
// Terminate DAP server instance
app.delete('/debug/:pid', (req, res) => {
const pid = parseInt(req.params.pid);
debug.log(chalk.cyan(`Received termination request for DAP server (PID ${pid})`));
const instance = dapInstances.get(pid);
if (instance) {
cleanupInstance(pid);
debug.log(chalk.green(`Successfully terminated DAP server (PID ${pid})`));
res.json({ status: 'terminated', pid });
} else {
debug.warn(chalk.yellow(`Attempted to terminate non-existent DAP server (PID ${pid})`));
res.status(404).json({
status: 'not_found',
message: 'No DAP server running with this PID'
});
}
});
// Cleanup function for a specific PID
async function cleanupInstance(pid) {
debug.log(chalk.cyan(`Cleaning up DAP server instance (PID ${pid})`));
const instance = dapInstances.get(pid);
if (instance) {
try {
if (instance.client) {
instance.client.end();
instance.client = null;
debug.log(chalk.yellow(`Closed client connection for DAP server (PID ${pid})`));
}
if (instance.child) {
instance.child.end();
instance.child = null;
debug.log(chalk.yellow(`Closed child client connection for DAP server (PID ${pid})`));
}
if (instance.server) {
instance.server.kill();
instance.server = null;
debug.log(chalk.yellow(`Terminated DAP server process (PID ${pid})`));
}
dapInstances.delete(pid);
debug.log(chalk.green(`Removed DAP server instance from tracking (PID ${pid})`));
} catch (error) {
debug.error(chalk.red(`Error cleaning up instance ${pid}:`), error);
}
}
}
function processMessage(message) {
let processedMsg;
let startTime = performance.now()
while (message.length > 0) {
const headerEnd = message.indexOf("\r\n\r\n")
console.log("processMessage - loop headerEnd:", headerEnd)
if (headerEnd === -1) break;
const header = message.slice(0, headerEnd).toString()
let contentLength = header.match(/Content-Length: (\d+)/)[1]
console.log("processMessage - loop contentLength:", contentLength)
if (!contentLength) break;
contentLength = parseInt(contentLength, 10);
const headerLength = headerEnd + 4;
console.log("processMessage - loop totalMessageLength & message.length:", { totalMessageLength: contentLength + headerLength, "message.length": message.length, contentLength })
const bodyBuffer = message.slice(headerLength)
if (bodyBuffer.length < contentLength) break;
const payloadBuffer = message.slice(headerLength, headerLength + contentLength + 1);
const JSONString = payloadBuffer.toString()
try {
const JSONContent = JSON.parse(JSONString);
processedMsg = bodyBuffer.length > contentLength ? [JSONContent, ...(processedMsg || [])] : JSONContent;
} catch (e) {
console.log('[ERROR] Invalid JSON:', e.message);
}
console.log(processedMsg)
message = message.slice(headerEnd + contentLength + 1)
console.log(message)
}
console.log(`[processed - batch mark (time spent)]: ⏱️ ${performance.now() - startTime} ms!`)
return processedMsg;
}
// Cleanup all instances
async function cleanupAll() {
debug.log(chalk.cyan('Cleaning up all DAP server instances'));
const cleanupPromises = [];
for (const pid of dapInstances.keys()) {
cleanupPromises.push(cleanupInstance(pid));
}
try {
// Wait for all cleanup operations to complete
await Promise.all(cleanupPromises);
debug.log(chalk.green('All cleanup operations completed'));
// Exit the process
process.exit(0);
} catch (error) {
debug.error(chalk.red('Error during cleanup:'), error);
process.exit(1);
}
}
// Handle process termination
process.on('SIGINT', cleanupAll);
process.on('SIGTERM', cleanupAll);
const PORT = process.env.PORT || 8777;
app.listen(PORT, () => {
debug.info(chalk.green(`Bridge server listening on port ${PORT}`));
});