Skip to content

Commit 3371579

Browse files
committed
refactor: put request logger into asynclocalstorage
1 parent 161d7b1 commit 3371579

File tree

7 files changed

+45
-9
lines changed

7 files changed

+45
-9
lines changed

deno.lock

Lines changed: 8 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/context.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import { createMiddleware } from "@hono/hono/factory";
2+
import { AsyncLocalStorage } from "node:async_hooks";
3+
4+
import { RequestLog, requestLog } from "./util.ts";
5+
6+
interface ContextData {
7+
requestLog: RequestLog;
8+
}
9+
10+
const store = new AsyncLocalStorage<ContextData>();
11+
12+
export const contextMiddleware = createMiddleware(async (c, next) => {
13+
const deliveryId = c.req.header("x-github-delivery");
14+
const reqLog = requestLog(deliveryId);
15+
16+
await store.run({ requestLog: reqLog }, next);
17+
});
18+
19+
export const getContext = () => {
20+
const ctx = store.getStore();
21+
if (ctx === undefined) throw new Error("getContext() may only be called in request handlers");
22+
return ctx;
23+
};
24+
25+
export const getRequestLog = () => getContext().requestLog;

src/filter.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
1+
import { getRequestLog } from "./context.ts";
12
import { getAndIncrementKV } from "./kv.ts";
23
import { UrlConfig } from "./types.d.ts";
3-
import { requestLog, wildcardMatch } from "./util.ts";
4+
import { wildcardMatch } from "./util.ts";
45

56
export default async function filter(
67
headers: Record<string, string>,
78
json: any,
89
config: UrlConfig,
910
): Promise<string | null> {
10-
const reqLog = requestLog(headers);
1111
const event = headers["x-github-event"] || "unknown";
1212
const login: string | undefined = json.sender?.login?.toLowerCase();
1313

@@ -51,6 +51,7 @@ export default async function filter(
5151
if (config.commentBurstLimit && reviewId) {
5252
const cacheKey = `${reviewId}-${login}`;
5353

54+
const reqLog = getRequestLog();
5455
reqLog.debug(`filter: checking cache key ${cacheKey}`);
5556
const curr = await getAndIncrementKV(cacheKey, reqLog);
5657
reqLog.debug(`filter: current value: ${curr}`);

src/handler.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
import { HTTPException } from "@hono/hono/http-exception";
22

3+
import { getRequestLog } from "./context.ts";
34
import filterWebhook from "./filter.ts";
45
import fixupEmbeds from "./formatter.ts";
56
import { UrlConfig } from "./types.d.ts";
6-
import { parseBool, requestLog } from "./util.ts";
7+
import { parseBool } from "./util.ts";
78
import { sendWebhook } from "./webhook.ts";
89

910
export default async function handle(
@@ -18,7 +19,7 @@ export default async function handle(
1819
// do the thing
1920
const filterReason = await filterWebhook(headers, json, urlConfig);
2021
if (filterReason !== null) {
21-
const reqLog = requestLog(headers);
22+
const reqLog = getRequestLog();
2223
reqLog.debug(`handler: ignored due to '${filterReason}'`);
2324
return [
2425
new Response(`Ignored by webhook filter (reason: ${filterReason})`, { status: 203 }),

src/main.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,14 @@ import { HTTPException } from "@hono/hono/http-exception";
33
import { logger } from "@hono/hono/logger";
44

55
import config from "./config.ts";
6+
import { contextMiddleware } from "./context.ts";
67
import { hasKey, verify } from "./crypto.ts";
78
import handler from "./handler.ts";
89

910
const app = new Hono();
1011

1112
app.use(logger());
13+
app.use(contextMiddleware);
1214

1315
if (config.mainRedirect) {
1416
app.get("/", (c) => {

src/util.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,7 @@ export function wildcardMatch(pattern: string, target: string): boolean {
3131
/**
3232
* logging proxy that adds some metadata to log messages
3333
*/
34-
export function requestLog(headers: Record<string, string>) {
35-
const deliveryId = headers["x-github-delivery"];
34+
export function requestLog(deliveryId: string | undefined) {
3635
const prefix = deliveryId ? `[${deliveryId}] ` : "";
3736

3837
// ugh

src/webhook.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
import config from "./config.ts";
2-
import { requestLog, sleep } from "./util.ts";
2+
import { getRequestLog } from "./context.ts";
3+
import { sleep } from "./util.ts";
34

45
export async function sendWebhook(
56
id: string,
67
token: string,
78
headers: Record<string, string>,
89
data: Record<string, any>,
910
): Promise<[Response, Record<string, string>]> {
10-
const reqLog = requestLog(headers);
11+
const reqLog = getRequestLog();
1112
const url = `https://discord.com/api/webhooks/${id}/${token}/github?wait=1`;
1213
const body = JSON.stringify(data);
1314

0 commit comments

Comments
 (0)