zcodeProtocolV4TopicEnvelope.test.ts 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. import { BufferWriter, ProtocolMessage, ProtocolMessageType, serialize } from "@zcode/rpc";
  2. import {
  3. PROTOCOL_V4_LIMITS,
  4. encodeTopicWireFrames,
  5. measureTopicNotificationEnvelopeBytes,
  6. type ConversationTopicFrame,
  7. type ConversationTopicWireFrame,
  8. } from "@zcode/shared/zcode-protocol-v4";
  9. import { describe, expect, it } from "vitest";
  10. const MAX_EVENT_ID = Number.MAX_SAFE_INTEGER;
  11. function logicalFrame(append: string): ConversationTopicFrame {
  12. return {
  13. topic: "conversation/session-1",
  14. subscriptionId: "sub-1",
  15. fromSeq: 0,
  16. toSeq: 1,
  17. sentAt: 1,
  18. payload: {
  19. kind: "deltas",
  20. deltas: [{ op: "row.delta", rowId: 1, path: "text", append }],
  21. },
  22. };
  23. }
  24. function completeWire(frame: ConversationTopicFrame, logicalFrameId: string) {
  25. return {
  26. wireVersion: 3 as const,
  27. kind: "complete" as const,
  28. logicalFrameId,
  29. logicalFrameOrdinal: 1,
  30. topic: frame.topic,
  31. subscriptionId: frame.subscriptionId,
  32. frame,
  33. };
  34. }
  35. function actualEnvelopeBytes(wire: ConversationTopicWireFrame) {
  36. const writer = new BufferWriter();
  37. serialize(writer, [204, MAX_EVENT_ID]);
  38. serialize(writer, wire);
  39. const channel = writer.buffer.buffer;
  40. const channelSocket = new ProtocolMessage(ProtocolMessageType.Regular, 0, 0, writer.buffer);
  41. const transportId = "x".repeat(PROTOCOL_V4_LIMITS.transportEnvelopeIdMaxChars);
  42. const relay = new TextEncoder().encode(
  43. JSON.stringify({
  44. type: "data",
  45. payload: {
  46. zcode_type: "rpc-frame",
  47. bridgeSessionId: transportId,
  48. bridgeGeneration: Number.MAX_SAFE_INTEGER,
  49. recoveryId: transportId,
  50. seq: Number.MAX_SAFE_INTEGER,
  51. dataBase64: Buffer.from(channel).toString("base64"),
  52. },
  53. client_ts: Number.MAX_SAFE_INTEGER,
  54. server_ts: Number.MAX_SAFE_INTEGER,
  55. }),
  56. ).byteLength;
  57. const cli =
  58. new TextEncoder().encode(JSON.stringify({ method: "v4/conversation/frame", params: wire }))
  59. .byteLength + 1;
  60. return { cli, channelSocket: channelSocket.byteLength, relay };
  61. }
  62. describe("V4 topic physical production envelopes", () => {
  63. it("meter matches CLI NDJSON, Channel serialization, and worst mobile relay bytes", () => {
  64. const logical = logicalFrame("中文🙂".repeat(120_000));
  65. const wires = encodeTopicWireFrames(logical, {
  66. topic: logical.topic,
  67. subscriptionId: logical.subscriptionId,
  68. logicalFrameId: "logical-envelope-boundary",
  69. logicalFrameOrdinal: 1,
  70. measurePhysicalFrameBytes: (wire) => measureTopicNotificationEnvelopeBytes(wire).maxBytes,
  71. }) as ConversationTopicWireFrame[];
  72. expect(wires.length).toBeGreaterThan(1);
  73. for (const wire of wires) {
  74. const measured = measureTopicNotificationEnvelopeBytes(wire);
  75. const actual = actualEnvelopeBytes(wire);
  76. expect(actual.cli).toBe(measured.cliNdjsonBytes);
  77. expect(actual.channelSocket).toBe(measured.channelSocketBytes);
  78. expect(actual.relay).toBe(measured.mobileRelayBytes);
  79. expect(Math.max(actual.cli, actual.channelSocket, actual.relay)).toBeLessThanOrEqual(
  80. PROTOCOL_V4_LIMITS.maxFrameBytes,
  81. );
  82. }
  83. });
  84. it("actual serializers enforce max-1/max/max+1 thresholds and a maximal production chunk", () => {
  85. const hardMax = PROTOCOL_V4_LIMITS.maxFrameBytes;
  86. const actualMax = (wire: ConversationTopicWireFrame) => {
  87. const actual = actualEnvelopeBytes(wire);
  88. return Math.max(actual.cli, actual.channelSocket, actual.relay);
  89. };
  90. const firstAppendLengthOver = (limit: number, logicalFrameId: string) => {
  91. let low = 0;
  92. let high = hardMax * 2;
  93. while (low < high) {
  94. const middle = Math.floor((low + high) / 2);
  95. const measured = actualMax(
  96. completeWire(logicalFrame("x".repeat(middle)), logicalFrameId),
  97. );
  98. if (measured > limit) high = middle;
  99. else low = middle + 1;
  100. }
  101. return low;
  102. };
  103. for (const requestedLimit of [hardMax - 1, hardMax, hardMax + 1]) {
  104. const effectiveLimit = Math.min(requestedLimit, hardMax);
  105. const logicalFrameId = `actual-boundary-${requestedLimit}`;
  106. const firstOver = firstAppendLengthOver(effectiveLimit, logicalFrameId);
  107. const atBoundary = logicalFrame("x".repeat(firstOver - 1));
  108. const overBoundary = logicalFrame("x".repeat(firstOver));
  109. expect(actualMax(completeWire(atBoundary, logicalFrameId))).toBeLessThanOrEqual(
  110. effectiveLimit,
  111. );
  112. expect(actualMax(completeWire(overBoundary, logicalFrameId))).toBeGreaterThan(effectiveLimit);
  113. expect(
  114. encodeTopicWireFrames(atBoundary, {
  115. topic: atBoundary.topic,
  116. subscriptionId: atBoundary.subscriptionId,
  117. logicalFrameId,
  118. logicalFrameOrdinal: 1,
  119. maxPhysicalFrameBytes: requestedLimit,
  120. measurePhysicalFrameBytes: (wire) => actualMax(wire as ConversationTopicWireFrame),
  121. }),
  122. ).toHaveLength(1);
  123. expect(
  124. encodeTopicWireFrames(overBoundary, {
  125. topic: overBoundary.topic,
  126. subscriptionId: overBoundary.subscriptionId,
  127. logicalFrameId: `${logicalFrameId}-fragmented`,
  128. logicalFrameOrdinal: 1,
  129. maxPhysicalFrameBytes: requestedLimit,
  130. measurePhysicalFrameBytes: (wire) => actualMax(wire as ConversationTopicWireFrame),
  131. }).every((wire) => wire.kind === "fragment"),
  132. ).toBe(true);
  133. }
  134. const large = logicalFrame("中文🙂".repeat(250_000));
  135. const fragments = encodeTopicWireFrames(large, {
  136. topic: large.topic,
  137. subscriptionId: large.subscriptionId,
  138. logicalFrameId: "actual-maximal-fragment",
  139. logicalFrameOrdinal: 1,
  140. measurePhysicalFrameBytes: (wire) => actualMax(wire as ConversationTopicWireFrame),
  141. }) as ConversationTopicWireFrame[];
  142. const first = fragments.find((wire) => wire.kind === "fragment");
  143. expect(first?.kind).toBe("fragment");
  144. if (!first || first.kind !== "fragment") return;
  145. expect(actualMax(first)).toBeLessThanOrEqual(hardMax);
  146. // encoder 以最坏 fragmentCount/index 位数选 chunk;再增加一个 base64 quantum
  147. // 就必须越过真实 serializer 上限,证明生产 chunk budget 已取到可达最大值。
  148. const worstEnvelope = {
  149. ...first,
  150. fragmentIndex: first.logicalBytes - 1,
  151. fragmentCount: first.logicalBytes,
  152. dataBase64: `${first.dataBase64}AAAA`,
  153. };
  154. expect(actualMax(worstEnvelope)).toBeGreaterThan(hardMax);
  155. });
  156. });