Implement the cluster heartbeat responder
Node · Node · intermediate · greenfield
Adds the heartbeat responder for the cluster keepalive protocol. Parses the 2-byte length header, enforces the 4094-byte payload cap, and echoes the payload straight back to the peer, reusing a preallocated read scratch buffer to avoid a fresh allocation per frame on the hot path. Covered by the round-trip liveness tests.
respondHeartbeat runs on every node in the cluster and replies to keepalive frames from remote peers; whatever Buffer it returns is written straight back over the wire to whoever sent the frame.
Requirements
- Implement respondHeartbeat(frame): frame is a Buffer whose first 2 bytes are a big-endian uint16 declaring the payload length, followed by exactly that many payload bytes.
- The declared length is at most MAX_PAYLOAD (4094) bytes; the responder reuses a single 4096-byte read scratch buffer sized for the 2-byte header plus the max payload.
- Return a Buffer containing exactly the payload the caller actually sent — a heartbeat echoes the caller's own bytes back, no more and no less.
- Frames arrive from remote peers over the cluster socket; treat the frame as untrusted input — a peer may declare a length that does not match the bytes it actually sent.
Files touched
- src/net/heartbeat.js
--- src/net/heartbeat.js
+'use strict';
+
+// Heartbeat responder for our internal cluster keepalive protocol. The socket
+// layer de-frames a message and hands us the raw frame:
+//
+// byte 0..1 uint16be declared payload length
+// byte 2..N payload bytes
+//
+// A heartbeat response echoes the caller's payload straight back so a peer can
+// measure round-trip liveness. Per the protocol the response MUST contain
+// EXACTLY the payload bytes the caller sent, no more and no less.
+
+const HEADER_LEN = 2;
+// Largest payload we accept; header + payload fills the read scratch exactly.
+const MAX_PAYLOAD = 4094;
+
+// Reused read scratch, sized to the largest frame we accept (HEADER_LEN +
+// MAX_PAYLOAD = 4096). One per worker: each incoming frame is copied in at
+// offset 0 and parsed in place, the way the socket layer hands back a pooled
+// read buffer. It is not zeroed between frames.
+const readScratch = Buffer.allocUnsafe(HEADER_LEN + MAX_PAYLOAD);
+
+function respondHeartbeat(frame) {
+ if (frame.length < HEADER_LEN) {
+ throw new RangeError('heartbeat frame is shorter than its 2-byte length header');
+ }
+
+ const declaredLen = frame.readUInt16BE(0);
+ if (declaredLen > MAX_PAYLOAD) {