attachment-upload-registry.test.ts 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. import { createHash } from "node:crypto";
  2. import { describe, expect, it, vi } from "vitest";
  3. import { PROTOCOL_V4_LIMITS } from "@zcode/shared/zcode-protocol-v4";
  4. import { AttachmentUploadRegistry } from "../src/zcode-protocol-v4/attachment-upload-registry.js";
  5. function sha256(bytes: Uint8Array): string {
  6. return `sha256:${createHash("sha256").update(bytes).digest("hex")}`;
  7. }
  8. function begin(bytes: Uint8Array, uploadId = "upload-1", totalChunks = 1) {
  9. return {
  10. connectionId: "connection-1",
  11. sessionId: "session-1",
  12. uploadId,
  13. fileName: "payload.bin",
  14. mime: "application/octet-stream",
  15. totalBytes: bytes.byteLength,
  16. totalChunks: bytes.byteLength === 0 ? 0 : totalChunks,
  17. checksum: sha256(bytes),
  18. };
  19. }
  20. describe("AttachmentUploadRegistry hard bounds", () => {
  21. it("20MiB exactly 以 40 个 512KiB chunk 原子 commit", async () => {
  22. const bytes = new Uint8Array(PROTOCOL_V4_LIMITS.attachmentMaxBytes);
  23. const put = vi.fn(async () => ({ ref: "zcode-artifact://exact-20mib" }));
  24. const registry = new AttachmentUploadRegistry({ now: () => 0, putSessionAttachment: put });
  25. const chunkBytes = PROTOCOL_V4_LIMITS.attachmentChunkMaxBytes;
  26. const totalChunks = bytes.byteLength / chunkBytes;
  27. registry.begin(begin(bytes, "exact-20mib", totalChunks));
  28. for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex += 1) {
  29. const start = chunkIndex * chunkBytes;
  30. registry.chunk({
  31. connectionId: "connection-1",
  32. sessionId: "session-1",
  33. uploadId: "exact-20mib",
  34. chunkIndex,
  35. dataBase64: Buffer.from(bytes.subarray(start, start + chunkBytes)).toString("base64"),
  36. });
  37. }
  38. await expect(
  39. registry.commit({
  40. connectionId: "connection-1",
  41. sessionId: "session-1",
  42. uploadId: "exact-20mib",
  43. }),
  44. ).resolves.toEqual({ ref: "zcode-artifact://exact-20mib" });
  45. expect(put).toHaveBeenCalledTimes(1);
  46. expect(put.mock.calls[0][1].bytes.byteLength).toBe(PROTOCOL_V4_LIMITS.attachmentMaxBytes);
  47. });
  48. it("active upload 数量有硬上限;conflicting begin 不覆盖原 metadata", () => {
  49. const empty = new Uint8Array();
  50. const registry = new AttachmentUploadRegistry({
  51. now: () => 0,
  52. putSessionAttachment: vi.fn(async () => ({ ref: "unused" })),
  53. });
  54. for (let index = 0; index < PROTOCOL_V4_LIMITS.attachmentUploadMaxConcurrent; index += 1) {
  55. registry.begin(begin(empty, `upload-${index}`, 0));
  56. }
  57. expect(() => registry.begin(begin(empty, "upload-overflow", 0))).toThrow(
  58. "fault.attachment.tooManyUploads",
  59. );
  60. expect(() =>
  61. registry.begin({ ...begin(empty, "upload-0", 0), fileName: "conflict.bin" }),
  62. ).toThrow("fault.attachment.beginConflict");
  63. });
  64. it("全局 decoded staging 64MiB 正好可用,后一字节拒绝", () => {
  65. const registry = new AttachmentUploadRegistry({
  66. now: () => 0,
  67. putSessionAttachment: vi.fn(async () => ({ ref: "unused" })),
  68. });
  69. const chunkBytes = PROTOCOL_V4_LIMITS.attachmentChunkMaxBytes;
  70. const chunkBase64 = Buffer.alloc(chunkBytes).toString("base64");
  71. const bytesPerUpload = 16 * 1024 * 1024;
  72. const chunksPerUpload = bytesPerUpload / chunkBytes;
  73. for (let uploadIndex = 0; uploadIndex < 4; uploadIndex += 1) {
  74. const uploadId = `capacity-${uploadIndex}`;
  75. registry.begin({
  76. connectionId: "connection-1",
  77. sessionId: "session-1",
  78. uploadId,
  79. fileName: "capacity.bin",
  80. mime: "application/octet-stream",
  81. totalBytes: bytesPerUpload,
  82. totalChunks: chunksPerUpload,
  83. checksum: `sha256:${"0".repeat(64)}`,
  84. });
  85. for (let chunkIndex = 0; chunkIndex < chunksPerUpload; chunkIndex += 1) {
  86. registry.chunk({
  87. connectionId: "connection-1",
  88. sessionId: "session-1",
  89. uploadId,
  90. chunkIndex,
  91. dataBase64: chunkBase64,
  92. });
  93. }
  94. }
  95. registry.begin({
  96. connectionId: "connection-1",
  97. sessionId: "session-1",
  98. uploadId: "capacity-overflow",
  99. fileName: "one.bin",
  100. mime: "application/octet-stream",
  101. totalBytes: 1,
  102. totalChunks: 1,
  103. checksum: `sha256:${"0".repeat(64)}`,
  104. });
  105. expect(() =>
  106. registry.chunk({
  107. connectionId: "connection-1",
  108. sessionId: "session-1",
  109. uploadId: "capacity-overflow",
  110. chunkIndex: 0,
  111. dataBase64: "AA==",
  112. }),
  113. ).toThrow("fault.attachment.stagingCapacityExceeded");
  114. registry.clear();
  115. });
  116. it("incomplete commit 明确失败;TTL 到期释放 staging", async () => {
  117. let now = 0;
  118. const bytes = Buffer.from("two chunks");
  119. const put = vi.fn(async () => ({ ref: "unused" }));
  120. const registry = new AttachmentUploadRegistry({ now: () => now, putSessionAttachment: put });
  121. registry.begin(begin(bytes, "incomplete", 2));
  122. registry.chunk({
  123. connectionId: "connection-1",
  124. sessionId: "session-1",
  125. uploadId: "incomplete",
  126. chunkIndex: 0,
  127. dataBase64: Buffer.from("two ").toString("base64"),
  128. });
  129. await expect(
  130. registry.commit({
  131. connectionId: "connection-1",
  132. sessionId: "session-1",
  133. uploadId: "incomplete",
  134. }),
  135. ).rejects.toThrow("fault.attachment.uploadIncomplete");
  136. now = PROTOCOL_V4_LIMITS.attachmentUploadTtlMs + 1;
  137. registry.pruneExpired();
  138. await expect(
  139. registry.commit({
  140. connectionId: "connection-1",
  141. sessionId: "session-1",
  142. uploadId: "incomplete",
  143. }),
  144. ).rejects.toThrow("fault.attachment.uploadNotFound");
  145. expect(put).not.toHaveBeenCalled();
  146. });
  147. it("并发 commit single-flight,只写一个 artifact", async () => {
  148. const bytes = Buffer.from("single flight");
  149. let resolvePut!: (value: { ref: string }) => void;
  150. const put = vi.fn(
  151. () =>
  152. new Promise<{ ref: string }>((resolve) => {
  153. resolvePut = resolve;
  154. }),
  155. );
  156. const registry = new AttachmentUploadRegistry({ now: () => 0, putSessionAttachment: put });
  157. registry.begin(begin(bytes));
  158. registry.chunk({
  159. connectionId: "connection-1",
  160. sessionId: "session-1",
  161. uploadId: "upload-1",
  162. chunkIndex: 0,
  163. dataBase64: bytes.toString("base64"),
  164. });
  165. const terminal = {
  166. connectionId: "connection-1",
  167. sessionId: "session-1",
  168. uploadId: "upload-1",
  169. };
  170. const first = registry.commit(terminal);
  171. const second = registry.commit(terminal);
  172. await vi.waitFor(() => expect(put).toHaveBeenCalledTimes(1));
  173. resolvePut({ ref: "zcode-artifact://single" });
  174. await expect(Promise.all([first, second])).resolves.toEqual([
  175. { ref: "zcode-artifact://single" },
  176. { ref: "zcode-artifact://single" },
  177. ]);
  178. });
  179. });