| 1 | import { createHash, timingSafeEqual } from "node:crypto"; |
| 2 | import { Hono } |
| 3 | import { bearerAuth } |
| 4 | |
| 5 | import { type Config, |
| 6 | import { type Job, |
| 7 | |
| 8 | export function createApp(config |
| 9 | const running = |
| 10 | const app = |
| 11 | |
| 12 | app.get("/health |
| 13 | |
| 14 | app.post( |
| 15 | "/imports", |
| 16 | bearerAuth({ |
| 17 | verifyToken: (token) |
| 18 | const given = |
| 19 | const expected = |
| 20 | .update(config.IMPORTER_SECRET |
| 21 | .digest(); |
| 22 | return timingSafeEqual(given |
| 23 | }, |
| 24 | }), |
| 25 | async (c) |
| 26 | const parsed = |
| 27 | if (!parsed.success |
| 28 | // A refused job is not lost: the API retries it with backoff. |
| 29 | const job = |
| 30 | // One attempt per import at a time: they share its working directory, and a superseded one stops at its next heartbeat. |
| 31 | if ( |
| 32 | running.size >= |
| 33 | running.has(job |
| 34 | ) |
| 35 | return c.json |
| 36 | |
| 37 | running.add(job |
| 38 | console.log( |
| 39 | `import ${job.importId |
| 40 | ); |
| 41 | void run(job) |
| 42 | return c.body |
| 43 | }, |
| 44 | ); |
| 45 | |
| 46 | return app; |
| 47 | } |
| 48 | |
| 49 | if (import.meta.main |
| 50 | const config = |
| 51 | // A killed importer simply stops calling back; the API sees its leases lapse and dispatches those imports again. |
| 52 | const app = |
| 53 | Bun.serve({ |
| 54 | console.log(`importer listening on : |
| 55 | } |