-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocessWebhookRequestEffect.ts
More file actions
195 lines (185 loc) Β· 6.15 KB
/
Copy pathprocessWebhookRequestEffect.ts
File metadata and controls
195 lines (185 loc) Β· 6.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
import { Duration, Effect } from "effect";
import type { Config } from "../../config.js";
import { posthog } from "../../posthog.js";
import { emitOperationLogger, recordEvent } from "../../evlog.js";
import { GITHUB_WEBHOOK_RESPONSE_MARGIN_MS } from "../../settings/index.js";
import { verifyGithubWebhookSignature } from "../../webhook/verifySignature.js";
import { IntakeLogger } from "../intakeLogger.js";
import { WebhookHandlerError } from "../errors.js";
import { WebhookDispatcher } from "../services/webhookDispatcher.js";
type DispatchResult =
| { readonly kind: "ok" }
| { readonly kind: "failed" }
| { readonly kind: "timeout" };
export type WebhookPostRequest = {
headers: Record<string, string | undefined>;
rawBody: Buffer;
};
export type WebhookResponseLike = {
status: number;
body: string;
contentType?: string;
};
export function processWebhookPostRequestEffect(
cfg: Config,
req: WebhookPostRequest,
): Effect.Effect<WebhookResponseLike, never, WebhookDispatcher | IntakeLogger> {
return Effect.gen(function* () {
const intakeLog = yield* IntakeLogger;
const dispatcher = yield* WebhookDispatcher;
const delivery = req.headers["x-github-delivery"];
const githubEvent = req.headers["x-github-event"] ?? "";
const logDelivery = delivery ?? "(missing)";
intakeLog.set({
github: { event: githubEvent, delivery: logDelivery },
webhook: { method: "POST", path: "/webhooks" },
runtime: "effect",
});
const sig = req.headers["x-hub-signature-256"];
if (!verifyGithubWebhookSignature(cfg.webhookSecret, req.rawBody, sig)) {
recordEvent(intakeLog, "invalid_signature", undefined, "warn");
const response = {
status: 401,
body: "invalid signature",
} satisfies WebhookResponseLike;
intakeLog.set({
webhook: { status: response.status, signatureInvalid: true },
});
yield* Effect.promise(() => emitOperationLogger(intakeLog, { event: "invalid_signature" }));
return response;
}
let payload: Record<string, unknown>;
try {
payload = JSON.parse(req.rawBody.toString("utf8")) as Record<string, unknown>;
} catch {
recordEvent(intakeLog, "invalid_json", undefined, "warn");
const response = {
status: 400,
body: "invalid json",
} satisfies WebhookResponseLike;
intakeLog.set({ webhook: { status: response.status } });
yield* Effect.promise(() => emitOperationLogger(intakeLog, { event: "invalid_json" }));
return response;
}
const t0 = Date.now();
const responseBudgetMs = Math.max(1, cfg.webhookTimeoutMs - GITHUB_WEBHOOK_RESPONSE_MARGIN_MS);
const result: DispatchResult = yield* dispatcher
.dispatch({
cfg,
headers: { delivery, event: githubEvent, rawBody: req.rawBody },
payload,
})
.pipe(
Effect.timeout(Duration.millis(responseBudgetMs)),
Effect.map(() => ({ kind: "ok" as const })),
Effect.catchTag("TimeoutException", () =>
Effect.sync(() => {
recordEvent(
intakeLog,
"webhook_timeout_budget_exceeded",
{
event: githubEvent,
delivery: logDelivery,
budgetMs: cfg.webhookTimeoutMs,
responseBudgetMs,
},
"warn",
);
return { kind: "timeout" as const };
}),
),
Effect.catchTag("WebhookHandlerError", (err: WebhookHandlerError) =>
Effect.sync(() => {
recordEvent(
intakeLog,
"webhook_handler_error",
{
event: githubEvent,
delivery: logDelivery,
message: err.message,
},
"error",
);
return { kind: "failed" as const };
}),
),
);
const elapsedMs = Date.now() - t0;
if (result.kind !== "ok") {
const response = {
status: 503,
body: "service unavailable",
} satisfies WebhookResponseLike;
intakeLog.set({
webhook: {
status: response.status,
elapsedMs,
handlerFailed: result.kind === "failed",
timeout: result.kind === "timeout",
responseBudgetMs,
},
});
yield* Effect.promise(() =>
emitOperationLogger(intakeLog, {
event:
result.kind === "timeout" ? "webhook_timeout_budget_exceeded" : "webhook_handler_error",
}),
);
return response;
}
recordEvent(
intakeLog,
"webhook_handled",
{ event: githubEvent, delivery: logDelivery, ms: elapsedMs },
"info",
);
posthog.capture({
distinctId: "server",
event: "webhook received",
properties: {
github_event: githubEvent,
delivery: logDelivery,
elapsed_ms: elapsedMs,
},
});
intakeLog.set({
webhook: {
status: 200,
elapsedMs,
budgetExceeded: elapsedMs > cfg.webhookTimeoutMs,
budgetMs: cfg.webhookTimeoutMs,
responseBudgetMs,
},
});
if (elapsedMs > cfg.webhookTimeoutMs) {
recordEvent(
intakeLog,
"webhook_timeout_budget_exceeded",
{
event: githubEvent,
delivery: logDelivery,
ms: elapsedMs,
budgetMs: cfg.webhookTimeoutMs,
},
"warn",
);
}
void emitOperationLogger(intakeLog, { event: "webhook_handled" }).catch(() => undefined);
return { status: 200, body: "ok" } satisfies WebhookResponseLike;
}).pipe(
Effect.ensuring(
Effect.gen(function* () {
const intakeLog = yield* IntakeLogger;
if (intakeLog.getContext().emitted === true) return;
const webhook = intakeLog.getContext().webhook as { status?: number } | undefined;
if (webhook?.status === 200) return;
const lastEvent = intakeLog.getContext().lastEvent;
yield* Effect.promise(() =>
emitOperationLogger(intakeLog, {
event: typeof lastEvent === "string" ? lastEvent : "webhook_request_aborted",
}),
).pipe(Effect.catchAll(() => Effect.void));
}),
),
);
}