attachment-upload-registry.test.ts 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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(() =>
  58. registry.begin(begin(empty, "upload-overflow", 0)),
  59. ).toThrow("fault.attachment.tooManyUploads");
  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("CLI registry 换代后半上传不存在,不自动 replay bytes", async () => {
  148. const bytes = Buffer.from("restart pending");
  149. const put = vi.fn(async () => ({ ref: "unused" }));
  150. const beforeRestart = new AttachmentUploadRegistry({
  151. now: () => 0,
  152. putSessionAttachment: put,
  153. });
  154. beforeRestart.begin(begin(bytes, "restart-upload"));
  155. beforeRestart.chunk({
  156. connectionId: "connection-1",
  157. sessionId: "session-1",
  158. uploadId: "restart-upload",
  159. chunkIndex: 0,
  160. dataBase64: bytes.toString("base64"),
  161. });
  162. beforeRestart.clear();
  163. const afterRestart = new AttachmentUploadRegistry({
  164. now: () => 1,
  165. putSessionAttachment: put,
  166. });
  167. await expect(
  168. afterRestart.commit({
  169. connectionId: "connection-1",
  170. sessionId: "session-1",
  171. uploadId: "restart-upload",
  172. }),
  173. ).rejects.toThrow("fault.attachment.uploadNotFound");
  174. expect(put).not.toHaveBeenCalled();
  175. });
  176. it("并发 commit single-flight,只写一个 artifact", async () => {
  177. const bytes = Buffer.from("single flight");
  178. let resolvePut!: (value: { ref: string }) => void;
  179. const put = vi.fn(
  180. () =>
  181. new Promise<{ ref: string }>((resolve) => {
  182. resolvePut = resolve;
  183. }),
  184. );
  185. const registry = new AttachmentUploadRegistry({ now: () => 0, putSessionAttachment: put });
  186. registry.begin(begin(bytes));
  187. registry.chunk({
  188. connectionId: "connection-1",
  189. sessionId: "session-1",
  190. uploadId: "upload-1",
  191. chunkIndex: 0,
  192. dataBase64: bytes.toString("base64"),
  193. });
  194. const terminal = {
  195. connectionId: "connection-1",
  196. sessionId: "session-1",
  197. uploadId: "upload-1",
  198. };
  199. const first = registry.commit(terminal);
  200. const second = registry.commit(terminal);
  201. await vi.waitFor(() => expect(put).toHaveBeenCalledTimes(1));
  202. resolvePut({ ref: "zcode-artifact://single" });
  203. await expect(Promise.all([first, second])).resolves.toEqual([
  204. { ref: "zcode-artifact://single" },
  205. { ref: "zcode-artifact://single" },
  206. ]);
  207. });
  208. });