topicResourceRelayClient.test.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { describe, expect, it, vi } from "vitest";
  2. import { createHash } from "node:crypto";
  3. import type { IChannel } from "@zcode/rpc";
  4. import { readTopicResourceFromRelay } from "../src/zcode-agent/topicResourceRelayClient.js";
  5. import { TOPIC_RESOURCE_RELAY_CHUNK_BYTES } from "@zcode/shared";
  6. const request = {
  7. requestId: "r",
  8. taskId: "t",
  9. inputId: "i",
  10. authorizationId: "a",
  11. messageId: "m",
  12. resourceIndex: 0,
  13. workspacePath: "/work",
  14. workspaceIdentity: "ssh://host/work",
  15. remoteSessionId: "remote",
  16. };
  17. describe("topic resource reverse transfer client", () => {
  18. it("assembles bounded chunks and verifies the file before returning it", async () => {
  19. const data = Buffer.alloc(TOPIC_RESOURCE_RELAY_CHUNK_BYTES + 7, 65);
  20. const call = vi.fn(async (command: string, value: { index?: number }) => {
  21. if (command === "begin")
  22. return {
  23. fileName: "a.txt",
  24. mime: "text/plain",
  25. bytes: data.length,
  26. totalChunks: 2,
  27. checksum: `sha256:${createHash("sha256").update(data).digest("hex")}`,
  28. };
  29. if (command === "chunk")
  30. return {
  31. dataBase64: data
  32. .subarray(
  33. value.index! * TOPIC_RESOURCE_RELAY_CHUNK_BYTES,
  34. (value.index! + 1) * TOPIC_RESOURCE_RELAY_CHUNK_BYTES,
  35. )
  36. .toString("base64"),
  37. };
  38. return { completed: true };
  39. });
  40. const output = await readTopicResourceFromRelay(
  41. { call } as unknown as IChannel,
  42. request,
  43. new AbortController().signal,
  44. );
  45. expect(output.dataBase64).toBe(data.toString("base64"));
  46. expect(call.mock.calls.map(([command]) => command)).toEqual([
  47. "begin",
  48. "chunk",
  49. "chunk",
  50. "finish",
  51. ]);
  52. });
  53. it("rejects corrupted bytes and cancels instead of finishing the transfer", async () => {
  54. const call = vi.fn(async (command: string) => {
  55. if (command === "begin")
  56. return {
  57. fileName: "a.txt",
  58. mime: "text/plain",
  59. bytes: 1,
  60. totalChunks: 1,
  61. checksum: `sha256:${createHash("sha256").update("a").digest("hex")}`,
  62. };
  63. return { dataBase64: "Yg==" };
  64. });
  65. await expect(
  66. readTopicResourceFromRelay(
  67. { call } as unknown as IChannel,
  68. request,
  69. new AbortController().signal,
  70. ),
  71. ).rejects.toThrow("checksum");
  72. expect(call.mock.calls.map(([command]) => command)).toEqual(["begin", "chunk", "cancel"]);
  73. });
  74. });