Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFS from "node:fs";
3import * as NodePath from "node:path";
4
5import * as NodeServices from "@effect/platform-node/NodeServices";
6import { describe, expect, it } from "@effect/vitest";
7import { ChatAttachmentId, type ChatAttachment } from "@t3tools/contracts";
8import * as Deferred from "effect/Deferred";
9import * as Effect from "effect/Effect";
10import * as Exit from "effect/Exit";
11import * as Fiber from "effect/Fiber";
12import * as FileSystem from "effect/FileSystem";
13import * as Layer from "effect/Layer";
14
15import {
16 createPendingAttachmentId,
17 parseThreadSegmentFromAttachmentId,
18} from "../attachmentStore.ts";
19import * as ServerConfig from "../config.ts";
20import { attachmentIsPendingUpload, claimPendingAttachments } from "./AttachmentClaims.ts";
21
22const layerTest = Layer.mergeAll(NodeServices.layer).pipe(
23 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-attachment-claims-" })),
24 Layer.provideMerge(NodeServices.layer),
25);
26
27const stagePendingUpload = Effect.fn("test.stagePendingUpload")(function* (input: {
28 readonly name: string;
29 readonly bytes: Uint8Array;
30 readonly mimeType: string;
31}) {
32 const config = yield* ServerConfig.ServerConfig;
33 const pendingId = createPendingAttachmentId();
34 const attachment: ChatAttachment = {
35 type: "image",
36 id: ChatAttachmentId.make(pendingId!),
37 name: input.name,
38 mimeType: input.mimeType,
39 sizeBytes: input.bytes.byteLength,
40 };
41 yield* Effect.sync(() => {
42 NodeFS.mkdirSync(config.attachmentsDir, { recursive: true });
43 NodeFS.writeFileSync(NodePath.join(config.attachmentsDir, `${pendingId}.png`), input.bytes);
44 });
45 return attachment;
46});
47
48describe("AttachmentClaims", () => {
49 it.effect("rejects oversized image batches before copying a pending upload", () =>
50 Effect.gen(function* () {
51 const pending = yield* stagePendingUpload({
52 name: "pending.png",
53 bytes: new Uint8Array([1]),
54 mimeType: "image/png",
55 });
56 const images: ChatAttachment[] = Array.from({ length: 9 }, (_, index) => ({
57 type: "image",
58 id: ChatAttachmentId.make(`existing-image-${index}`),
59 name: `${index}.png`,
60 mimeType: "image/png",
61 sizeBytes: 10 * 1024 * 1024,
62 }));
63 const result = yield* Effect.exit(
64 claimPendingAttachments({
65 threadId: "thread-image-budget",
66 attachments: [pending, ...images],
67 }),
68 );
69 expect(result._tag).toBe("Failure");
70 if (result._tag === "Failure") expect(String(result.cause)).toContain("80 MiB");
71 const config = yield* ServerConfig.ServerConfig;
72 expect(NodeFS.readdirSync(config.attachmentsDir)).toHaveLength(1);
73 }).pipe(Effect.provide(layerTest)),
74 );
75
76 it.effect("claims a pending upload into the thread store and rewrites the id", () =>
77 Effect.gen(function* () {
78 const pending = yield* stagePendingUpload({
79 name: "screenshot.png",
80 bytes: new Uint8Array([1, 2, 3, 4]),
81 mimeType: "image/png",
82 });
83 const config = yield* ServerConfig.ServerConfig;
84
85 const claimed = yield* claimPendingAttachments({
86 threadId: "thread-claims-1",
87 attachments: [pending],
88 });
89
90 expect(claimed.attachments).toHaveLength(1);
91 const attachment = claimed.attachments[0]!;
92 expect(attachmentIsPendingUpload(attachment)).toBe(false);
93 expect(parseThreadSegmentFromAttachmentId(attachment.id)).toBe("thread-claims-1");
94 expect(claimed.claimedPaths).toHaveLength(1);
95 expect(NodeFS.existsSync(claimed.claimedPaths[0]!)).toBe(true);
96 const pendingFiles = NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
97 entry.startsWith("pending-"),
98 );
99 expect(pendingFiles).toHaveLength(1);
100 }).pipe(Effect.provide(layerTest)),
101 );
102
103 it.effect("rejects a size mismatch and cleans up earlier claims from the batch", () =>
104 Effect.gen(function* () {
105 const good = yield* stagePendingUpload({
106 name: "one.png",
107 bytes: new Uint8Array([1, 2, 3, 4]),
108 mimeType: "image/png",
109 });
110 const staged = yield* stagePendingUpload({
111 name: "two.png",
112 bytes: new Uint8Array([1, 2, 3, 4]),
113 mimeType: "image/png",
114 });
115 const mismatched = { ...staged, sizeBytes: 999 };
116 const config = yield* ServerConfig.ServerConfig;
117
118 const result = yield* Effect.exit(
119 claimPendingAttachments({
120 threadId: "thread-claims-4",
121 attachments: [good, mismatched],
122 }),
123 );
124
125 expect(result._tag).toBe("Failure");
126 if (result._tag === "Failure") {
127 const error = result.cause;
128 expect(String(error)).toContain("stored size does not match");
129 }
130 const claimedFiles = NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
131 entry.startsWith("thread-claims-4-"),
132 );
133 expect(claimedFiles).toHaveLength(0);
134 }).pipe(Effect.provide(layerTest)),
135 );
136
137 it.effect("rejects duplicate attachment ids before copying anything", () =>
138 Effect.gen(function* () {
139 const pending = yield* stagePendingUpload({
140 name: "dupe.png",
141 bytes: new Uint8Array([5, 5, 5]),
142 mimeType: "image/png",
143 });
144 const config = yield* ServerConfig.ServerConfig;
145
146 const result = yield* Effect.exit(
147 claimPendingAttachments({
148 threadId: "thread-claims-dupe",
149 attachments: [pending, pending],
150 }),
151 );
152
153 expect(result._tag).toBe("Failure");
154 if (result._tag === "Failure") {
155 expect(String(result.cause)).toContain("Duplicate attachment ids");
156 }
157 expect(
158 NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
159 entry.startsWith("thread-claims-dupe-"),
160 ),
161 ).toHaveLength(0);
162 expect(
163 NodeFS.readdirSync(config.attachmentsDir).filter((entry) => entry.startsWith("pending-")),
164 ).toHaveLength(1);
165 }).pipe(Effect.provide(layerTest)),
166 );
167
168 it.effect("rolls back a copy that finishes after the claim is interrupted", () =>
169 Effect.gen(function* () {
170 const pending = yield* stagePendingUpload({
171 name: "interrupt.png",
172 bytes: new Uint8Array([7, 7, 7]),
173 mimeType: "image/png",
174 });
175 const config = yield* ServerConfig.ServerConfig;
176 const fileSystem = yield* FileSystem.FileSystem;
177
178 const copyArgs = yield* Deferred.make<readonly [string, string]>();
179 const copyDone = yield* Deferred.make<void>();
180 // fs.copyFile cannot be cancelled: the write runs on a separate fiber
181 // while the claim's copyFile only observes its completion, so the file
182 // still lands after the awaiting effect is interrupted.
183 const gatedFileSystem = Object.create(fileSystem, {
184 copyFile: {
185 value: (from: string, to: string) =>
186 Deferred.succeed(copyArgs, [from, to] as const).pipe(
187 Effect.andThen(Deferred.await(copyDone)),
188 ),
189 },
190 }) as FileSystem.FileSystem;
191
192 const claimFiber = yield* claimPendingAttachments({
193 threadId: "thread-claims-interrupt",
194 attachments: [pending],
195 }).pipe(Effect.provideService(FileSystem.FileSystem, gatedFileSystem), Effect.forkChild);
196
197 const [sourcePath, claimedPath] = yield* Deferred.await(copyArgs);
198 claimFiber.interruptUnsafe();
199 const writer = yield* fileSystem
200 .copyFile(sourcePath, claimedPath)
201 .pipe(Effect.ensuring(Deferred.succeed(copyDone, undefined)), Effect.forkChild);
202
203 const exit = yield* Fiber.await(claimFiber);
204 const writerExit = yield* Fiber.await(writer);
205 expect(Exit.isSuccess(writerExit)).toBe(true);
206
207 expect(Exit.hasInterrupts(exit)).toBe(true);
208 expect(NodeFS.existsSync(claimedPath)).toBe(false);
209 expect(NodeFS.existsSync(sourcePath)).toBe(true);
210 expect(
211 NodeFS.readdirSync(config.attachmentsDir).filter((entry) => entry.startsWith("pending-")),
212 ).toHaveLength(1);
213 }).pipe(Effect.provide(layerTest)),
214 );
215});