fix: production hardening for merge races, timeouts, and webhook ops
Pin merge SHA, lock conflict repair, bound subprocess/proxy output, fail-fast incomplete R2/webhook config, redact validation/stderr secrets, and document that webhook 202 is best-effort after ACK. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
d6f33a71c3
commit
039acabd96
29 files changed
+1163
-240
No files matched your search
@@ -1,7 +1,7 @@
|
||||
import fs from "node:fs";
|
||||
import { config } from "../config.js";
|
||||
import { createGitHubCredentials } from "../github/client.js";
|
||||
import { logger } from "../logger.js";
|
||||
import { createEventLogger, logger } from "../logger.js";
|
||||
import { withRetry } from "../retry.js";
|
||||
import { processPullRequestChat } from "../chat/processor.js";
|
||||
import { processIssueTriage, processPullRequestTriage } from "../triage/processor.js";
|
||||
@@ -96,6 +96,12 @@ async function main(): Promise<void> {
|
||||
}
|
||||
|
||||
const pullNumberForCache = getPullNumberForCache(eventName, payload);
|
||||
const eventLogger = createEventLogger({
|
||||
eventName,
|
||||
owner: repository.owner.login,
|
||||
repo: repository.name,
|
||||
pullNumber: pullNumberForCache
|
||||
});
|
||||
const persistentCache = {
|
||||
repositoryId: process.env.GHBOT_REPOSITORY_ID || String(repository.id ?? ""),
|
||||
owner: repository.owner.login,
|
||||
@@ -131,7 +137,7 @@ async function main(): Promise<void> {
|
||||
});
|
||||
const octokit = github.octokit;
|
||||
|
||||
logger.info({ eventName }, "Handling GitHub Actions review event.");
|
||||
eventLogger.info("Handling GitHub Actions review event.");
|
||||
|
||||
let eventFailed = false;
|
||||
try {
|
||||
@@ -301,6 +307,15 @@ async function main(): Promise<void> {
|
||||
);
|
||||
}
|
||||
});
|
||||
const rejectedResults = results.filter(
|
||||
(result): result is PromiseRejectedResult => result.status === "rejected"
|
||||
);
|
||||
if (rejectedResults.length > 0) {
|
||||
throw new AggregateError(
|
||||
rejectedResults.map((result) => result.reason),
|
||||
"One or more issue comment handlers failed; GitHub Actions should retry this delivery."
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
+60
-24
@@ -5,6 +5,9 @@ import { Readable } from "node:stream";
|
||||
import type { ReadableStream as WebReadableStream } from "node:stream/web";
|
||||
import { logger } from "../logger.js";
|
||||
|
||||
const PROXY_REQUEST_TIMEOUT_MS = 10 * 60 * 1000;
|
||||
const MAX_PROXY_BODY_BYTES = 20 * 1024 * 1024;
|
||||
|
||||
export async function startOneRunApiProxy(
|
||||
upstreamBaseUrl: string,
|
||||
realApiKey: string
|
||||
@@ -14,6 +17,19 @@ export async function startOneRunApiProxy(
|
||||
const sockets = new Set<Socket>();
|
||||
const upstreamRequests = new Set<AbortController>();
|
||||
const server = http.createServer(async (request, response) => {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => {
|
||||
controller.abort();
|
||||
request.destroy(new Error("goose proxy request timed out."));
|
||||
}, PROXY_REQUEST_TIMEOUT_MS);
|
||||
const abortOnClose = () => {
|
||||
if (!response.writableEnded) {
|
||||
controller.abort();
|
||||
}
|
||||
};
|
||||
request.once("aborted", abortOnClose);
|
||||
response.once("close", abortOnClose);
|
||||
|
||||
try {
|
||||
if (
|
||||
request.method !== "POST" ||
|
||||
@@ -25,40 +41,53 @@ export async function startOneRunApiProxy(
|
||||
return;
|
||||
}
|
||||
|
||||
const body = await readRequestBody(request, 20 * 1024 * 1024);
|
||||
const controller = new AbortController();
|
||||
upstreamRequests.add(controller);
|
||||
let upstreamResponse: Response;
|
||||
try {
|
||||
upstreamResponse = await fetch(upstream, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
authorization: `Bearer ${realApiKey}`,
|
||||
"content-type": request.headers["content-type"] ?? "application/json",
|
||||
accept: request.headers.accept ?? "*/*"
|
||||
},
|
||||
body: body.toString("utf8"),
|
||||
signal: controller.signal
|
||||
});
|
||||
} finally {
|
||||
upstreamRequests.delete(controller);
|
||||
const contentLength = Number(request.headers["content-length"]);
|
||||
if (Number.isFinite(contentLength) && contentLength > MAX_PROXY_BODY_BYTES) {
|
||||
response.writeHead(413, { "content-type": "application/json" });
|
||||
response.end('{"error":{"message":"Request body is too large"}}');
|
||||
request.destroy();
|
||||
return;
|
||||
}
|
||||
|
||||
const body = await readRequestBody(request, MAX_PROXY_BODY_BYTES, controller);
|
||||
upstreamRequests.add(controller);
|
||||
const upstreamResponse = await fetch(upstream, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
authorization: `Bearer ${realApiKey}`,
|
||||
"content-type": request.headers["content-type"] ?? "application/json",
|
||||
accept: request.headers.accept ?? "*/*"
|
||||
},
|
||||
body: body.toString("utf8"),
|
||||
signal: controller.signal
|
||||
});
|
||||
|
||||
response.writeHead(upstreamResponse.status, copyResponseHeaders(upstreamResponse.headers));
|
||||
if (!upstreamResponse.body) {
|
||||
response.end();
|
||||
return;
|
||||
}
|
||||
|
||||
Readable.fromWeb(upstreamResponse.body as WebReadableStream)
|
||||
.on("error", (error) => response.destroy(error as Error))
|
||||
.pipe(response);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const stream = Readable.fromWeb(upstreamResponse.body as WebReadableStream);
|
||||
stream.once("error", reject);
|
||||
response.once("finish", resolve);
|
||||
response.once("close", resolve);
|
||||
stream.pipe(response);
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error({ error }, "goose API proxy request failed.");
|
||||
if (!response.headersSent) {
|
||||
response.writeHead(502, { "content-type": "application/json" });
|
||||
}
|
||||
response.end('{"error":{"message":"goose proxy request failed"}}');
|
||||
if (!response.writableEnded) {
|
||||
response.end('{"error":{"message":"goose proxy request failed"}}');
|
||||
}
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
request.off("aborted", abortOnClose);
|
||||
response.off("close", abortOnClose);
|
||||
upstreamRequests.delete(controller);
|
||||
}
|
||||
});
|
||||
server.on("connection", (socket) => {
|
||||
@@ -83,8 +112,8 @@ export async function startOneRunApiProxy(
|
||||
port: address.port,
|
||||
token,
|
||||
close: async () => {
|
||||
for (const controller of upstreamRequests) {
|
||||
controller.abort();
|
||||
for (const requestController of upstreamRequests) {
|
||||
requestController.abort();
|
||||
}
|
||||
for (const socket of sockets) {
|
||||
socket.destroy();
|
||||
@@ -103,10 +132,17 @@ function hasMatchingBearerToken(value: string | undefined, expectedToken: string
|
||||
return supplied.length === expected.length && timingSafeEqual(supplied, expected);
|
||||
}
|
||||
|
||||
async function readRequestBody(request: http.IncomingMessage, maxBytes: number): Promise<Buffer> {
|
||||
async function readRequestBody(
|
||||
request: http.IncomingMessage,
|
||||
maxBytes: number,
|
||||
controller: AbortController
|
||||
): Promise<Buffer> {
|
||||
const chunks: Buffer[] = [];
|
||||
let size = 0;
|
||||
for await (const chunk of request) {
|
||||
if (controller.signal.aborted) {
|
||||
throw new Error("goose proxy request was aborted.");
|
||||
}
|
||||
const value = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
||||
size += value.length;
|
||||
if (size > maxBytes) {
|
||||
|
||||
+106
-22
@@ -8,8 +8,10 @@ import { config } from "../config.js";
|
||||
import { logger } from "../logger.js";
|
||||
import { startOneRunApiProxy } from "./apiProxy.js";
|
||||
import { tempRootDirectory } from "../runtimePaths.js";
|
||||
import { redactSecrets } from "../security/secrets.js";
|
||||
|
||||
const GOOSE_RUN_TIMEOUT_MS = 10 * 60 * 1000;
|
||||
const MAX_PROCESS_OUTPUT_CHARS = 1_000_000;
|
||||
const GOOSE_DOCKER_IMAGE = "node:24-bookworm";
|
||||
const GOOSE_DOCKER_VERSION = "v1.46.0";
|
||||
const GOOSE_CONTAINER_PATH = "/usr/local/bin/goose";
|
||||
@@ -21,7 +23,7 @@ const GOOSE_CONTAINER_BOOTSTRAP = [
|
||||
'mkdir -p "$HOME"',
|
||||
"git config --global --add safe.directory /workspace",
|
||||
"if ! command -v goose >/dev/null 2>&1; then",
|
||||
" curl -fsSL https://github.com/aaif-goose/goose/releases/download/stable/download_cli.sh -o /tmp/download_cli.sh",
|
||||
` curl -fsSL https://github.com/aaif-goose/goose/releases/download/${GOOSE_DOCKER_VERSION}/download_cli.sh -o /tmp/download_cli.sh`,
|
||||
` if ! GOOSE_VERSION="${GOOSE_DOCKER_VERSION}" GOOSE_BIN_DIR=/tmp/goose-bin CONFIGURE=false bash /tmp/download_cli.sh >/tmp/goose-install.log 2>&1; then`,
|
||||
" cat /tmp/goose-install.log >&2",
|
||||
" exit 1",
|
||||
@@ -57,12 +59,12 @@ export async function runGoosePrompt(
|
||||
throw new Error("GOOSE_API_KEY is required when running a goose prompt.");
|
||||
}
|
||||
|
||||
const tempRoot = tempRootDirectory();
|
||||
await fs.mkdir(tempRoot, { recursive: true });
|
||||
const tempDir = await fs.mkdtemp(path.join(tempRoot, "goose-"));
|
||||
const workingDirectory = options.workingDirectory
|
||||
? await fs.realpath(options.workingDirectory)
|
||||
: process.cwd();
|
||||
const tempRoot = tempRootDirectory();
|
||||
await fs.mkdir(tempRoot, { recursive: true });
|
||||
const tempDir = await fs.mkdtemp(path.join(tempRoot, "goose-"));
|
||||
const args = [
|
||||
"run",
|
||||
"--no-session",
|
||||
@@ -87,6 +89,7 @@ export async function runGoosePrompt(
|
||||
"Running goose prompt."
|
||||
);
|
||||
|
||||
let primaryError: unknown;
|
||||
try {
|
||||
const stdout = await runGoose(
|
||||
args,
|
||||
@@ -95,8 +98,11 @@ export async function runGoosePrompt(
|
||||
options.timeoutMs
|
||||
);
|
||||
return extractGooseFinalText(stdout);
|
||||
} catch (error) {
|
||||
primaryError = error;
|
||||
throw error;
|
||||
} finally {
|
||||
await fs.rm(tempDir, { recursive: true, force: true });
|
||||
await removeDirectoryBestEffort(tempDir, "goose prompt temp directory", primaryError);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,6 +134,7 @@ export async function runGooseAgent(
|
||||
prompt
|
||||
});
|
||||
|
||||
let primaryError: unknown;
|
||||
try {
|
||||
const stdout = await runProcess(
|
||||
"docker",
|
||||
@@ -138,16 +145,21 @@ export async function runGooseAgent(
|
||||
options.timeoutMs
|
||||
);
|
||||
return extractGooseFinalText(stdout);
|
||||
} catch (error) {
|
||||
primaryError = error;
|
||||
throw error;
|
||||
} finally {
|
||||
try {
|
||||
await removeDockerContainer(containerName, realWorkingDirectory);
|
||||
} finally {
|
||||
try {
|
||||
await restoreAgentWorkspacePermissions(realWorkingDirectory);
|
||||
} finally {
|
||||
await proxy.close();
|
||||
}
|
||||
}
|
||||
await removeDockerContainer(containerName, realWorkingDirectory);
|
||||
await restoreAgentWorkspacePermissions(realWorkingDirectory).catch((error: unknown) => {
|
||||
logger.warn(
|
||||
{ error, workingDirectory: realWorkingDirectory },
|
||||
"Agent workspace cleanup failed."
|
||||
);
|
||||
});
|
||||
await proxy.close().catch((error: unknown) => {
|
||||
logger.warn({ error }, "One-run Goose API proxy cleanup failed.");
|
||||
});
|
||||
void primaryError;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -442,6 +454,15 @@ async function runProcess(
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
let finished = false;
|
||||
let outputOverflowed = false;
|
||||
const appendOutput = (current: string, chunk: string): string => {
|
||||
const next = current + chunk;
|
||||
if (next.length <= MAX_PROCESS_OUTPUT_CHARS) {
|
||||
return next;
|
||||
}
|
||||
outputOverflowed = true;
|
||||
return next.slice(-MAX_PROCESS_OUTPUT_CHARS);
|
||||
};
|
||||
const timeout = setTimeout(() => {
|
||||
if (finished) {
|
||||
return;
|
||||
@@ -451,17 +472,48 @@ async function runProcess(
|
||||
child.kill("SIGTERM");
|
||||
setTimeout(() => child.kill("SIGKILL"), 5_000).unref();
|
||||
reject(
|
||||
Object.assign(new Error(`${label} timed out after ${timeoutMs}ms.`), { stdout, stderr })
|
||||
Object.assign(new Error(`${label} timed out after ${timeoutMs}ms.`), {
|
||||
stdout,
|
||||
stderr
|
||||
})
|
||||
);
|
||||
}, timeoutMs);
|
||||
|
||||
child.stdout.on("data", (chunk: Buffer | string) => {
|
||||
stdout += chunk.toString();
|
||||
stdout = appendOutput(stdout, chunk.toString());
|
||||
if (outputOverflowed && !finished) {
|
||||
finished = true;
|
||||
clearTimeout(timeout);
|
||||
child.kill("SIGTERM");
|
||||
reject(
|
||||
Object.assign(
|
||||
new Error(`${label} exceeded the ${MAX_PROCESS_OUTPUT_CHARS}-character output limit.`),
|
||||
{
|
||||
stdout,
|
||||
stderr
|
||||
}
|
||||
)
|
||||
);
|
||||
}
|
||||
});
|
||||
child.stderr.on("data", (chunk: Buffer | string) => {
|
||||
const text = chunk.toString();
|
||||
stderr += text;
|
||||
streamStderr(text, label);
|
||||
stderr = appendOutput(stderr, text);
|
||||
streamStderr(text.slice(-MAX_PROCESS_OUTPUT_CHARS), label);
|
||||
if (outputOverflowed && !finished) {
|
||||
finished = true;
|
||||
clearTimeout(timeout);
|
||||
child.kill("SIGTERM");
|
||||
reject(
|
||||
Object.assign(
|
||||
new Error(`${label} exceeded the ${MAX_PROCESS_OUTPUT_CHARS}-character output limit.`),
|
||||
{
|
||||
stdout,
|
||||
stderr
|
||||
}
|
||||
)
|
||||
);
|
||||
}
|
||||
});
|
||||
child.on("error", (error) => {
|
||||
if (finished) {
|
||||
@@ -513,11 +565,42 @@ async function removeDockerContainer(
|
||||
env: buildChildEnv({}),
|
||||
stdio: "ignore"
|
||||
});
|
||||
child.on("error", () => resolve());
|
||||
child.on("close", () => resolve());
|
||||
const timeout = setTimeout(() => {
|
||||
child.kill("SIGKILL");
|
||||
logger.warn({ containerName }, "Docker container cleanup timed out; continuing.");
|
||||
resolve();
|
||||
}, 10_000);
|
||||
child.on("error", (error) => {
|
||||
clearTimeout(timeout);
|
||||
logger.warn({ error, containerName }, "Docker container cleanup failed; continuing.");
|
||||
resolve();
|
||||
});
|
||||
child.on("close", () => {
|
||||
clearTimeout(timeout);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function removeDirectoryBestEffort(
|
||||
directory: string,
|
||||
label: string,
|
||||
primaryError: unknown
|
||||
): Promise<void> {
|
||||
try {
|
||||
await fs.rm(directory, { recursive: true, force: true });
|
||||
} catch (error) {
|
||||
logger.warn(
|
||||
{
|
||||
error,
|
||||
directory,
|
||||
primaryError: primaryError instanceof Error ? primaryError.message : undefined
|
||||
},
|
||||
`${label} cleanup failed; preserving the primary operation result.`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function buildChildEnv(extraEnv: Record<string, string>): NodeJS.ProcessEnv {
|
||||
const env: NodeJS.ProcessEnv = {};
|
||||
for (const key of [
|
||||
@@ -634,9 +717,10 @@ export function redactProcessArgs(
|
||||
}
|
||||
|
||||
function streamStderr(text: string, label: string): void {
|
||||
for (const line of text.replace(/\r\n/g, "\n").split("\n")) {
|
||||
const redacted = redactSecrets(text);
|
||||
for (const line of redacted.replace(/\r\n/g, "\n").split("\n")) {
|
||||
if (line.trim()) {
|
||||
process.stderr.write(`[${label} stderr] ${line}\n`);
|
||||
logger.warn({ label }, `[${label} stderr] ${line}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
+93
-65
@@ -39,76 +39,103 @@ function csvListWithDefault(defaultValue: string[]) {
|
||||
}, z.array(z.string()));
|
||||
}
|
||||
|
||||
const configSchema = z.object({
|
||||
port: z.coerce.number().int().positive().default(3000),
|
||||
githubToken: optionalString,
|
||||
githubAppId: optionalString,
|
||||
githubAppPrivateKey: optionalString,
|
||||
githubAppInstallationId: z.preprocess((value) => {
|
||||
if (value === "" || value === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return value;
|
||||
}, z.coerce.number().int().positive().optional()),
|
||||
webhookEnabled: envBoolean.default(false),
|
||||
webhookSecret: optionalString,
|
||||
webhookPath: z.string().startsWith("/").default("/webhooks/github"),
|
||||
webhookChatPermission: z.enum(["anyone", "read", "write"]).default("read"),
|
||||
webhookQueueConcurrency: z.coerce.number().int().positive().max(20).default(2),
|
||||
webhookQueueLimit: z.coerce.number().int().positive().max(10_000).default(500),
|
||||
gooseModel: optionalString.default("gpt-5.4"),
|
||||
gooseThinkingEffort: z.preprocess(
|
||||
(value) => {
|
||||
const configSchema = z
|
||||
.object({
|
||||
port: z.coerce.number().int().positive().default(3000),
|
||||
githubToken: optionalString,
|
||||
githubAppId: optionalString,
|
||||
githubAppPrivateKey: optionalString,
|
||||
githubAppInstallationId: z.preprocess((value) => {
|
||||
if (value === "" || value === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (value === "minimal") {
|
||||
return "low";
|
||||
}
|
||||
|
||||
if (value === "xhigh") {
|
||||
return "max";
|
||||
}
|
||||
|
||||
return value;
|
||||
},
|
||||
z.enum(["off", "low", "medium", "high", "max"]).optional()
|
||||
),
|
||||
gooseBaseUrl: optionalString,
|
||||
gooseApiKey: optionalString,
|
||||
reviewPolicy: z.enum(["allow", "require_approval", "reject"]).default("allow"),
|
||||
reviewStrictness: z.enum(["normal", "strict"]).default("normal"),
|
||||
reviewInstructions: optionalString,
|
||||
reviewBranches: csvListWithDefault([]),
|
||||
repositoryKnowledgeEnabled: envBoolean.default(true),
|
||||
repositoryKnowledgeWrite: envBoolean.default(false),
|
||||
r2Endpoint: optionalString,
|
||||
r2BucketName: optionalString,
|
||||
r2Prefix: optionalString,
|
||||
r2AccessKeyId: optionalString,
|
||||
r2SecretAccessKey: optionalString,
|
||||
triageEnabled: envBoolean.default(true),
|
||||
triageLabels: csvListWithDefault([
|
||||
"bug",
|
||||
"enhancement",
|
||||
"documentation",
|
||||
"question",
|
||||
"maintenance"
|
||||
]).refine((labels) => labels.length > 0, "TRIAGE_LABELS must contain at least one label."),
|
||||
triageDuplicateLabel: z.string().min(1).default("duplicate"),
|
||||
triageCandidateLimit: z.coerce.number().int().positive().max(100).default(50),
|
||||
triageInstructions: optionalString,
|
||||
botName: z.string().min(1).default("ghbot"),
|
||||
autoMerge: envBoolean.default(false),
|
||||
autoResolveConflicts: envBoolean.default(false),
|
||||
conflictTestCommand: optionalString,
|
||||
mergeMethod: z.enum(["merge", "squash", "rebase"]).default("squash"),
|
||||
requireChecks: envBoolean.default(true),
|
||||
maxPatchChars: z.coerce.number().int().positive().default(120_000),
|
||||
logLevel: z.string().min(1).default("info")
|
||||
});
|
||||
}, z.coerce.number().int().positive().optional()),
|
||||
webhookEnabled: envBoolean.default(false),
|
||||
webhookSecret: optionalString,
|
||||
webhookPath: z.string().startsWith("/").default("/webhooks/github"),
|
||||
webhookChatPermission: z.enum(["anyone", "read", "write"]).default("read"),
|
||||
webhookQueueConcurrency: z.coerce.number().int().positive().max(20).default(2),
|
||||
webhookQueueLimit: z.coerce.number().int().positive().max(10_000).default(500),
|
||||
runtimeDirectory: optionalString,
|
||||
gooseModel: optionalString.default("gpt-5.4"),
|
||||
gooseThinkingEffort: z.preprocess(
|
||||
(value) => {
|
||||
if (value === "" || value === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (value === "minimal") {
|
||||
return "low";
|
||||
}
|
||||
|
||||
if (value === "xhigh") {
|
||||
return "max";
|
||||
}
|
||||
|
||||
return value;
|
||||
},
|
||||
z.enum(["off", "low", "medium", "high", "max"]).optional()
|
||||
),
|
||||
gooseBaseUrl: optionalString.default("https://api.openai.com/v1"),
|
||||
gooseApiKey: optionalString,
|
||||
reviewPolicy: z.enum(["allow", "require_approval", "reject"]).default("allow"),
|
||||
reviewStrictness: z.enum(["normal", "strict"]).default("normal"),
|
||||
reviewInstructions: optionalString,
|
||||
reviewBranches: csvListWithDefault([]),
|
||||
repositoryKnowledgeEnabled: envBoolean.default(true),
|
||||
repositoryKnowledgeWrite: envBoolean.default(false),
|
||||
r2Endpoint: optionalString,
|
||||
r2BucketName: optionalString,
|
||||
r2Prefix: optionalString,
|
||||
r2AccessKeyId: optionalString,
|
||||
r2SecretAccessKey: optionalString,
|
||||
triageEnabled: envBoolean.default(true),
|
||||
triageLabels: csvListWithDefault([
|
||||
"bug",
|
||||
"enhancement",
|
||||
"documentation",
|
||||
"question",
|
||||
"maintenance"
|
||||
]).refine((labels) => labels.length > 0, "TRIAGE_LABELS must contain at least one label."),
|
||||
triageDuplicateLabel: z.string().min(1).default("duplicate"),
|
||||
triageCandidateLimit: z.coerce.number().int().positive().max(100).default(50),
|
||||
triageInstructions: optionalString,
|
||||
botName: z.string().min(1).default("ghbot"),
|
||||
autoMerge: envBoolean.default(false),
|
||||
autoResolveConflicts: envBoolean.default(false),
|
||||
conflictTestCommand: optionalString,
|
||||
mergeMethod: z.enum(["merge", "squash", "rebase"]).default("squash"),
|
||||
requireChecks: envBoolean.default(true),
|
||||
maxPatchChars: z.coerce.number().int().positive().default(120_000),
|
||||
logLevel: z.string().min(1).default("info")
|
||||
})
|
||||
.superRefine((value, ctx) => {
|
||||
if (value.webhookEnabled && !value.webhookSecret) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ["webhookSecret"],
|
||||
message: "WEBHOOK_SECRET is required when WEBHOOK_ENABLED=true."
|
||||
});
|
||||
}
|
||||
|
||||
const r2Values = [
|
||||
value.r2Endpoint,
|
||||
value.r2BucketName,
|
||||
value.r2AccessKeyId,
|
||||
value.r2SecretAccessKey
|
||||
];
|
||||
const configuredR2Values = r2Values.filter(Boolean).length;
|
||||
if (configuredR2Values > 0 && configuredR2Values < r2Values.length) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ["r2Endpoint"],
|
||||
message:
|
||||
"R2_ENDPOINT, R2_BUCKET_NAME, R2_ACCESS_KEY_ID, and R2_SECRET_ACCESS_KEY must be configured together."
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const config = configSchema.parse({
|
||||
port: process.env.PORT,
|
||||
@@ -123,6 +150,7 @@ export const config = configSchema.parse({
|
||||
webhookChatPermission: process.env.WEBHOOK_CHAT_PERMISSION,
|
||||
webhookQueueConcurrency: process.env.WEBHOOK_QUEUE_CONCURRENCY,
|
||||
webhookQueueLimit: process.env.WEBHOOK_QUEUE_LIMIT,
|
||||
runtimeDirectory: process.env.GHBOT_RUNTIME_DIR,
|
||||
gooseModel: process.env.GOOSE_MODEL ?? process.env.OPENCODE_MODEL,
|
||||
gooseThinkingEffort: process.env.GOOSE_THINKING_EFFORT ?? process.env.OPENCODE_REASONING_EFFORT,
|
||||
gooseBaseUrl: process.env.GOOSE_BASE_URL ?? process.env.OPENCODE_BASE_URL,
|
||||
|
||||
+39
-1
@@ -4,7 +4,45 @@ import { config } from "./config.js";
|
||||
export const logger = pino({
|
||||
level: config.logLevel,
|
||||
redact: {
|
||||
paths: ["gitToken", "*.gitToken", "GHBOT_GIT_TOKEN", "*.GHBOT_GIT_TOKEN"],
|
||||
paths: [
|
||||
"gitToken",
|
||||
"*.gitToken",
|
||||
"GHBOT_GIT_TOKEN",
|
||||
"*.GHBOT_GIT_TOKEN",
|
||||
"gooseApiKey",
|
||||
"*.gooseApiKey",
|
||||
"authorization",
|
||||
"*.authorization",
|
||||
"WEBHOOK_SECRET",
|
||||
"*.WEBHOOK_SECRET",
|
||||
"R2_SECRET_ACCESS_KEY",
|
||||
"*.R2_SECRET_ACCESS_KEY",
|
||||
"githubToken",
|
||||
"*.githubToken",
|
||||
"GITHUB_TOKEN",
|
||||
"*.GITHUB_TOKEN",
|
||||
"GOOSE_API_KEY",
|
||||
"*.GOOSE_API_KEY",
|
||||
"OPENAI_API_KEY",
|
||||
"*.OPENAI_API_KEY",
|
||||
"webhookSecret",
|
||||
"*.webhookSecret",
|
||||
"r2SecretAccessKey",
|
||||
"*.r2SecretAccessKey",
|
||||
"err.stderr",
|
||||
"error.stderr",
|
||||
"*.stderr"
|
||||
],
|
||||
censor: "[REDACTED]"
|
||||
}
|
||||
});
|
||||
|
||||
export function createEventLogger(bindings: {
|
||||
eventName: string;
|
||||
owner?: string;
|
||||
repo?: string;
|
||||
pullNumber?: number;
|
||||
issueNumber?: number;
|
||||
}) {
|
||||
return logger.child(bindings);
|
||||
}
|
||||
@@ -42,6 +42,8 @@ const CONFLICT_VALIDATION_REPAIR_AGENT_TIMEOUT_MS = 10 * 60 * 1000;
|
||||
const CONFLICT_VALIDATION_TIMEOUT_MS = 7 * 60 * 1000;
|
||||
const CONFLICT_CONFIRMATION_TIMEOUT_MS = 5 * 60 * 1000;
|
||||
const VALIDATION_LOG_OUTPUT_LIMIT = 12_000;
|
||||
const GIT_COMMAND_TIMEOUT_MS = 2 * 60 * 1000;
|
||||
const activeConflictLocks = new Set<string>();
|
||||
|
||||
type SnapshotFile = {
|
||||
hash: string;
|
||||
@@ -66,6 +68,16 @@ export function canAutoResolveConflicts(input: ConflictResolutionEligibility): b
|
||||
);
|
||||
}
|
||||
|
||||
export async function acquireConflictLock(key: string): Promise<() => void> {
|
||||
if (activeConflictLocks.has(key)) {
|
||||
throw new Error("Another conflict-resolution run is already active for this pull request.");
|
||||
}
|
||||
activeConflictLocks.add(key);
|
||||
return () => {
|
||||
activeConflictLocks.delete(key);
|
||||
};
|
||||
}
|
||||
|
||||
export async function resolvePullRequestConflicts(
|
||||
octokit: Octokit,
|
||||
params: {
|
||||
@@ -101,15 +113,28 @@ export async function resolvePullRequestConflicts(
|
||||
}
|
||||
|
||||
const worktree = await fs.realpath(params.worktree);
|
||||
const releaseConflictLock = await acquireConflictLock(`${baseRepository}#${params.pullNumber}`);
|
||||
const tempRoot = tempRootDirectory();
|
||||
await fs.mkdir(tempRoot, { recursive: true });
|
||||
const askPassDirectory = await fs.mkdtemp(path.join(tempRoot, "git-auth-"));
|
||||
let askPassDirectory: string;
|
||||
try {
|
||||
await fs.mkdir(tempRoot, { recursive: true });
|
||||
askPassDirectory = await fs.mkdtemp(path.join(tempRoot, "git-auth-"));
|
||||
} catch (error) {
|
||||
releaseConflictLock();
|
||||
throw error;
|
||||
}
|
||||
const askPassPath = path.join(askPassDirectory, "askpass.sh");
|
||||
await fs.writeFile(
|
||||
askPassPath,
|
||||
'#!/bin/sh\ncase "$1" in *Username*) printf "%s\\n" "x-access-token" ;; *) printf "%s\\n" "$GHBOT_GIT_TOKEN" ;; esac\n',
|
||||
{ mode: 0o700 }
|
||||
);
|
||||
try {
|
||||
await fs.writeFile(
|
||||
askPassPath,
|
||||
'#!/bin/sh\ncase "$1" in *Username*) printf "%s\\n" "x-access-token" ;; *) printf "%s\\n" "$GHBOT_GIT_TOKEN" ;; esac\n',
|
||||
{ mode: 0o700 }
|
||||
);
|
||||
} catch (error) {
|
||||
await fs.rm(askPassDirectory, { recursive: true, force: true }).catch(() => undefined);
|
||||
releaseConflictLock();
|
||||
throw error;
|
||||
}
|
||||
const gitEnv = {
|
||||
GIT_ASKPASS: askPassPath,
|
||||
GIT_TERMINAL_PROMPT: "0",
|
||||
@@ -467,13 +492,21 @@ export async function resolvePullRequestConflicts(
|
||||
);
|
||||
return true;
|
||||
} catch (error) {
|
||||
await runCommand("git", ["reset", "--hard", params.expectedHeadSha], worktree, gitEnv).catch(
|
||||
() => undefined
|
||||
);
|
||||
await runCommand("git", ["merge", "--abort"], worktree, gitEnv).catch(() => undefined);
|
||||
throw error;
|
||||
} finally {
|
||||
if (snapshot) {
|
||||
await fs.rm(snapshot, { recursive: true, force: true });
|
||||
await fs.rm(snapshot, { recursive: true, force: true }).catch((error: unknown) => {
|
||||
logger.warn({ error, snapshot }, "Conflict snapshot cleanup failed; continuing.");
|
||||
});
|
||||
}
|
||||
await fs.rm(askPassDirectory, { recursive: true, force: true });
|
||||
await fs.rm(askPassDirectory, { recursive: true, force: true }).catch((error: unknown) => {
|
||||
logger.warn({ error, askPassDirectory }, "Git askpass cleanup failed; continuing.");
|
||||
});
|
||||
releaseConflictLock();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1014,13 +1047,11 @@ function commandFailureOutput(result: { stdout: string; stderr: string }): strin
|
||||
return redactSecrets(raw);
|
||||
}
|
||||
|
||||
function formatValidationResult(
|
||||
export function formatValidationResult(
|
||||
command: string,
|
||||
result: { code: number; stdout: string; stderr: string }
|
||||
): string {
|
||||
const output =
|
||||
[result.stderr.trim(), result.stdout.trim()].filter(Boolean).join("\n").slice(0, 20_000) ||
|
||||
"no output";
|
||||
const output = commandFailureOutput(result);
|
||||
return [`Command: ${command}`, `Exit code: ${result.code}`, "Output:", output].join("\n");
|
||||
}
|
||||
|
||||
@@ -1128,7 +1159,8 @@ async function runCommandAllowFailure(
|
||||
command: string,
|
||||
args: string[],
|
||||
cwd: string,
|
||||
extraEnv: Record<string, string>
|
||||
extraEnv: Record<string, string>,
|
||||
timeoutMs = GIT_COMMAND_TIMEOUT_MS
|
||||
): Promise<{ code: number; stdout: string; stderr: string }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn(command, args, {
|
||||
@@ -1138,17 +1170,52 @@ async function runCommandAllowFailure(
|
||||
});
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
let settled = false;
|
||||
const timeout = setTimeout(() => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
child.kill("SIGTERM");
|
||||
setTimeout(() => child.kill("SIGKILL"), 5_000).unref();
|
||||
reject(
|
||||
Object.assign(new Error(`${command} timed out after ${timeoutMs}ms.`), {
|
||||
stdout,
|
||||
stderr,
|
||||
code: null
|
||||
})
|
||||
);
|
||||
}, timeoutMs);
|
||||
child.stdout.on("data", (chunk: Buffer | string) => {
|
||||
stdout += chunk.toString();
|
||||
stdout = appendBoundedOutput(stdout, chunk.toString());
|
||||
});
|
||||
child.stderr.on("data", (chunk: Buffer | string) => {
|
||||
stderr += chunk.toString();
|
||||
stderr = appendBoundedOutput(stderr, chunk.toString());
|
||||
});
|
||||
child.on("error", (error) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
clearTimeout(timeout);
|
||||
reject(error);
|
||||
});
|
||||
child.on("close", (code) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
clearTimeout(timeout);
|
||||
resolve({ code: code ?? 1, stdout, stderr });
|
||||
});
|
||||
child.on("error", reject);
|
||||
child.on("close", (code) => resolve({ code: code ?? 1, stdout, stderr }));
|
||||
});
|
||||
}
|
||||
|
||||
function appendBoundedOutput(current: string, chunk: string): string {
|
||||
const next = current + chunk;
|
||||
return next.length <= 1_000_000 ? next : next.slice(-1_000_000);
|
||||
}
|
||||
|
||||
function buildCommandEnvironment(extraEnv: Record<string, string>): NodeJS.ProcessEnv {
|
||||
const env: NodeJS.ProcessEnv = {};
|
||||
for (const key of [
|
||||
|
||||
+21
-2
@@ -864,6 +864,19 @@ async function maybeMergePullRequest(
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (livePullRequest.head.sha !== params.headSha) {
|
||||
logger.info(
|
||||
{
|
||||
owner,
|
||||
repo,
|
||||
pullNumber,
|
||||
reviewedHead: params.headSha,
|
||||
currentHead: livePullRequest.head.sha
|
||||
},
|
||||
"Skipping merge because the pull request head changed after review."
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (params.requireAdminApproval) {
|
||||
const approvedByEligibleReviewer = await hasCurrentHeadApprovalFrom(octokit, {
|
||||
@@ -893,8 +906,7 @@ async function maybeMergePullRequest(
|
||||
}
|
||||
}
|
||||
|
||||
const mergeablePullRequest =
|
||||
params.mergeablePullRequest ?? (await waitForMergeable(octokit, owner, repo, pullNumber));
|
||||
const mergeablePullRequest = await waitForMergeable(octokit, owner, repo, pullNumber);
|
||||
if (mergeablePullRequest.mergeable !== true || mergeablePullRequest.mergeable_state === "dirty") {
|
||||
if (params.emitStatusComments) {
|
||||
await withRetry("github.issues.createComment.notMergeable", async () => {
|
||||
@@ -936,6 +948,7 @@ async function maybeMergePullRequest(
|
||||
owner,
|
||||
repo,
|
||||
pull_number: pullNumber,
|
||||
sha: params.headSha,
|
||||
merge_method: config.mergeMethod,
|
||||
commit_title: `${params.title} (#${pullNumber})`
|
||||
});
|
||||
@@ -996,6 +1009,7 @@ async function hasCurrentHeadApprovalFrom(
|
||||
params.headSha
|
||||
);
|
||||
|
||||
let lastLookupError: unknown;
|
||||
for (const login of approvedLogins) {
|
||||
try {
|
||||
const { data: permission } = await octokit.rest.repos
|
||||
@@ -1027,6 +1041,7 @@ async function hasCurrentHeadApprovalFrom(
|
||||
return true;
|
||||
}
|
||||
} catch (error) {
|
||||
lastLookupError = error;
|
||||
logger.warn(
|
||||
{
|
||||
error,
|
||||
@@ -1040,6 +1055,10 @@ async function hasCurrentHeadApprovalFrom(
|
||||
}
|
||||
}
|
||||
|
||||
if (lastLookupError) {
|
||||
throw lastLookupError;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
+3
-2
@@ -1,5 +1,6 @@
|
||||
import path from "node:path";
|
||||
import process from "node:process";
|
||||
import { config } from "./config.js";
|
||||
|
||||
/**
|
||||
* Runtime scratch/cache directories live under one configurable root so
|
||||
@@ -7,8 +8,8 @@ import process from "node:process";
|
||||
* them without code changes. Defaults to the process working directory.
|
||||
*/
|
||||
export function runtimeDirectory(): string {
|
||||
const configured = process.env.GHBOT_RUNTIME_DIR?.trim();
|
||||
return configured ? configured : process.cwd();
|
||||
const environmentValue = process.env.GHBOT_RUNTIME_DIR?.trim();
|
||||
return environmentValue || config.runtimeDirectory || process.cwd();
|
||||
}
|
||||
|
||||
export function tempRootDirectory(): string {
|
||||
|
||||
+101
-68
@@ -8,6 +8,7 @@ import { parseWebhookMentionEvent, processWebhookMention } from "./processor.js"
|
||||
import { MetricsRegistry } from "./metrics.js";
|
||||
|
||||
const MAX_WEBHOOK_BODY_BYTES = 2 * 1024 * 1024;
|
||||
const WEBHOOK_BODY_TIMEOUT_MS = 30_000;
|
||||
const DELIVERY_RETENTION_MS = 24 * 60 * 60 * 1000;
|
||||
const MAX_TASK_ATTEMPTS = 2;
|
||||
|
||||
@@ -60,78 +61,99 @@ export function createWebhookServer(
|
||||
options.handleDelivery ?? createDefaultDeliveryHandler(options.botName ?? config.botName);
|
||||
|
||||
return http.createServer(async (request, response) => {
|
||||
const pathname = new URL(request.url ?? "/", "http://localhost").pathname;
|
||||
if (request.method === "GET" && pathname === "/healthz") {
|
||||
writeJson(response, 200, { ok: true, webhook: true });
|
||||
return;
|
||||
}
|
||||
if (request.method === "GET" && pathname === "/metrics") {
|
||||
response.writeHead(200, { "content-type": "text/plain; version=0.0.4; charset=utf-8" });
|
||||
response.end(metrics.snapshotPrometheus());
|
||||
return;
|
||||
}
|
||||
if (request.method !== "POST" || pathname !== webhookPath) {
|
||||
response.setHeader("allow", "GET, POST");
|
||||
writeJson(response, 404, { error: "Not found." });
|
||||
return;
|
||||
}
|
||||
|
||||
const deliveryId = singleHeader(request.headers["x-github-delivery"]);
|
||||
const eventName = singleHeader(request.headers["x-github-event"]);
|
||||
const signature = singleHeader(request.headers["x-hub-signature-256"]);
|
||||
if (!deliveryId || !eventName || !signature) {
|
||||
metrics.inc("webhook_requests_total", { result: "missing_headers" });
|
||||
writeJson(response, 400, { error: "Missing GitHub webhook headers." });
|
||||
return;
|
||||
}
|
||||
|
||||
let body: Buffer;
|
||||
try {
|
||||
body = await readRawBody(request, maxBodyBytes);
|
||||
} catch (error) {
|
||||
logger.warn(
|
||||
{ error, deliveryId, eventName },
|
||||
"Rejected oversized or unreadable GitHub webhook body."
|
||||
);
|
||||
metrics.inc("webhook_requests_total", { result: "too_large" });
|
||||
writeJson(response, 413, { error: "Webhook payload is too large." });
|
||||
return;
|
||||
}
|
||||
if (!verifyGitHubWebhookSignature(body, signature, options.secret)) {
|
||||
metrics.inc("webhook_requests_total", { result: "bad_signature" });
|
||||
writeJson(response, 401, { error: "Invalid webhook signature." });
|
||||
return;
|
||||
}
|
||||
|
||||
let payload: unknown;
|
||||
try {
|
||||
payload = JSON.parse(body.toString("utf8"));
|
||||
} catch {
|
||||
writeJson(response, 400, { error: "Webhook payload is not valid JSON." });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const accepted = queue.enqueue(deliveryId, () =>
|
||||
handleDelivery(eventName, payload, deliveryId)
|
||||
);
|
||||
if (!accepted) {
|
||||
metrics.inc("webhook_deliveries_total", { result: "duplicate" });
|
||||
writeJson(response, 202, { ok: true, duplicate: true });
|
||||
const pathname = new URL(request.url ?? "/", "http://localhost").pathname;
|
||||
if (request.method === "GET" && pathname === "/healthz") {
|
||||
writeJson(response, 200, { ok: true, webhook: true });
|
||||
return;
|
||||
}
|
||||
if (request.method === "GET" && pathname === "/metrics") {
|
||||
response.writeHead(200, { "content-type": "text/plain; version=0.0.4; charset=utf-8" });
|
||||
response.end(metrics.snapshotPrometheus());
|
||||
return;
|
||||
}
|
||||
if (request.method !== "POST" || pathname !== webhookPath) {
|
||||
response.setHeader("allow", "GET, POST");
|
||||
writeJson(response, 404, { error: "Not found." });
|
||||
return;
|
||||
}
|
||||
metrics.inc("webhook_deliveries_total", { event: eventName, result: "accepted" });
|
||||
} catch (error) {
|
||||
logger.warn(
|
||||
{ error, deliveryId, eventName },
|
||||
"Webhook queue is full; asking GitHub to retry."
|
||||
);
|
||||
metrics.inc("webhook_deliveries_total", { result: "queue_full" });
|
||||
writeJson(response, 503, { error: "Webhook queue is temporarily full." });
|
||||
return;
|
||||
}
|
||||
|
||||
writeJson(response, 202, { ok: true });
|
||||
const deliveryId = singleHeader(request.headers["x-github-delivery"]);
|
||||
const eventName = singleHeader(request.headers["x-github-event"]);
|
||||
const signature = singleHeader(request.headers["x-hub-signature-256"]);
|
||||
if (!deliveryId || !eventName || !signature) {
|
||||
metrics.inc("webhook_requests_total", { result: "missing_headers" });
|
||||
writeJson(response, 400, { error: "Missing GitHub webhook headers." });
|
||||
return;
|
||||
}
|
||||
|
||||
let body: Buffer;
|
||||
const declaredLength = Number(request.headers["content-length"]);
|
||||
if (Number.isFinite(declaredLength) && declaredLength > maxBodyBytes) {
|
||||
metrics.inc("webhook_requests_total", { result: "too_large" });
|
||||
writeJson(response, 413, { error: "Webhook payload is too large." });
|
||||
request.destroy();
|
||||
return;
|
||||
}
|
||||
const bodyTimeout = setTimeout(() => {
|
||||
request.destroy(new Error("Webhook body read timed out."));
|
||||
}, WEBHOOK_BODY_TIMEOUT_MS);
|
||||
try {
|
||||
body = await readRawBody(request, maxBodyBytes);
|
||||
} catch (error) {
|
||||
clearTimeout(bodyTimeout);
|
||||
logger.warn(
|
||||
{ error, deliveryId, eventName },
|
||||
"Rejected oversized or unreadable GitHub webhook body."
|
||||
);
|
||||
metrics.inc("webhook_requests_total", { result: "too_large" });
|
||||
writeJson(response, 413, { error: "Webhook payload is too large." });
|
||||
return;
|
||||
}
|
||||
clearTimeout(bodyTimeout);
|
||||
if (!verifyGitHubWebhookSignature(body, signature, options.secret)) {
|
||||
metrics.inc("webhook_requests_total", { result: "bad_signature" });
|
||||
writeJson(response, 401, { error: "Invalid webhook signature." });
|
||||
return;
|
||||
}
|
||||
|
||||
let payload: unknown;
|
||||
try {
|
||||
payload = JSON.parse(body.toString("utf8"));
|
||||
} catch {
|
||||
writeJson(response, 400, { error: "Webhook payload is not valid JSON." });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const accepted = queue.enqueue(deliveryId, () =>
|
||||
handleDelivery(eventName, payload, deliveryId)
|
||||
);
|
||||
if (!accepted) {
|
||||
metrics.inc("webhook_deliveries_total", { result: "duplicate" });
|
||||
writeJson(response, 202, { ok: true, duplicate: true });
|
||||
return;
|
||||
}
|
||||
metrics.inc("webhook_deliveries_total", { event: eventName, result: "accepted" });
|
||||
} catch (error) {
|
||||
logger.warn(
|
||||
{ error, deliveryId, eventName },
|
||||
"Webhook queue is full; asking GitHub to retry."
|
||||
);
|
||||
metrics.inc("webhook_deliveries_total", { result: "queue_full" });
|
||||
writeJson(response, 503, { error: "Webhook queue is temporarily full." });
|
||||
return;
|
||||
}
|
||||
|
||||
writeJson(response, 202, { ok: true });
|
||||
} catch (error: unknown) {
|
||||
logger.error({ error }, "Webhook request handler failed.");
|
||||
if (!response.headersSent) {
|
||||
writeJson(response, 500, { error: "Webhook request failed." });
|
||||
} else {
|
||||
response.destroy(error instanceof Error ? error : undefined);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -147,6 +169,9 @@ export async function startWebhookServer(): Promise<http.Server> {
|
||||
if (!config.githubAppId || !config.githubAppPrivateKey) {
|
||||
throw new Error("GH_APP_ID and GH_APP_PRIVATE_KEY are required when WEBHOOK_ENABLED=true.");
|
||||
}
|
||||
if (!config.gooseApiKey) {
|
||||
throw new Error("GOOSE_API_KEY is required when WEBHOOK_ENABLED=true.");
|
||||
}
|
||||
|
||||
const server = createWebhookServer({
|
||||
secret: config.webhookSecret,
|
||||
@@ -165,6 +190,14 @@ export async function startWebhookServer(): Promise<http.Server> {
|
||||
{ port: config.port, path: config.webhookPath },
|
||||
"GitHub webhook server is listening."
|
||||
);
|
||||
|
||||
const shutdown = () => {
|
||||
logger.info("Shutting down GitHub webhook server.");
|
||||
server.close();
|
||||
};
|
||||
process.once("SIGTERM", shutdown);
|
||||
process.once("SIGINT", shutdown);
|
||||
|
||||
return server;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user