Skip to content
File

Blob: src/worker/router.ts

typescript75 lines
1import { Hono } from "hono";
2import { ErrorResponse } from "@/shared/contracts";
3import { D1_BOOKMARK_HEADER } from "@/shared/d1";
4import { registerAdminRoutes } from "@/worker/api/admin";
5import { registerAdminOidcRoutes } from "@/worker/api/admin-oidc";
6import { registerConfigRoutes } from "@/worker/api/config";
7import { registerDomainRoutes } from "@/worker/api/domains";
8import { registerEmailRoutes } from "@/worker/api/emails";
9import { registerInboxRoutes } from "@/worker/api/inboxes";
10import { createDb } from "@/worker/db";
11import { createLogger, errorContext } from "@/worker/logger";
12import type { AppBindings } from "@/worker/types";
13 
14export const app = new Hono<AppBindings>();
15const logger = createLogger("router");
16 
17const 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 
29function 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 
37app.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 
53registerConfigRoutes(app);
54registerDomainRoutes(app);
55registerInboxRoutes(app);
56registerEmailRoutes(app);
57registerAdminRoutes(app);
58registerAdminOidcRoutes(app);
59 
60app.notFound((c) => c.json(ErrorResponse.create({ error: "Not found" }), 404));
61 
62app.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});