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

Files touched

--- 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) {

Review this PR

Node practice