Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
50 changes: 47 additions & 3 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { AckManager } from "./protocol/ack";
import { AuthManager } from "./protocol/auth";
import {
decodeBinaryMessage,
encodeBinaryAck,
encodeBinaryMessage,
extractBinaryControlPayload,
identifyBinaryControl,
Expand All @@ -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";
Expand Down Expand Up @@ -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);

Expand Down Expand Up @@ -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);

Expand Down Expand Up @@ -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();
Expand Down
16 changes: 16 additions & 0 deletions src/protocol/binary-codec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
12 changes: 12 additions & 0 deletions src/protocol/json-codec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
21 changes: 21 additions & 0 deletions tests/unit/binary-codec.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { describe, it, expect } from "vitest";
import {
encodeBinaryAck,
encodeBinaryMessage,
decodeBinaryMessage,
identifyBinaryControl,
Expand Down Expand Up @@ -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);
});
});
});
154 changes: 154 additions & 0 deletions tests/unit/client-acks.test.ts
Original file line number Diff line number Diff line change
@@ -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<Harness> {
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"]);
});
});
18 changes: 17 additions & 1 deletion tests/unit/json-codec.test.ts
Original file line number Diff line number Diff line change
@@ -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", () => {
Expand Down Expand Up @@ -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" },
});
});
});
});
Loading