2026-06-02 00:11:29 +07:00
|
|
|
import type { Server } from "node:http";
|
2026-06-09 17:34:18 +07:00
|
|
|
import { BACKEND_COMMAND, BACKEND_VOICE_TRANSMIT } from "@bete/shared";
|
2026-06-02 21:06:42 +07:00
|
|
|
import { createChildLogger } from "@bete/shared/logger";
|
2026-06-08 19:14:34 +07:00
|
|
|
import { WebSocket, WebSocketServer } from "ws";
|
2026-06-09 11:56:03 +07:00
|
|
|
import { setBroadcastFunctions } from "./broadcast.js";
|
2026-06-02 00:11:29 +07:00
|
|
|
|
|
|
|
|
const logger = createChildLogger("ws.server");
|
|
|
|
|
|
|
|
|
|
interface BroadcastEvent {
|
|
|
|
|
type: string;
|
|
|
|
|
data: unknown;
|
|
|
|
|
timestamp: string;
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-09 16:56:44 +07:00
|
|
|
// Track the active WebSocket server for lifecycle management
|
|
|
|
|
let _wss: WebSocketServer | null = null;
|
|
|
|
|
|
2026-06-02 10:44:27 +07:00
|
|
|
async function sendInitialStates(ws: WebSocket): Promise<void> {
|
|
|
|
|
// Send initial user state
|
|
|
|
|
ws.send(
|
|
|
|
|
JSON.stringify({
|
|
|
|
|
type: "user_state",
|
|
|
|
|
users: [],
|
|
|
|
|
}),
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
// Send initial UI state from database
|
|
|
|
|
try {
|
|
|
|
|
const { uiStateService } = await import(
|
|
|
|
|
"../modules/ui-state/ui-state.service.js"
|
|
|
|
|
);
|
|
|
|
|
const uiState = await uiStateService.getState();
|
|
|
|
|
ws.send(
|
|
|
|
|
JSON.stringify({
|
|
|
|
|
type: "ui_state",
|
|
|
|
|
state: uiState,
|
|
|
|
|
}),
|
|
|
|
|
);
|
|
|
|
|
} catch (err) {
|
|
|
|
|
logger.warn({ err }, "Failed to send initial ui_state");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Send initial media state
|
|
|
|
|
try {
|
|
|
|
|
const { getStatus } = await import("../modules/media/media.service.js");
|
|
|
|
|
const mediaState = await getStatus();
|
|
|
|
|
ws.send(
|
|
|
|
|
JSON.stringify({
|
|
|
|
|
type: "media_state",
|
|
|
|
|
state: mediaState,
|
|
|
|
|
}),
|
|
|
|
|
);
|
|
|
|
|
} catch (err) {
|
|
|
|
|
logger.warn({ err }, "Failed to send initial media_state");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-09 16:56:44 +07:00
|
|
|
export function closeWebSocketServer(): void {
|
|
|
|
|
if (!_wss) return;
|
|
|
|
|
logger.info("Closing WebSocket server");
|
|
|
|
|
_wss.close(() => logger.info("WebSocket server closed"));
|
|
|
|
|
_wss = null;
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-02 00:11:29 +07:00
|
|
|
export function createWebSocketServer(server: Server): WebSocketServer {
|
|
|
|
|
const clients = new Set<WebSocket>();
|
|
|
|
|
|
|
|
|
|
const wss = new WebSocketServer({ server, path: "/ws" });
|
2026-06-09 16:56:44 +07:00
|
|
|
_wss = wss;
|
2026-06-02 00:11:29 +07:00
|
|
|
|
|
|
|
|
wss.on("connection", (ws: WebSocket) => {
|
|
|
|
|
clients.add(ws);
|
|
|
|
|
logger.info(`Client connected (${clients.size} total)`);
|
|
|
|
|
|
2026-06-02 10:44:27 +07:00
|
|
|
// Send initial states (user, ui, media) — fire-and-forget
|
|
|
|
|
sendInitialStates(ws).catch((err) =>
|
|
|
|
|
logger.error({ err }, "sendInitialStates failed"),
|
2026-06-02 00:11:29 +07:00
|
|
|
);
|
|
|
|
|
|
|
|
|
|
ws.on("message", (data: Buffer) => {
|
2026-06-08 21:29:41 +07:00
|
|
|
// Handle JSON messages from browser
|
2026-06-09 10:16:04 +07:00
|
|
|
if (
|
|
|
|
|
typeof data === "string" ||
|
|
|
|
|
(Buffer.isBuffer(data) && data.length > 0 && data[0] === 0x7b)
|
|
|
|
|
) {
|
2026-06-08 21:29:41 +07:00
|
|
|
try {
|
|
|
|
|
const message = JSON.parse(data.toString());
|
|
|
|
|
|
2026-06-09 10:16:04 +07:00
|
|
|
if (message.type === "voice_transmit" && message.buffer) {
|
2026-06-08 21:29:41 +07:00
|
|
|
// Forward PCM data to Redis for discord-gateway
|
2026-06-09 10:16:04 +07:00
|
|
|
import("../shared/redis/index.js").then(
|
|
|
|
|
({ getCommandPublisher }) => {
|
|
|
|
|
const publisher = getCommandPublisher();
|
|
|
|
|
publisher
|
|
|
|
|
.publish(
|
2026-06-09 17:34:18 +07:00
|
|
|
BACKEND_VOICE_TRANSMIT,
|
2026-06-09 10:16:04 +07:00
|
|
|
JSON.stringify({
|
|
|
|
|
type: "pcm",
|
|
|
|
|
buffer: message.buffer,
|
|
|
|
|
}),
|
|
|
|
|
)
|
|
|
|
|
.catch((err: Error) => {
|
|
|
|
|
logger.error(
|
|
|
|
|
{ err },
|
|
|
|
|
"Failed to publish voice transmit to Redis",
|
|
|
|
|
);
|
|
|
|
|
});
|
|
|
|
|
},
|
|
|
|
|
);
|
|
|
|
|
} else if (message.type === "voice_command" && message.command) {
|
2026-06-09 16:36:23 +07:00
|
|
|
// Forward voice commands to discord-gateway with payload
|
2026-06-09 10:16:04 +07:00
|
|
|
import("../shared/redis/index.js").then(
|
|
|
|
|
({ getCommandPublisher }) => {
|
|
|
|
|
const publisher = getCommandPublisher();
|
|
|
|
|
const commandId = `cmd-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
|
|
|
|
|
publisher
|
|
|
|
|
.publish(
|
2026-06-09 17:34:18 +07:00
|
|
|
BACKEND_COMMAND,
|
2026-06-09 10:16:04 +07:00
|
|
|
JSON.stringify({
|
|
|
|
|
id: commandId,
|
|
|
|
|
type: message.command,
|
2026-06-09 16:36:23 +07:00
|
|
|
payload: message.payload ?? {},
|
2026-06-09 10:16:04 +07:00
|
|
|
replyChannel: `reply:${commandId}`,
|
|
|
|
|
}),
|
|
|
|
|
)
|
|
|
|
|
.catch((err: Error) => {
|
|
|
|
|
logger.error(
|
|
|
|
|
{ err },
|
|
|
|
|
"Failed to publish voice command to Redis",
|
|
|
|
|
);
|
|
|
|
|
});
|
|
|
|
|
},
|
|
|
|
|
);
|
2026-06-08 21:29:41 +07:00
|
|
|
}
|
|
|
|
|
} catch (err) {
|
2026-06-09 10:16:04 +07:00
|
|
|
logger.debug({ err }, "Failed to parse WebSocket message as JSON");
|
2026-06-08 21:29:41 +07:00
|
|
|
}
|
2026-06-02 00:11:29 +07:00
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
ws.on("close", () => {
|
|
|
|
|
clients.delete(ws);
|
|
|
|
|
logger.info(`Client disconnected (${clients.size} total)`);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
ws.on("error", (err: Error) => {
|
|
|
|
|
logger.error({ err }, "WebSocket client error");
|
|
|
|
|
clients.delete(ws);
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Heartbeat every 30s
|
|
|
|
|
const heartbeatInterval = setInterval(() => {
|
|
|
|
|
const message = JSON.stringify({ type: "heartbeat" });
|
|
|
|
|
for (const client of clients) {
|
|
|
|
|
if (client.readyState === WebSocket.OPEN) {
|
|
|
|
|
client.send(message);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}, 30_000);
|
|
|
|
|
|
|
|
|
|
// Don't let the interval keep the process alive after wss closes
|
|
|
|
|
heartbeatInterval.unref();
|
|
|
|
|
|
2026-06-09 11:56:03 +07:00
|
|
|
// Defines broadcast functions and injects them via setBroadcastFunctions
|
2026-06-02 00:11:29 +07:00
|
|
|
function broadcast(event: Omit<BroadcastEvent, "timestamp">) {
|
|
|
|
|
const payload = JSON.stringify({
|
|
|
|
|
...event,
|
|
|
|
|
timestamp: new Date().toISOString(),
|
|
|
|
|
});
|
|
|
|
|
for (const client of clients) {
|
|
|
|
|
if (client.readyState === WebSocket.OPEN) {
|
|
|
|
|
try {
|
|
|
|
|
client.send(payload);
|
|
|
|
|
} catch (err) {
|
|
|
|
|
logger.error({ err }, "Failed to broadcast to client");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-09 11:56:03 +07:00
|
|
|
function broadcastBinary(data: Buffer) {
|
2026-06-08 19:14:34 +07:00
|
|
|
for (const client of clients) {
|
|
|
|
|
if (client.readyState === WebSocket.OPEN) {
|
|
|
|
|
try {
|
|
|
|
|
client.send(data);
|
|
|
|
|
} catch (err) {
|
|
|
|
|
logger.error({ err }, "Failed to broadcast binary data to client");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-09 22:04:05 +07:00
|
|
|
setBroadcastFunctions(
|
|
|
|
|
(type: string, data: unknown) => broadcast({ type, data }),
|
|
|
|
|
broadcastBinary,
|
|
|
|
|
);
|
2026-06-02 00:11:29 +07:00
|
|
|
|
|
|
|
|
// Cleanup on close
|
|
|
|
|
wss.on("close", () => {
|
|
|
|
|
clearInterval(heartbeatInterval);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
logger.info({ path: "/ws" }, "WebSocket server created");
|
|
|
|
|
|
|
|
|
|
return wss;
|
|
|
|
|
}
|