From 99b62797ffef81ac6b93afee46c96c09699e281b Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Sun, 16 Aug 2026 21:48:13 +0100 Subject: [PATCH] feat: add support for server requested acknowledgements --- README.md | 6 ++ src/client.ts | 50 ++++++++++- src/protocol/binary-codec.ts | 16 ++++ src/protocol/json-codec.ts | 12 +++ tests/unit/binary-codec.test.ts | 21 +++++ tests/unit/client-acks.test.ts | 154 ++++++++++++++++++++++++++++++++ tests/unit/json-codec.test.ts | 18 +++- 7 files changed, 273 insertions(+), 4 deletions(-) create mode 100644 tests/unit/client-acks.test.ts diff --git a/README.md b/README.md index 506cdf6..d374d59 100644 --- a/README.md +++ b/README.md @@ -106,6 +106,12 @@ client.sendBinary("audio.chunk", audioBuffer); const ack = await client.sendBinaryWithAck("audio.chunk", audioBuffer); ``` +Acknowledgement runs the other way too. When a server message asks to be acknowledged, by +carrying a `messageId` alongside `"ack": true` in JSON or the `requireAck` byte in binary, the +client answers on receipt without the application having to do anything. A resend the +deduplication window suppresses is still acknowledged, so a message that arrived the first time +is not reported lost. + ## Listening for Events ```typescript diff --git a/src/client.ts b/src/client.ts index ef168b3..7fe2d44 100644 --- a/src/client.ts +++ b/src/client.ts @@ -12,6 +12,7 @@ import { AckManager } from "./protocol/ack"; import { AuthManager } from "./protocol/auth"; import { decodeBinaryMessage, + encodeBinaryAck, encodeBinaryMessage, extractBinaryControlPayload, identifyBinaryControl, @@ -24,8 +25,13 @@ import { import { CLOSE_CODES } from "./protocol/constants"; import { DeduplicationStore } from "./protocol/dedup"; import { HeartbeatManager } from "./protocol/heartbeat"; -import { decodeJsonMessage, encodeJsonMessage, extractRoute } from "./protocol/json-codec"; -import { getRecord, getString, parseJsonPayload } from "./protocol/parse"; +import { + decodeJsonMessage, + encodeJsonAck, + encodeJsonMessage, + extractRoute, +} from "./protocol/json-codec"; +import { getBoolean, getRecord, getString, parseJsonPayload } from "./protocol/parse"; import { MessageBuffer } from "./reconnect/buffer"; import { ReconnectManager } from "./reconnect/manager"; import { ConnectionStateMachine } from "./state/machine"; @@ -595,6 +601,14 @@ export class CelerityWsClient { const decoded = decodeBinaryMessage(bytes); if (!decoded) return true; + // Send ack ahead of the deduplication check, as a resend the client has already seen + // is still one the server is waiting to hear about. Suppressing the + // acknowledgement along with the delivery would leave it resending until it + // gave up on a message that arrived the first time. + if (decoded.ack && decoded.messageId) { + this.sendAck(decoded.messageId); + } + if (this.dedupStore.has(decoded.messageId)) return true; this.dedupStore.track(decoded.messageId); @@ -647,9 +661,17 @@ export class CelerityWsClient { const route = extractRoute(parsed, this.config.routeKey) ?? extractRoute(parsed, "event"); if (this.handleControlRoute(route, parsed)) return; - if (!route) return; const messageId = decoded.messageId ?? ""; + + // Before the route check as well as the deduplication one. A message the + // client cannot dispatch still arrived, and the server is owed the answer + // either way. + if (getBoolean(parsed, "ack") && messageId) { + this.sendAck(messageId); + } + + if (!route) return; if (this.dedupStore.has(messageId || undefined)) return; this.dedupStore.track(messageId || undefined); @@ -694,6 +716,28 @@ export class CelerityWsClient { } } + // Answers a message that asked to be acknowledged. The form follows the + // negotiated capabilities rather than the form the message arrived in, since + // a transport that cannot carry binary frames cannot carry the reply in one + // either. + private sendAck(messageId: string): void { + if (!this.ws || this.ws.readyState() !== WebSocketState.OPEN) return; + + const timestamp = new Date().toISOString(); + const frame = + this._capabilities?.ackFormat === "binary" + ? encodeBinaryAck(messageId, timestamp) + : encodeJsonAck(messageId, timestamp); + + try { + this.ws.send(frame); + } catch (err) { + this.debug("ack:sendFailed", { messageId, error: String(err) }); + return; + } + this.debug("ack:sent", { messageId }); + } + private handleHeartbeatTimeout(): void { if (this.stateMachine.canTransition("HEARTBEAT_TIMEOUT")) { this.heartbeat.stop(); diff --git a/src/protocol/binary-codec.ts b/src/protocol/binary-codec.ts index 06bc374..570b83d 100644 --- a/src/protocol/binary-codec.ts +++ b/src/protocol/binary-codec.ts @@ -32,6 +32,22 @@ export function encodeBinaryMessage( return buffer; } +/** + * Encodes an acknowledgement as a reserved binary frame: + * [0x1 0x4 0x0 0x0] followed by the JSON body naming the message and the time. + * The two trailing zero bytes say that the acknowledgement asks for none of its + * own and carries no id of its own. + */ +export function encodeBinaryAck(messageId: string, timestamp: string): Uint8Array { + const body = TEXT_ENCODER.encode(JSON.stringify({ messageId, timestamp })); + + const frame = new Uint8Array(BINARY_PREFIX_LENGTH + body.length); + frame.set(BINARY_PREFIX.ACK, 0); + frame.set(body, BINARY_PREFIX_LENGTH); + + return frame; +} + export type DecodedBinaryMessage = { routeKey: string; ack: boolean; diff --git a/src/protocol/json-codec.ts b/src/protocol/json-codec.ts index f2d1b12..0597075 100644 --- a/src/protocol/json-codec.ts +++ b/src/protocol/json-codec.ts @@ -18,6 +18,18 @@ export function encodeJsonMessage( return JSON.stringify(message); } +/** + * Encodes an acknowledgement as JSON text, for a transport that cannot carry + * binary frames. The key is `event` rather than the configured route key, as + * the reserved form is fixed by the protocol. + */ +export function encodeJsonAck(messageId: string, timestamp: string): string { + return JSON.stringify({ + event: "ack", + data: { messageId, timestamp }, + }); +} + export function decodeJsonMessage(raw: string): { route: string | undefined; data: unknown; diff --git a/tests/unit/binary-codec.test.ts b/tests/unit/binary-codec.test.ts index ebecd04..cf5ff28 100644 --- a/tests/unit/binary-codec.test.ts +++ b/tests/unit/binary-codec.test.ts @@ -1,5 +1,6 @@ import { describe, it, expect } from "vitest"; import { + encodeBinaryAck, encodeBinaryMessage, decodeBinaryMessage, identifyBinaryControl, @@ -84,4 +85,24 @@ describe("binary-codec", () => { expect(extractBinaryControlPayload(data)).toBe(json); }); }); + + describe("encodeBinaryAck", () => { + it("should carry the reserved prefix and name the message", () => { + const frame = encodeBinaryAck("msg-1", "2026-01-01T00:00:00.000Z"); + + expect(identifyBinaryControl(frame)).toBe("ack"); + expect(JSON.parse(extractBinaryControlPayload(frame))).toEqual({ + messageId: "msg-1", + timestamp: "2026-01-01T00:00:00.000Z", + }); + }); + + it("should ask for no acknowledgement of its own and carry no id of its own", () => { + const frame = encodeBinaryAck("msg-1", "2026-01-01T00:00:00.000Z"); + + // The requireAck byte and the messageIdLength byte of the framing. + expect(frame[2]).toBe(0x0); + expect(frame[3]).toBe(0x0); + }); + }); }); diff --git a/tests/unit/client-acks.test.ts b/tests/unit/client-acks.test.ts new file mode 100644 index 0000000..9e20a74 --- /dev/null +++ b/tests/unit/client-acks.test.ts @@ -0,0 +1,154 @@ +import { describe, it, expect, afterEach } from "vitest"; +import { CelerityWsClient } from "../../src/client"; +import { encodeBinaryMessage } from "../../src/protocol/binary-codec"; +import { BINARY_PREFIX } from "../../src/protocol/constants"; +import { MockWebSocket, MockWebSocketFactory } from "../helpers/mock-ws"; + +type Harness = { + client: CelerityWsClient; + ws: MockWebSocket; +}; + +const CONSTRAINED_HANDSHAKE_TIMEOUT = 5; + +describe("client acknowledgements", () => { + let harness: Harness | null = null; + + afterEach(() => { + harness?.client.destroy(); + harness = null; + }); + + // Drives a client to the ready state. Sending the capabilities signal gets + // full capabilities; withholding it leaves the handshake to time out into the + // constrained ones, which is the only way to reach that branch. + async function connect(options: { capabilities: "full" | "constrained" }): Promise { + const factory = new MockWebSocketFactory(); + const client = new CelerityWsClient( + { + url: "wss://example.com/ws", + WebSocket: factory, + reconnect: { enabled: false }, + heartbeat: { interval: 60_000 }, + handshakeTimeout: CONSTRAINED_HANDSHAKE_TIMEOUT, + }, + factory, + ); + + const ready = client.connect(); + const ws = factory.latest; + ws.simulateOpen(); + + if (options.capabilities === "full") { + ws.simulateMessage(BINARY_PREFIX.CAPABILITIES); + } + + await ready; + ws.sentMessages.length = 0; + + harness = { client, ws }; + return harness; + } + + function sentAcks(ws: MockWebSocket): { messageId: string; timestamp: string }[] { + return ws.sentMessages.map((sent) => { + if (typeof sent === "string") { + const parsed = JSON.parse(sent) as { + event: string; + data: { messageId: string; timestamp: string }; + }; + expect(parsed.event).toBe("ack"); + return parsed.data; + } + + const bytes = sent instanceof Uint8Array ? sent : new Uint8Array(sent); + expect(Array.from(bytes.subarray(0, 4))).toEqual(Array.from(BINARY_PREFIX.ACK)); + return JSON.parse(new TextDecoder().decode(bytes.subarray(4))) as { + messageId: string; + timestamp: string; + }; + }); + } + + it("should acknowledge a binary message that asked to be", async () => { + const { ws } = await connect({ capabilities: "full" }); + + ws.simulateMessage(encodeBinaryMessage("updates", new Uint8Array([1, 2]), "msg-1", true)); + + expect(sentAcks(ws)).toEqual([ + { messageId: "msg-1", timestamp: expect.any(String) as unknown as string }, + ]); + }); + + it("should acknowledge a JSON message that asked to be", async () => { + const { ws } = await connect({ capabilities: "full" }); + + ws.simulateMessage( + JSON.stringify({ event: "updates", data: { x: 1 }, messageId: "msg-1", ack: true }), + ); + + expect(sentAcks(ws)).toEqual([ + { messageId: "msg-1", timestamp: expect.any(String) as unknown as string }, + ]); + }); + + it("should stay quiet for messages that did not ask", async () => { + const { ws } = await connect({ capabilities: "full" }); + + // Carries an id but does not opt in. + ws.simulateMessage(JSON.stringify({ event: "updates", data: {}, messageId: "msg-1" })); + ws.simulateMessage(encodeBinaryMessage("updates", new Uint8Array([1]), "msg-2", false)); + // Opts in with no id, so there is nothing an acknowledgement could name. + ws.simulateMessage(JSON.stringify({ event: "updates", data: {}, ack: true })); + ws.simulateMessage(encodeBinaryMessage("updates", new Uint8Array([1]), "", true)); + + expect(ws.sentMessages).toEqual([]); + }); + + it("should acknowledge a resend the deduplication store suppresses", async () => { + const { client, ws } = await connect({ capabilities: "full" }); + + const delivered: string[] = []; + client.on("updates", (_data, metadata) => { + delivered.push(metadata.messageId); + }); + + const message = JSON.stringify({ + event: "updates", + data: { x: 1 }, + messageId: "msg-1", + ack: true, + }); + ws.simulateMessage(message); + ws.simulateMessage(message); + + // The application sees it once, but the server hears about both, otherwise + // it keeps resending a message that already arrived. + expect(delivered).toEqual(["msg-1"]); + expect(sentAcks(ws).map((ack) => ack.messageId)).toEqual(["msg-1", "msg-1"]); + }); + + it("should answer in JSON when the transport carries no binary frames", async () => { + const { ws } = await connect({ capabilities: "constrained" }); + + ws.simulateMessage( + JSON.stringify({ event: "updates", data: { x: 1 }, messageId: "msg-1", ack: true }), + ); + + expect(ws.sentMessages.every((sent) => typeof sent === "string")).toBe(true); + expect(sentAcks(ws).map((ack) => ack.messageId)).toEqual(["msg-1"]); + }); + + it("should answer in a binary frame when the transport carries them", async () => { + const { ws } = await connect({ capabilities: "full" }); + + // Asked for in JSON, answered in binary. The form follows the negotiated + // capabilities rather than the form the message arrived in. + ws.simulateMessage( + JSON.stringify({ event: "updates", data: { x: 1 }, messageId: "msg-1", ack: true }), + ); + + expect(ws.sentMessages.every((sent) => typeof sent !== "string")).toBe(true); + expect(sentAcks(ws).map((ack) => ack.messageId)).toEqual(["msg-1"]); + }); +}); diff --git a/tests/unit/json-codec.test.ts b/tests/unit/json-codec.test.ts index 52d0819..f80aa4c 100644 --- a/tests/unit/json-codec.test.ts +++ b/tests/unit/json-codec.test.ts @@ -1,5 +1,10 @@ import { describe, it, expect } from "vitest"; -import { encodeJsonMessage, decodeJsonMessage, extractRoute } from "../../src/protocol/json-codec"; +import { + encodeJsonAck, + encodeJsonMessage, + decodeJsonMessage, + extractRoute, +} from "../../src/protocol/json-codec"; describe("json-codec", () => { describe("encodeJsonMessage", () => { @@ -56,4 +61,15 @@ describe("json-codec", () => { expect(extractRoute({ event: 123, data: {} }, "event")).toBeUndefined(); }); }); + + describe("encodeJsonAck", () => { + it("should use the reserved event key rather than the configured route key", () => { + const parsed = JSON.parse(encodeJsonAck("msg-1", "2026-01-01T00:00:00.000Z")); + + expect(parsed).toEqual({ + event: "ack", + data: { messageId: "msg-1", timestamp: "2026-01-01T00:00:00.000Z" }, + }); + }); + }); });