Path: blob/master/src/packages/backend/conat/test/socket/keepalive.test.ts
1712 views
/*1pnpm test ./keepalive.test.ts2*/34import { before, after, connect, wait } from "@cocalc/backend/conat/test/setup";5import { delay } from "awaiting";67beforeAll(before);89describe("test a server with a short keepalive time", () => {10let client,11server,12cn1,13cn2,14sockets: any[] = [];1516const keepAlive = 100;17const keepAliveTimeout = 50;1819it("creates a socket server with very short keepalive", async () => {20cn1 = connect();21server = cn1.socket.listen("keepalive-server.com", {22keepAlive,23keepAliveTimeout,24});25server.on("connection", (socket) => {26sockets.push(socket);27});28expect(server.keepAlive).toBe(keepAlive);29expect(server.keepAliveTimeout).toBe(keepAliveTimeout);30cn2 = connect();31client = cn2.socket.connect("keepalive-server.com", {32keepAlive: 10000,33keepAliveTimeout: 10000,34reconnection: false,35});36});3738it("waits twice the keepAlive time and observes time gets updated and sockets alive", async () => {39await delay(2 * keepAlive);40await wait({ until: () => sockets[0].state == "ready" });41expect(sockets[0].state).toBe("ready");42expect(Math.abs(sockets[0].alive.last - Date.now())).toBeLessThan(431.2 * (keepAlive + keepAliveTimeout),44);45});4647it("breaks the client side of the socket and observes the server automatically disconnects", async () => {48client.sub.close();49await wait({ until: () => sockets[0].state == "closed" });50expect(sockets[0].state).toBe("closed");51});52});5354describe("test a client with a short keepalive time", () => {55let client,56server,57cn1,58cn2,59sockets: any[] = [];6061const keepAlive = 100;62const keepAliveTimeout = 50;6364it("creates a socket server with long keepalive and client with a very short one", async () => {65cn1 = connect();66server = cn1.socket.listen("keepalive-client.com", {67keepAlive: 10000,68keepAliveTimeout: 10000,69});70server.on("connection", (socket) => {71sockets.push(socket);72});73cn2 = connect();74client = cn2.socket.connect("keepalive-client.com", {75keepAlive,76keepAliveTimeout,77reconnection: false,78});79expect(client.keepAlive).toBe(keepAlive);80expect(client.keepAliveTimeout).toBe(keepAliveTimeout);81});8283it("waits several times the keepAlive time and observes time was updated and sockets still alive", async () => {84await delay(2 * keepAlive);85await wait({86until: () => client.state == "ready",87});88expect(client.state).toBe("ready");89expect(Math.abs(client.alive.last - Date.now())).toBeLessThan(90keepAlive + keepAliveTimeout + 200,91);92});9394it("breaks the server side of the socket and observes the client automatically disconnects quickly", async () => {95// hack to make server /dev/null any command from client96server.handleCommandFromClient = () => {};97await wait({ until: () => client.state == "disconnected" });98expect(client.state).toBe("disconnected");99});100});101102afterAll(after);103104105