File
Blob: src/worker/router.ts
| 1 | import { Hono } from "hono"; |
| 2 | import { ErrorResponse } from "@/shared/contracts"; |
| 3 | import { D1_BOOKMARK_HEADER } from "@/shared/d1"; |
| 4 | import { registerAdminRoutes } from "@/worker/api/admin"; |
| 5 | import { registerAdminOidcRoutes } from "@/worker/api/admin-oidc"; |
| 6 | import { registerConfigRoutes } from "@/worker/api/config"; |
| 7 | import { registerDomainRoutes } from "@/worker/api/domains"; |
| 8 | import { registerEmailRoutes } from "@/worker/api/emails"; |
| 9 | import { registerInboxRoutes } from "@/worker/api/inboxes"; |
| 10 | import { createDb } from "@/worker/db"; |
| 11 | import { createLogger, errorContext } from "@/worker/logger"; |
| 12 | import type { AppBindings } from "@/worker/types"; |
| 13 | |
| 14 | export const app = new Hono<AppBindings>(); |
| 15 | const logger = createLogger("router"); |
| 16 | |
| 17 | const REPLICA_FRIENDLY_ROUTES = [ |
| 18 | /^\/api\/public\/config$/, |
| 19 | /^\/api\/public\/domains$/, |
| 20 | /^\/api\/protected\/inboxes\/[^/]+$/, |
| 21 | /^\/api\/protected\/inboxes\/[^/]+\/emails$/, |
| 22 | /^\/api\/protected\/inboxes\/[^/]+\/emails\/[^/]+\/raw$/, |
| 23 | /^\/api\/protected\/inboxes\/[^/]+\/emails\/[^/]+\/attachments\/[^/]+$/, |
| 24 | /^\/api\/protected\/admin\/domains$/, |
| 25 | /^\/api\/protected\/admin\/inboxes$/, |
| 26 | /^\/api\/protected\/admin\/temp-inboxes$/, |
| 27 | ]; |
| 28 | |
| 29 | function selectSessionConstraint(method: string, path: string): D1SessionConstraint { |
| 30 | if (method === "GET" && REPLICA_FRIENDLY_ROUTES.some((route) => route.test(path))) { |
| 31 | return "first-unconstrained"; |
| 32 | } |
| 33 | |
| 34 | return "first-primary"; |
| 35 | } |
| 36 | |
| 37 | app.use("*", async (c, next) => { |
| 38 | const bookmark = c.req.header(D1_BOOKMARK_HEADER)?.trim(); |
| 39 | const session = bookmark |
| 40 | ? c.env.DB.withSession(bookmark) |
| 41 | : c.env.DB.withSession(selectSessionConstraint(c.req.method, c.req.path)); |
| 42 | |
| 43 | c.set("db", createDb(session)); |
| 44 | |
| 45 | await next(); |
| 46 | |
| 47 | const nextBookmark = session.getBookmark(); |
| 48 | if (nextBookmark) { |
| 49 | c.header(D1_BOOKMARK_HEADER, nextBookmark); |
| 50 | } |
| 51 | }); |
| 52 | |
| 53 | registerConfigRoutes(app); |
| 54 | registerDomainRoutes(app); |
| 55 | registerInboxRoutes(app); |
| 56 | registerEmailRoutes(app); |
| 57 | registerAdminRoutes(app); |
| 58 | registerAdminOidcRoutes(app); |
| 59 | |
| 60 | app.notFound((c) => c.json(ErrorResponse.create({ error: "Not found" }), 404)); |
| 61 | |
| 62 | app.onError((error, c) => { |
| 63 | logger.error("request_failed", "Unhandled API error", { |
| 64 | method: c.req.method, |
| 65 | path: c.req.path, |
| 66 | ...errorContext(error), |
| 67 | }); |
| 68 | return c.json( |
| 69 | ErrorResponse.create({ |
| 70 | error: "Internal server error", |
| 71 | }), |
| 72 | 500, |
| 73 | ); |
| 74 | }); |