From 1e82f2f1f89bc099ea2d57796bc0d8bfcb954bde Mon Sep 17 00:00:00 2001 From: Rory& Date: Fri, 13 Mar 2026 06:09:27 +0100 Subject: [PATCH] gateway: util function to do gateway offload stuff --- src/gateway/util/Utils.ts | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/src/gateway/util/Utils.ts b/src/gateway/util/Utils.ts index a629751b7..74ec33cf2 100644 --- a/src/gateway/util/Utils.ts +++ b/src/gateway/util/Utils.ts @@ -1,4 +1,7 @@ -import { VoiceState } from "@spacebar/util"; +import { Event, VoiceState } from "@spacebar/util"; +import { WebSocket } from "./WebSocket"; +import { OPCODES } from "./Constants"; +import { Send } from "./Send"; export function parseStreamKey(streamKey: string): { type: "guild" | "call"; @@ -58,3 +61,34 @@ export async function cleanupOnStartup(): Promise { .then((e) => console.log("[Gateway] Successfully cleaned voice states")) .catch((e) => console.error("[Gateway] Error cleaning voice states on startup:", e)); } + +export async function handleOffloadedGatewayRequest(socket: WebSocket, url: string, body: unknown) { + // TODO: async json object streaming + const resp = await fetch(url, { + body: JSON.stringify(body), + method: "POST", + headers: { + Authorization: `Bearer ${socket.accessToken}`, + // because the session may not have an id in the token! + "X-Session-Id": socket.session_id, + }, + }); + + if (!resp.ok) { + const text = await resp.text(); + console.error(`[Gateway] Offloaded request to ${url} failed with status ${resp.status}: ${text}`); + throw new Error(`Offloaded request failed with status ${resp.status}: ${text}`); + } + + const data = ((await resp.json()) as Event[]).toReversed(); + while (data.length > 0) { + const event = data.pop()!; + if (process.env.WS_VERBOSE) console.log(`[Gateway] Received offloaded event: ${JSON.stringify(event)}`); + await Send(socket, { + op: OPCODES.Dispatch, + s: socket.sequence++, + t: event.event, + d: event.data, + }); + } +}