Skip to content
This repository has been archived by the owner on Dec 14, 2023. It is now read-only.

Commit

Permalink
network/websockets: extract heartbeat into a separate module
Browse files Browse the repository at this point in the history
  • Loading branch information
denis-sokolov committed Mar 2, 2021
1 parent 5579e96 commit fcbc018
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 24 deletions.
28 changes: 28 additions & 0 deletions src/network/websockets/server/heartbeat.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import type WebSocket from "ws";

export function heartbeat(getClients: () => Set<WebSocket>) {
function setGood(this: any) {
this.lifeFlag = "good";
}
setInterval(function ping() {
getClients().forEach(
(socket: WebSocket & { lifeFlag?: "good" | "sleepy" }) => {
if (socket.lifeFlag === undefined) {
socket.lifeFlag = "good";
socket.on("pong", setGood);
socket.on("message", setGood);
return;
}
if (socket.lifeFlag === "good") {
socket.lifeFlag = "sleepy";
socket.ping();
return;
}
if (socket.lifeFlag === "sleepy") {
socket.terminate();
return;
}
}
);
}, 60000);
}
27 changes: 3 additions & 24 deletions src/network/websockets/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { createNanoEvents } from "nanoevents";
import WebSocket from "ws";
import { jsonSerialization } from "../serialization";
import { makeAuthQueue } from "./authQueue";
import { heartbeat } from "./heartbeat";
import { stringy, K, KV, Params, ValueContainer } from "./types";

export function runWebsocketServer<AuthDetails>(params: Params<AuthDetails>) {
Expand Down Expand Up @@ -47,30 +48,8 @@ export function runWebsocketServer<AuthDetails>(params: Params<AuthDetails>) {
server: params.server,
});

function heartbeat(this: any) {
this.lifeFlag = "good";
}
setInterval(function ping() {
server.clients.forEach(
(socket: WebSocket & { lifeFlag?: "good" | "sleepy" }) => {
if (socket.lifeFlag === undefined) {
socket.lifeFlag = "good";
socket.on("pong", heartbeat);
socket.on("message", heartbeat);
return;
}
if (socket.lifeFlag === "good") {
socket.lifeFlag = "sleepy";
socket.ping();
return;
}
if (socket.lifeFlag === "sleepy") {
socket.terminate();
return;
}
}
);
}, 60000);
heartbeat(() => server.clients);

server.on("connection", function (socket: WebSocket & { isAlive?: boolean }) {
const authQueue = makeAuthQueue<AuthDetails>({
onTerminate: () => socket.terminate(),
Expand Down

0 comments on commit fcbc018

Please sign in to comment.