-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
427 lines (366 loc) · 15.2 KB
/
server.js
File metadata and controls
427 lines (366 loc) · 15.2 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
const express = require('express');
const puppeteer = require('puppeteer');
const PQueue = require('p-queue').default;
const crypto = require('crypto');
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware
app.use(express.json());
// Queue configuration - Max 2 concurrent PDF generations
const pdfQueue = new PQueue({
concurrency: 2,
timeout: 150000, // 2.5 minutes for large PDFs
throwOnTimeout: true
});
// Job storage
const jobHistory = [];
const MAX_HISTORY = 100;
const completedJobs = new Map(); // jobId -> {pdfBuffer, metadata}
const JOB_RETENTION = 5 * 60 * 1000; // Keep completed PDFs for 5 minutes
// Daily statistics
let dailyStats = {
date: new Date().toDateString(),
total: 0,
success: 0,
failed: 0,
totalDuration: 0,
totalSize: 0
};
const log = (level, event, data = {}) => {
const timestamp = new Date().toISOString();
console.log(JSON.stringify({ timestamp, level, event, ...data }));
};
const logMemory = () => {
const used = process.memoryUsage().heapUsed / 1024 / 1024;
return Math.round(used * 100) / 100;
};
// Reset daily stats at midnight
setInterval(() => {
const today = new Date().toDateString();
if (dailyStats.date !== today) {
dailyStats = { date: today, total: 0, success: 0, failed: 0, totalDuration: 0, totalSize: 0 };
}
}, 60000);
// Cleanup old completed jobs
setInterval(() => {
const now = Date.now();
for (const [jobId, job] of completedJobs.entries()) {
if (now - job.completedAt > JOB_RETENTION) {
completedJobs.delete(jobId);
log('INFO', 'JOB_EXPIRED', { jobId });
}
}
}, 30000);
// Health check
app.get('/health', (req, res) => {
res.json({
status: 'healthy',
uptime: process.uptime(),
queue: {
size: pdfQueue.size,
pending: pdfQueue.pending
}
});
});
// Dashboard
app.get('/', (req, res) => {
const uptime = Math.floor(process.uptime());
const queueSize = pdfQueue.size;
const processing = pdfQueue.pending;
// Calculate stats
const avgDuration = dailyStats.total > 0 ? (dailyStats.totalDuration / dailyStats.total).toFixed(2) : 0;
const avgSize = dailyStats.total > 0 ? Math.round(dailyStats.totalSize / dailyStats.total / 1024) : 0;
const successRate = dailyStats.total > 0 ? ((dailyStats.success / dailyStats.total) * 100).toFixed(1) : 0;
const recentJobs = jobHistory.slice(-20).reverse();
const logsHtml = recentJobs.map(job => {
const statusBadge = job.status === 'completed' ?
'<span class="px-2 py-1 text-xs font-bold rounded bg-green-100 text-green-700">✓ Success</span>' :
'<span class="px-2 py-1 text-xs font-bold rounded bg-red-100 text-red-700">✗ Failed</span>';
const sizeDisplay = job.fileSize ? `${Math.round(job.fileSize / 1024)}KB` : '-';
const memDisplay = job.memoryUsed ? `${job.memoryUsed}MB` : '-';
const queueWait = job.queueWaitTime ? `${job.queueWaitTime.toFixed(1)}s` : '0s';
return `
<tr class="${job.status === 'completed' ? 'bg-green-50' : 'bg-red-50'}">
<td class="p-3 border-b text-sm">${new Date(job.completedAt).toLocaleTimeString()}</td>
<td class="p-3 border-b text-sm">${statusBadge}</td>
<td class="p-3 border-b text-sm font-mono truncate max-w-xs" title="${job.filename}">${job.filename}</td>
<td class="p-3 border-b text-sm text-gray-600">${job.duration.toFixed(2)}s</td>
<td class="p-3 border-b text-sm text-gray-600">${sizeDisplay}</td>
<td class="p-3 border-b text-sm text-gray-600">${memDisplay}</td>
<td class="p-3 border-b text-sm text-gray-600">${queueWait}</td>
${job.error ? `<td class="p-3 border-b text-sm text-red-600 max-w-xs truncate" title="${job.error}">${job.error}</td>` : '<td class="p-3 border-b"></td>'}
</tr>
`;
}).join('');
const html = `
<!DOCTYPE html>
<html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PDF Service Dashboard</title><script src="https://cdn.tailwindcss.com"></script>
<meta http-equiv="refresh" content="5"></head>
<body class="bg-gray-100 min-h-screen p-8">
<div class="max-w-7xl mx-auto">
<!-- Header -->
<div class="bg-white rounded-xl shadow-sm p-6 mb-6">
<div class="flex justify-between items-center">
<div>
<h1 class="text-3xl font-bold text-gray-800">📄 WebAssets PDF Service</h1>
<p class="text-gray-500 text-sm mt-1">Production Dashboard • Uptime: ${uptime}s • Auto-refresh: 5s</p>
</div>
<div class="text-right">
<div class="text-xs text-gray-400 uppercase tracking-widest font-semibold">Total Jobs</div>
<div class="text-4xl font-bold text-indigo-600">${dailyStats.total}</div>
</div>
</div>
</div>
<!-- Queue Status -->
<div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
<div class="bg-white rounded-lg shadow-sm p-4">
<div class="flex items-center justify-between">
<div>
<p class="text-gray-500 text-xs font-semibold uppercase">Queue Size</p>
<p class="text-2xl font-bold text-orange-600">${queueSize}</p>
</div>
<div class="text-4xl">⏳</div>
</div>
</div>
<div class="bg-white rounded-lg shadow-sm p-4">
<div class="flex items-center justify-between">
<div>
<p class="text-gray-500 text-xs font-semibold uppercase">Processing</p>
<p class="text-2xl font-bold text-blue-600">${processing}/2</p>
</div>
<div class="text-4xl">⚙️</div>
</div>
</div>
<div class="bg-white rounded-lg shadow-sm p-4">
<div class="flex items-center justify-between">
<div>
<p class="text-gray-500 text-xs font-semibold uppercase">Success Rate</p>
<p class="text-2xl font-bold text-green-600">${successRate}%</p>
</div>
<div class="text-4xl">✅</div>
</div>
</div>
<div class="bg-white rounded-lg shadow-sm p-4">
<div class="flex items-center justify-between">
<div>
<p class="text-gray-500 text-xs font-semibold uppercase">Failed Today</p>
<p class="text-2xl font-bold text-red-600">${dailyStats.failed}</p>
</div>
<div class="text-4xl">❌</div>
</div>
</div>
</div>
<!-- Daily Stats -->
<div class="bg-white rounded-xl shadow-sm p-6 mb-6">
<h2 class="text-xl font-bold text-gray-800 mb-4">📈 Today's Performance (${dailyStats.date})</h2>
<div class="grid grid-cols-2 md:grid-cols-4 gap-4">
<div class="text-center p-3 bg-gray-50 rounded-lg">
<p class="text-gray-500 text-xs font-semibold uppercase">Avg Duration</p>
<p class="text-xl font-bold text-gray-800">${avgDuration}s</p>
</div>
<div class="text-center p-3 bg-gray-50 rounded-lg">
<p class="text-gray-500 text-xs font-semibold uppercase">Avg File Size</p>
<p class="text-xl font-bold text-gray-800">${avgSize}KB</p>
</div>
<div class="text-center p-3 bg-gray-50 rounded-lg">
<p class="text-gray-500 text-xs font-semibold uppercase">Completed</p>
<p class="text-xl font-bold text-green-600">${dailyStats.success}</p>
</div>
<div class="text-center p-3 bg-gray-50 rounded-lg">
<p class="text-gray-500 text-xs font-semibold uppercase">Memory Usage</p>
<p class="text-xl font-bold text-gray-800">${logMemory()}MB</p>
</div>
</div>
</div>
<!-- Job History -->
<div class="bg-white rounded-xl shadow-sm overflow-hidden">
<div class="p-4 border-b flex justify-between items-center">
<h2 class="font-semibold text-gray-700">Recent Jobs (Last 20)</h2>
<a href="" class="text-sm text-indigo-500 hover:text-indigo-700">↻ Refresh</a>
</div>
<div class="overflow-x-auto">
<table class="w-full">
<thead><tr class="bg-gray-50">
<th class="p-3 border-b text-xs font-semibold text-gray-500 uppercase text-left">Time</th>
<th class="p-3 border-b text-xs font-semibold text-gray-500 uppercase text-left">Status</th>
<th class="p-3 border-b text-xs font-semibold text-gray-500 uppercase text-left">Filename</th>
<th class="p-3 border-b text-xs font-semibold text-gray-500 uppercase text-left">Duration</th>
<th class="p-3 border-b text-xs font-semibold text-gray-500 uppercase text-left">Size</th>
<th class="p-3 border-b text-xs font-semibold text-gray-500 uppercase text-left">Memory</th>
<th class="p-3 border-b text-xs font-semibold text-gray-500 uppercase text-left">Queue Wait</th>
<th class="p-3 border-b text-xs font-semibold text-gray-500 uppercase text-left">Error</th>
</tr></thead>
<tbody>${recentJobs.length > 0 ? logsHtml : '<tr><td colspan="8" class="p-8 text-center text-gray-400 italic">No jobs yet</td></tr>'}</tbody>
</table>
</div>
</div>
<div class="mt-6 text-center text-xs text-gray-400">
Powered by WebAssets • Docker + Chromium + p-queue
</div>
</div></body></html>`;
res.send(html);
});
// Generate PDF (queued)
app.post('/generate', async (req, res) => {
const jobId = crypto.randomUUID();
const { targetUrl, secretKey, filename } = req.body;
// Auth check
const AUTH_TOKEN = process.env.PDF_SECRET_KEY || 'default_secret_key_change_me';
if (secretKey !== AUTH_TOKEN) {
return res.status(401).json({ status: 'error', message: 'Invalid secret key' });
}
if (!targetUrl) {
return res.status(400).json({ status: 'error', message: 'Missing targetUrl' });
}
const queuedAt = Date.now();
const position = pdfQueue.size + 1;
const estimatedWait = position * 4; // ~4s per job
log('INFO', 'JOB_QUEUED', { jobId, position, filename });
// Add to queue (non-blocking)
pdfQueue.add(async () => {
return await processPDFJob(jobId, targetUrl, filename || 'document.pdf', queuedAt);
}).catch(err => {
log('ERROR', 'JOB_FAILED', { jobId, error: err.message });
});
// Return immediately with job ID
res.json({
status: 'queued',
jobId,
position,
estimatedWait: `~${estimatedWait} seconds`,
statusUrl: `/status/${jobId}`,
downloadUrl: `/download/${jobId}`
});
});
// Check job status
app.get('/status/:jobId', (req, res) => {
const { jobId } = req.params;
const completed = completedJobs.get(jobId);
if (completed) {
return res.json({ status: 'completed', ...completed.metadata });
}
const inHistory = jobHistory.find(j => j.jobId === jobId);
if (inHistory) {
if (inHistory.status === 'failed') {
return res.json({ status: 'failed', error: inHistory.error });
}
return res.json({ status: inHistory.status });
}
// Check if in queue
if (pdfQueue.size > 0 || pdfQueue.pending > 0) {
return res.json({ status: 'queued', message: 'Job is in queue or processing' });
}
res.status(404).json({ status: 'not_found', message: 'Job not found' });
});
// Download PDF
app.get('/download/:jobId', (req, res) => {
const { jobId } = req.params;
const job = completedJobs.get(jobId);
if (!job) {
return res.status(404).json({ status: 'error', message: 'PDF not found or expired' });
}
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', `attachment; filename="${job.metadata.filename}"`);
res.send(job.pdfBuffer);
log('INFO', 'PDF_DOWNLOADED', { jobId });
});
// Process PDF job
async function processPDFJob(jobId, targetUrl, filename, queuedAt) {
let browser = null;
const startTime = Date.now();
const queueWaitTime = (startTime - queuedAt) / 1000;
const memBefore = process.memoryUsage().heapUsed;
try {
log('INFO', 'JOB_STARTED', { jobId, targetUrl });
browser = await puppeteer.launch({
headless: 'new',
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage',
'--disable-accelerated-2d-canvas',
'--no-first-run',
'--no-zygote',
'--disable-gpu'
]
});
const page = await browser.newPage();
// Set timeout for ALL page operations (including PDF generation)
page.setDefaultTimeout(120000); // 2 minutes for large PDFs
await page.setExtraHTTPHeaders({
'ngrok-skip-browser-warning': 'true',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
});
log('INFO', 'NAVIGATING', { jobId, targetUrl });
await page.goto(targetUrl, { waitUntil: 'networkidle0', timeout: 60000 });
log('INFO', 'PAGE_LOADED', { jobId });
log('INFO', 'GENERATING_PDF', { jobId });
const pdfBuffer = await page.pdf({
format: 'A4',
printBackground: true,
margin: { top: '0px', right: '0px', bottom: '0px', left: '0px' }
});
const duration = (Date.now() - startTime) / 1000;
const memAfter = process.memoryUsage().heapUsed;
const memoryUsed = Math.round((memAfter - memBefore) / 1024 / 1024);
const metadata = {
jobId,
filename,
duration,
fileSize: pdfBuffer.length,
memoryUsed,
queueWaitTime,
completedAt: Date.now()
};
// Store completed job
completedJobs.set(jobId, { pdfBuffer, metadata });
// Update history
jobHistory.push({
jobId,
status: 'completed',
filename,
duration,
fileSize: pdfBuffer.length,
memoryUsed,
queueWaitTime,
completedAt: Date.now(),
error: null
});
if (jobHistory.length > MAX_HISTORY) jobHistory.shift();
// Update daily stats
dailyStats.total++;
dailyStats.success++;
dailyStats.totalDuration += duration;
dailyStats.totalSize += pdfBuffer.length;
log('SUCCESS', 'JOB_COMPLETED', { jobId, duration, size: pdfBuffer.length });
} catch (error) {
const duration = (Date.now() - startTime) / 1000;
jobHistory.push({
jobId,
status: 'failed',
filename,
duration,
fileSize: 0,
memoryUsed: 0,
queueWaitTime,
completedAt: Date.now(),
error: error.message
});
if (jobHistory.length > MAX_HISTORY) jobHistory.shift();
dailyStats.total++;
dailyStats.failed++;
log('ERROR', 'JOB_FAILED', { jobId, error: error.message });
throw error;
} finally {
if (browser) {
await browser.close();
}
}
}
// Start server
app.listen(PORT, '0.0.0.0', () => {
log('INFO', 'SERVER_STARTED', { port: PORT });
log('INFO', 'DASHBOARD', { url: `http://localhost:${PORT}` });
log('INFO', 'QUEUE_CONFIG', { concurrency: 2, timeout: 60000 });
});