Rename and fix screenshots

This commit is contained in:
Andras Schmelczer 2026-02-07 22:19:06 +00:00
parent 9e71ed77df
commit e5d5819098
8 changed files with 81 additions and 18 deletions

82
screenshot/src/server.ts Normal file
View file

@ -0,0 +1,82 @@
import express from 'express';
import { ScreenshotCache } from './cache.js';
import { takeScreenshot, checkWebGL, closeBrowser } from './screenshot.js';
const PORT = parseInt(process.env.PORT || '8002', 10);
const NARROWIT_URL = process.env.NARROWIT_URL || 'http://localhost:8001';
const CACHE_DIR = process.env.CACHE_DIR || '/cache';
const cache = new ScreenshotCache(CACHE_DIR);
const app = express();
app.get('/health', (_req, res) => {
res.status(200).send('ok');
});
app.get('/debug', async (_req, res) => {
try {
const info = await checkWebGL();
res.json(info);
} catch (err) {
res.status(500).json({ error: String(err) });
}
});
app.get('/screenshot', async (req, res) => {
try {
const params: Record<string, string> = {};
for (const key of ['v', 'f', 'poi', 'tab', 'og']) {
const val = req.query[key];
if (typeof val === 'string' && val) {
params[key] = val;
}
}
const cacheKey = cache.buildKey(params);
// Check cache first
const cached = cache.get(cacheKey);
if (cached) {
res.setHeader('Content-Type', 'image/png');
res.setHeader('Cache-Control', 'public, max-age=86400');
res.setHeader('X-Cache', 'HIT');
cached.pipe(res);
return;
}
// Build the URL for the frontend in screenshot mode
const qs = new URLSearchParams(params);
qs.set('screenshot', '1');
const url = `${NARROWIT_URL}/?${qs}`;
console.log(`Taking screenshot: ${url}`);
const png = await takeScreenshot(url);
// Cache it
cache.set(cacheKey, png);
res.setHeader('Content-Type', 'image/png');
res.setHeader('Cache-Control', 'public, max-age=86400');
res.setHeader('X-Cache', 'MISS');
res.send(png);
} catch (err) {
console.error('Screenshot failed:', err);
res.status(500).json({ error: 'Screenshot failed' });
}
});
const server = app.listen(PORT, () => {
console.log(`Screenshot service listening on port ${PORT}`);
console.log(` NARROWIT_URL: ${NARROWIT_URL}`);
console.log(` CACHE_DIR: ${CACHE_DIR}`);
});
// Graceful shutdown
for (const signal of ['SIGTERM', 'SIGINT']) {
process.on(signal, async () => {
console.log(`Received ${signal}, shutting down...`);
server.close();
await closeBrowser();
process.exit(0);
});
}