|
| 1 | +import { Router, Request, Response } from 'express'; |
| 2 | +import { mkdir, readFile, writeFile, access } from 'fs/promises'; |
| 3 | +import { join } from 'path'; |
| 4 | +import { GIFGenerator } from '../gif-generator.js'; |
| 5 | +import { fetchProjectById } from '../hasura.js'; |
| 6 | +import { compileProjectIsolated } from '../compile-isolated.js'; |
| 7 | +import { CompileError } from '../errors.js'; |
| 8 | + |
| 9 | +const router = Router(); |
| 10 | + |
| 11 | +const CACHE_DIR = process.env.SCREENSHOT_CACHE_DIR ?? '/cache'; |
| 12 | +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; |
| 13 | + |
| 14 | +// Single-flight: collapse concurrent requests for the same cache key onto one render. |
| 15 | +const inFlight = new Map<string, Promise<Buffer>>(); |
| 16 | + |
| 17 | +async function fileExists(path: string): Promise<boolean> { |
| 18 | + try { |
| 19 | + await access(path); |
| 20 | + return true; |
| 21 | + } catch { |
| 22 | + return false; |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +/** |
| 27 | + * Serve a PNG screenshot of a public project, with the ZX ribbon baked into a |
| 28 | + * corner. Cached per project + updated_at, so it self-invalidates on edit and |
| 29 | + * the cache can't be exploded with arbitrary keys. 404 (→ web shows the |
| 30 | + * cartridge fallback) when the project is missing or not public. |
| 31 | + */ |
| 32 | +router.get('/:id', async (req: Request, res: Response) => { |
| 33 | + const id = (req.params.id || '').replace(/\.png$/i, '').toLowerCase(); |
| 34 | + if (!UUID.test(id)) { |
| 35 | + res.status(400).end(); |
| 36 | + return; |
| 37 | + } |
| 38 | + |
| 39 | + try { |
| 40 | + const project = await fetchProjectById(id); |
| 41 | + if (!project) { |
| 42 | + res.status(404).end(); |
| 43 | + return; |
| 44 | + } |
| 45 | + |
| 46 | + const key = `${id}-${Date.parse(project.updated_at) || 0}`; |
| 47 | + const file = join(CACHE_DIR, `${key}.png`); |
| 48 | + |
| 49 | + let png: Buffer; |
| 50 | + if (await fileExists(file)) { |
| 51 | + png = await readFile(file); |
| 52 | + } else { |
| 53 | + let pending = inFlight.get(key); |
| 54 | + if (!pending) { |
| 55 | + pending = (async () => { |
| 56 | + const tap = await compileProjectIsolated(project.lang, project.code); |
| 57 | + const generator = new GIFGenerator({ maxDurationMs: 4000, scale: 2 }); |
| 58 | + await generator.initialize(); |
| 59 | + const out = await generator.generatePngFromTAP(tap, 48); |
| 60 | + await mkdir(CACHE_DIR, { recursive: true }).catch(() => undefined); |
| 61 | + await writeFile(file, out).catch(() => undefined); |
| 62 | + return out; |
| 63 | + })(); |
| 64 | + inFlight.set(key, pending); |
| 65 | + pending.finally(() => inFlight.delete(key)); |
| 66 | + } |
| 67 | + png = await pending; |
| 68 | + } |
| 69 | + |
| 70 | + res.setHeader('Content-Type', 'image/png'); |
| 71 | + res.setHeader('Cache-Control', 'public, max-age=86400'); |
| 72 | + res.send(png); |
| 73 | + } catch (err) { |
| 74 | + if (err instanceof CompileError) { |
| 75 | + res.status(422).end(); // unrenderable source → web falls back to cartridge |
| 76 | + return; |
| 77 | + } |
| 78 | + console.error('Screenshot error:', err); |
| 79 | + res.status(500).end(); |
| 80 | + } |
| 81 | +}); |
| 82 | + |
| 83 | +export default router; |
0 commit comments