protocol.test.ts 9.4 KB

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