-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocessWebhookRequestEffect.ts
More file actions
260 lines (244 loc) Β· 8.17 KB
/
Copy pathprocessWebhookRequestEffect.ts
File metadata and controls
260 lines (244 loc) Β· 8.17 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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
import { Duration, Effect } from "effect";
import { AgentWorkScheduler } from "../../agentWork/scheduler.js";
import type { WebhookHeaders } from "../../agentWork/types.js";
import type { Config } from "../../config.js";
import { posthog } from "../../posthog.js";
import { emitOperationLogger, recordEvent, type RequestLogger } from "../../evlog.js";
import { GITHUB_WEBHOOK_RESPONSE_MARGIN_MS } from "../../settings/index.js";
import { WebhookParseError, parseGithubPayload } from "../../webhook/parseGithubPayload.js";
import { verifyGithubWebhookSignature } from "../../webhook/verifySignature.js";
import { WebhookHandlers } from "../services/webhookHandlers.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;
};
type DispatchInput = {
readonly cfg: Config;
readonly headers: WebhookHeaders;
readonly intakeLog: RequestLogger;
readonly payload: Record<string, unknown>;
};
function dispatchGithubEventEffect(
input: DispatchInput,
): Effect.Effect<void, Error, AgentWorkScheduler | WebhookHandlers> {
return Effect.gen(function* () {
const { cfg, headers, intakeLog, payload } = input;
const event = headers.event ?? "";
if (!headers.delivery) {
recordEvent(intakeLog, "missing_delivery_id_using_body_hash", undefined, "warn");
}
let parsed: ReturnType<typeof parseGithubPayload>;
try {
parsed = parseGithubPayload(event, payload);
} catch (e) {
if (e instanceof WebhookParseError) {
recordEvent(intakeLog, "webhook_parse_error", { event, message: e.message }, "warn");
return;
}
yield* Effect.fail(e instanceof Error ? e : new Error(String(e)));
return;
}
const scheduler = yield* AgentWorkScheduler;
if (parsed.name === "ignored") {
recordEvent(intakeLog, "ignored_event", { event }, "debug");
yield* scheduler.recordIgnored(headers, `ignored_event_${event || "missing"}`, intakeLog);
return;
}
const handlers = yield* WebhookHandlers;
switch (parsed.name) {
case "pull_request":
yield* handlers.pullRequest(cfg, headers, parsed.data, intakeLog);
return;
case "issue_comment":
yield* handlers.issueComment(cfg, headers, parsed.data, intakeLog);
return;
case "pull_request_review_comment":
yield* handlers.pullRequestReviewComment(cfg, headers, parsed.data, intakeLog);
return;
default:
parsed satisfies never;
recordEvent(intakeLog, "unhandled_parsed_event", { event }, "warn");
yield* scheduler.recordIgnored(
headers,
`ignored_unhandled_${event || "missing"}`,
intakeLog,
);
}
});
}
export function processWebhookPostRequestEffect(
cfg: Config,
req: WebhookPostRequest,
intakeLog: RequestLogger,
): Effect.Effect<WebhookResponseLike, never, AgentWorkScheduler | WebhookHandlers> {
return Effect.gen(function* () {
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 headers = {
...(delivery === undefined ? {} : { delivery }),
event: githubEvent,
rawBody: req.rawBody,
} satisfies WebhookHeaders;
const dispatch = dispatchGithubEventEffect({
cfg,
headers,
intakeLog,
payload,
});
const result: DispatchResult = yield* dispatch.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.catchAll((err) =>
Effect.sync(() => {
const message = err instanceof Error ? err.message : String(err);
recordEvent(
intakeLog,
"webhook_handler_error",
{
event: githubEvent,
delivery: logDelivery,
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* () {
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));
}),
),
);
}