zcodeProtocolV4PhysicalTopic.test.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. PROTOCOL_V4_LIMITS,
  4. TopicWireFrameAssembler,
  5. conversationTopicFrameSchema,
  6. conversationTopicWireCandidateSchema,
  7. conversationTopicWireFrameSchema,
  8. encodeTopicWireFrames,
  9. measureTopicNotificationEnvelopeBytes,
  10. reassembleTopicWireFrames,
  11. routedTopicFrameSchema,
  12. routedTopicWireFrameSchema,
  13. sessionsIndexTopicWireFrameSchema,
  14. workspaceConfigTopicWireFrameSchema,
  15. type ConversationTopicFrame,
  16. type RoutedTopicWireFrame,
  17. type SessionsIndexTopicFrame,
  18. type WorkspaceConfigTopicFrame,
  19. } from "../src/zcode-protocol-v4/index.js";
  20. import { crc32WireBytes, encodeWireBytesBase64 } from "../src/zcode-protocol-v4/wire-binary.js";
  21. const encoder = new TextEncoder();
  22. const TOPIC = "conversation/session-physical";
  23. const SUBSCRIPTION_ID = "sub-physical";
  24. function conversationFrame(text = "hello"): ConversationTopicFrame {
  25. return {
  26. topic: TOPIC,
  27. subscriptionId: SUBSCRIPTION_ID,
  28. fromSeq: 1,
  29. toSeq: 2,
  30. sentAt: 1_700_000_000_000,
  31. payload: {
  32. kind: "deltas",
  33. deltas: [{ op: "row.delta", rowId: 1, path: "text", append: text }],
  34. },
  35. };
  36. }
  37. function sessionsIndexFrame(): SessionsIndexTopicFrame {
  38. return {
  39. topic: "sessions-index/workspace-physical",
  40. subscriptionId: "sub-index",
  41. fromSeq: 0,
  42. toSeq: 0,
  43. sentAt: 1,
  44. payload: {
  45. kind: "snapshot",
  46. snapshot: {
  47. protocolVersion: 1,
  48. workspaceId: "workspace-physical",
  49. logEpoch: "epoch-index",
  50. sessions: [],
  51. },
  52. },
  53. };
  54. }
  55. function workspaceConfigFrame(): WorkspaceConfigTopicFrame {
  56. return {
  57. topic: "workspace-config/workspace-physical",
  58. subscriptionId: "sub-config",
  59. fromSeq: 0,
  60. toSeq: 0,
  61. sentAt: 1,
  62. payload: {
  63. kind: "snapshot",
  64. snapshot: {
  65. protocolVersion: 1,
  66. workspaceId: "workspace-physical",
  67. logEpoch: "epoch-config",
  68. config: { configOptions: [], slashCommands: [] },
  69. },
  70. },
  71. };
  72. }
  73. function completeWire<F extends { topic: string; subscriptionId: string }>(
  74. logicalFrameId: string,
  75. frame: F,
  76. logicalFrameOrdinal = 1,
  77. deliveryKind: "initial" | "online" | "recovery" = "online",
  78. ) {
  79. return {
  80. wireVersion: 3 as const,
  81. kind: "complete" as const,
  82. deliveryKind,
  83. logicalFrameId,
  84. logicalFrameOrdinal,
  85. topic: frame.topic,
  86. subscriptionId: frame.subscriptionId,
  87. frame,
  88. };
  89. }
  90. function fragmentedWire(
  91. frame: ConversationTopicFrame,
  92. logicalFrameId: string,
  93. fragmentCount: number,
  94. logicalFrameOrdinal = 1,
  95. ): RoutedTopicWireFrame[] {
  96. const logical = encoder.encode(JSON.stringify(frame));
  97. expect(logical.byteLength).toBeGreaterThanOrEqual(fragmentCount);
  98. const checksum = { algorithm: "crc32" as const, value: crc32WireBytes(logical) };
  99. const wires: RoutedTopicWireFrame[] = [];
  100. let offset = 0;
  101. for (let index = 0; index < fragmentCount; index += 1) {
  102. const remainingBytes = logical.byteLength - offset;
  103. const remainingFragments = fragmentCount - index;
  104. const size = Math.ceil(remainingBytes / remainingFragments);
  105. const bytes = logical.subarray(offset, offset + size);
  106. offset += size;
  107. wires.push({
  108. wireVersion: 3,
  109. kind: "fragment",
  110. deliveryKind: "online",
  111. logicalFrameId,
  112. logicalFrameOrdinal,
  113. topic: frame.topic,
  114. subscriptionId: frame.subscriptionId,
  115. fragmentIndex: index,
  116. fragmentCount,
  117. logicalBytes: logical.byteLength,
  118. checksum,
  119. dataBase64: encodeWireBytesBase64(bytes),
  120. });
  121. }
  122. return wires;
  123. }
  124. function singleFragment(params: {
  125. logicalFrameId: string;
  126. logicalFrameOrdinal?: number;
  127. topic?: string;
  128. subscriptionId?: string;
  129. bytes: Uint8Array;
  130. logicalBytes?: number;
  131. checksum?: string;
  132. }): RoutedTopicWireFrame {
  133. return {
  134. wireVersion: 3,
  135. kind: "fragment",
  136. deliveryKind: "online",
  137. logicalFrameId: params.logicalFrameId,
  138. logicalFrameOrdinal: params.logicalFrameOrdinal ?? 1,
  139. topic: params.topic ?? TOPIC,
  140. subscriptionId: params.subscriptionId ?? SUBSCRIPTION_ID,
  141. fragmentIndex: 0,
  142. fragmentCount: 1,
  143. logicalBytes: params.logicalBytes ?? params.bytes.byteLength,
  144. checksum: {
  145. algorithm: "crc32",
  146. value: params.checksum ?? crc32WireBytes(params.bytes),
  147. },
  148. dataBase64: encodeWireBytesBase64(params.bytes),
  149. };
  150. }
  151. describe("V4 三 topic physical schema 与真实 envelope", () => {
  152. it("三 topic physical schema 与 routed logical/physical union 均 strict", () => {
  153. const conversation = conversationFrame();
  154. const index = sessionsIndexFrame();
  155. const config = workspaceConfigFrame();
  156. expect(conversationTopicWireFrameSchema.parse(completeWire("c", conversation))).toBeTruthy();
  157. expect(sessionsIndexTopicWireFrameSchema.parse(completeWire("i", index))).toBeTruthy();
  158. expect(workspaceConfigTopicWireFrameSchema.parse(completeWire("w", config))).toBeTruthy();
  159. expect(routedTopicFrameSchema.parse(conversation)).toEqual(conversation);
  160. expect(routedTopicFrameSchema.parse(index)).toEqual(index);
  161. expect(routedTopicFrameSchema.parse(config)).toEqual(config);
  162. expect(routedTopicWireFrameSchema.parse(completeWire("i", index))).toBeTruthy();
  163. const validDelivery = completeWire("delivery", conversation, 1, "recovery");
  164. expect(conversationTopicWireFrameSchema.parse(validDelivery).deliveryKind).toBe("recovery");
  165. const { deliveryKind: _deliveryKind, ...missingDeliveryKind } = validDelivery;
  166. for (const invalidDelivery of [missingDeliveryKind, { ...validDelivery, deliveryKind: "guessed" }]) {
  167. const ownedCandidate = conversationTopicWireCandidateSchema.parse(invalidDelivery);
  168. expect(
  169. new TopicWireFrameAssembler(conversationTopicFrameSchema).accept(ownedCandidate),
  170. ).toMatchObject([
  171. { kind: "fault", fault: { reasonCode: "proto.frameAssemblyMetadataMismatch" } },
  172. ]);
  173. expect(conversationTopicWireFrameSchema.safeParse(invalidDelivery).success).toBe(false);
  174. }
  175. expect(
  176. sessionsIndexTopicWireFrameSchema.safeParse(completeWire("bad", conversation)).success,
  177. ).toBe(false);
  178. expect(
  179. workspaceConfigTopicWireFrameSchema.safeParse({
  180. ...completeWire("extra", config),
  181. unexpected: true,
  182. }).success,
  183. ).toBe(false);
  184. const invalidBase64 = {
  185. ...fragmentedWire(conversation, "candidate", 1)[0]!,
  186. dataBase64: "%%%",
  187. };
  188. expect(conversationTopicWireCandidateSchema.safeParse(invalidBase64).success).toBe(true);
  189. expect(conversationTopicWireFrameSchema.safeParse(invalidBase64).success).toBe(false);
  190. const validFragment = fragmentedWire(conversation, "candidate-inner", 1)[0]!;
  191. const { checksum: _checksum, ...missingChecksum } = validFragment;
  192. const routeableInvalid = [
  193. missingChecksum,
  194. { ...validFragment, checksum: { algorithm: "crc32", value: 1 } },
  195. { ...validFragment, dataBase64: 1 },
  196. { ...validFragment, unexpected: true },
  197. { ...validFragment, checksum: { ...validFragment.checksum, unexpected: true } },
  198. ];
  199. for (const candidate of routeableInvalid) {
  200. const outer = conversationTopicWireCandidateSchema.parse(candidate);
  201. expect(
  202. new TopicWireFrameAssembler(conversationTopicFrameSchema).accept(outer),
  203. ).toMatchObject([
  204. { kind: "fault", fault: { reasonCode: "proto.frameAssemblyMetadataMismatch" } },
  205. ]);
  206. }
  207. });
  208. it("CLI NDJSON、Channel/Socket 与 mobile relay outer 都机械保持 1MiB 边界", () => {
  209. const max = PROTOCOL_V4_LIMITS.maxFrameBytes;
  210. for (const limit of [max - 1, max, max + 1]) {
  211. const frame = conversationFrame("中文🙂".repeat(160_000));
  212. const wires = encodeTopicWireFrames(frame, {
  213. deliveryKind: "online",
  214. topic: frame.topic,
  215. subscriptionId: frame.subscriptionId,
  216. logicalFrameId: `meter-${limit}`,
  217. logicalFrameOrdinal: 1,
  218. maxPhysicalFrameBytes: limit,
  219. measurePhysicalFrameBytes: (wire) => measureTopicNotificationEnvelopeBytes(wire).maxBytes,
  220. });
  221. expect(wires.length).toBeGreaterThan(1);
  222. for (const wire of wires) {
  223. const measured = measureTopicNotificationEnvelopeBytes(wire);
  224. const productionLimit = Math.min(limit, max);
  225. expect(measured.cliNdjsonBytes).toBeLessThanOrEqual(productionLimit);
  226. expect(measured.channelSocketBytes).toBeLessThanOrEqual(productionLimit);
  227. expect(measured.mobileRelayBytes).toBeLessThanOrEqual(productionLimit);
  228. }
  229. }
  230. const boundary = conversationFrame("boundary");
  231. for (const completeBytes of [max - 1, max]) {
  232. expect(
  233. encodeTopicWireFrames(boundary, {
  234. deliveryKind: "initial",
  235. topic: boundary.topic,
  236. subscriptionId: boundary.subscriptionId,
  237. logicalFrameId: `exact-${completeBytes}`,
  238. logicalFrameOrdinal: 1,
  239. measurePhysicalFrameBytes: (wire) => (wire.kind === "complete" ? completeBytes : max),
  240. }),
  241. ).toHaveLength(1);
  242. }
  243. const plusOne = encodeTopicWireFrames(boundary, {
  244. deliveryKind: "recovery",
  245. topic: boundary.topic,
  246. subscriptionId: boundary.subscriptionId,
  247. logicalFrameId: "exact-plus-one",
  248. logicalFrameOrdinal: 1,
  249. measurePhysicalFrameBytes: (wire) => (wire.kind === "complete" ? max + 1 : max),
  250. });
  251. expect(plusOne.every((wire) => wire.kind === "fragment")).toBe(true);
  252. });
  253. });
  254. describe("TopicWireFrameAssembler incremental 原子状态机", () => {
  255. it("最后一片前不产 logical frame;乱序、相同重复片只完成一次", () => {
  256. const frame = conversationFrame("中文🙂".repeat(300));
  257. const wires = fragmentedWire(frame, "logical-atomic", 12);
  258. const assembler = new TopicWireFrameAssembler(conversationTopicFrameSchema);
  259. const apply: ConversationTopicFrame[] = [];
  260. for (const wire of [...wires].reverse().slice(0, -1)) {
  261. for (const event of assembler.accept(wire, 1)) {
  262. if (event.kind === "complete") apply.push(event.frame);
  263. }
  264. }
  265. expect(apply).toEqual([]);
  266. expect(assembler.accept(wires.at(-1)!, 2)).toEqual([]); // identical duplicate
  267. const final = assembler.accept(wires[0]!, 3);
  268. expect(final).toEqual([{ kind: "complete", frame, deliveryKind: "online" }]);
  269. expect(assembler.accept(wires[0]!, 4)).toEqual([]); // completed id duplicate
  270. });
  271. it("冲突重复片、checksum、base64、UTF-8、JSON、schema mismatch 都 typed fault 并释放", () => {
  272. const frame = conversationFrame("conflict".repeat(100));
  273. const wires = fragmentedWire(frame, "logical-conflict", 2);
  274. const assembler = new TopicWireFrameAssembler(conversationTopicFrameSchema);
  275. expect(assembler.accept(wires[0]!, 0)).toEqual([]);
  276. const conflict = {
  277. ...wires[0]!,
  278. dataBase64: encodeWireBytesBase64(Uint8Array.of(1, 2, 3)),
  279. };
  280. expect(assembler.accept(conflict, 1)).toMatchObject([
  281. { kind: "fault", fault: { reasonCode: "proto.frameAssemblyFragmentConflict" } },
  282. ]);
  283. expect(assembler.getStats()).toEqual({ assemblies: 0, stagedDecodedBytes: 0 });
  284. const checksum = fragmentedWire(frame, "logical-checksum", 2, 2).map((wire) => ({
  285. ...wire,
  286. checksum: { algorithm: "crc32" as const, value: "00000000" },
  287. }));
  288. expect(checksum.flatMap((wire) => assembler.accept(wire, 2))).toMatchObject([
  289. { kind: "fault", fault: { reasonCode: "proto.frameAssemblyChecksumMismatch" } },
  290. ]);
  291. expect(
  292. assembler.accept(
  293. {
  294. ...singleFragment({
  295. logicalFrameId: "bad-base64",
  296. logicalFrameOrdinal: 3,
  297. bytes: Uint8Array.of(0),
  298. }),
  299. dataBase64: "%%%=",
  300. },
  301. 3,
  302. ),
  303. ).toMatchObject([{ kind: "fault", fault: { reasonCode: "proto.frameAssemblyInvalidBase64" } }]);
  304. expect(
  305. assembler.accept(
  306. singleFragment({
  307. logicalFrameId: "bad-utf8",
  308. logicalFrameOrdinal: 4,
  309. bytes: Uint8Array.of(0xff),
  310. }),
  311. 4,
  312. ),
  313. ).toMatchObject([{ kind: "fault", fault: { reasonCode: "proto.frameAssemblyInvalidUtf8" } }]);
  314. const invalidJson = encoder.encode("not-json");
  315. expect(
  316. assembler.accept(
  317. singleFragment({
  318. logicalFrameId: "bad-json",
  319. logicalFrameOrdinal: 5,
  320. bytes: invalidJson,
  321. }),
  322. 5,
  323. ),
  324. ).toMatchObject([{ kind: "fault", fault: { reasonCode: "proto.frameAssemblyInvalidJson" } }]);
  325. const invalidSchema = encoder.encode(
  326. JSON.stringify({ topic: TOPIC, subscriptionId: SUBSCRIPTION_ID }),
  327. );
  328. expect(
  329. assembler.accept(
  330. singleFragment({
  331. logicalFrameId: "bad-schema",
  332. logicalFrameOrdinal: 6,
  333. bytes: invalidSchema,
  334. }),
  335. 6,
  336. ),
  337. ).toMatchObject([
  338. { kind: "fault", fault: { reasonCode: "proto.frameAssemblyInvalidPayload" } },
  339. ]);
  340. });
  341. it("新 logical id supersede 旧 assembly;超时从首片计算且重复片不续期", () => {
  342. const first = fragmentedWire(conversationFrame("first".repeat(100)), "logical-old", 2, 1);
  343. const next = fragmentedWire(conversationFrame("next".repeat(100)), "logical-new", 2, 2);
  344. const assembler = new TopicWireFrameAssembler(conversationTopicFrameSchema, {
  345. timeoutMs: 30_000,
  346. });
  347. expect(assembler.accept(first[0]!, 100)).toEqual([]);
  348. expect(assembler.accept(next[0]!, 200)).toMatchObject([
  349. {
  350. kind: "fault",
  351. fault: { logicalFrameId: "logical-old", reasonCode: "proto.frameAssemblySuperseded" },
  352. },
  353. ]);
  354. expect(assembler.accept(next[0]!, 29_999)).toEqual([]);
  355. expect(assembler.expire(30_199)).toEqual([]);
  356. expect(assembler.expire(30_200)).toMatchObject([
  357. {
  358. kind: "fault",
  359. fault: { logicalFrameId: "logical-new", reasonCode: "proto.frameAssemblyTimedOut" },
  360. },
  361. ]);
  362. });
  363. it("权威 recovery 可原子 supersede 旧 online 残片;fragment deliveryKind 不一致 fail closed", () => {
  364. const old = fragmentedWire(conversationFrame("old".repeat(100)), "logical-old-online", 2, 1);
  365. const recoveryFrame = conversationFrame("recovered");
  366. const assembler = new TopicWireFrameAssembler(conversationTopicFrameSchema);
  367. expect(assembler.accept(old[0]!, 0)).toEqual([]);
  368. expect(
  369. assembler.accept(completeWire("logical-recovery", recoveryFrame, 2, "recovery"), 1),
  370. ).toEqual([{ kind: "complete", frame: recoveryFrame, deliveryKind: "recovery" }]);
  371. const mismatched = fragmentedWire(conversationFrame("mixed".repeat(100)), "logical-mixed-kind", 2, 3);
  372. expect(assembler.accept(mismatched[0]!, 2)).toEqual([]);
  373. expect(
  374. assembler.accept({ ...mismatched[1]!, deliveryKind: "recovery" }, 3),
  375. ).toMatchObject([
  376. { kind: "fault", fault: { reasonCode: "proto.frameAssemblyMetadataMismatch" } },
  377. ]);
  378. });
  379. it("ordinal 阻止 completed replay、反向 supersede 与同 ordinal 换 id", () => {
  380. const assembler = new TopicWireFrameAssembler(conversationTopicFrameSchema);
  381. const a = conversationFrame("A");
  382. const b = conversationFrame("B");
  383. const completeA = completeWire("logical-a", a, 1);
  384. const completeB = completeWire("logical-b", b, 2);
  385. expect(assembler.accept(completeA, 0)).toEqual([
  386. { kind: "complete", frame: a, deliveryKind: "online" },
  387. ]);
  388. expect(assembler.accept(completeB, 1)).toEqual([
  389. { kind: "complete", frame: b, deliveryKind: "online" },
  390. ]);
  391. expect(assembler.accept(completeA, 2)).toEqual([]);
  392. expect(assembler.accept(completeB, 3)).toEqual([]);
  393. expect(assembler.accept(completeWire("logical-b-conflict", b, 2), 4)).toMatchObject([
  394. { kind: "fault", fault: { reasonCode: "proto.frameAssemblyOrdinalConflict" } },
  395. ]);
  396. const partial = new TopicWireFrameAssembler(conversationTopicFrameSchema);
  397. const old = fragmentedWire(conversationFrame("old".repeat(100)), "logical-old", 2, 1);
  398. const next = fragmentedWire(conversationFrame("next".repeat(100)), "logical-next", 2, 2);
  399. expect(partial.accept(old[0]!, 0)).toEqual([]);
  400. expect(partial.accept(next[0]!, 1)).toMatchObject([
  401. { kind: "fault", fault: { reasonCode: "proto.frameAssemblySuperseded" } },
  402. ]);
  403. expect(partial.accept(old[1]!, 2)).toEqual([]);
  404. expect(partial.accept(next[1]!, 3)).toEqual([
  405. {
  406. kind: "complete",
  407. frame: conversationFrame("next".repeat(100)),
  408. deliveryKind: "online",
  409. },
  410. ]);
  411. });
  412. it("同 ordinal/id 的 fragment 与 complete 混用只 fault,不同时 complete", () => {
  413. const frame = conversationFrame("mixed".repeat(100));
  414. const fragments = fragmentedWire(frame, "logical-mixed", 2, 1);
  415. const assembler = new TopicWireFrameAssembler(conversationTopicFrameSchema);
  416. expect(assembler.accept(fragments[0]!, 0)).toEqual([]);
  417. expect(assembler.accept(completeWire("logical-mixed", frame, 1), 1)).toMatchObject([
  418. { kind: "fault", fault: { reasonCode: "proto.frameAssemblyMetadataMismatch" } },
  419. ]);
  420. expect(assembler.getStats()).toEqual({ assemblies: 0, stagedDecodedBytes: 0 });
  421. });
  422. it("timeout 会 retire ordinal;触发 timeout 的迟到片与后续同 ordinal 不得重建", () => {
  423. const frame = conversationFrame("timeout".repeat(100));
  424. const fragments = fragmentedWire(frame, "logical-timeout", 2, 1);
  425. const assembler = new TopicWireFrameAssembler(conversationTopicFrameSchema, {
  426. timeoutMs: 30_000,
  427. });
  428. expect(assembler.accept(fragments[0]!, 100)).toEqual([]);
  429. expect(assembler.accept(fragments[0]!, 30_100)).toMatchObject([
  430. { kind: "fault", fault: { reasonCode: "proto.frameAssemblyTimedOut" } },
  431. ]);
  432. expect(assembler.getStats()).toEqual({ assemblies: 0, stagedDecodedBytes: 0 });
  433. expect(assembler.accept(fragments[1]!, 30_101)).toEqual([]);
  434. expect(assembler.getStats()).toEqual({ assemblies: 0, stagedDecodedBytes: 0 });
  435. });
  436. it("16MiB 正好可完成,+1 明确拒绝;1024 片可完成、1025 schema 拒绝", () => {
  437. const max = PROTOCOL_V4_LIMITS.logicalFrameAssemblyMaxBytes;
  438. const empty = conversationFrame("");
  439. const overhead = encoder.encode(JSON.stringify(empty)).byteLength;
  440. const exact = conversationFrame("x".repeat(max - overhead));
  441. const assembler = new TopicWireFrameAssembler(conversationTopicFrameSchema);
  442. const exactWires = encodeTopicWireFrames(exact, {
  443. deliveryKind: "online",
  444. topic: exact.topic,
  445. subscriptionId: exact.subscriptionId,
  446. logicalFrameId: "exact-16m",
  447. logicalFrameOrdinal: 1,
  448. measurePhysicalFrameBytes: (wire) => measureTopicNotificationEnvelopeBytes(wire).maxBytes,
  449. });
  450. expect(exactWires.length).toBeGreaterThan(1);
  451. expect(exactWires.flatMap((wire) => assembler.accept(wire, 0))).toEqual([
  452. { kind: "complete", frame: exact, deliveryKind: "online" },
  453. ]);
  454. const tooLargeMetadata = {
  455. ...singleFragment({
  456. logicalFrameId: "over-16m",
  457. logicalFrameOrdinal: 2,
  458. bytes: Uint8Array.of(0),
  459. logicalBytes: max + 1,
  460. }),
  461. logicalBytes: max + 1,
  462. };
  463. expect(assembler.accept(tooLargeMetadata, 1)).toMatchObject([
  464. { kind: "fault", fault: { reasonCode: "proto.frameAssemblyTooLarge" } },
  465. ]);
  466. expect(assembler.accept(completeWire("oversized-complete", exact, 3), 1)).toMatchObject([
  467. { kind: "fault", fault: { reasonCode: "proto.frameEnvelopeTooLarge" } },
  468. ]);
  469. const many = conversationFrame("y".repeat(2_000));
  470. const fragments = fragmentedWire(many, "logical-1024", 1_024, 4);
  471. const events = fragments.flatMap((wire) => assembler.accept(wire, 2));
  472. expect(events).toEqual([{ kind: "complete", frame: many, deliveryKind: "online" }]);
  473. expect(
  474. conversationTopicWireFrameSchema.safeParse({
  475. ...fragments[0],
  476. fragmentCount: 1_025,
  477. logicalBytes: 1_025,
  478. }).success,
  479. ).toBe(false);
  480. });
  481. it("调用方不能用 options 放宽 assembler/codec/reassembly 协议硬上限", () => {
  482. const limits = PROTOCOL_V4_LIMITS;
  483. const assembler = new TopicWireFrameAssembler(conversationTopicFrameSchema, {
  484. maxAssemblyBytes: limits.logicalFrameAssemblyMaxBytes + 1,
  485. maxFragments: limits.logicalFrameAssemblyMaxFragments + 1,
  486. maxConcurrentAssemblies: limits.logicalFrameAssemblyMaxConcurrent + 1,
  487. maxStagedDecodedBytes: limits.logicalFrameAssemblyMaxStagedBytes + 1,
  488. timeoutMs: limits.logicalFrameAssemblyTimeoutMs + 1,
  489. maxPhysicalFrameBytes: limits.maxFrameBytes + 1,
  490. });
  491. expect(
  492. assembler as unknown as {
  493. maxAssemblyBytes: number;
  494. maxFragments: number;
  495. maxConcurrentAssemblies: number;
  496. maxStagedDecodedBytes: number;
  497. timeoutMs: number;
  498. maxPhysicalFrameBytes: number;
  499. },
  500. ).toMatchObject({
  501. maxAssemblyBytes: limits.logicalFrameAssemblyMaxBytes,
  502. maxFragments: limits.logicalFrameAssemblyMaxFragments,
  503. maxConcurrentAssemblies: limits.logicalFrameAssemblyMaxConcurrent,
  504. maxStagedDecodedBytes: limits.logicalFrameAssemblyMaxStagedBytes,
  505. timeoutMs: limits.logicalFrameAssemblyTimeoutMs,
  506. maxPhysicalFrameBytes: limits.maxFrameBytes,
  507. });
  508. expect(
  509. () => new TopicWireFrameAssembler(conversationTopicFrameSchema, { maxAssemblyBytes: NaN }),
  510. ).toThrow(/positive finite/u);
  511. const oversized = conversationFrame("x".repeat(limits.logicalFrameAssemblyMaxBytes));
  512. expect(() =>
  513. encodeTopicWireFrames(oversized, {
  514. deliveryKind: "online",
  515. topic: oversized.topic,
  516. subscriptionId: oversized.subscriptionId,
  517. logicalFrameId: "codec-hard-cap",
  518. logicalFrameOrdinal: 1,
  519. maxAssemblyBytes: limits.logicalFrameAssemblyMaxBytes + 1,
  520. maxPhysicalFrameBytes: limits.maxFrameBytes + 1,
  521. measurePhysicalFrameBytes: (wire) => measureTopicNotificationEnvelopeBytes(wire).maxBytes,
  522. }),
  523. ).toThrow("proto.frameAssemblyTooLarge");
  524. expect(() =>
  525. encodeTopicWireFrames(conversationFrame(), {
  526. deliveryKind: "online",
  527. topic: TOPIC,
  528. subscriptionId: SUBSCRIPTION_ID,
  529. logicalFrameId: "codec-invalid-limit",
  530. logicalFrameOrdinal: 1,
  531. maxPhysicalFrameBytes: Number.POSITIVE_INFINITY,
  532. measurePhysicalFrameBytes: () => 1,
  533. }),
  534. ).toThrow("proto.invalidLimit.maxPhysicalFrameBytes");
  535. expect(
  536. reassembleTopicWireFrames(
  537. [completeWire("reassembly-hard-cap", oversized)],
  538. conversationTopicFrameSchema,
  539. { maxAssemblyBytes: limits.logicalFrameAssemblyMaxBytes + 1 },
  540. ),
  541. ).toEqual({ kind: "rejected", reasonCode: "proto.frameAssemblyTooLarge" });
  542. expect(
  543. reassembleTopicWireFrames(
  544. [completeWire("reassembly-invalid-limit", conversationFrame())],
  545. conversationTopicFrameSchema,
  546. { maxAssemblyBytes: NaN },
  547. ),
  548. ).toEqual({ kind: "rejected", reasonCode: "proto.invalidLimit.maxAssemblyBytes" });
  549. });
  550. it("第 33 个并发 assembly 与总 staging budget 溢出显式 fault,不驱逐健康项", () => {
  551. const assembler = new TopicWireFrameAssembler(conversationTopicFrameSchema, {
  552. maxConcurrentAssemblies: 32,
  553. maxStagedDecodedBytes: 32,
  554. });
  555. for (let index = 0; index < 32; index += 1) {
  556. const wire = {
  557. ...singleFragment({
  558. logicalFrameId: `logical-${index}`,
  559. topic: `conversation/session-${index}`,
  560. subscriptionId: `sub-${index}`,
  561. bytes: Uint8Array.of(index),
  562. logicalBytes: 2,
  563. }),
  564. fragmentCount: 2,
  565. };
  566. expect(assembler.accept(wire, index)).toEqual([]);
  567. }
  568. expect(assembler.getStats()).toEqual({ assemblies: 32, stagedDecodedBytes: 32 });
  569. const overflow = {
  570. ...singleFragment({
  571. logicalFrameId: "logical-33",
  572. topic: "conversation/session-33",
  573. subscriptionId: "sub-33",
  574. bytes: Uint8Array.of(33),
  575. logicalBytes: 2,
  576. }),
  577. fragmentCount: 2,
  578. };
  579. expect(assembler.accept(overflow, 33)).toMatchObject([
  580. { kind: "fault", fault: { reasonCode: "proto.frameAssemblyConcurrentLimit" } },
  581. ]);
  582. expect(assembler.getStats()).toEqual({ assemblies: 32, stagedDecodedBytes: 32 });
  583. const budget = new TopicWireFrameAssembler(conversationTopicFrameSchema, {
  584. maxStagedDecodedBytes: 1,
  585. });
  586. expect(budget.accept({ ...overflow, logicalFrameId: "budget-one" }, 0)).toEqual([]);
  587. expect(
  588. budget.accept(
  589. { ...overflow, logicalFrameId: "budget-two", topic: "conversation/budget-two" },
  590. 1,
  591. ),
  592. ).toMatchObject([
  593. { kind: "fault", fault: { reasonCode: "proto.frameAssemblyBudgetExceeded" } },
  594. ]);
  595. expect(budget.getStats()).toEqual({ assemblies: 1, stagedDecodedBytes: 1 });
  596. });
  597. it("consumer fail-closed abort 释放 active bytes 但保留 ordinal tombstone", () => {
  598. const assembler = new TopicWireFrameAssembler(conversationTopicFrameSchema);
  599. const old = fragmentedWire(conversationFrame("old".repeat(100)), "logical-old", 2, 1);
  600. const newer = fragmentedWire(conversationFrame("newer".repeat(100)), "logical-newer", 2, 2);
  601. expect(assembler.accept(old[0]!, 0)).toEqual([]);
  602. expect(assembler.accept(newer[0]!, 1)).toMatchObject([
  603. { kind: "fault", fault: { reasonCode: "proto.frameAssemblySuperseded" } },
  604. ]);
  605. // consumer 对 [fault, possible complete] 整批 fail closed;abort 不能调用 discard,
  606. // 否则迟到旧片/当前片会从 ordinal 1 重新建 assembly 并复活已判坏序列。
  607. assembler.abort(TOPIC, SUBSCRIPTION_ID);
  608. expect(assembler.getStats()).toEqual({ assemblies: 0, stagedDecodedBytes: 0 });
  609. expect(assembler.accept(old[1]!, 2)).toEqual([]);
  610. expect(assembler.accept(newer[1]!, 3)).toEqual([]);
  611. const latest = conversationFrame("latest");
  612. expect(assembler.accept(completeWire("logical-latest", latest, 3), 4)).toEqual([
  613. { kind: "complete", frame: latest, deliveryKind: "online" },
  614. ]);
  615. });
  616. it("discard/clear 释放指定 subscription 与全部 assembly", () => {
  617. const assembler = new TopicWireFrameAssembler(conversationTopicFrameSchema);
  618. const a = fragmentedWire(conversationFrame("a".repeat(100)), "a", 2)[0]!;
  619. const b = { ...a, topic: "conversation/b", subscriptionId: "sub-b", logicalFrameId: "b" };
  620. assembler.accept(a, 0);
  621. assembler.accept(b, 0);
  622. assembler.discard(a.topic, a.subscriptionId);
  623. expect(assembler.getStats().assemblies).toBe(1);
  624. assembler.clear();
  625. expect(assembler.getStats()).toEqual({ assemblies: 0, stagedDecodedBytes: 0 });
  626. });
  627. });