Handle newt online offline with websocket

This commit is contained in:
Owen
2026-03-14 11:59:20 -07:00
parent 75ab074805
commit 1a43f1ef4b
6 changed files with 159 additions and 99 deletions

View File

@@ -6,7 +6,8 @@ import {
handleDockerContainersMessage,
handleNewtPingRequestMessage,
handleApplyBlueprintMessage,
handleNewtPingMessage
handleNewtPingMessage,
startNewtOfflineChecker
} from "../newt";
import {
handleOlmRegisterMessage,
@@ -43,3 +44,4 @@ export const messageHandlers: Record<string, MessageHandler> = {
};
startOlmOfflineChecker(); // this is to handle the offline check for olms
startNewtOfflineChecker(); // this is to handle the offline check for newts

View File

@@ -3,7 +3,7 @@ import zlib from "zlib";
import { Server as HttpServer } from "http";
import { WebSocket, WebSocketServer } from "ws";
import { Socket } from "net";
import { Newt, newts, NewtSession, olms, Olm, OlmSession } from "@server/db";
import { Newt, newts, NewtSession, olms, Olm, OlmSession, sites } from "@server/db";
import { eq } from "drizzle-orm";
import { db } from "@server/db";
import { validateNewtSessionToken } from "@server/auth/sessions/newt";
@@ -380,6 +380,31 @@ const setupConnection = async (
);
});
// Handle WebSocket protocol-level pings from older newt clients that do
// not send application-level "newt/ping" messages. Update the site's
// online state and lastPing timestamp so the offline checker treats them
// the same as modern newt clients.
if (clientType === "newt") {
const newtClient = client as Newt;
ws.on("ping", async () => {
if (!newtClient.siteId) return;
try {
await db
.update(sites)
.set({
online: true,
lastPing: Math.floor(Date.now() / 1000)
})
.where(eq(sites.siteId, newtClient.siteId));
} catch (error) {
logger.error(
"Error updating newt site online state on WS ping",
{ error }
);
}
});
}
ws.on("error", (error: Error) => {
logger.error(
`WebSocket error for ${clientType.toUpperCase()} ID ${clientId}:`,