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

attachmentUpload.test.ts

594 lines19.1 KB

1import { EnvironmentId } from "@t3tools/contracts";
2import * as Option from "effect/Option";
3import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
4​
5const mocks = vi.hoisted(() => ({
6 documentUri: "file:///documents",
7 createAssetUrl: vi.fn(),
8 createUploadUrl: Symbol("create-upload-url"),
9 executeAtomQuery: vi.fn(),
10 removeUpload: Symbol("remove-upload"),
11 preparedConnection: Symbol("prepared-connection"),
12 runAtomCommand: vi.fn(),
13 readAtom: vi.fn(),
14 upload: vi.fn(),
15 writeFile: vi.fn(),
16 deleteFile: vi.fn(),
17}));
18​
19vi.mock("@t3tools/client-runtime/state/runtime", () => ({
20 // The client-runtime attachments module resolves the same file through its
21 // relative import, so these fakes also feed runAttachmentUploadCycle and
22 // verifyPersistedAttachmentUpload.
23 createEnvironmentRpcCommand: () => Symbol("rpc-command"),
24 executeAtomQuery: mocks.executeAtomQuery,
25 runAtomCommand: mocks.runAtomCommand,
26 squashAtomCommandFailure: (result: { readonly error: unknown }) => result.error,
27}));
28​
29vi.mock("../state/atom-registry", () => ({
30 appAtomRegistry: { get: mocks.readAtom },
31}));
32​
33vi.mock("../state/assets", () => ({
34 assetEnvironment: { createUrl: mocks.createAssetUrl },
35}));
36​
37vi.mock("../state/attachments", () => ({
38 attachmentEnvironment: {
39 createUploadUrl: mocks.createUploadUrl,
40 remove: mocks.removeUpload,
41 },
42}));
43​
44vi.mock("../state/session", () => ({
45 environmentSession: {
46 preparedConnectionValueAtom: () => mocks.preparedConnection,
47 },
48}));
49​
50// Cuts the expo-crypto -> react-native import chain out of the test graph.
51vi.mock("./uuid", () => ({
52 uuidv4: () => "uuid",
53 randomHex: () => "0000",
54}));
55​
56vi.mock("expo-file-system", () => ({
57 File: class {
58 readonly uri: string;
59 exists = true;
60 constructor(uri: string, name?: string) {
61 this.uri = name ? `${uri}/${name}` : uri;
62 }
63 create() {}
64 write(bytes: string, options: unknown) {
65 mocks.writeFile(this.uri, bytes, options);
66 }
67 delete() {
68 mocks.deleteFile(this.uri);
69 }
70​
71 upload(url: string, options: unknown) {
72 return mocks.upload(this.uri, url, options);
73 }
74 },
75 Paths: {
76 cache: "file:///cache",
77 get document() {
78 return { uri: mocks.documentUri };
79 },
80 },
81 UploadType: { BINARY_CONTENT: 0 },
82}));
83​
84import {
85 prepareTurnAttachments,
86 releasePendingAttachmentUploads,
87 withUploadedMobileAttachmentReferences,
88 validateDraftFileAttachments,
89} from "./attachmentUpload";
90import type { DraftComposerAttachment } from "./composerImages";
91​
92const environmentId = EnvironmentId.make("environment-1");
93const MINTED_ID = "pending-00000000-0000-4000-8000-000000000001-pdf";
94​
95const image = {
96 id: "image-1",
97 type: "image",
98 name: "screenshot.png",
99 mimeType: "image/png",
100 sizeBytes: 3,
101 dataUrl: "data:image/png;base64,YWJj",
102 previewUri: "file:///images/screenshot.png",
103} as const satisfies DraftComposerAttachment;
104​
105const file = {
106 id: "file-1",
107 type: "file",
108 name: "report.pdf",
109 mimeType: "application/pdf",
110 sizeBytes: 42,
111 fileUri: "file:///documents/report.pdf",
112} as const satisfies DraftComposerAttachment;
113​
114describe("validateDraftFileAttachments", () => {
115 it("allows legacy image-only sends without server config", () => {
116 expect(validateDraftFileAttachments({ attachments: [image], serverConfig: null })).toBeNull();
117 });
118​
119 it("blocks files while config is unknown or file uploads are unsupported", () => {
120 expect(validateDraftFileAttachments({ attachments: [file], serverConfig: null })).toBe(
121 "Server attachment support is still loading.",
122 );
123 expect(
124 validateDraftFileAttachments({
125 attachments: [file],
126 serverConfig: { environment: { capabilities: { attachmentUploads: true } } },
127 }),
128 ).toBe("This server does not support file attachments.");
129 });
130​
131 it("uses the current clamped limit and allows valid mixed attachments", () => {
132 const lowerLimit = {
133 environment: {
134 capabilities: {
135 attachmentUploads: true,
136 fileAttachments: { maxUploadBytes: 20 },
137 },
138 },
139 };
140 expect(validateDraftFileAttachments({ attachments: [file], serverConfig: lowerLimit })).toBe(
141 "'report.pdf' exceeds the 20 bytes attachment limit.",
142 );
143 const allowed = {
144 environment: {
145 capabilities: {
146 attachmentUploads: true,
147 fileAttachments: { maxUploadBytes: 100 },
148 },
149 },
150 };
151 expect(
152 validateDraftFileAttachments({ attachments: [image, file], serverConfig: allowed }),
153 ).toBeNull();
154 });
155});
156​
157function removeCallsFor(attachmentId: string): number {
158 return mocks.runAtomCommand.mock.calls.filter(
159 ([, command, target]) =>
160 command === mocks.removeUpload &&
161 (target as { input: { attachmentId: string } }).input.attachmentId === attachmentId,
162 ).length;
164​
165describe("prepareTurnAttachments", () => {
166 beforeEach(() => {
167 mocks.documentUri = "file:///documents";
168 mocks.createAssetUrl.mockReset();
169 mocks.createAssetUrl.mockImplementation((target: unknown) => target);
170 mocks.executeAtomQuery.mockReset();
171 mocks.executeAtomQuery.mockResolvedValue({ _tag: "Success", value: {} });
172 mocks.runAtomCommand.mockReset();
173 mocks.readAtom.mockReset();
174 mocks.upload.mockReset();
175 mocks.writeFile.mockReset();
176 mocks.deleteFile.mockReset();
177 mocks.readAtom.mockReturnValue(Option.some({ httpBaseUrl: "https://environment.example/" }));
178 mocks.runAtomCommand.mockImplementation(async (_registry: unknown, command: unknown) =>
179 command === mocks.createUploadUrl
180 ? {
181 _tag: "Success",
182 value: {
183 attachmentId: MINTED_ID,
184 relativeUrl: "/api/attachments/upload/signed",
185 expiresAt: 1,
186 },
187 }
188 : { _tag: "Success", value: undefined },
189 );
190 mocks.upload.mockResolvedValue({ status: 204, body: "", headers: {} });
191 });
192​
193 it("keeps existing image attachments on the legacy wire path", async () => {
194 const prepared = await prepareTurnAttachments({ environmentId, attachments: [image] });
195​
196 expect(prepared.status).toBe("ready");
197 if (prepared.status !== "ready") return;
198 expect(prepared.attachments).toEqual([
199 {
200 type: "image",
201 name: "screenshot.png",
202 mimeType: "image/png",
203 sizeBytes: 3,
204 dataUrl: "data:image/png;base64,YWJj",
205 },
206 ]);
207 expect(prepared.pendingAttachmentIds).toEqual([]);
208 expect(mocks.upload).not.toHaveBeenCalled();
209 });
210​
211 it("uploads generic file bytes directly and keeps mixed attachment order", async () => {
212 const prepared = await prepareTurnAttachments({ environmentId, attachments: [file, image] });
213​
214 expect(mocks.upload).toHaveBeenCalledWith(
215 "file:///documents/report.pdf",
216 "https://environment.example/api/attachments/upload/signed",
217 expect.objectContaining({
218 httpMethod: "POST",
219 uploadType: 0,
220 headers: { "Content-Type": "application/pdf" },
221 }),
222 );
223 expect(prepared.status).toBe("ready");
224 if (prepared.status !== "ready") return;
225 expect(prepared.attachments[0]).toEqual({
226 type: "file",
227 id: MINTED_ID,
228 name: "report.pdf",
229 mimeType: "application/pdf",
230 sizeBytes: 42,
231 });
232 expect(prepared.attachments[1]?.type).toBe("image");
233 expect(prepared.pendingAttachmentIds).toEqual([MINTED_ID]);
234 expect(prepared.draftAttachments[0]).toEqual({
235 ...file,
236 uploadedAttachmentId: MINTED_ID,
237 uploadEnvironmentId: environmentId,
238 });
239 });
240​
241 it("uses the current connection when an environment reconnects during URL creation", async () => {
242 mocks.readAtom
243 .mockReturnValueOnce(Option.some({ httpBaseUrl: "https://old-environment.example/" }))
244 .mockReturnValueOnce(Option.some({ httpBaseUrl: "https://new-environment.example/" }));
245​
246 await prepareTurnAttachments({ environmentId, attachments: [file] });
247​
248 expect(mocks.upload).toHaveBeenCalledWith(
249 file.fileUri,
250 "https://new-environment.example/api/attachments/upload/signed",
251 expect.anything(),
252 );
253 });
254​
255 it("uploads a restored draft file from the current iOS document container", async () => {
256 const fileName = "33333333-3333-4333-8333-333333333333-report%20%23.pdf";
257 const restoredFile = {
258 ...file,
259 fileUri: `file:///private/var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`,
260 };
261 mocks.documentUri =
262 "file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents";
263 const currentUri = `${mocks.documentUri}/t3-composer-attachments/${fileName}`;
264 mocks.upload.mockImplementation(async (uri: string) => {
265 if (uri !== currentUri) {
266 throw new Error("File does not exist in the previous application container.");
267 }
268 return { status: 204, body: "", headers: {} };
269 });
270​
271 const prepared = await prepareTurnAttachments({
272 environmentId,
273 attachments: [restoredFile],
274 });
275​
276 expect(prepared.status).toBe("ready");
277 expect(mocks.upload).toHaveBeenCalledWith(
278 currentUri,
279 "https://environment.example/api/attachments/upload/signed",
280 expect.anything(),
281 );
282 });
283​
284 it("adds uploaded file references to durable drafts without changing images", () => {
285 expect(
286 withUploadedMobileAttachmentReferences({
287 environmentId,
288 attachments: [file, image],
289 uploadedAttachments: [
290 {
291 type: "file",
292 id: "pending-existing-pdf",
293 name: file.name,
294 mimeType: file.mimeType,
295 sizeBytes: file.sizeBytes,
296 },
297 {
298 type: "image",
299 name: image.name,
300 mimeType: image.mimeType,
301 sizeBytes: image.sizeBytes,
302 dataUrl: image.dataUrl,
303 },
304 ],
305 }),
306 ).toEqual([
307 {
308 ...file,
309 uploadedAttachmentId: "pending-existing-pdf",
310 uploadEnvironmentId: environmentId,
311 },
312 image,
313 ]);
314 });
315​
316 it("reuses a pending file upload from a previous outbox attempt", async () => {
317 const previouslyUploaded = {
318 ...file,
319 uploadedAttachmentId: "pending-existing-pdf",
320 uploadEnvironmentId: environmentId,
321 };
322​
323 const prepared = await prepareTurnAttachments({
324 environmentId,
325 attachments: [previouslyUploaded, image],
326 });
327​
328 expect(prepared.status).toBe("ready");
329 if (prepared.status !== "ready") return;
330 expect(prepared.attachments).toEqual([
331 {
332 type: "file",
333 id: "pending-existing-pdf",
334 name: "report.pdf",
335 mimeType: "application/pdf",
336 sizeBytes: 42,
337 },
338 {
339 type: "image",
340 name: "screenshot.png",
341 mimeType: "image/png",
342 sizeBytes: 3,
343 dataUrl: "data:image/png;base64,YWJj",
344 },
345 ]);
346 expect(prepared.pendingAttachmentIds).toEqual(["pending-existing-pdf"]);
347 expect(mocks.upload).not.toHaveBeenCalled();
348 expect(mocks.runAtomCommand).not.toHaveBeenCalled();
349 });
350​
351 it("uploads a file again when its saved pending upload has expired", async () => {
352 mocks.executeAtomQuery.mockResolvedValueOnce({
353 _tag: "Failure",
354 error: { _tag: "AssetAttachmentNotFoundError" },
355 });
356 const previouslyUploaded = {
357 ...file,
358 uploadedAttachmentId: "pending-expired-pdf",
359 uploadEnvironmentId: environmentId,
360 };
361​
362 const prepared = await prepareTurnAttachments({
363 environmentId,
364 attachments: [previouslyUploaded],
365 });
366​
367 expect(mocks.upload).toHaveBeenCalledOnce();
368 expect(prepared.status).toBe("ready");
369 if (prepared.status !== "ready") return;
370 expect(prepared.pendingAttachmentIds).toEqual([MINTED_ID]);
371 });
372​
373 it("uploads image bytes over HTTP while retaining the durable offline image", async () => {
374 const persisted = vi.fn(async () => "persisted" as const);
375 const prepared = await prepareTurnAttachments({
376 environmentId,
377 attachments: [image],
378 supportsImageUploads: true,
379 persistUploadedReferences: persisted,
380 });
381 expect(mocks.writeFile).toHaveBeenCalledWith("file:///cache/t3-upload-uuid", "YWJj", {
382 encoding: "base64",
383 });
384 expect(mocks.upload).toHaveBeenCalledWith(
385 "file:///cache/t3-upload-uuid",
386 "https://environment.example/api/attachments/upload/signed",
387 expect.objectContaining({ headers: { "Content-Type": "image/png" } }),
388 );
389 expect(mocks.deleteFile).toHaveBeenCalledExactlyOnceWith("file:///cache/t3-upload-uuid");
390 expect(prepared.status).toBe("ready");
391 if (prepared.status !== "ready") return;
392 expect(prepared.attachments).toEqual([
393 {
394 type: "image",
395 id: MINTED_ID,
396 name: image.name,
397 mimeType: image.mimeType,
398 sizeBytes: image.sizeBytes,
399 },
400 ]);
401 expect(prepared.draftAttachments).toEqual([
402 { ...image, uploadedAttachmentId: MINTED_ID, uploadEnvironmentId: environmentId },
403 ]);
404 expect(persisted).toHaveBeenCalledWith(prepared.draftAttachments);
405 });
406​
407 it("reuses an uploaded image and reuploads its local bytes after server expiry", async () => {
408 const saved = {
409 ...image,
410 uploadedAttachmentId: "saved-image",
411 uploadEnvironmentId: environmentId,
412 };
413 const reused = await prepareTurnAttachments({
414 environmentId,
415 attachments: [saved],
416 supportsImageUploads: true,
417 });
418 expect(reused.status === "ready" && reused.attachments[0]).toEqual({
419 type: "image",
420 id: "saved-image",
421 name: image.name,
422 mimeType: image.mimeType,
423 sizeBytes: image.sizeBytes,
424 });
425 expect(mocks.upload).not.toHaveBeenCalled();
426 mocks.executeAtomQuery.mockResolvedValueOnce({
427 _tag: "Failure",
428 error: { _tag: "AssetAttachmentNotFoundError" },
429 });
430 const restored = await prepareTurnAttachments({
431 environmentId,
432 attachments: [saved],
433 supportsImageUploads: true,
434 });
435 expect(restored.status === "ready" && restored.draftAttachments[0]).toEqual({
436 ...saved,
437 uploadedAttachmentId: MINTED_ID,
438 });
439 expect(mocks.writeFile).toHaveBeenCalledWith("file:///cache/t3-upload-uuid", "YWJj", {
440 encoding: "base64",
441 });
442 });
443​
444 it("does not reuse an image upload from another environment", async () => {
445 const prepared = await prepareTurnAttachments({
446 environmentId,
447 attachments: [
448 {
449 ...image,
450 uploadedAttachmentId: "other-image",
451 uploadEnvironmentId: EnvironmentId.make("other"),
452 },
453 ],
454 supportsImageUploads: true,
455 });
456 expect(mocks.executeAtomQuery).not.toHaveBeenCalled();
457 expect(mocks.upload).toHaveBeenCalledOnce();
458 expect(prepared.status === "ready" && prepared.draftAttachments[0]?.uploadEnvironmentId).toBe(
459 environmentId,
460 );
461 });
462​
463 it("aborts an active transfer without dropping local bytes or stamping a partial upload", async () => {
464 const started = Promise.withResolvers<void>();
465 const controller = new AbortController();
466 const persist = vi.fn(async () => "persisted" as const);
467 mocks.upload.mockImplementation(
468 (_uri: string, _url: string, options: { signal: AbortSignal }) =>
469 new Promise((_, reject) => {
470 options.signal.addEventListener("abort", () => reject(new Error("cancelled")), {
471 once: true,
472 });
473 started.resolve();
474 }),
475 );
476 const preparing = prepareTurnAttachments({
477 environmentId,
478 attachments: [file],
479 signal: controller.signal,
480 persistUploadedReferences: persist,
481 });
482 await started.promise;
483 controller.abort();
484 expect(await preparing).toEqual({ status: "abandoned" });
485 expect(persist).not.toHaveBeenCalled();
486 expect(mocks.deleteFile).not.toHaveBeenCalled();
487 expect(removeCallsFor(MINTED_ID)).toBe(1);
488 });
489​
490 it("removes pending uploads when the native HTTP request fails", async () => {
491 mocks.upload.mockResolvedValue({ status: 500, body: "failed", headers: {} });
492​
493 await expect(prepareTurnAttachments({ environmentId, attachments: [file] })).rejects.toThrow(
494 "Upload failed for 'report.pdf' (500).",
495 );
496 expect(removeCallsFor(MINTED_ID)).toBe(1);
497 });
498​
499 it("keeps a previously persisted upload when a later attachment fails", async () => {
500 const previouslyUploaded = {
501 ...file,
502 id: "file-existing",
503 uploadedAttachmentId: "pending-existing-pdf",
504 uploadEnvironmentId: environmentId,
505 };
506 mocks.upload.mockResolvedValue({ status: 500, body: "failed", headers: {} });
507​
508 await expect(
509 prepareTurnAttachments({ environmentId, attachments: [previouslyUploaded, file] }),
510 ).rejects.toThrow("Upload failed for 'report.pdf' (500).");
511​
512 expect(removeCallsFor("pending-existing-pdf")).toBe(0);
513 });
514​
515 it("deletes the minted uploads when the owner abandons the send", async () => {
516 const result = await prepareTurnAttachments({
517 environmentId,
518 attachments: [file],
519 persistUploadedReferences: async () => "abandon",
520 });
521​
522 expect(result.status).toBe("abandoned");
523 expect(removeCallsFor(MINTED_ID)).toBe(1);
524 });
525​
526 it("deletes the minted uploads when persisting the references throws", async () => {
527 await expect(
528 prepareTurnAttachments({
529 environmentId,
530 attachments: [file],
531 persistUploadedReferences: async () => {
532 throw new Error("draft write failed");
533 },
534 }),
535 ).rejects.toThrow("draft write failed");
536​
537 expect(removeCallsFor(MINTED_ID)).toBe(1);
538 });
539​
540 it("skips persisting when every reference is already stored", async () => {
541 const previouslyUploaded = {
542 ...file,
543 uploadedAttachmentId: "pending-existing-pdf",
544 uploadEnvironmentId: environmentId,
545 };
546 const persist = vi.fn(async () => "persisted" as const);
547​
548 const prepared = await prepareTurnAttachments({
549 environmentId,
550 attachments: [previouslyUploaded],
551 persistUploadedReferences: persist,
552 });
553​
554 expect(prepared.status).toBe("ready");
555 expect(persist).not.toHaveBeenCalled();
556 });
557});
558​
559describe("releasePendingAttachmentUploads", () => {
560 beforeEach(() => {
561 mocks.runAtomCommand.mockReset();
562 });
563​
564 it("retries a failed delete once before reporting it", async () => {
565 mocks.runAtomCommand
566 .mockResolvedValueOnce({ _tag: "Failure", error: new Error("offline") })
567 .mockResolvedValue({ _tag: "Success", value: undefined });
568​
569 await expect(
570 releasePendingAttachmentUploads(environmentId, ["pending-a"]),
571 ).resolves.toBeUndefined();
572 expect(mocks.runAtomCommand).toHaveBeenCalledTimes(2);
573 });
574​
575 it("throws when a delete keeps failing so the caller sees the leak", async () => {
576 mocks.runAtomCommand.mockResolvedValue({ _tag: "Failure", error: new Error("offline") });
577​
578 await expect(releasePendingAttachmentUploads(environmentId, ["pending-a"])).rejects.toThrow(
579 "pending-a",
580 );
581 });
582​
583 it("treats an already-deleted pending upload as released", async () => {
584 mocks.runAtomCommand.mockResolvedValue({
585 _tag: "Failure",
586 error: { _tag: "AssetAttachmentNotFoundError" },
587 });
588​
589 await expect(
590 releasePendingAttachmentUploads(environmentId, ["pending-a"]),
591 ).resolves.toBeUndefined();
592 expect(mocks.runAtomCommand).toHaveBeenCalledTimes(1);
593 });
594});