Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

socketHeartbeat.ts

27 lines985 Bytes

1import * as Duration from "effect/Duration";
2import * as Effect from "effect/Effect";
3import * as Socket from "effect/socket/Socket";
4​
5// Reverse proxies close a socket after 60 seconds without upstream bytes
6// (nginx proxy_read_timeout, AWS ALB), and a suspended client stops pinging.
7export const SOCKET_HEARTBEAT_INTERVAL = Duration.seconds(20);
8​
9// RPC clients count any decoded frame as liveness and ignore unsolicited pongs.
10export const SOCKET_HEARTBEAT_FRAME = '{"_tag":"Pong"}';
11​
12/** Server side: writes a heartbeat frame on an interval for as long as the writer is open. */
13export function withSocketHeartbeat(socket: Socket.Socket): Socket.Socket {
14 return Socket.make({
15 reader: socket.reader,
16 writer: Effect.tap(socket.writer, (writer) =>
17 writer
18 .write(SOCKET_HEARTBEAT_FRAME)
19 .pipe(
20 Effect.delay(SOCKET_HEARTBEAT_INTERVAL),
21 Effect.forever,
22 Effect.ignore,
23 Effect.forkScoped,
24 ),
25 ),
26 });