2022-09-03 18:11:04 +00:00
|
|
|
import { log } from "../deps.ts";
|
|
|
|
import config from "./config.ts";
|
2022-09-03 18:14:57 +00:00
|
|
|
import { sleep } from "./util.ts";
|
2022-09-03 18:11:04 +00:00
|
|
|
|
|
|
|
export async function sendWebhook(
|
|
|
|
id: string,
|
|
|
|
token: string,
|
|
|
|
headers: HeadersInit,
|
|
|
|
body: string,
|
|
|
|
): Promise<Response> {
|
|
|
|
const url = `https://discord.com/api/webhooks/${id}/${token}/github?wait=1`;
|
|
|
|
|
|
|
|
let res: Response;
|
|
|
|
let retries = 0;
|
|
|
|
do {
|
|
|
|
const req = new Request(url, {
|
|
|
|
method: "POST",
|
|
|
|
headers: headers,
|
|
|
|
body: body,
|
|
|
|
});
|
|
|
|
|
|
|
|
log.info(`sending webhook request to ${url}`);
|
|
|
|
res = await fetch(req);
|
|
|
|
|
|
|
|
// return response if everything's fine
|
|
|
|
if (res.status !== 429) break;
|
|
|
|
|
|
|
|
const reset = res.headers.get("retry-after");
|
|
|
|
// should always exist, even for cf bans, but checking anyway
|
|
|
|
if (reset === null) break;
|
|
|
|
|
|
|
|
const resetms = parseFloat(reset);
|
|
|
|
// if we'd wait longer than the configured limit, just return the 429
|
2022-09-04 13:08:35 +00:00
|
|
|
if (resetms > config.maxWebhookRetryMs) {
|
|
|
|
log.warning(
|
|
|
|
`ratelimited for ${resetms}ms (> ${config.maxWebhookRetryMs}ms), not retrying`,
|
|
|
|
);
|
|
|
|
break;
|
|
|
|
}
|
2022-09-03 18:11:04 +00:00
|
|
|
|
2022-09-04 13:00:53 +00:00
|
|
|
// maybe wait and retry
|
2022-09-04 13:08:35 +00:00
|
|
|
if (retries >= config.maxWebhookRetries) {
|
|
|
|
log.warning(`reached maximum number of retries (${retries})`);
|
|
|
|
break;
|
|
|
|
}
|
2022-09-03 18:11:04 +00:00
|
|
|
retries++;
|
2022-09-04 13:00:53 +00:00
|
|
|
log.warning(`retrying after ${resetms}ms (retry ${retries})`);
|
|
|
|
await sleep(resetms);
|
|
|
|
} while (true);
|
2022-09-03 18:11:04 +00:00
|
|
|
return res;
|
|
|
|
}
|