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

attachmentUploadQueue.test.ts

840 lines26.9 KB

1import { EnvironmentId } from "@t3tools/contracts";
2import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
3​
4import {
5 composerFileNeedsReattach,
6 DraftId,
7 useComposerDraftStore,
8 type ComposerFileAttachment,
9 type ComposerImageAttachment,
10} from "../composerDraftStore";
11​
12const mocks = vi.hoisted(() => ({
13 createAssetUrl: vi.fn(),
14 createUploadUrl: Symbol("create-upload-url"),
15 executeAtomQuery: vi.fn(),
16 removeUpload: Symbol("remove-upload"),
17 runAtomCommand: vi.fn(),
18 readPreparedConnection: vi.fn(),
19}));
20​
21vi.mock("@t3tools/client-runtime/state/runtime", () => ({
22 executeAtomQuery: mocks.executeAtomQuery,
23 runAtomCommand: mocks.runAtomCommand,
24 squashAtomCommandFailure: (result: { readonly error: unknown }) => result.error,
25}));
26​
27vi.mock("../rpc/atomRegistry", () => ({ appAtomRegistry: {} }));
28​
29vi.mock("../state/assets", () => ({
30 assetEnvironment: { createUrl: mocks.createAssetUrl },
31}));
32​
33vi.mock("../state/attachments", () => ({
34 attachmentEnvironment: {
35 createUploadUrl: mocks.createUploadUrl,
36 remove: mocks.removeUpload,
37 },
38}));
39​
40vi.mock("../state/session", () => ({
41 readPreparedConnection: mocks.readPreparedConnection,
42}));
43​
44import {
45 awaitAttachmentUploads,
46 getUploadedAttachments,
47 readAttachmentUpload,
48 releaseAttachmentUpload,
49 releaseDraftAttachment,
50 releaseDraftAttachments,
51 releasePersistedAttachmentUpload,
52 retryAttachmentUpload,
53 startAttachmentUpload,
54 useAttachmentUploadStore,
55} from "./attachmentUploadQueue";
56​
57type ProgressListener = (event: {
58 readonly lengthComputable: boolean;
59 readonly loaded: number;
60 readonly total: number;
61}) => void;
62​
63class TestXmlHttpRequest {
64 static requests: TestXmlHttpRequest[] = [];
65​
66 status = 0;
67 timeout = 0;
68 method: string | null = null;
69 url: string | null = null;
70 readonly headers = new Map<string, string>();
71 readonly listeners = new Map<string, () => void>();
72 progressListener: ProgressListener | null = null;
73​
74 readonly upload = {
75 addEventListener: (_event: string, listener: ProgressListener) => {
76 this.progressListener = listener;
77 },
78 };
79​
80 constructor() {
81 TestXmlHttpRequest.requests.push(this);
82 }
83​
84 open(method: string, url: string): void {
85 this.method = method;
86 this.url = url;
87 }
88​
89 setRequestHeader(name: string, value: string): void {
90 this.headers.set(name, value);
91 }
92​
93 addEventListener(event: string, listener: () => void): void {
94 this.listeners.set(event, listener);
95 }
96​
97 send(): void {}
98​
99 abort(): void {
100 this.listeners.get("abort")?.();
101 }
102​
103 progress(loaded: number, total: number): void {
104 this.progressListener?.({ lengthComputable: true, loaded, total });
105 }
106​
107 complete(status = 204): void {
108 this.status = status;
109 this.listeners.get("load")?.();
110 }
112​
113const firstEnvironment = EnvironmentId.make("environment-1");
114const secondEnvironment = EnvironmentId.make("environment-2");
115​
116function makeImage(id: string): ComposerImageAttachment {
117 const file = new File([new Uint8Array([1, 2, 3])], `${id}.png`, { type: "image/png" });
118 return {
119 type: "image",
120 id,
121 name: file.name,
122 mimeType: file.type,
123 sizeBytes: file.size,
124 previewUrl: `blob:${id}`,
125 file,
126 };
128​
129function makeFile(id: string): ComposerFileAttachment {
130 const file = new File([new Uint8Array([1, 2, 3])], `${id}.pdf`, {
131 type: "application/pdf",
132 });
133 return {
134 type: "file",
135 id,
136 name: file.name,
137 mimeType: file.type,
138 sizeBytes: file.size,
139 file,
140 };
142​
143describe("attachmentUploadQueue", () => {
144 beforeEach(() => {
145 TestXmlHttpRequest.requests = [];
146 mocks.createAssetUrl.mockReset();
147 mocks.createAssetUrl.mockImplementation((target: unknown) => target);
148 mocks.executeAtomQuery.mockReset();
149 mocks.executeAtomQuery.mockResolvedValue({ _tag: "Success", value: {} });
150 mocks.runAtomCommand.mockReset();
151 mocks.readPreparedConnection.mockReset();
152 mocks.readPreparedConnection.mockReturnValue({ httpBaseUrl: "https://environment.test/" });
153 mocks.runAtomCommand.mockImplementation(
154 async (
155 _registry: unknown,
156 command: unknown,
157 target: {
158 readonly environmentId: EnvironmentId;
159 readonly input: { readonly name?: string };
160 },
161 ) => {
162 if (command === mocks.createUploadUrl) {
163 const attachmentId = `pending-${target.environmentId}-${target.input.name}`;
164 return {
165 _tag: "Success",
166 value: {
167 attachmentId,
168 relativeUrl: `/api/attachments/upload/${attachmentId}`,
169 expiresAt: 1,
170 },
171 };
172 }
173 return { _tag: "Success", value: undefined };
174 },
175 );
176 vi.stubGlobal("XMLHttpRequest", TestXmlHttpRequest);
177 });
178​
179 afterEach(() => {
180 for (const imageId of Object.keys(useAttachmentUploadStore.getState().uploadsByImageId)) {
181 releaseAttachmentUpload(imageId);
182 }
183 vi.unstubAllGlobals();
184 });
185​
186 it("uploads images immediately and sends attachment references", async () => {
187 const image = {
188 ...makeImage("image-1"),
189 source: {
190 kind: "snap-shot" as const,
191 capturedAt: "2026-08-24T11:00:00.000Z",
192 appName: "Terminal",
193 windowTitle: "Tests",
194 },
195 };
196 startAttachmentUpload({ environmentId: firstEnvironment, image });
197 await Promise.resolve();
198​
199 const request = TestXmlHttpRequest.requests[0]!;
200 expect(request.method).toBe("POST");
201 expect(request.url).toBe(
202 "https://environment.test/api/attachments/upload/pending-environment-1-image-1.png",
203 );
204 request.progress(1, 3);
205 expect(readAttachmentUpload(image.id)).toMatchObject({ status: "uploading", progress: 1 / 3 });
206​
207 const settled = awaitAttachmentUploads([image.id]);
208 request.complete();
209 await settled;
210​
211 expect(getUploadedAttachments({ environmentId: firstEnvironment, images: [image] })).toEqual([
212 {
213 type: "image",
214 id: "pending-environment-1-image-1.png",
215 name: "image-1.png",
216 mimeType: "image/png",
217 sizeBytes: 3,
218 source: {
219 kind: "snap-shot",
220 capturedAt: "2026-08-24T11:00:00.000Z",
221 appName: "Terminal",
222 windowTitle: "Tests",
223 },
224 },
225 ]);
226​
227 releaseDraftAttachments([image]);
228 expect(readAttachmentUpload(image.id)).toBeUndefined();
229 expect(mocks.runAtomCommand).toHaveBeenCalledWith(
230 expect.anything(),
231 mocks.removeUpload,
232 {
233 environmentId: firstEnvironment,
234 input: { attachmentId: "pending-environment-1-image-1.png" },
235 },
236 expect.anything(),
237 );
238 });
239​
240 it("uploads generic files and sends file attachment references", async () => {
241 const file = makeFile("report");
242 startAttachmentUpload({ environmentId: firstEnvironment, image: file });
243 await Promise.resolve();
244​
245 expect(mocks.runAtomCommand).toHaveBeenCalledWith(
246 expect.anything(),
247 mocks.createUploadUrl,
248 {
249 environmentId: firstEnvironment,
250 input: {
251 type: "file",
252 name: "report.pdf",
253 mimeType: "application/pdf",
254 sizeBytes: 3,
255 },
256 },
257 expect.anything(),
258 );
259​
260 const settled = awaitAttachmentUploads([file.id]);
261 TestXmlHttpRequest.requests[0]!.complete();
262 await settled;
263​
264 expect(getUploadedAttachments({ environmentId: firstEnvironment, images: [file] })).toEqual([
265 {
266 type: "file",
267 id: "pending-environment-1-report.pdf",
268 name: "report.pdf",
269 mimeType: "application/pdf",
270 sizeBytes: 3,
271 },
272 ]);
273 });
274​
275 it("uses the fallback MIME type for both the upload claim and request header", async () => {
276 const bytes = new File([new Uint8Array([1, 2, 3])], "unknown.bin");
277 const file: ComposerFileAttachment = {
278 type: "file",
279 id: "file-without-browser-mime",
280 name: bytes.name,
281 mimeType: "application/octet-stream",
282 sizeBytes: bytes.size,
283 file: bytes,
284 };
285​
286 startAttachmentUpload({ environmentId: firstEnvironment, image: file });
287 await Promise.resolve();
288​
289 expect(mocks.runAtomCommand).toHaveBeenCalledWith(
290 expect.anything(),
291 mocks.createUploadUrl,
292 {
293 environmentId: firstEnvironment,
294 input: {
295 type: "file",
296 name: "unknown.bin",
297 mimeType: "application/octet-stream",
298 sizeBytes: 3,
299 },
300 },
301 expect.anything(),
302 );
303 expect(TestXmlHttpRequest.requests[0]?.headers.get("Content-Type")).toBe(
304 "application/octet-stream",
305 );
306​
307 const settled = awaitAttachmentUploads([file.id]);
308 TestXmlHttpRequest.requests[0]!.complete();
309 await settled;
310 });
311​
312 it("persists a background completion's ids to the draft with no composer mounted", async () => {
313 const draftId = DraftId.make("draft-background-upload");
314 const file = makeFile("background");
315 const draftStore = useComposerDraftStore.getState();
316 draftStore.addFiles(draftId, [file]);
317 try {
318 startAttachmentUpload({
319 environmentId: firstEnvironment,
320 image: file,
321 draftTarget: draftId,
322 });
323 await Promise.resolve();
324​
325 // No composer effect is subscribed; only the queue can stamp the draft.
326 const settled = awaitAttachmentUploads([file.id]);
327 TestXmlHttpRequest.requests[0]!.complete();
328 await settled;
329​
330 expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.files).toMatchObject([
331 {
332 id: file.id,
333 uploadedAttachmentId: "pending-environment-1-background.pdf",
334 uploadEnvironmentId: firstEnvironment,
335 },
336 ]);
337 } finally {
338 useComposerDraftStore.getState().clearComposerContent(draftId);
339 }
340 });
341​
342 it("persists a retried question upload without a mounted composer", async () => {
343 const draftId = DraftId.make("question-retry-upload");
344 const file = makeFile("question-retry");
345 const store = useComposerDraftStore.getState();
346 store.addFiles(draftId, [file]);
347 try {
348 startAttachmentUpload({ environmentId: firstEnvironment, image: file, draftTarget: draftId });
349 await Promise.resolve();
350 let settled = awaitAttachmentUploads([file.id]);
351 TestXmlHttpRequest.requests[0]!.complete(500);
352 await settled;
353 expect(store.getComposerDraft(draftId)?.files[0]?.uploadedAttachmentId).toBeUndefined();
354 retryAttachmentUpload({ environmentId: firstEnvironment, image: file, draftTarget: draftId });
355 await Promise.resolve();
356 settled = awaitAttachmentUploads([file.id]);
357 TestXmlHttpRequest.requests[1]!.complete();
358 await settled;
359 expect(store.getComposerDraft(draftId)?.files[0]).toMatchObject({
360 uploadedAttachmentId: "pending-environment-1-question-retry.pdf",
361 uploadEnvironmentId: firstEnvironment,
362 });
363 } finally {
364 store.clearComposerContent(draftId);
365 }
366 });
367​
368 it("verifies an uploaded file reference before restoring it", async () => {
369 const file: ComposerFileAttachment = {
370 ...makeFile("restored"),
371 file: null,
372 uploadedAttachmentId: "pending-restored-pdf",
373 uploadEnvironmentId: firstEnvironment,
374 };
375​
376 startAttachmentUpload({ environmentId: firstEnvironment, image: file });
377 await awaitAttachmentUploads([file.id]);
378​
379 expect(readAttachmentUpload(file.id)).toEqual({
380 status: "ready",
381 environmentId: firstEnvironment,
382 attachmentId: "pending-restored-pdf",
383 });
384 expect(mocks.createAssetUrl).toHaveBeenCalledWith({
385 environmentId: firstEnvironment,
386 input: { resource: { _tag: "attachment", attachmentId: "pending-restored-pdf" } },
387 });
388 expect(TestXmlHttpRequest.requests).toHaveLength(0);
389 });
390​
391 it("turns an expired persisted file into a marker that a re-pick can replace", async () => {
392 const draftId = DraftId.make("draft-expired-upload");
393 const file: ComposerFileAttachment = {
394 ...makeFile("expired"),
395 file: null,
396 uploadedAttachmentId: "pending-expired-pdf",
397 uploadEnvironmentId: firstEnvironment,
398 };
399 mocks.executeAtomQuery.mockResolvedValueOnce({
400 _tag: "Failure",
401 error: { _tag: "AssetAttachmentNotFoundError" },
402 });
403 useComposerDraftStore.getState().addFiles(draftId, [file]);
404​
405 try {
406 startAttachmentUpload({
407 environmentId: firstEnvironment,
408 image: file,
409 draftTarget: draftId,
410 });
411 await awaitAttachmentUploads([file.id]);
412​
413 const marker = useComposerDraftStore.getState().getComposerDraft(draftId)?.files[0];
414 expect(readAttachmentUpload(file.id)).toBeUndefined();
415 expect(marker?.uploadedAttachmentId).toBeUndefined();
416 expect(marker?.uploadEnvironmentId).toBeUndefined();
417 expect(marker && composerFileNeedsReattach(marker)).toBe(true);
418​
419 const replacementBytes = new File([new Uint8Array([1, 2, 3])], file.name, {
420 type: file.mimeType,
421 });
422 const replacement: ComposerFileAttachment = {
423 type: "file",
424 id: "expired-repicked",
425 name: file.name,
426 mimeType: file.mimeType,
427 sizeBytes: file.sizeBytes,
428 file: replacementBytes,
429 };
430 useComposerDraftStore.getState().addFiles(draftId, [replacement]);
431 expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.files).toMatchObject([
432 { id: replacement.id, file: replacementBytes },
433 ]);
434​
435 startAttachmentUpload({
436 environmentId: firstEnvironment,
437 image: replacement,
438 draftTarget: draftId,
439 });
440 await Promise.resolve();
441 const settled = awaitAttachmentUploads([replacement.id]);
442 TestXmlHttpRequest.requests[0]!.complete();
443 await settled;
444​
445 expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.files).toMatchObject([
446 {
447 id: replacement.id,
448 uploadedAttachmentId: "pending-environment-1-expired.pdf",
449 uploadEnvironmentId: firstEnvironment,
450 },
451 ]);
452 const removeCalls = mocks.runAtomCommand.mock.calls.filter(
453 ([, command]) => command === mocks.removeUpload,
454 );
455 expect(removeCalls).toEqual([]);
456 } finally {
457 useComposerDraftStore.getState().clearComposerContent(draftId);
458 }
459 });
460​
461 it("uploads the original file again when its persisted server upload expired", async () => {
462 const file: ComposerFileAttachment = {
463 ...makeFile("recoverable"),
464 uploadedAttachmentId: "pending-expired-pdf",
465 uploadEnvironmentId: firstEnvironment,
466 };
467 mocks.executeAtomQuery.mockResolvedValueOnce({
468 _tag: "Failure",
469 error: { _tag: "AssetAttachmentNotFoundError" },
470 });
471​
472 startAttachmentUpload({ environmentId: firstEnvironment, image: file });
473 // The verify-then-reupload path crosses several awaits before the
474 // transfer starts; drain microtasks until the XHR exists.
475 for (let hop = 0; hop < 20 && TestXmlHttpRequest.requests.length === 0; hop += 1) {
476 await Promise.resolve();
477 }
478​
479 const settled = awaitAttachmentUploads([file.id]);
480 TestXmlHttpRequest.requests[0]!.complete();
481 await settled;
482​
483 expect(readAttachmentUpload(file.id)).toMatchObject({
484 status: "ready",
485 attachmentId: "pending-environment-1-recoverable.pdf",
486 });
487 });
488​
489 it("removes a persisted upload when its draft is discarded during verification", async () => {
490 const file: ComposerFileAttachment = {
491 ...makeFile("checking"),
492 file: null,
493 uploadedAttachmentId: "pending-checking-pdf",
494 uploadEnvironmentId: firstEnvironment,
495 };
496 let resolveVerification: (result: {
497 readonly _tag: "Success";
498 readonly value: object;
499 }) => void = () => {};
500 mocks.executeAtomQuery.mockReturnValueOnce(
501 new Promise((resolve) => {
502 resolveVerification = resolve;
503 }),
504 );
505​
506 startAttachmentUpload({ environmentId: firstEnvironment, image: file });
507 releaseDraftAttachment(file);
508 resolveVerification({ _tag: "Success", value: {} });
509​
510 expect(mocks.runAtomCommand).toHaveBeenCalledWith(
511 expect.anything(),
512 mocks.removeUpload,
513 {
514 environmentId: firstEnvironment,
515 input: { attachmentId: "pending-checking-pdf" },
516 },
517 expect.anything(),
518 );
519 });
520​
521 it("keeps the persisted upload when retrying after a transient verification failure", async () => {
522 const draftId = DraftId.make("draft-transient-verification");
523 const file: ComposerFileAttachment = {
524 ...makeFile("flaky"),
525 file: null,
526 uploadedAttachmentId: "pending-flaky-pdf",
527 uploadEnvironmentId: firstEnvironment,
528 };
529 mocks.executeAtomQuery.mockResolvedValueOnce({
530 _tag: "Failure",
531 error: new Error("socket closed"),
532 });
533 useComposerDraftStore.getState().addFiles(draftId, [file]);
534​
535 try {
536 startAttachmentUpload({
537 environmentId: firstEnvironment,
538 image: file,
539 draftTarget: draftId,
540 });
541 await awaitAttachmentUploads([file.id]);
542 expect(readAttachmentUpload(file.id)).toMatchObject({
543 status: "failed",
544 reason: "Uploaded file could not be verified. Retry when the server reconnects.",
545 });
546 expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.files).toMatchObject([
547 {
548 uploadedAttachmentId: "pending-flaky-pdf",
549 uploadEnvironmentId: firstEnvironment,
550 },
551 ]);
552​
553 // The persisted id is the only server copy of the bytes (`file` is null
554 // after a reload), so the retry must verify it again, not delete it.
555 retryAttachmentUpload({
556 environmentId: firstEnvironment,
557 image: file,
558 draftTarget: draftId,
559 });
560 await awaitAttachmentUploads([file.id]);
561​
562 expect(readAttachmentUpload(file.id)).toEqual({
563 status: "ready",
564 environmentId: firstEnvironment,
565 attachmentId: "pending-flaky-pdf",
566 });
567 expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.files).toMatchObject([
568 {
569 uploadedAttachmentId: "pending-flaky-pdf",
570 uploadEnvironmentId: firstEnvironment,
571 },
572 ]);
573 const removeCalls = mocks.runAtomCommand.mock.calls.filter(
574 ([, command]) => command === mocks.removeUpload,
575 );
576 expect(removeCalls).toEqual([]);
577 } finally {
578 useComposerDraftStore.getState().clearComposerContent(draftId);
579 }
580 });
581​
582 it("keeps the persisted upload when an environment switch cancels its verification", async () => {
583 const file: ComposerFileAttachment = {
584 ...makeFile("moving"),
585 file: null,
586 uploadedAttachmentId: "pending-moving-pdf",
587 uploadEnvironmentId: firstEnvironment,
588 };
589 let resolveVerification: (result: {
590 readonly _tag: "Success";
591 readonly value: object;
592 }) => void = () => {};
593 mocks.executeAtomQuery.mockReturnValueOnce(
594 new Promise((resolve) => {
595 resolveVerification = resolve;
596 }),
597 );
598​
599 startAttachmentUpload({ environmentId: firstEnvironment, image: file });
600 // Switching environments cancels the in-flight verification. The draft
601 // still references the upload in the first environment, so the cancel
602 // must not delete it.
603 startAttachmentUpload({ environmentId: secondEnvironment, image: file });
604 resolveVerification({ _tag: "Success", value: {} });
605 await awaitAttachmentUploads([file.id]);
606​
607 const persistedRemoveCalls = mocks.runAtomCommand.mock.calls.filter(
608 ([, command, target]) =>
609 command === mocks.removeUpload &&
610 (target as { readonly input: { readonly attachmentId: string } }).input.attachmentId ===
611 "pending-moving-pdf",
612 );
613 expect(persistedRemoveCalls).toEqual([]);
614 });
615​
616 it("cancels persisted-upload verification when a stash discards its file", async () => {
617 const file: ComposerFileAttachment = {
618 ...makeFile("stashed-checking"),
619 file: null,
620 uploadedAttachmentId: "pending-stashed-checking-pdf",
621 uploadEnvironmentId: firstEnvironment,
622 };
623 let resolveVerification: (result: {
624 readonly _tag: "Success";
625 readonly value: object;
626 }) => void = () => {};
627 mocks.executeAtomQuery.mockReturnValueOnce(
628 new Promise((resolve) => {
629 resolveVerification = resolve;
630 }),
631 );
632​
633 startAttachmentUpload({ environmentId: firstEnvironment, image: file });
634 releasePersistedAttachmentUpload({
635 id: file.id,
636 environmentId: firstEnvironment,
637 attachmentId: "pending-stashed-checking-pdf",
638 });
639 resolveVerification({ _tag: "Success", value: {} });
640 await Promise.resolve();
641​
642 expect(readAttachmentUpload(file.id)).toBeUndefined();
643 expect(mocks.runAtomCommand).toHaveBeenCalledWith(
644 expect.anything(),
645 mocks.removeUpload,
646 {
647 environmentId: firstEnvironment,
648 input: { attachmentId: "pending-stashed-checking-pdf" },
649 },
650 expect.anything(),
651 );
652 });
653​
654 it("releases the persisted server upload when a hydrated draft is discarded after a reload", () => {
655 // After a reload the in-memory queue is empty; the draft file only carries
656 // its persisted attachment id. Discarding it must still delete the
657 // server-side pending upload.
658 const file: ComposerFileAttachment = {
659 ...makeFile("hydrated"),
660 file: null,
661 uploadedAttachmentId: "pending-hydrated-pdf",
662 uploadEnvironmentId: firstEnvironment,
663 };
664​
665 releaseDraftAttachment(file);
666​
667 expect(mocks.runAtomCommand).toHaveBeenCalledWith(
668 expect.anything(),
669 mocks.removeUpload,
670 {
671 environmentId: firstEnvironment,
672 input: { attachmentId: "pending-hydrated-pdf" },
673 },
674 expect.anything(),
675 );
676 });
677​
678 it("routes a live persisted upload through the queue release exactly once", async () => {
679 const file: ComposerFileAttachment = {
680 ...makeFile("live"),
681 file: null,
682 uploadedAttachmentId: "pending-live-pdf",
683 uploadEnvironmentId: firstEnvironment,
684 };
685 startAttachmentUpload({ environmentId: firstEnvironment, image: file });
686 await awaitAttachmentUploads([file.id]);
687 expect(readAttachmentUpload(file.id)).toMatchObject({ status: "ready" });
688​
689 releaseDraftAttachment(file);
690​
691 expect(readAttachmentUpload(file.id)).toBeUndefined();
692 const removeCalls = mocks.runAtomCommand.mock.calls.filter(
693 ([, command]) => command === mocks.removeUpload,
694 );
695 expect(removeCalls).toEqual([
696 [
697 expect.anything(),
698 mocks.removeUpload,
699 {
700 environmentId: firstEnvironment,
701 input: { attachmentId: "pending-live-pdf" },
702 },
703 expect.anything(),
704 ],
705 ]);
706 });
707​
708 it("deletes a persisted server upload even when browser upload state is gone", () => {
709 releasePersistedAttachmentUpload({
710 id: "stashed-report",
711 environmentId: firstEnvironment,
712 attachmentId: "pending-00000000-0000-4000-8000-000000000001-pdf",
713 });
714​
715 expect(mocks.runAtomCommand).toHaveBeenCalledWith(
716 expect.anything(),
717 mocks.removeUpload,
718 {
719 environmentId: firstEnvironment,
720 input: { attachmentId: "pending-00000000-0000-4000-8000-000000000001-pdf" },
721 },
722 expect.anything(),
723 );
724 });
725​
726 it("retries rejected uploads", async () => {
727 const image = makeImage("image-retry");
728 startAttachmentUpload({ environmentId: firstEnvironment, image });
729 await Promise.resolve();
730​
731 let settled = awaitAttachmentUploads([image.id]);
732 TestXmlHttpRequest.requests[0]!.complete(500);
733 await settled;
734 expect(readAttachmentUpload(image.id)).toMatchObject({
735 status: "failed",
736 reason: "Upload rejected (500)",
737 });
738​
739 retryAttachmentUpload({ environmentId: firstEnvironment, image });
740 await Promise.resolve();
741 settled = awaitAttachmentUploads([image.id]);
742 TestXmlHttpRequest.requests[1]!.complete();
743 await settled;
744​
745 expect(readAttachmentUpload(image.id)).toMatchObject({ status: "ready" });
746 });
747​
748 it("releases an upload URL that resolves after its image was removed", async () => {
749 const image = makeImage("image-cancelled");
750 const minted = {
751 _tag: "Success" as const,
752 value: {
753 attachmentId: "pending-environment-1-image-cancelled.png",
754 relativeUrl: "/api/attachments/upload/cancelled",
755 expiresAt: 1,
756 },
757 };
758 let resolveMint: (result: typeof minted) => void = () => {};
759 const pendingMint = new Promise<typeof minted>((resolve) => {
760 resolveMint = resolve;
761 });
762 let resolveDelete: () => void = () => {};
763 const deleted = new Promise<void>((resolve) => {
764 resolveDelete = resolve;
765 });
766 mocks.runAtomCommand.mockImplementation((_registry: unknown, command: unknown) => {
767 if (command === mocks.createUploadUrl) {
768 return pendingMint;
769 }
770 resolveDelete();
771 return Promise.resolve({ _tag: "Success", value: undefined });
772 });
773​
774 startAttachmentUpload({ environmentId: firstEnvironment, image });
775 releaseAttachmentUpload(image.id);
776 resolveMint(minted);
777 await deleted;
778​
779 expect(TestXmlHttpRequest.requests).toEqual([]);
780 expect(readAttachmentUpload(image.id)).toBeUndefined();
781 expect(mocks.runAtomCommand).toHaveBeenCalledWith(
782 expect.anything(),
783 mocks.removeUpload,
784 {
785 environmentId: firstEnvironment,
786 input: { attachmentId: minted.value.attachmentId },
787 },
788 expect.anything(),
789 );
790 });
791​
792 it("restores the previous environment after a replacement upload fails", async () => {
793 const image = makeImage("image-move");
794 startAttachmentUpload({ environmentId: firstEnvironment, image });
795 await Promise.resolve();
796 let settled = awaitAttachmentUploads([image.id]);
797 TestXmlHttpRequest.requests[0]!.complete();
798 await settled;
799​
800 startAttachmentUpload({ environmentId: secondEnvironment, image });
801 await Promise.resolve();
802 settled = awaitAttachmentUploads([image.id]);
803 TestXmlHttpRequest.requests[1]!.complete(500);
804 await settled;
805​
806 startAttachmentUpload({ environmentId: firstEnvironment, image });
807 expect(readAttachmentUpload(image.id)).toMatchObject({
808 status: "ready",
809 environmentId: firstEnvironment,
810 attachmentId: "pending-environment-1-image-move.png",
811 });
812 });
813​
814 it("does not let stalled uploads block another environment", async () => {
815 const images = ["image-a", "image-b", "image-c", "image-d"].map(makeImage);
816 for (const image of images) {
817 startAttachmentUpload({ environmentId: firstEnvironment, image });
818 }
819 const otherEnvironmentImage = makeImage("image-other");
820 startAttachmentUpload({ environmentId: secondEnvironment, image: otherEnvironmentImage });
821 await Promise.resolve();
822​
823 expect(TestXmlHttpRequest.requests).toHaveLength(4);
824 const otherRequest = TestXmlHttpRequest.requests.find((request) =>
825 request.url?.includes("environment-2"),
826 );
827 expect(otherRequest).toBeDefined();
828​
829 for (const request of TestXmlHttpRequest.requests) {
830 request.complete();
831 }
832 await Promise.all([
833 ...images.slice(0, 3).map((image) => awaitAttachmentUploads([image.id])),
834 awaitAttachmentUploads([otherEnvironmentImage.id]),
835 ]);
836 await Promise.resolve();
837 TestXmlHttpRequest.requests[4]!.complete();
838 await awaitAttachmentUploads([images[3]!.id]);
839 });
840});