protocol.test.ts 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. import { afterEach, beforeEach, describe, it, expect, vi } from "vitest";
  2. import { VSBuffer } from "../src/buffer.js";
  3. import {
  4. ChunkStream,
  5. createQueuePair,
  6. MessagePortProtocol,
  7. ProtocolMessageType,
  8. type ISocket,
  9. type MessagePortLike,
  10. type MessagePortPayload,
  11. } from "../src/protocol.js";
  12. import { PersistentProtocol } from "../src/persistent-protocol.js";
  13. import { Event, Emitter } from "../src/foundation.js";
  14. describe("ChunkStream", () => {
  15. it("should accept and read exact chunk", () => {
  16. const stream = new ChunkStream();
  17. stream.acceptChunk(VSBuffer.fromString("hello"));
  18. expect(stream.byteLength).toBe(5);
  19. const result = stream.read(5);
  20. expect(result).not.toBeNull();
  21. expect(result!.toString()).toBe("hello");
  22. expect(stream.byteLength).toBe(0);
  23. });
  24. it("should return null when not enough data", () => {
  25. const stream = new ChunkStream();
  26. stream.acceptChunk(VSBuffer.fromString("hi"));
  27. expect(stream.read(10)).toBeNull();
  28. expect(stream.byteLength).toBe(2);
  29. });
  30. it("should handle partial reads from a larger chunk", () => {
  31. const stream = new ChunkStream();
  32. stream.acceptChunk(VSBuffer.fromString("abcdef"));
  33. const r1 = stream.read(3);
  34. expect(r1!.toString()).toBe("abc");
  35. const r2 = stream.read(3);
  36. expect(r2!.toString()).toBe("def");
  37. });
  38. it("should handle reads spanning multiple chunks", () => {
  39. const stream = new ChunkStream();
  40. stream.acceptChunk(VSBuffer.fromString("ab"));
  41. stream.acceptChunk(VSBuffer.fromString("cd"));
  42. stream.acceptChunk(VSBuffer.fromString("ef"));
  43. const result = stream.read(5);
  44. expect(result!.toString()).toBe("abcde");
  45. expect(stream.byteLength).toBe(1);
  46. });
  47. });
  48. // ── PersistentProtocol 两个补丁(docs/v4-refactor/05 §@zcode/rpc)──
  49. /** 可注入数据的假 socket:write 收集出站帧,emitData 模拟对端来包。 */
  50. class FakeSocket implements ISocket {
  51. private readonly _onData = new Emitter<VSBuffer>();
  52. onData = this._onData.event;
  53. private readonly _onClose = new Emitter<void>();
  54. onClose = this._onClose.event;
  55. private readonly _onEnd = new Emitter<void>();
  56. onEnd = this._onEnd.event;
  57. readonly written: VSBuffer[] = [];
  58. write(buffer: VSBuffer): void {
  59. this.written.push(buffer);
  60. }
  61. emitData(buffer: VSBuffer): void {
  62. this._onData.fire(buffer);
  63. }
  64. end(): void {}
  65. async drain(): Promise<void> {}
  66. dispose(): void {}
  67. }
  68. /** 构造对端 ACK 帧(type=Ack, 13 字节 header, 无 payload)。 */
  69. function ackFrame(ack: number): VSBuffer {
  70. const buffer = VSBuffer.alloc(13);
  71. buffer.writeUInt8(ProtocolMessageType.Ack, 0);
  72. buffer.writeUInt32BE(0, 1);
  73. buffer.writeUInt32BE(ack, 5);
  74. buffer.writeUInt32BE(0, 9);
  75. return buffer;
  76. }
  77. function lastWrittenType(socket: FakeSocket): ProtocolMessageType {
  78. const frame = socket.written[socket.written.length - 1]!;
  79. return frame.readUInt8(0) as ProtocolMessageType;
  80. }
  81. describe("PersistentProtocol 拥塞信号(补丁 1)", () => {
  82. it("unacknowledgedBytes 随 send 增长、随 ACK 回落", () => {
  83. const socket = new FakeSocket();
  84. const protocol = new PersistentProtocol(socket);
  85. protocol.send(VSBuffer.fromString("aaaa"));
  86. protocol.send(VSBuffer.fromString("bb"));
  87. expect(protocol.unacknowledgedBytes).toBe(6);
  88. // 对端确认到第 1 条。
  89. socket.emitData(ackFrame(1));
  90. expect(protocol.unacknowledgedBytes).toBe(2);
  91. socket.emitData(ackFrame(2));
  92. expect(protocol.unacknowledgedBytes).toBe(0);
  93. protocol.dispose();
  94. });
  95. it("越过高水位 onSaturated(边沿触发),回落低水位 onDrained", () => {
  96. const socket = new FakeSocket();
  97. const protocol = new PersistentProtocol(socket, {
  98. saturationHighWaterMarkBytes: 10,
  99. saturationLowWaterMarkBytes: 4,
  100. });
  101. let saturatedCount = 0;
  102. let drainedCount = 0;
  103. protocol.onSaturated(() => saturatedCount++);
  104. protocol.onDrained(() => drainedCount++);
  105. protocol.send(VSBuffer.fromString("12345678")); // 8B,未过水位
  106. expect(saturatedCount).toBe(0);
  107. protocol.send(VSBuffer.fromString("1234")); // 12B,越过高水位
  108. expect(saturatedCount).toBe(1);
  109. protocol.send(VSBuffer.fromString("x")); // 持续饱和不重复通知
  110. expect(saturatedCount).toBe(1);
  111. socket.emitData(ackFrame(1)); // 剩 5B,仍高于低水位
  112. expect(drainedCount).toBe(0);
  113. socket.emitData(ackFrame(2)); // 剩 1B ≤ 4 → drained
  114. expect(drainedCount).toBe(1);
  115. protocol.dispose();
  116. });
  117. });
  118. describe("PersistentProtocol 重放缓冲有界(补丁 2)", () => {
  119. beforeEach(() => vi.useFakeTimers());
  120. afterEach(() => vi.useRealTimers());
  121. it("未 ACK 字节越过上限 → 发 Disconnect 并 onClose(客户端走 subscribe(base))", () => {
  122. const socket = new FakeSocket();
  123. const protocol = new PersistentProtocol(socket, {
  124. replayBufferMaxBytes: 10,
  125. });
  126. let closed = 0;
  127. protocol.onClose(() => closed++);
  128. protocol.send(VSBuffer.fromString("12345678"));
  129. expect(closed).toBe(0);
  130. protocol.send(VSBuffer.fromString("1234")); // 12B > 10 → 放弃会话
  131. expect(closed).toBe(1);
  132. expect(lastWrittenType(socket)).toBe(ProtocolMessageType.Disconnect);
  133. protocol.send(VSBuffer.fromString("more")); // 已放弃,不重复触发
  134. expect(closed).toBe(1);
  135. protocol.dispose();
  136. });
  137. it("最老未 ACK 消息超过宽限窗 → 放弃会话", () => {
  138. const socket = new FakeSocket();
  139. const protocol = new PersistentProtocol(socket, {
  140. replayBufferGraceMs: 30_000,
  141. });
  142. let closed = 0;
  143. protocol.onClose(() => closed++);
  144. protocol.send(VSBuffer.fromString("hello"));
  145. vi.advanceTimersByTime(20_000); // 首次 ackCheck:年龄 20s < 30s
  146. expect(closed).toBe(0);
  147. vi.advanceTimersByTime(20_000); // 第二次:年龄 40s > 30s → 放弃
  148. expect(closed).toBe(1);
  149. protocol.dispose();
  150. });
  151. it("及时 ACK 时宽限窗不触发", () => {
  152. const socket = new FakeSocket();
  153. const protocol = new PersistentProtocol(socket, {
  154. replayBufferGraceMs: 30_000,
  155. });
  156. let closed = 0;
  157. protocol.onClose(() => closed++);
  158. protocol.send(VSBuffer.fromString("hello"));
  159. vi.advanceTimersByTime(10_000);
  160. socket.emitData(ackFrame(1)); // 队列清空
  161. vi.advanceTimersByTime(60_000);
  162. expect(closed).toBe(0);
  163. protocol.dispose();
  164. });
  165. });
  166. describe("createQueuePair", () => {
  167. it("should work bidirectionally", async () => {
  168. const [a, b] = createQueuePair();
  169. const fromA = Event.toPromise(b.onMessage);
  170. const fromB = Event.toPromise(a.onMessage);
  171. a.send(VSBuffer.fromString("to B"));
  172. b.send(VSBuffer.fromString("to A"));
  173. expect((await fromA).toString()).toBe("to B");
  174. expect((await fromB).toString()).toBe("to A");
  175. });
  176. });
  177. class FakeMessagePort implements MessagePortLike {
  178. private readonly listeners = new Set<(event: { data: MessagePortPayload }) => void>();
  179. peer?: FakeMessagePort;
  180. readonly posted: unknown[] = [];
  181. addEventListener(
  182. _type: "message",
  183. listener: (event: { data: MessagePortPayload }) => void,
  184. ): void {
  185. this.listeners.add(listener);
  186. }
  187. removeEventListener(
  188. _type: "message",
  189. listener: (event: { data: MessagePortPayload }) => void,
  190. ): void {
  191. this.listeners.delete(listener);
  192. }
  193. postMessage(message: MessagePortPayload): void {
  194. this.posted.push(message);
  195. this.peer?.emit(message);
  196. }
  197. emit(data: unknown): void {
  198. for (const listener of this.listeners) {
  199. listener({ data: data as MessagePortPayload });
  200. }
  201. }
  202. start(): void {}
  203. close(): void {}
  204. }
  205. describe("MessagePortProtocol connection flow sideband", () => {
  206. it("大块二进制消息不枚举每个字节,非法控制对象仍丢弃", () => {
  207. const port = new FakeMessagePort();
  208. const protocol = new MessagePortProtocol(port);
  209. const binary = new Uint8Array(3 * 1024 * 1024);
  210. const receive = vi.fn();
  211. const flow = vi.fn();
  212. protocol.onMessage(receive);
  213. protocol.onFlowState(flow);
  214. const keys = vi.spyOn(Object, "keys");
  215. try {
  216. port.emit(binary);
  217. const enumerated = keys.mock.calls.some(([value]) => value === binary);
  218. expect(enumerated).toBe(false);
  219. expect(receive).toHaveBeenCalledOnce();
  220. expect(receive.mock.calls[0]![0].buffer).toBe(binary);
  221. port.emit({ __zcodeRpcControl: "connection-flow-v1", state: "drained", extra: true });
  222. port.emit({ __zcodeRpcControl: "connection-flow-v1", state: "invalid" });
  223. expect(flow).not.toHaveBeenCalled();
  224. expect(receive).toHaveBeenCalledOnce();
  225. port.emit({ __zcodeRpcControl: "connection-flow-v1", state: "drained" });
  226. expect(flow).toHaveBeenCalledWith("drained");
  227. } finally {
  228. keys.mockRestore();
  229. protocol.disconnect();
  230. }
  231. });
  232. it("consumes strict control objects before Channel binary delivery", () => {
  233. const leftPort = new FakeMessagePort();
  234. const rightPort = new FakeMessagePort();
  235. leftPort.peer = rightPort;
  236. rightPort.peer = leftPort;
  237. const left = new MessagePortProtocol(leftPort);
  238. const right = new MessagePortProtocol(rightPort);
  239. const binary: string[] = [];
  240. const flow: string[] = [];
  241. right.onMessage((message) => binary.push(message.toString()));
  242. const flowProtocol = right as MessagePortProtocol & {
  243. onFlowState(listener: (state: string) => void): { dispose(): void };
  244. };
  245. flowProtocol.onFlowState((state) => flow.push(state));
  246. left.send(VSBuffer.fromString("rpc-binary"));
  247. (
  248. left as MessagePortProtocol & {
  249. sendFlowState(state: "saturated" | "drained"): void;
  250. }
  251. ).sendFlowState("saturated");
  252. rightPort.emit({ __zcodeRpcControl: "connection-flow-v1", state: "forged" });
  253. expect(binary).toEqual(["rpc-binary"]);
  254. expect(flow).toEqual(["saturated"]);
  255. expect(leftPort.posted).toContainEqual({
  256. __zcodeRpcControl: "connection-flow-v1",
  257. state: "saturated",
  258. });
  259. left.disconnect();
  260. right.disconnect();
  261. });
  262. });