mirror of
https://github.com/Elysola/WebHooker.git
synced 2026-11-20 17:13:49 +00:00
A successful create may lose its response. Reuse a stable nonce with enforce_nonce so retries recover that message instead of posting duplicates or accepting an unreadable success.
131 lines
4.5 KiB
TypeScript
131 lines
4.5 KiB
TypeScript
import { log } from "../../lib/log";
|
|
import type { SendResult } from "../types";
|
|
|
|
const DISCORD_API = "https://discord.com/api/v10";
|
|
|
|
interface DiscordMessage {
|
|
id?: string;
|
|
}
|
|
|
|
/**
|
|
* Longest rate-limit wait (seconds) slept inside one request; a longer one is
|
|
* returned as a 429 failure so the delivery queue retries it later instead.
|
|
*/
|
|
const MAX_INLINE_RETRY_AFTER = 10;
|
|
|
|
/**
|
|
* Longest a single API call may take. Bounded, so a message edit always ends
|
|
* well within the update-chain lock it runs under (see `deliverUpdate`).
|
|
*/
|
|
export const REQUEST_TIMEOUT_MS = 15_000;
|
|
|
|
async function request(
|
|
url: string,
|
|
method: string,
|
|
token: string,
|
|
message: unknown,
|
|
channelId: string,
|
|
): Promise<SendResult> {
|
|
for (let attempt = 0; attempt < 3; attempt++) {
|
|
try {
|
|
const res = await fetch(url, {
|
|
method,
|
|
headers: {
|
|
Authorization: `Bot ${token}`,
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: JSON.stringify(message),
|
|
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
});
|
|
|
|
if (res.status === 429) {
|
|
const rateLimit = (await res.json().catch(() => ({}))) as { retry_after?: number };
|
|
const seconds = Number(rateLimit.retry_after);
|
|
const retryAfter = Number.isFinite(seconds) && seconds > 0 ? seconds : 1;
|
|
log.warn({ retryAfter, attempt }, "Rate limited");
|
|
if (retryAfter > MAX_INLINE_RETRY_AFTER || attempt === 2) {
|
|
return {
|
|
ok: false,
|
|
error: `Rate limited (retry_after=${retryAfter})`,
|
|
errorCode: "RATE_LIMITED",
|
|
status: 429,
|
|
attempts: attempt + 1,
|
|
};
|
|
}
|
|
await new Promise((r) => setTimeout(r, retryAfter * 1000));
|
|
continue;
|
|
}
|
|
|
|
if (!res.ok) {
|
|
const err = await res.text();
|
|
if (res.status >= 500) {
|
|
log.error({ status: res.status, err, attempt, channelId }, "Discord API 5xx");
|
|
if (attempt === 2)
|
|
return {
|
|
ok: false,
|
|
error: err,
|
|
errorCode: "DISCORD_5XX",
|
|
status: res.status,
|
|
attempts: attempt + 1,
|
|
};
|
|
await new Promise((r) => setTimeout(r, 1000 * (attempt + 1)));
|
|
continue;
|
|
}
|
|
log.error({ status: res.status, err, channelId }, "Discord API error");
|
|
return {
|
|
ok: false,
|
|
error: err,
|
|
errorCode: "DISCORD_ERROR",
|
|
status: res.status,
|
|
attempts: attempt + 1,
|
|
};
|
|
}
|
|
|
|
// A success whose body cannot be read (cut off, timed out) is not known
|
|
// to have happened: tried again — a create carries its nonce, so it is
|
|
// never doubled.
|
|
const data = (await res.json()) as DiscordMessage | null;
|
|
return { ok: true, status: res.status, messageId: data?.id, attempts: attempt + 1 };
|
|
} catch (err) {
|
|
log.error({ err, attempt, channelId }, "Failed to send message");
|
|
if (attempt === 2)
|
|
return { ok: false, error: String(err), errorCode: "NETWORK", attempts: attempt + 1 };
|
|
await new Promise((r) => setTimeout(r, 1000 * (attempt + 1)));
|
|
}
|
|
}
|
|
|
|
return { ok: false, error: "Max retries exceeded", errorCode: "RETRIES", attempts: 3 };
|
|
}
|
|
|
|
export async function sendMessage(
|
|
token: string,
|
|
channelId: string,
|
|
message: unknown,
|
|
threadId?: string,
|
|
sendKey?: string,
|
|
): Promise<SendResult> {
|
|
// Ids are path segments: encoded, so no stored value can address another
|
|
// resource (`x/../123` is never the channel `123`).
|
|
const url = `${DISCORD_API}/channels/${encodeURIComponent(threadId || channelId)}/messages`;
|
|
// One nonce for every attempt of this send — and, given a `sendKey`, for
|
|
// every attempt of the delivery: when a create went through but its
|
|
// response was lost, Discord answers the retry with that same message
|
|
// instead of posting a second one (`enforce_nonce`, a few minutes' window).
|
|
const nonce = (sendKey ?? crypto.randomUUID().replace(/-/g, "")).slice(0, 25);
|
|
const body =
|
|
message && typeof message === "object" ? { ...message, nonce, enforce_nonce: true } : message;
|
|
return request(url, "POST", token, body, channelId);
|
|
}
|
|
|
|
export async function editMessage(
|
|
token: string,
|
|
channelId: string,
|
|
messageId: string,
|
|
message: unknown,
|
|
threadId?: string,
|
|
): Promise<SendResult> {
|
|
const base = encodeURIComponent(threadId || channelId);
|
|
const url = `${DISCORD_API}/channels/${base}/messages/${encodeURIComponent(messageId)}`;
|
|
return request(url, "PATCH", token, message, channelId);
|
|
}
|