v4AttachmentUploadTransaction.test.ts 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. import { createHash, webcrypto } from "node:crypto";
  2. import { describe, expect, it, vi } from "vitest";
  3. import { PROTOCOL_V4_LIMITS } from "@zcode/shared/zcode-protocol-v4";
  4. import {
  5. ATTACHMENT_UPLOAD_CHUNK_BYTES,
  6. measureAttachmentChannelRequestBytes,
  7. uploadAttachmentTransaction,
  8. type AttachmentUploadAgent,
  9. } from "../src/v4/attachmentUploadTransaction.js";
  10. if (!globalThis.crypto?.subtle) {
  11. Object.defineProperty(globalThis, "crypto", { value: webcrypto });
  12. }
  13. function input(bytes: Uint8Array) {
  14. return {
  15. sessionId: "session-1",
  16. fileName: "payload.bin",
  17. mime: "application/octet-stream",
  18. dataBase64: Buffer.from(bytes).toString("base64"),
  19. };
  20. }
  21. function agent(overrides: Partial<AttachmentUploadAgent> = {}): AttachmentUploadAgent {
  22. return {
  23. attachmentBeginV4: vi.fn(async (params) => ({
  24. uploadId: params.uploadId,
  25. state: "staging" as const,
  26. nextChunkIndex: 0,
  27. })),
  28. attachmentChunkV4: vi.fn(async (params) => ({
  29. uploadId: params.uploadId,
  30. nextChunkIndex: params.chunkIndex + 1,
  31. })),
  32. attachmentCommitV4: vi.fn(async () => ({ ref: "zcode-artifact://upload/one" })),
  33. attachmentAbortV4: vi.fn(async () => {}),
  34. ...overrides,
  35. };
  36. }
  37. describe("v4 attachment upload transaction", () => {
  38. it("20MiB exactly 分片成功,所有真实 Channel request <=1MiB", async () => {
  39. const bytes = new Uint8Array(PROTOCOL_V4_LIMITS.attachmentMaxBytes);
  40. const service = agent();
  41. await expect(
  42. uploadAttachmentTransaction(
  43. service,
  44. {
  45. workspacePath: "/workspace/含多字节路径",
  46. workspaceIdentity: "remote:ssh:test:/workspace/含多字节路径",
  47. },
  48. input(bytes),
  49. ),
  50. ).resolves.toEqual({ ref: "zcode-artifact://upload/one" });
  51. const expectedChunks = Math.ceil(bytes.byteLength / ATTACHMENT_UPLOAD_CHUNK_BYTES);
  52. expect(service.attachmentChunkV4).toHaveBeenCalledTimes(expectedChunks);
  53. for (const [params] of vi.mocked(service.attachmentChunkV4).mock.calls) {
  54. expect(Buffer.from(params.dataBase64, "base64").byteLength).toBeLessThanOrEqual(
  55. PROTOCOL_V4_LIMITS.attachmentChunkMaxBytes,
  56. );
  57. expect(measureAttachmentChannelRequestBytes("attachmentChunkV4", params)).toBeLessThanOrEqual(
  58. PROTOCOL_V4_LIMITS.maxFrameBytes,
  59. );
  60. }
  61. const begin = vi.mocked(service.attachmentBeginV4).mock.calls[0][0];
  62. expect(begin.checksum).toBe(`sha256:${createHash("sha256").update(bytes).digest("hex")}`);
  63. expect(begin.totalBytes).toBe(PROTOCOL_V4_LIMITS.attachmentMaxBytes);
  64. });
  65. it("20MiB+1 在 begin 前拒绝", async () => {
  66. const service = agent();
  67. await expect(
  68. uploadAttachmentTransaction(
  69. service,
  70. { workspacePath: "/workspace" },
  71. input(new Uint8Array(PROTOCOL_V4_LIMITS.attachmentMaxBytes + 1)),
  72. ),
  73. ).rejects.toThrow("proto.payloadTooLarge");
  74. expect(service.attachmentBeginV4).not.toHaveBeenCalled();
  75. });
  76. it("非法 base64 在 begin 前拒绝", async () => {
  77. const service = agent();
  78. await expect(
  79. uploadAttachmentTransaction(
  80. service,
  81. { workspacePath: "/workspace" },
  82. {
  83. ...input(new Uint8Array()),
  84. dataBase64: "%%%=",
  85. },
  86. ),
  87. ).rejects.toThrow("proto.invalidBase64");
  88. expect(service.attachmentBeginV4).not.toHaveBeenCalled();
  89. });
  90. it("chunk 失败 abort,但不修改调用者持有的 attachment payload", async () => {
  91. const original = input(Buffer.from("preserve me"));
  92. const service = agent({
  93. attachmentChunkV4: vi.fn(async () => {
  94. throw new Error("fault.injected");
  95. }),
  96. });
  97. await expect(
  98. uploadAttachmentTransaction(service, { workspacePath: "/workspace" }, original),
  99. ).rejects.toThrow("fault.injected");
  100. expect(service.attachmentAbortV4).toHaveBeenCalledTimes(1);
  101. expect(original).toEqual(input(Buffer.from("preserve me")));
  102. });
  103. it("begin retry 已 committed 时直接复用 ref,不重复 chunk/artifact", async () => {
  104. const service = agent({
  105. attachmentBeginV4: vi.fn(async (params) => ({
  106. uploadId: params.uploadId,
  107. state: "committed" as const,
  108. nextChunkIndex: 1,
  109. ref: "zcode-artifact://upload/existing",
  110. })),
  111. });
  112. await expect(
  113. uploadAttachmentTransaction(
  114. service,
  115. { workspacePath: "/workspace" },
  116. input(Buffer.from("already there")),
  117. ),
  118. ).resolves.toEqual({ ref: "zcode-artifact://upload/existing" });
  119. expect(service.attachmentChunkV4).not.toHaveBeenCalled();
  120. expect(service.attachmentCommitV4).not.toHaveBeenCalled();
  121. });
  122. it("分块进度单调递增,并在 commit 前切换为 committing", async () => {
  123. const bytes = new Uint8Array(ATTACHMENT_UPLOAD_CHUNK_BYTES * 2 + 7);
  124. const service = agent();
  125. const progress: Array<{
  126. phase: "uploading" | "committing";
  127. uploadedBytes: number;
  128. totalBytes: number;
  129. }> = [];
  130. await uploadAttachmentTransaction(service, { workspacePath: "/workspace" }, input(bytes), {
  131. onProgress: (value) => progress.push(value),
  132. });
  133. expect(progress.at(-1)).toEqual({
  134. phase: "committing",
  135. uploadedBytes: bytes.byteLength,
  136. totalBytes: bytes.byteLength,
  137. });
  138. expect(progress.some((value) => value.phase === "uploading")).toBe(true);
  139. const uploadedBytes = progress.map((value) => value.uploadedBytes);
  140. const sortedUploadedBytes = progress.map((value) => value.uploadedBytes).sort((a, b) => a - b);
  141. expect(uploadedBytes).toEqual(sortedUploadedBytes);
  142. expect(progress.filter((value) => value.phase === "uploading").at(-1)?.uploadedBytes).toBe(
  143. bytes.byteLength,
  144. );
  145. });
  146. it("AbortSignal 在分块之间取消并调用 abort,不进入 commit", async () => {
  147. const controller = new AbortController();
  148. const service = agent({
  149. attachmentChunkV4: vi.fn(async (params) => {
  150. controller.abort();
  151. return {
  152. uploadId: params.uploadId,
  153. nextChunkIndex: params.chunkIndex + 1,
  154. };
  155. }),
  156. });
  157. await expect(
  158. uploadAttachmentTransaction(
  159. service,
  160. { workspacePath: "/workspace" },
  161. input(new Uint8Array(ATTACHMENT_UPLOAD_CHUNK_BYTES + 1)),
  162. { signal: controller.signal },
  163. ),
  164. ).rejects.toMatchObject({ name: "AbortError" });
  165. expect(service.attachmentChunkV4).toHaveBeenCalledTimes(1);
  166. expect(service.attachmentCommitV4).not.toHaveBeenCalled();
  167. expect(service.attachmentAbortV4).toHaveBeenCalledTimes(1);
  168. });
  169. });