forked from Talenttrust/Talenttrust-Backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
397 lines (336 loc) · 11.6 KB
/
Copy pathindex.ts
File metadata and controls
397 lines (336 loc) · 11.6 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
/**
* @module index
* @description Server entry and exported Express app.
*
* Import `{ app }` in tests. The HTTP server and BullMQ workers start only
* when this file is the program entry and Jest is not running.
*/
import type { NextFunction, Request, Response } from 'express';
import { createApp, attachTerminalHandlers } from './app';
import { AppError } from './errors/appError';
import { JobType, JobPayload, QueueManager } from './queue';
import { auditService } from './audit/service';
import { createAuditRouter } from './audit/router';
import { createRateLimiter } from './middleware/rateLimiter';
import { rateLimitConfig } from './config/rateLimit';
import { requireAuth, requireRole } from './middleware/authorization';
import { authMiddleware, type AuthenticatedRequest } from './middleware/auth';
import { adminAuthGuard } from './middleware/adminAuthGuard';
import { registerShutdownHandlers } from './shutdown';
const queueManager = QueueManager.getInstance();
const app = createApp({ includeTerminalHandlers: false });
function auditActorKeyFn(prefix: string) {
return (req: Request) => {
const authReq = req as typeof req & { user?: { id?: string } };
const actor = authReq.user?.id ?? 'anonymous';
return `${prefix}:${actor}:${req.ip ?? req.socket.remoteAddress ?? 'unknown'}`;
};
}
const auditExportLimiter = createRateLimiter({
...rateLimitConfig.auditExport,
keyFn: auditActorKeyFn('audit-export'),
});
const auditQueryLimiter = createRateLimiter({
...rateLimitConfig.audit,
keyFn: auditActorKeyFn('audit'),
});
const auditIntegrityLimiter = createRateLimiter({
...rateLimitConfig.auditIntegrity,
keyFn: auditActorKeyFn('audit-integrity'),
});
app.use(
'/api/v1/audit',
createAuditRouter({
accessMiddleware: [requireAuth, requireRole('admin', 'auditor'), auditQueryLimiter],
exportMiddleware: [auditExportLimiter],
integrityMiddleware: [auditIntegrityLimiter],
}),
);
const DLQ_DEFAULT_LIMIT = 50;
const DLQ_MAX_LIMIT = 100;
function parsePositiveInt(value: unknown, fallback: number): number {
const parsed = Number(value);
if (!Number.isFinite(parsed) || parsed < 0) {
return fallback;
}
return Math.floor(parsed);
}
function requireAdmin(req: AuthenticatedRequest, res: Response, next: NextFunction): void {
if (!req.user) {
res.status(401).json({ error: 'Authentication required' });
return;
}
if (req.user.role !== 'admin') {
res.status(403).json({ error: 'Admin role required' });
return;
}
next();
}
app.get(
'/api/v1/jobs/dlq',
adminAuthGuard,
async (req: Request & { user?: { id: string } }, res: Response) => {
try {
const typeQuery = (req as any).query['type'];
const limitQuery = (req as any).query['limit'];
const offsetQuery = (req as any).query['offset'];
const jobType = typeof typeQuery === 'string' ? typeQuery : undefined;
if (jobType && !Object.values(JobType).includes(jobType as JobType)) {
return res.status(400).json({ error: `Invalid job type: ${jobType}` });
}
const limit = Math.min(
Math.max(parsePositiveInt(limitQuery, DLQ_DEFAULT_LIMIT), 1),
DLQ_MAX_LIMIT,
);
const offset = Math.max(parsePositiveInt(offsetQuery, 0), 0);
const entries = await queueManager.getFailedJobs({
jobType: jobType as JobType | undefined,
limit,
offset,
});
auditService.log({
action: 'ADMIN_ACTION',
severity: 'INFO',
actor: req.user!.id,
resource: 'jobs-dlq',
resourceId: jobType ?? 'all',
metadata: {
operation: 'view',
count: entries.length,
limit,
offset,
},
ipAddress: (req as any).ip,
correlationId: (req as any).headers['x-correlation-id'] as string | undefined,
});
return res.status(200).json({ entries, limit, offset, count: entries.length });
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error';
return res.status(500).json({ error: `Failed to get DLQ entries: ${message}` });
}
},
);
app.post(
'/api/v1/jobs/dlq/reprocess',
adminAuthGuard,
async (req: Request & { user?: { id: string } }, res: Response) => {
try {
const { type, jobId, reason } = (req as any).body as {
type?: string;
jobId?: string;
reason?: string;
};
if (!type || !jobId || !reason || typeof reason !== 'string' || reason.trim().length < 5) {
return res.status(400).json({
error: 'type, jobId, and reason (min 5 chars) are required',
});
}
if (!Object.values(JobType).includes(type as JobType)) {
return res.status(400).json({ error: `Invalid job type: ${type}` });
}
const replayResult = await queueManager.reprocessFailedJob(type as JobType, jobId);
auditService.log({
action: 'ADMIN_ACTION',
severity: 'WARNING',
actor: req.user!.id,
resource: 'jobs-dlq',
resourceId: jobId,
metadata: {
operation: 'reprocess',
reason: reason.trim(),
jobType: type,
replayJobId: replayResult.replayJobId,
deduplicated: replayResult.deduplicated,
},
ipAddress: (req as any).ip,
correlationId: (req as any).headers['x-correlation-id'] as string | undefined,
});
const statusCode = replayResult.deduplicated ? 200 : 202;
return res.status(statusCode).json(replayResult);
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error';
if (message.startsWith('Failed job not found')) {
return res.status(404).json({ error: message });
}
if (message.includes('not in failed state')) {
return res.status(409).json({ error: message });
}
return res.status(500).json({ error: `Failed to reprocess DLQ job: ${message}` });
}
},
);
app.post('/api/v1/jobs', async (req: Request, res: Response, next: NextFunction) => {
try {
const { type, payload, options } = req.body as {
type?: string;
payload?: unknown;
options?: any;
};
if (!type || payload === undefined) {
return res.status(400).json({ error: 'Job type and payload are required' });
}
if (!Object.values(JobType).includes(type as JobType)) {
return res.status(400).json({ error: 'Invalid job type' });
}
const result = await queueManager.addJob(type as JobType, payload as JobPayload, options);
const httpStatus = (result as any).deduplicated ? 200 : 201;
return res.status(httpStatus).json({
jobId: (result as any).jobId,
type,
status: 'queued',
deduplicated: (result as any).deduplicated,
});
} catch (error) {
next(error);
return;
}
});
app.get(
'/api/v1/jobs/dlq',
authMiddleware,
requireAdmin,
async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
try {
const typeQuery = (req as any).query['type'];
const limitQuery = (req as any).query['limit'];
const offsetQuery = (req as any).query['offset'];
const jobType = typeof typeQuery === 'string' ? typeQuery : undefined;
if (jobType && !Object.values(JobType).includes(jobType as JobType)) {
return res.status(400).json({ error: 'Invalid job type' });
}
const limit = Math.min(
Math.max(parsePositiveInt(limitQuery, DLQ_DEFAULT_LIMIT), 1),
DLQ_MAX_LIMIT,
);
const offset = Math.max(parsePositiveInt(offsetQuery, 0), 0);
const entries = await queueManager.getFailedJobs({
jobType: jobType as JobType | undefined,
limit,
offset,
});
auditService.log({
action: 'ADMIN_ACTION',
severity: 'INFO',
actor: req.user!.id,
resource: 'jobs-dlq',
resourceId: jobType ?? 'all',
metadata: {
operation: 'view',
count: entries.length,
limit,
offset,
},
ipAddress: (req as any).ip,
correlationId: (req as any).headers['x-correlation-id'] as string | undefined,
});
return res.status(200).json({ entries, limit, offset, count: entries.length });
} catch (error) {
next(error);
return;
}
},
);
app.post(
'/api/v1/jobs/dlq/reprocess',
authMiddleware,
requireAdmin,
async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
try {
const { type, jobId, reason } = (req as any).body as {
type?: string;
jobId?: string;
reason?: string;
};
if (!type || !jobId || !reason || typeof reason !== 'string' || reason.trim().length < 5) {
return res.status(400).json({
error: 'type, jobId, and reason (min 5 chars) are required',
});
}
if (!Object.values(JobType).includes(type as JobType)) {
return res.status(400).json({ error: 'Invalid job type' });
}
const replayResult = await queueManager.reprocessFailedJob(type as JobType, jobId);
auditService.log({
action: 'ADMIN_ACTION',
severity: 'WARNING',
actor: req.user!.id,
resource: 'jobs-dlq',
resourceId: jobId,
metadata: {
operation: 'reprocess',
reason: reason.trim(),
jobType: type,
replayJobId: replayResult.replayJobId,
deduplicated: replayResult.deduplicated,
},
ipAddress: (req as any).ip,
correlationId: (req as any).headers['x-correlation-id'] as string | undefined,
});
const statusCode = replayResult.deduplicated ? 200 : 202;
return res.status(statusCode).json(replayResult);
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error';
if (message.startsWith('Failed job not found')) {
next(new AppError(404, 'not_found', 'The requested resource was not found'));
return;
}
if (message.includes('not in failed state')) {
next(new AppError(409, 'conflict', 'The request conflicts with the current state'));
return;
}
next(error);
return;
}
},
);
app.get('/api/v1/jobs/:type/:jobId', async (req: Request, res: Response, next: NextFunction) => {
try {
const { type, jobId } = req.params;
if (!Object.values(JobType).includes(type as JobType)) {
return res.status(400).json({ error: 'Invalid job type' });
}
const status = await queueManager.getJobStatus(type as JobType, jobId);
if (!status) {
return res.status(404).json({ error: 'Job not found' });
}
return res.json(status);
} catch (error) {
next(error);
return;
}
});
attachTerminalHandlers(app);
export { app };
export default app;
const isMainModule = false;
const isJest = Boolean(process.env.JEST_WORKER_ID);
const shouldBootstrapServer = (isMainModule && !isJest) || process.env.FORCE_START_INDEX === '1';
async function initializeQueues(): Promise<void> {
if (isJest) {
return;
}
for (const jobType of Object.values(JobType)) {
await queueManager.initializeQueue(jobType);
}
}
async function startServer(): Promise<void> {
const PORT = Number(process.env.PORT) || 3001;
if (!isJest) {
await initializeQueues();
}
if (!isJest) {
const server = app.listen(PORT, () => {
console.log(`TalentTrust API listening on http://localhost:${PORT}`);
});
registerShutdownHandlers(server, [], [], {
shutdownDrainHandlers: [queueManager],
shutdownDrainTimeoutMs: Number(process.env['SHUTDOWN_DRAIN_TIMEOUT_MS'] ?? 30_000),
});
}
}
if (isJest) {
// Tests import `app` only; do not start listeners or Redis-backed queues here.
}
if (shouldBootstrapServer) {
void startServer();
}