Skip to content

Commit

Permalink
add HOSTNAME var
Browse files Browse the repository at this point in the history
  • Loading branch information
99percentpeople committed Oct 28, 2024
1 parent f665108 commit c37fa29
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 8 deletions.
1 change: 1 addition & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
LOG_LEVEL=debug
HOSTNAME=0.0.0.0
PORT=9000
HEARTBEAT_INTERVAL=30000
PONG_TIMEOUT=60000
Expand Down
50 changes: 42 additions & 8 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,20 @@ import {
DISCONNECT_TIMEOUT,
REDIS_URL,
ALLOWED_ORIGINS,
HOSTNAME,
} from "./var";

import os from "os";
import Redis from "ioredis";

import type { ServerWebSocket } from "bun";

import type { ClientSignal, RawSignal, Room, ServerWebSocketData, TransferClient } from "./types";
import type {
ClientSignal,
RawSignal,
Room,
ServerWebSocketData,
TransferClient,
} from "./types";

const logger = pino({
level: LOG_LEVEL,
Expand Down Expand Up @@ -111,6 +118,7 @@ redisSub?.on("message", (channel, message) => {

const server = Bun.serve<ServerWebSocketData>({
port: PORT,
hostname: HOSTNAME,
fetch(req, server) {
const url = new URL(req.url);
const roomId = url.searchParams.get("room") || "";
Expand Down Expand Up @@ -187,7 +195,10 @@ function handleWSOpen(ws: ServerWebSocket<ServerWebSocketData>) {
);
}

function handleWSMessage(ws: ServerWebSocket<ServerWebSocketData>, message: string | Buffer) {
function handleWSMessage(
ws: ServerWebSocket<ServerWebSocketData>,
message: string | Buffer
) {
try {
const signal: RawSignal = JSON.parse(message.toString());
const room: Room | undefined = rooms.get(ws.data.roomId);
Expand Down Expand Up @@ -264,7 +275,10 @@ function handleClientJoin(
}
existingClient.session = ws;
existingClient.lastPongTime = Date.now();
logger.info({ clientId: client.clientId, name: client.name }, "Client reconnected");
logger.info(
{ clientId: client.clientId, name: client.name },
"Client reconnected"
);

// send cached messages
existingClient.messageCache.forEach((message) => {
Expand Down Expand Up @@ -322,7 +336,10 @@ function handleClientJoin(
if (session === ws) return;
if (session.readyState === WebSocket.OPEN) {
session.send(JSON.stringify(joinMessage));
logger.info({ clientId: client.clientId, name: client.name }, "send join message to client");
logger.info(
{ clientId: client.clientId, name: client.name },
"send join message to client"
);
} else {
messageCache.push(joinMessage);
}
Expand Down Expand Up @@ -443,7 +460,10 @@ function startHeartbeat() {
room.clients.forEach((clientData, clientId) => {
if (clientData.session.readyState === WebSocket.OPEN) {
if (now - clientData.lastPongTime > PONG_TIMEOUT) {
logger.warn({ clientId, roomId }, "Client timed out, closing connection");
logger.warn(
{ clientId, roomId },
"Client timed out, closing connection"
);
clientData.session.close();
} else {
clientData.session.send(JSON.stringify({ type: "ping" }));
Expand All @@ -454,9 +474,23 @@ function startHeartbeat() {
}, HEARTBEAT_INTERVAL);
}

logger.info({ port: server.port }, "WebSocket server started");
startHeartbeat();
const addresses: string[] = [HOSTNAME];

// get all ip addresses
if (HOSTNAME === "0.0.0.0") {
const interfaces = os.networkInterfaces();
const ips = Object.values(interfaces).flatMap((iface) =>
iface?.map((iface) => iface.address)
);
addresses.push(...(ips.filter((ip) => ip !== undefined) as string[]));
}

logger.info(
{ port: server.port, hostname: HOSTNAME, addresses },
"WebSocket server started"
);

startHeartbeat();
process.on("SIGINT", () => {
logger.info("Shutting down server...");
server.stop();
Expand Down
1 change: 1 addition & 0 deletions src/var.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export const LOG_LEVEL = process.env["LOG_LEVEL"] || "info";
export const HOSTNAME = process.env["HOSTNAME"] || "0.0.0.0";
export const PORT = parseInt(process.env["PORT"] || "9000", 10);
export const HEARTBEAT_INTERVAL = parseInt(process.env["HEARTBEAT_INTERVAL"] || "30000", 10);
export const PONG_TIMEOUT = parseInt(process.env["PONG_TIMEOUT"] || "60000", 10);
Expand Down

0 comments on commit c37fa29

Please sign in to comment.