webRemoteControlRelayPayloadSerializer.test.ts 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. WEB_REMOTE_CONTROL_RPC_TRANSPORT_LIMITS,
  4. encodeWebRemoteControlRpcTransportMessage,
  5. type WebRemoteControlAppPayload,
  6. } from "@zcode/shared";
  7. import { parseWebRemoteControlRelayV2OutgoingMessage } from "@zcode/shared/web-remote-relay";
  8. import { WebRemoteControlRelayPayloadSerializer } from "../src/webRemoteControlRelayPayloadSerializer.js";
  9. describe("WebRemoteControlRelayPayloadSerializer", () => {
  10. it("reuses the identical final JSON and byte count for one immutable raw payload", () => {
  11. const serializer = new WebRemoteControlRelayPayloadSerializer();
  12. const [payload] = encodeWebRemoteControlRpcTransportMessage(new Uint8Array([1, 2, 3]), {
  13. bridgeSessionId: "bridge-1",
  14. firstPhysicalSeq: 1,
  15. messageSeq: 1,
  16. });
  17. const first = serializer.prepare(payload, 100);
  18. const replay = serializer.prepare(payload, 200);
  19. expect(replay).toBe(first);
  20. expect(replay.json).toBe(first.json);
  21. expect(replay.message.client_ts).toBe(100);
  22. expect(replay.bytes).toBe(new TextEncoder().encode(replay.json).byteLength);
  23. });
  24. it("uses Unix seconds for the default V2 data timestamp", () => {
  25. const now = vi.spyOn(Date, "now").mockReturnValue(1_800_000_000_123);
  26. try {
  27. const prepared = new WebRemoteControlRelayPayloadSerializer().prepare({
  28. zcode_type: "bootstrap-request",
  29. requestId: "request-1",
  30. });
  31. expect(prepared.message.client_ts).toBe(1_800_000_000);
  32. expect(parseWebRemoteControlRelayV2OutgoingMessage(JSON.parse(prepared.json))).not.toBeNull();
  33. } finally {
  34. now.mockRestore();
  35. }
  36. });
  37. it("distinguishes a permanent oversize envelope from a bounded payload", () => {
  38. const serializer = new WebRemoteControlRelayPayloadSerializer();
  39. const bounded: WebRemoteControlAppPayload = {
  40. zcode_type: "app-error",
  41. reason: "unexpected-error",
  42. error: "中文🙂bounded",
  43. };
  44. const oversize: WebRemoteControlAppPayload = {
  45. zcode_type: "app-error",
  46. reason: "unexpected-error",
  47. error: "x".repeat(WEB_REMOTE_CONTROL_RPC_TRANSPORT_LIMITS.maxPhysicalFrameBytes),
  48. };
  49. const preparedBounded = serializer.prepare(bounded, 1);
  50. expect(serializer.isOversize(preparedBounded)).toBe(false);
  51. expect(preparedBounded.bytes).toBe(new TextEncoder().encode(preparedBounded.json).byteLength);
  52. const preparedOversize = serializer.prepare(oversize, 1);
  53. expect(serializer.isOversize(preparedOversize)).toBe(true);
  54. expect(preparedOversize.bytes).toBeGreaterThan(
  55. WEB_REMOTE_CONTROL_RPC_TRANSPORT_LIMITS.maxPhysicalFrameBytes,
  56. );
  57. });
  58. });