Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AttachmentClaims.test.ts

304 lines11.0 KB

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 {
21 attachmentIsPendingUpload,
22 claimPendingAttachments,
23 releaseClaimedAttachments,
24} from "./AttachmentClaims.ts";
25​
26const layerTest = Layer.mergeAll(NodeServices.layer).pipe(
27 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-attachment-claims-" })),
28 Layer.provideMerge(NodeServices.layer),
29);
30​
31const stagePendingUpload = Effect.fn("test.stagePendingUpload")(function* (input: {
32 readonly name: string;
33 readonly bytes: Uint8Array;
34 readonly mimeType: string;
35}) {
36 const config = yield* ServerConfig.ServerConfig;
37 const pendingId = createPendingAttachmentId();
38 const attachment: ChatAttachment = {
39 type: "image",
40 id: ChatAttachmentId.make(pendingId!),
41 name: input.name,
42 mimeType: input.mimeType,
43 sizeBytes: input.bytes.byteLength,
44 };
45 yield* Effect.sync(() => {
46 NodeFS.mkdirSync(config.attachmentsDir, { recursive: true });
47 NodeFS.writeFileSync(NodePath.join(config.attachmentsDir, `${pendingId}.png`), input.bytes);
48 });
49 return attachment;
50});
51​
52describe("AttachmentClaims", () => {
53 it.effect("accepts 100 existing files without claiming new copies", () =>
54 Effect.gen(function* () {
55 const attachments: ChatAttachment[] = Array.from({ length: 100 }, (_, index) => ({
56 type: "file",
57 id: ChatAttachmentId.make(`existing-file-${index}`),
58 name: `${index}.txt`,
59 mimeType: "text/plain",
60 sizeBytes: 1,
61 }));
62 const claimed = yield* claimPendingAttachments({ threadId: "thread-many", attachments });
63 expect(claimed.attachments).toEqual(attachments);
64 expect(claimed.claimedPaths).toEqual([]);
65 }).pipe(Effect.provide(layerTest)),
66 );
67​
68 it.effect("rejects oversized image batches before copying a pending upload", () =>
69 Effect.gen(function* () {
70 const pending = yield* stagePendingUpload({
71 name: "pending.png",
72 bytes: new Uint8Array([1]),
73 mimeType: "image/png",
74 });
75 const images: ChatAttachment[] = Array.from({ length: 9 }, (_, index) => ({
76 type: "image",
77 id: ChatAttachmentId.make(`existing-image-${index}`),
78 name: `${index}.png`,
79 mimeType: "image/png",
80 sizeBytes: 10 * 1024 * 1024,
81 }));
82 const result = yield* Effect.exit(
83 claimPendingAttachments({
84 threadId: "thread-image-budget",
85 attachments: [pending, ...images],
86 }),
87 );
88 expect(result._tag).toBe("Failure");
89 if (result._tag === "Failure") expect(String(result.cause)).toContain("80 MiB");
90 const config = yield* ServerConfig.ServerConfig;
91 expect(NodeFS.readdirSync(config.attachmentsDir)).toHaveLength(1);
92 }).pipe(Effect.provide(layerTest)),
93 );
94​
95 it.effect("claims a pending upload into the thread store and rewrites the id", () =>
96 Effect.gen(function* () {
97 const pending = yield* stagePendingUpload({
98 name: "screenshot.png",
99 bytes: new Uint8Array([1, 2, 3, 4]),
100 mimeType: "image/png",
101 });
102 const config = yield* ServerConfig.ServerConfig;
103​
104 const claimed = yield* claimPendingAttachments({
105 threadId: "thread-claims-1",
106 attachments: [pending],
107 });
108​
109 expect(claimed.attachments).toHaveLength(1);
110 const attachment = claimed.attachments[0]!;
111 expect(attachmentIsPendingUpload(attachment)).toBe(false);
112 expect(parseThreadSegmentFromAttachmentId(attachment.id)).toBe("thread-claims-1");
113 expect(claimed.claimedPaths).toHaveLength(1);
114 expect(NodeFS.existsSync(claimed.claimedPaths[0]!)).toBe(true);
115 const pendingFiles = NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
116 entry.startsWith("pending-"),
117 );
118 expect(pendingFiles).toHaveLength(1);
119 }).pipe(Effect.provide(layerTest)),
120 );
121​
122 it.effect("passes already-claimed attachments through untouched", () =>
123 Effect.gen(function* () {
124 const stored: ChatAttachment = {
125 type: "image",
126 id: ChatAttachmentId.make("thread-claims-2-00000000-0000-4000-8000-000000000001"),
127 name: "existing.png",
128 mimeType: "image/png",
129 sizeBytes: 4,
130 };
131 const claimed = yield* claimPendingAttachments({
132 threadId: "thread-claims-2",
133 attachments: [stored],
134 });
135 expect(claimed.attachments[0]).toBe(stored);
136 expect(claimed.claimedPaths).toHaveLength(0);
137 }).pipe(Effect.provide(layerTest)),
138 );
139​
140 it.effect("rejects a pending ref whose staged file is missing", () =>
141 Effect.gen(function* () {
142 const missing: ChatAttachment = {
143 type: "image",
144 id: ChatAttachmentId.make(createPendingAttachmentId()!),
145 name: "gone.png",
146 mimeType: "image/png",
147 sizeBytes: 4,
148 };
149 const result = yield* Effect.exit(
150 claimPendingAttachments({ threadId: "thread-claims-3", attachments: [missing] }),
151 );
152 expect(result._tag).toBe("Failure");
153 }).pipe(Effect.provide(layerTest)),
154 );
155​
156 it.effect("rejects a size mismatch and cleans up earlier claims from the batch", () =>
157 Effect.gen(function* () {
158 const good = yield* stagePendingUpload({
159 name: "one.png",
160 bytes: new Uint8Array([1, 2, 3, 4]),
161 mimeType: "image/png",
162 });
163 const staged = yield* stagePendingUpload({
164 name: "two.png",
165 bytes: new Uint8Array([1, 2, 3, 4]),
166 mimeType: "image/png",
167 });
168 const mismatched = { ...staged, sizeBytes: 999 };
169 const config = yield* ServerConfig.ServerConfig;
170​
171 const result = yield* Effect.exit(
172 claimPendingAttachments({
173 threadId: "thread-claims-4",
174 attachments: [good, mismatched],
175 }),
176 );
177​
178 expect(result._tag).toBe("Failure");
179 if (result._tag === "Failure") {
180 const error = result.cause;
181 expect(String(error)).toContain("stored size does not match");
182 }
183 const claimedFiles = NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
184 entry.startsWith("thread-claims-4-"),
185 );
186 expect(claimedFiles).toHaveLength(0);
187 }).pipe(Effect.provide(layerTest)),
188 );
189​
190 it.effect("rejects duplicate attachment ids before copying anything", () =>
191 Effect.gen(function* () {
192 const pending = yield* stagePendingUpload({
193 name: "dupe.png",
194 bytes: new Uint8Array([5, 5, 5]),
195 mimeType: "image/png",
196 });
197 const config = yield* ServerConfig.ServerConfig;
198​
199 const result = yield* Effect.exit(
200 claimPendingAttachments({
201 threadId: "thread-claims-dupe",
202 attachments: [pending, pending],
203 }),
204 );
205​
206 expect(result._tag).toBe("Failure");
207 if (result._tag === "Failure") {
208 expect(String(result.cause)).toContain("Duplicate attachment ids");
209 }
210 expect(
211 NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
212 entry.startsWith("thread-claims-dupe-"),
213 ),
214 ).toHaveLength(0);
215 expect(
216 NodeFS.readdirSync(config.attachmentsDir).filter((entry) => entry.startsWith("pending-")),
217 ).toHaveLength(1);
218 }).pipe(Effect.provide(layerTest)),
219 );
220​
221 it.effect("rolls back a copy that finishes after the claim is interrupted", () =>
222 Effect.gen(function* () {
223 const pending = yield* stagePendingUpload({
224 name: "interrupt.png",
225 bytes: new Uint8Array([7, 7, 7]),
226 mimeType: "image/png",
227 });
228 const config = yield* ServerConfig.ServerConfig;
229 const fileSystem = yield* FileSystem.FileSystem;
230​
231 const copyArgs = yield* Deferred.make<readonly [string, string]>();
232 const copyDone = yield* Deferred.make<void>();
233 // fs.copyFile cannot be cancelled: the write runs on a separate fiber
234 // while the claim's copyFile only observes its completion, so the file
235 // still lands after the awaiting effect is interrupted.
236 const gatedFileSystem = Object.create(fileSystem, {
237 copyFile: {
238 value: (from: string, to: string) =>
239 Deferred.succeed(copyArgs, [from, to] as const).pipe(
240 Effect.andThen(Deferred.await(copyDone)),
241 ),
242 },
243 }) as FileSystem.FileSystem;
244​
245 const claimFiber = yield* claimPendingAttachments({
246 threadId: "thread-claims-interrupt",
247 attachments: [pending],
248 }).pipe(Effect.provideService(FileSystem.FileSystem, gatedFileSystem), Effect.forkChild);
249​
250 const [sourcePath, claimedPath] = yield* Deferred.await(copyArgs);
251 claimFiber.interruptUnsafe();
252 const writer = yield* fileSystem
253 .copyFile(sourcePath, claimedPath)
254 .pipe(Effect.ensuring(Deferred.succeed(copyDone, undefined)), Effect.forkChild);
255​
256 const exit = yield* Fiber.await(claimFiber);
257 const writerExit = yield* Fiber.await(writer);
258 expect(Exit.isSuccess(writerExit)).toBe(true);
259​
260 expect(Exit.hasInterrupts(exit)).toBe(true);
261 expect(NodeFS.existsSync(claimedPath)).toBe(false);
262 expect(NodeFS.existsSync(sourcePath)).toBe(true);
263 expect(
264 NodeFS.readdirSync(config.attachmentsDir).filter((entry) => entry.startsWith("pending-")),
265 ).toHaveLength(1);
266 }).pipe(Effect.provide(layerTest)),
267 );
268​
269 it.effect("releaseClaimedAttachments removes claimed copies best-effort", () =>
270 Effect.gen(function* () {
271 const pending = yield* stagePendingUpload({
272 name: "release.png",
273 bytes: new Uint8Array([9, 9]),
274 mimeType: "image/png",
275 });
276 const claimed = yield* claimPendingAttachments({
277 threadId: "thread-claims-5",
278 attachments: [pending],
279 });
280 expect(NodeFS.existsSync(claimed.claimedPaths[0]!)).toBe(true);
281 yield* releaseClaimedAttachments(claimed.claimedPaths);
282 expect(NodeFS.existsSync(claimed.claimedPaths[0]!)).toBe(false);
283 yield* releaseClaimedAttachments(claimed.claimedPaths);
284 }).pipe(Effect.provide(layerTest)),
285 );
286​
287 it.effect("treats malformed ids as non-pending and passes them through", () =>
288 Effect.gen(function* () {
289 const bogus: ChatAttachment = {
290 type: "image",
291 id: ChatAttachmentId.make("pending-not-a-uuid"),
292 name: "weird.png",
293 mimeType: "image/png",
294 sizeBytes: 1,
295 };
296 const claimed = yield* claimPendingAttachments({
297 threadId: "thread-claims-6",
298 attachments: [bogus],
299 });
300 expect(claimed.attachments[0]).toBe(bogus);
301 expect(claimed.claimedPaths).toHaveLength(0);
302 }).pipe(Effect.provide(layerTest)),
303 );
304});