wire-codec.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. // V4 physical wire encoder:按调用方真实 JSON/RPC envelope 计量,logical frame
  2. // 超过物理上限时只在 UTF-8 bytes 层分片,不改变 seq/apply 语义。
  3. import { PROTOCOL_V4_LIMITS, V4_WIRE_PROTOCOL_VERSION } from "./core.js";
  4. import { crc32WireBytes, encodeWireBytesBase64 } from "./wire-binary.js";
  5. import type {
  6. TopicFrameDeliveryKind,
  7. TopicWireChecksum,
  8. TopicWireFrame,
  9. TopicWireFrameCandidate,
  10. } from "./wire.js";
  11. const CHANNEL_EVENT_RESPONSE_TYPE = 204;
  12. const SOCKET_PROTOCOL_HEADER_BYTES = 13;
  13. function vqlByteLength(value: number): number {
  14. let bytes = 1;
  15. for (let remaining = value >>> 7; remaining > 0; remaining >>>= 7) bytes += 1;
  16. return bytes;
  17. }
  18. /**
  19. * 按当前生产三层真实承载计量 topic notification。mobile relay
  20. * 会把 Channel binary 再 base64,不能只测 CLI 的 logical JSON。
  21. */
  22. export function measureTopicNotificationEnvelopeBytes(wire: TopicWireFrameCandidate): {
  23. cliNdjsonBytes: number;
  24. channelSocketBytes: number;
  25. mobileRelayBytes: number;
  26. maxBytes: number;
  27. } {
  28. const cliNdjsonBytes =
  29. utf8JsonByteLength({
  30. method: "v4/conversation/frame",
  31. params: wire,
  32. }) + 1;
  33. const wireJsonBytes = utf8JsonByteLength(wire);
  34. // @zcode/rpc serialization:Array tag+length+[EventFire,id],再加 Object tag+length+JSON。
  35. // ChannelClient 的 id 无 31-bit wrap;超过 signed int 后 serialize 会走 Object JSON
  36. // fallback。因此按 Number.MAX_SAFE_INTEGER 的 16-byte JSON 形态计算最坏 header。
  37. const maxEventIdJsonBytes = String(Number.MAX_SAFE_INTEGER).length;
  38. const maxEventIdSerializedBytes = 1 + vqlByteLength(maxEventIdJsonBytes) + maxEventIdJsonBytes;
  39. const channelHeaderBytes =
  40. 1 +
  41. vqlByteLength(2) +
  42. 1 +
  43. vqlByteLength(CHANNEL_EVENT_RESPONSE_TYPE) +
  44. maxEventIdSerializedBytes;
  45. const channelPayloadBytes = channelHeaderBytes + 1 + vqlByteLength(wireJsonBytes) + wireJsonBytes;
  46. // SocketProtocol/PersistentProtocol 在 Channel payload 外再加固定 13-byte frame header。
  47. const channelSocketBytes = channelPayloadBytes + SOCKET_PROTOCOL_HEADER_BYTES;
  48. // topic encoder 继续用 legacy 单片 outer 作为保守 logical budget;production 已不发送该形态,
  49. // Channel payload 会再经 acknowledged raw adapter 独立分片并按最终 JSON 精确计量。
  50. // 两层预算分别约束 topic logical frame 与 relay physical frame,不能互相替代。
  51. const dataBase64Bytes = 4 * Math.ceil(channelPayloadBytes / 3);
  52. const transportId = "x".repeat(PROTOCOL_V4_LIMITS.transportEnvelopeIdMaxChars);
  53. const mobileRelayFixedBytes = utf8JsonByteLength({
  54. type: "data",
  55. payload: {
  56. zcode_type: "rpc-frame",
  57. bridgeSessionId: transportId,
  58. bridgeGeneration: Number.MAX_SAFE_INTEGER,
  59. recoveryId: transportId,
  60. seq: Number.MAX_SAFE_INTEGER,
  61. dataBase64: "",
  62. },
  63. client_ts: Number.MAX_SAFE_INTEGER,
  64. server_ts: Number.MAX_SAFE_INTEGER,
  65. });
  66. const mobileRelayBytes = mobileRelayFixedBytes + dataBase64Bytes;
  67. return {
  68. cliNdjsonBytes,
  69. channelSocketBytes,
  70. mobileRelayBytes,
  71. maxBytes: Math.max(cliNdjsonBytes, channelSocketBytes, mobileRelayBytes),
  72. };
  73. }
  74. export function utf8JsonByteLength(value: unknown): number {
  75. return new TextEncoder().encode(JSON.stringify(value)).byteLength;
  76. }
  77. function encodeJson(value: unknown): Uint8Array {
  78. return new TextEncoder().encode(JSON.stringify(value));
  79. }
  80. export class TopicWireFrameEncodingError extends Error {
  81. constructor(readonly reasonCode: string) {
  82. super(reasonCode);
  83. this.name = "TopicWireFrameEncodingError";
  84. }
  85. }
  86. function hardBound(value: number | undefined, maximum: number, name: string): number {
  87. const resolved = value ?? maximum;
  88. if (!Number.isFinite(resolved) || resolved <= 0) {
  89. throw new TopicWireFrameEncodingError(`proto.invalidLimit.${name}`);
  90. }
  91. return Math.min(Math.floor(resolved), maximum);
  92. }
  93. export interface EncodeTopicWireFramesOptions<F> {
  94. deliveryKind: TopicFrameDeliveryKind;
  95. topic: string;
  96. subscriptionId: string;
  97. logicalFrameId: string;
  98. logicalFrameOrdinal: number;
  99. maxPhysicalFrameBytes?: number;
  100. maxAssemblyBytes?: number;
  101. measurePhysicalFrameBytes(wire: TopicWireFrame<F>): number;
  102. }
  103. function makeFragment<F>(params: {
  104. options: EncodeTopicWireFramesOptions<F>;
  105. fragmentIndex: number;
  106. fragmentCount: number;
  107. logicalBytes: number;
  108. checksum: TopicWireChecksum;
  109. dataBase64: string;
  110. }): TopicWireFrame<F> {
  111. return {
  112. wireVersion: V4_WIRE_PROTOCOL_VERSION,
  113. kind: "fragment",
  114. deliveryKind: params.options.deliveryKind,
  115. logicalFrameId: params.options.logicalFrameId,
  116. logicalFrameOrdinal: params.options.logicalFrameOrdinal,
  117. topic: params.options.topic,
  118. subscriptionId: params.options.subscriptionId,
  119. fragmentIndex: params.fragmentIndex,
  120. fragmentCount: params.fragmentCount,
  121. logicalBytes: params.logicalBytes,
  122. checksum: params.checksum,
  123. dataBase64: params.dataBase64,
  124. };
  125. }
  126. function findFragmentByteBudget<F>(params: {
  127. options: EncodeTopicWireFramesOptions<F>;
  128. logicalBytes: number;
  129. checksum: TopicWireChecksum;
  130. maxPhysicalFrameBytes: number;
  131. }): number {
  132. let low = 1;
  133. let high = Math.min(params.logicalBytes, params.maxPhysicalFrameBytes);
  134. let best = 0;
  135. // 使用最坏索引位数测量,实际 fragment 的 envelope 只会更小。
  136. const worstCount = params.logicalBytes;
  137. while (low <= high) {
  138. const candidate = Math.floor((low + high) / 2);
  139. const dataBase64 = "A".repeat(4 * Math.ceil(candidate / 3));
  140. const wire = makeFragment({
  141. options: params.options,
  142. fragmentIndex: Math.max(0, worstCount - 1),
  143. fragmentCount: worstCount,
  144. logicalBytes: params.logicalBytes,
  145. checksum: params.checksum,
  146. dataBase64,
  147. });
  148. if (params.options.measurePhysicalFrameBytes(wire) <= params.maxPhysicalFrameBytes) {
  149. best = candidate;
  150. low = candidate + 1;
  151. } else {
  152. high = candidate - 1;
  153. }
  154. }
  155. return best;
  156. }
  157. export function encodeTopicWireFrames<F>(
  158. frame: F,
  159. options: EncodeTopicWireFramesOptions<F>,
  160. ): TopicWireFrame<F>[] {
  161. const maxPhysicalFrameBytes = hardBound(
  162. options.maxPhysicalFrameBytes,
  163. PROTOCOL_V4_LIMITS.maxFrameBytes,
  164. "maxPhysicalFrameBytes",
  165. );
  166. const maxAssemblyBytes = hardBound(
  167. options.maxAssemblyBytes,
  168. PROTOCOL_V4_LIMITS.logicalFrameAssemblyMaxBytes,
  169. "maxAssemblyBytes",
  170. );
  171. const logical = encodeJson(frame);
  172. if (logical.byteLength > maxAssemblyBytes) {
  173. throw new TopicWireFrameEncodingError("proto.frameAssemblyTooLarge");
  174. }
  175. const complete: TopicWireFrame<F> = {
  176. wireVersion: V4_WIRE_PROTOCOL_VERSION,
  177. kind: "complete",
  178. deliveryKind: options.deliveryKind,
  179. logicalFrameId: options.logicalFrameId,
  180. logicalFrameOrdinal: options.logicalFrameOrdinal,
  181. topic: options.topic,
  182. subscriptionId: options.subscriptionId,
  183. frame,
  184. };
  185. if (options.measurePhysicalFrameBytes(complete) <= maxPhysicalFrameBytes) {
  186. return [complete];
  187. }
  188. const checksum: TopicWireChecksum = {
  189. algorithm: "crc32",
  190. value: crc32WireBytes(logical),
  191. };
  192. const chunkBytes = findFragmentByteBudget({
  193. options,
  194. logicalBytes: logical.byteLength,
  195. checksum,
  196. maxPhysicalFrameBytes,
  197. });
  198. if (chunkBytes < 1) {
  199. throw new TopicWireFrameEncodingError("proto.frameEnvelopeTooLarge");
  200. }
  201. const fragmentCount = Math.ceil(logical.byteLength / chunkBytes);
  202. if (fragmentCount > PROTOCOL_V4_LIMITS.logicalFrameAssemblyMaxFragments) {
  203. throw new TopicWireFrameEncodingError("proto.frameFragmentCountExceeded");
  204. }
  205. const frames: TopicWireFrame<F>[] = [];
  206. for (let fragmentIndex = 0; fragmentIndex < fragmentCount; fragmentIndex += 1) {
  207. const start = fragmentIndex * chunkBytes;
  208. const end = Math.min(start + chunkBytes, logical.byteLength);
  209. const wire = makeFragment({
  210. options,
  211. fragmentIndex,
  212. fragmentCount,
  213. logicalBytes: logical.byteLength,
  214. checksum,
  215. dataBase64: encodeWireBytesBase64(logical.subarray(start, end)),
  216. });
  217. if (options.measurePhysicalFrameBytes(wire) > maxPhysicalFrameBytes) {
  218. // physical 上限包含调用方真实 envelope;任何估算漂移都必须
  219. // fail closed,不能把超限 frame 交给下游再静默截断。
  220. throw new TopicWireFrameEncodingError("proto.frameEnvelopeTooLarge");
  221. }
  222. frames.push(wire);
  223. }
  224. return frames;
  225. }