-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
454 lines (393 loc) · 16.5 KB
/
server.ts
File metadata and controls
454 lines (393 loc) · 16.5 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
import express, { Request, Response, NextFunction } from 'express';
import { createProxyMiddleware } from 'http-proxy-middleware';
import cors from 'cors';
import { ServerResponse } from 'http';
import './db/init';
import { logRequest, getOrCreateSession, updateSessionCount, getRequests, getUniqueEndpoints, getEndpointRequests, clearDatabase } from './logger';
import { randomBytes } from 'crypto';
import { extractShape, analyzeEndpointDiffs } from './diff/analyzer';
// Parse command-line arguments
function parseArgs() {
const args = process.argv.slice(2);
let targetPort = 50000; // default port
for (let i = 0; i < args.length; i++) {
if (args[i] === '--target' && args[i + 1]) {
targetPort = parseInt(args[i + 1], 10);
i++;
}
}
return { targetPort };
}
const { targetPort } = parseArgs();
const PORT = 50017;
const TARGET_URL = `http://localhost:${targetPort}/graphql`;
// Session management
const CURRENT_SESSION_ID = randomBytes(16).toString('hex');
getOrCreateSession(CURRENT_SESSION_ID, `Session ${new Date().toISOString()}`);
console.log(`[SESSION] Active session: ${CURRENT_SESSION_ID}`);
const app = express();
// Configure CORS to allow requests from your frontend
app.use(cors({
origin: [
'https://payment-local.test.cergea.com:4010',
'http://localhost:4010',
'http://localhost:3000',
'http://localhost:3001',
'http://localhost:4000',
],
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'Accept'],
exposedHeaders: ['Content-Length', 'X-Request-Id']
}));
app.use(express.json({ limit: '10mb' }));
app.use(express.text({ limit: '10mb' }));
app.use(express.raw({ limit: '10mb' }));
// Request metadata storage
interface RequestMetadata {
startTime: number;
method: string;
path: string;
requestHeaders: Record<string, string | string[]>;
requestBody: any;
graphqlOperation?: string; // GraphQL operation name if applicable
}
const requestMetadataMap = new Map<string, RequestMetadata>();
// Middleware to capture request metadata
app.use((req: Request, res: Response, next: NextFunction) => {
const requestId = `${Date.now()}-${Math.random()}`;
// Capture request body
let requestBody = '';
let graphqlOperation: string | undefined;
if (req.body) {
requestBody = typeof req.body === 'string' ? req.body : JSON.stringify(req.body);
// Extract GraphQL operation name if this is a GraphQL request
try {
const parsedBody = typeof req.body === 'string' ? JSON.parse(req.body) : req.body;
if (parsedBody && parsedBody.operationName) {
graphqlOperation = parsedBody.operationName;
}
} catch (e) {
// Not a valid JSON body, skip GraphQL detection
}
}
const metadata: RequestMetadata = {
startTime: Date.now(),
method: req.method,
path: req.url,
requestHeaders: req.headers as Record<string, string | string[]>,
requestBody,
graphqlOperation
};
requestMetadataMap.set(requestId, metadata);
(req as any).requestId = requestId;
next();
});
// API Routes (must be before proxy middleware)
app.get('/api/requests', (req: Request, res: Response) => {
try {
const { method, path, status, session } = req.query;
const filters: any = {};
if (method && typeof method === 'string') {
filters.method = method;
}
if (path && typeof path === 'string') {
filters.path = path;
}
if (status) {
filters.statusCode = parseInt(status as string, 10);
}
if (session && typeof session === 'string') {
filters.sessionId = session;
}
const requests = getRequests(filters);
res.json({
success: true,
count: requests.length,
data: requests
});
} catch (error) {
console.error('[API] Error fetching requests:', error);
res.status(500).json({
success: false,
error: 'Failed to fetch requests',
message: error instanceof Error ? error.message : 'Unknown error'
});
}
});
// Get diff analysis for all endpoints
app.get('/api/diffs', (req: Request, res: Response) => {
try {
// Get all unique endpoints from the database
const endpoints = getUniqueEndpoints();
const diffs: any[] = [];
for (const endpoint of endpoints) {
// Get recent requests for this endpoint
const requests = getEndpointRequests(endpoint.method, endpoint.path, 100);
// Build GroupedEndpoint structure for analysis
const shapes: any[] = [];
requests.forEach(req => {
if (req.responseBody && req.statusCode >= 200 && req.statusCode < 300) {
try {
const parsed = JSON.parse(req.responseBody);
const shape = extractShape(parsed);
shapes.push(shape);
} catch (e) {
// Skip non-JSON responses
}
}
});
// Only analyze if we have multiple shapes to compare
if (shapes.length > 1) {
const groupedEndpoint = {
method: endpoint.method,
path: endpoint.path,
requestCount: endpoint.count,
shapes,
firstSeen: requests[requests.length - 1]?.timestamp || Date.now(),
lastSeen: requests[0]?.timestamp || Date.now(),
statusCodes: [...new Set(requests.map(r => r.statusCode))],
avgDuration: 0
};
const analysis = analyzeEndpointDiffs(groupedEndpoint);
// Only include if there are inconsistencies
if (analysis.inconsistencies.length > 0) {
// Parse inconsistencies into structured format
const missingFields: any[] = [];
const typeChanges: any[] = [];
const extraFields: any[] = [];
analysis.inconsistencies.forEach(msg => {
if (msg.includes('missing in')) {
const match = msg.match(/field '([^']+)' missing in/);
if (match) {
missingFields.push({
field: match[1],
path: match[1],
type: 'missing'
});
}
} else if (msg.includes('has inconsistent types')) {
const match = msg.match(/field '([^']+)' has inconsistent types: (.+)/);
if (match) {
const types = match[2].split(', ');
typeChanges.push({
field: match[1],
path: match[1],
type: 'type_change',
expectedType: types[0],
actualType: types.slice(1).join(', ')
});
}
}
});
diffs.push({
method: endpoint.method,
path: endpoint.path,
totalResponses: shapes.length,
inconsistencies: {
missingFields,
typeChanges,
extraFields
},
baseShape: shapes[0] || {},
variantShapes: shapes.slice(1)
});
}
}
}
res.json({
success: true,
count: diffs.length,
data: diffs
});
} catch (error) {
console.error('[API] Error analyzing diffs:', error);
res.status(500).json({
success: false,
error: 'Failed to analyze endpoint diffs',
message: error instanceof Error ? error.message : 'Unknown error'
});
}
});
// Get latency statistics for all endpoints
app.get('/api/stats/latency', (req: Request, res: Response) => {
try {
const endpoints = getUniqueEndpoints();
const latencyStats = endpoints.map(endpoint => {
const requests = getEndpointRequests(endpoint.method, endpoint.path, 1000);
// Filter requests with valid duration
const validRequests = requests.filter(r => r.durationMs !== null && r.durationMs !== undefined);
if (validRequests.length === 0) {
return null;
}
const latencies = validRequests.map(r => r.durationMs as number);
const avgLatency = latencies.reduce((sum, lat) => sum + lat, 0) / latencies.length;
const minLatency = Math.min(...latencies);
const maxLatency = Math.max(...latencies);
return {
endpoint: `${endpoint.method} ${endpoint.path}`,
method: endpoint.method,
path: endpoint.path,
avgLatency,
minLatency,
maxLatency,
count: validRequests.length
};
}).filter(stat => stat !== null);
res.json({
success: true,
count: latencyStats.length,
data: latencyStats
});
} catch (error) {
console.error('[API] Error fetching latency stats:', error);
res.status(500).json({
success: false,
error: 'Failed to fetch latency statistics',
message: error instanceof Error ? error.message : 'Unknown error'
});
}
});
// Clear database
app.delete('/api/clear', (req: Request, res: Response) => {
try {
clearDatabase();
res.json({
success: true,
message: 'Database cleared successfully'
});
} catch (error) {
console.error('[API] Error clearing database:', error);
res.status(500).json({
success: false,
error: 'Failed to clear database',
message: error instanceof Error ? error.message : 'Unknown error'
});
}
});
// Proxy middleware with logging
const proxyMiddleware = createProxyMiddleware({
target: TARGET_URL,
changeOrigin: true,
selfHandleResponse: true, // We manually handle the response to capture it for logging
on: {
proxyReq: (proxyReq, req) => {
const requestId = (req as any).requestId;
const metadata = requestMetadataMap.get(requestId);
if (metadata) {
const displayPath = metadata.graphqlOperation
? `${metadata.path} [${metadata.graphqlOperation}]`
: metadata.path;
console.log(`[PROXY] ${metadata.method} ${displayPath} -> ${TARGET_URL}${metadata.path}`);
// If request has a body, write it to the proxy request
if (metadata.requestBody && metadata.requestBody.length > 0) {
const bodyData = Buffer.from(metadata.requestBody, 'utf8');
proxyReq.setHeader('Content-Length', bodyData.length);
proxyReq.write(bodyData);
proxyReq.end();
}
}
},
proxyRes: (proxyRes, req, res) => {
const requestId = (req as any).requestId;
const metadata = requestMetadataMap.get(requestId);
if (metadata) {
const duration = Date.now() - metadata.startTime;
const displayPath = metadata.graphqlOperation
? `${metadata.path} [${metadata.graphqlOperation}]`
: metadata.path;
console.log(`[RESPONSE] ${metadata.method} ${displayPath} - ${proxyRes.statusCode} - ${duration}ms`);
// Forward status code and headers to client
res.statusCode = proxyRes.statusCode || 200;
Object.keys(proxyRes.headers).forEach(key => {
const value = proxyRes.headers[key];
if (value !== undefined) {
res.setHeader(key, value);
}
});
// Capture response body while piping to client
const chunks: Buffer[] = [];
proxyRes.on('data', (chunk: Buffer) => {
chunks.push(chunk);
res.write(chunk); // Pipe to client
});
proxyRes.on('end', () => {
const responseBody = Buffer.concat(chunks).toString('utf8');
// Log to database - use GraphQL operation name as path suffix for differentiation
const effectivePath = metadata.graphqlOperation
? `${metadata.path}#${metadata.graphqlOperation}`
: metadata.path;
logRequest({
sessionId: CURRENT_SESSION_ID,
method: metadata.method,
path: effectivePath,
statusCode: proxyRes.statusCode,
durationMs: duration,
requestHeaders: metadata.requestHeaders,
requestBody: metadata.requestBody,
responseHeaders: proxyRes.headers as Record<string, string | string[]>,
responseBody,
timestamp: metadata.startTime
});
updateSessionCount(CURRENT_SESSION_ID);
res.end(); // End client response
});
// Cleanup metadata
requestMetadataMap.delete(requestId);
} else {
// No metadata - just proxy through
res.statusCode = proxyRes.statusCode || 200;
Object.keys(proxyRes.headers).forEach(key => {
const value = proxyRes.headers[key];
if (value !== undefined) {
res.setHeader(key, value);
}
});
proxyRes.pipe(res);
}
},
error: (err, req, res) => {
const requestId = (req as any).requestId;
const metadata = requestMetadataMap.get(requestId);
if (metadata) {
const duration = Date.now() - metadata.startTime;
const displayPath = metadata.graphqlOperation
? `${metadata.path} [${metadata.graphqlOperation}]`
: metadata.path;
console.error(`[ERROR] ${metadata.method} ${displayPath}: ${err.message} - ${duration}ms`);
// Log error to database - use GraphQL operation name as path suffix
const effectivePath = metadata.graphqlOperation
? `${metadata.path}#${metadata.graphqlOperation}`
: metadata.path;
logRequest({
sessionId: CURRENT_SESSION_ID,
method: metadata.method,
path: effectivePath,
durationMs: duration,
requestHeaders: metadata.requestHeaders,
requestBody: metadata.requestBody,
error: err.message,
timestamp: metadata.startTime
});
updateSessionCount(CURRENT_SESSION_ID);
// Cleanup metadata
requestMetadataMap.delete(requestId);
}
if (res && res instanceof ServerResponse && !res.headersSent) {
res.statusCode = 502;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({
error: 'Proxy Error',
message: 'Unable to reach backend server',
details: err.message
}));
}
}
}
});
// Proxy ALL requests to backend
app.use('/', proxyMiddleware);
app.listen(PORT, () => {
console.log(`[SERVER] API Inspector running on http://localhost:${PORT}`);
console.log(`[PROXY] Forwarding all requests to ${TARGET_URL}`);
});