v4-physical-delivery.test.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { describe, expect, it, vi } from "vitest";
  2. import type { ConversationTopicFrame } from "@zcode/shared/zcode-protocol-v4";
  3. import { measureTopicNotificationEnvelopeBytes } from "@zcode/shared/zcode-protocol-v4";
  4. import { emitReservedTopicFrame } from "../src/zcode-protocol-v4/v4-gateway.js";
  5. import type { TopicFrameReservation } from "../src/zcode-protocol-v4/topic-frame-reservation.js";
  6. function frame(text = ""): ConversationTopicFrame {
  7. return {
  8. topic: "conversation/session-delivery",
  9. subscriptionId: "sub-delivery",
  10. fromSeq: 0,
  11. toSeq: 1,
  12. sentAt: 1,
  13. payload: {
  14. kind: "deltas",
  15. deltas: text ? [{ op: "row.delta", rowId: 1, path: "text", append: text }] : [],
  16. },
  17. };
  18. }
  19. describe("V4 gateway physical reservation delivery", () => {
  20. it("emit 中途失败不 commit;retry 使用相同 logical id/content 并在全成功后 commit", () => {
  21. const commit = vi.fn(() => true);
  22. const reservation: TopicFrameReservation<ConversationTopicFrame> = {
  23. logicalFrameId: "logical-stable",
  24. logicalFrameOrdinal: 1,
  25. frame: frame("中文🙂".repeat(180_000)),
  26. commit,
  27. };
  28. const firstAttempt: unknown[] = [];
  29. let firstIndex = 0;
  30. expect(() =>
  31. emitReservedTopicFrame(reservation, (wire) => {
  32. firstAttempt.push(wire);
  33. if (firstIndex++ === 1) throw new Error("emit failed");
  34. }),
  35. ).toThrow("emit failed");
  36. expect(commit).not.toHaveBeenCalled();
  37. const retry: unknown[] = [];
  38. expect(emitReservedTopicFrame(reservation, (wire) => retry.push(wire))).toBe(true);
  39. expect(firstAttempt).toHaveLength(2);
  40. expect(retry.length).toBeGreaterThan(2);
  41. expect(retry.slice(0, firstAttempt.length)).toEqual(firstAttempt);
  42. expect(
  43. retry.every(
  44. (wire) => (wire as { logicalFrameId: string }).logicalFrameId === "logical-stable",
  45. ),
  46. ).toBe(true);
  47. const checksums = retry.map(
  48. (wire) => (wire as { checksum?: { value: string } }).checksum?.value,
  49. );
  50. expect(new Set(checksums).size).toBe(1);
  51. expect(commit).toHaveBeenCalledTimes(1);
  52. for (const wire of retry) {
  53. expect(measureTopicNotificationEnvelopeBytes(wire as never).maxBytes).toBeLessThanOrEqual(
  54. 1024 * 1024,
  55. );
  56. }
  57. });
  58. });