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

attachmentUploadQueue.test.ts

800 lines25.4 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 = makeImage("image-1");
188 startAttachmentUpload({ environmentId: firstEnvironment, image });
189 await Promise.resolve();
190​
191 const request = TestXmlHttpRequest.requests[0]!;
192 expect(request.method).toBe("POST");
193 expect(request.url).toBe(
194 "https://environment.test/api/attachments/upload/pending-environment-1-image-1.png",
195 );
196 request.progress(1, 3);
197 expect(readAttachmentUpload(image.id)).toMatchObject({ status: "uploading", progress: 1 / 3 });
198​
199 const settled = awaitAttachmentUploads([image.id]);
200 request.complete();
201 await settled;
202​
203 expect(getUploadedAttachments({ environmentId: firstEnvironment, images: [image] })).toEqual([
204 {
205 type: "image",
206 id: "pending-environment-1-image-1.png",
207 name: "image-1.png",
208 mimeType: "image/png",
209 sizeBytes: 3,
210 },
211 ]);
212​
213 releaseDraftAttachments([image]);
214 expect(readAttachmentUpload(image.id)).toBeUndefined();
215 expect(mocks.runAtomCommand).toHaveBeenCalledWith(
216 expect.anything(),
217 mocks.removeUpload,
218 {
219 environmentId: firstEnvironment,
220 input: { attachmentId: "pending-environment-1-image-1.png" },
221 },
222 expect.anything(),
223 );
224 });
225​
226 it("uploads generic files and sends file attachment references", async () => {
227 const file = makeFile("report");
228 startAttachmentUpload({ environmentId: firstEnvironment, image: file });
229 await Promise.resolve();
230​
231 expect(mocks.runAtomCommand).toHaveBeenCalledWith(
232 expect.anything(),
233 mocks.createUploadUrl,
234 {
235 environmentId: firstEnvironment,
236 input: {
237 type: "file",
238 name: "report.pdf",
239 mimeType: "application/pdf",
240 sizeBytes: 3,
241 },
242 },
243 expect.anything(),
244 );
245​
246 const settled = awaitAttachmentUploads([file.id]);
247 TestXmlHttpRequest.requests[0]!.complete();
248 await settled;
249​
250 expect(getUploadedAttachments({ environmentId: firstEnvironment, images: [file] })).toEqual([
251 {
252 type: "file",
253 id: "pending-environment-1-report.pdf",
254 name: "report.pdf",
255 mimeType: "application/pdf",
256 sizeBytes: 3,
257 },
258 ]);
259 });
260​
261 it("uses the fallback MIME type for both the upload claim and request header", async () => {
262 const bytes = new File([new Uint8Array([1, 2, 3])], "unknown.bin");
263 const file: ComposerFileAttachment = {
264 type: "file",
265 id: "file-without-browser-mime",
266 name: bytes.name,
267 mimeType: "application/octet-stream",
268 sizeBytes: bytes.size,
269 file: bytes,
270 };
271​
272 startAttachmentUpload({ environmentId: firstEnvironment, image: file });
273 await Promise.resolve();
274​
275 expect(mocks.runAtomCommand).toHaveBeenCalledWith(
276 expect.anything(),
277 mocks.createUploadUrl,
278 {
279 environmentId: firstEnvironment,
280 input: {
281 type: "file",
282 name: "unknown.bin",
283 mimeType: "application/octet-stream",
284 sizeBytes: 3,
285 },
286 },
287 expect.anything(),
288 );
289 expect(TestXmlHttpRequest.requests[0]?.headers.get("Content-Type")).toBe(
290 "application/octet-stream",
291 );
292​
293 const settled = awaitAttachmentUploads([file.id]);
294 TestXmlHttpRequest.requests[0]!.complete();
295 await settled;
296 });
297​
298 it("persists a background completion's ids to the draft with no composer mounted", async () => {
299 const draftId = DraftId.make("draft-background-upload");
300 const file = makeFile("background");
301 const draftStore = useComposerDraftStore.getState();
302 draftStore.addFiles(draftId, [file]);
303 try {
304 startAttachmentUpload({
305 environmentId: firstEnvironment,
306 image: file,
307 draftTarget: draftId,
308 });
309 await Promise.resolve();
310​
311 // No composer effect is subscribed; only the queue can stamp the draft.
312 const settled = awaitAttachmentUploads([file.id]);
313 TestXmlHttpRequest.requests[0]!.complete();
314 await settled;
315​
316 expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.files).toMatchObject([
317 {
318 id: file.id,
319 uploadedAttachmentId: "pending-environment-1-background.pdf",
320 uploadEnvironmentId: firstEnvironment,
321 },
322 ]);
323 } finally {
324 useComposerDraftStore.getState().clearComposerContent(draftId);
325 }
326 });
327​
328 it("verifies an uploaded file reference before restoring it", async () => {
329 const file: ComposerFileAttachment = {
330 ...makeFile("restored"),
331 file: null,
332 uploadedAttachmentId: "pending-restored-pdf",
333 uploadEnvironmentId: firstEnvironment,
334 };
335​
336 startAttachmentUpload({ environmentId: firstEnvironment, image: file });
337 await awaitAttachmentUploads([file.id]);
338​
339 expect(readAttachmentUpload(file.id)).toEqual({
340 status: "ready",
341 environmentId: firstEnvironment,
342 attachmentId: "pending-restored-pdf",
343 });
344 expect(mocks.createAssetUrl).toHaveBeenCalledWith({
345 environmentId: firstEnvironment,
346 input: { resource: { _tag: "attachment", attachmentId: "pending-restored-pdf" } },
347 });
348 expect(TestXmlHttpRequest.requests).toHaveLength(0);
349 });
350​
351 it("turns an expired persisted file into a marker that a re-pick can replace", async () => {
352 const draftId = DraftId.make("draft-expired-upload");
353 const file: ComposerFileAttachment = {
354 ...makeFile("expired"),
355 file: null,
356 uploadedAttachmentId: "pending-expired-pdf",
357 uploadEnvironmentId: firstEnvironment,
358 };
359 mocks.executeAtomQuery.mockResolvedValueOnce({
360 _tag: "Failure",
361 error: { _tag: "AssetAttachmentNotFoundError" },
362 });
363 useComposerDraftStore.getState().addFiles(draftId, [file]);
364​
365 try {
366 startAttachmentUpload({
367 environmentId: firstEnvironment,
368 image: file,
369 draftTarget: draftId,
370 });
371 await awaitAttachmentUploads([file.id]);
372​
373 const marker = useComposerDraftStore.getState().getComposerDraft(draftId)?.files[0];
374 expect(readAttachmentUpload(file.id)).toBeUndefined();
375 expect(marker?.uploadedAttachmentId).toBeUndefined();
376 expect(marker?.uploadEnvironmentId).toBeUndefined();
377 expect(marker && composerFileNeedsReattach(marker)).toBe(true);
378​
379 const replacementBytes = new File([new Uint8Array([1, 2, 3])], file.name, {
380 type: file.mimeType,
381 });
382 const replacement: ComposerFileAttachment = {
383 type: "file",
384 id: "expired-repicked",
385 name: file.name,
386 mimeType: file.mimeType,
387 sizeBytes: file.sizeBytes,
388 file: replacementBytes,
389 };
390 useComposerDraftStore.getState().addFiles(draftId, [replacement]);
391 expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.files).toMatchObject([
392 { id: replacement.id, file: replacementBytes },
393 ]);
394​
395 startAttachmentUpload({
396 environmentId: firstEnvironment,
397 image: replacement,
398 draftTarget: draftId,
399 });
400 await Promise.resolve();
401 const settled = awaitAttachmentUploads([replacement.id]);
402 TestXmlHttpRequest.requests[0]!.complete();
403 await settled;
404​
405 expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.files).toMatchObject([
406 {
407 id: replacement.id,
408 uploadedAttachmentId: "pending-environment-1-expired.pdf",
409 uploadEnvironmentId: firstEnvironment,
410 },
411 ]);
412 const removeCalls = mocks.runAtomCommand.mock.calls.filter(
413 ([, command]) => command === mocks.removeUpload,
414 );
415 expect(removeCalls).toEqual([]);
416 } finally {
417 useComposerDraftStore.getState().clearComposerContent(draftId);
418 }
419 });
420​
421 it("uploads the original file again when its persisted server upload expired", async () => {
422 const file: ComposerFileAttachment = {
423 ...makeFile("recoverable"),
424 uploadedAttachmentId: "pending-expired-pdf",
425 uploadEnvironmentId: firstEnvironment,
426 };
427 mocks.executeAtomQuery.mockResolvedValueOnce({
428 _tag: "Failure",
429 error: { _tag: "AssetAttachmentNotFoundError" },
430 });
431​
432 startAttachmentUpload({ environmentId: firstEnvironment, image: file });
433 // The verify-then-reupload path crosses several awaits before the
434 // transfer starts; drain microtasks until the XHR exists.
435 for (let hop = 0; hop < 20 && TestXmlHttpRequest.requests.length === 0; hop += 1) {
436 await Promise.resolve();
437 }
438​
439 const settled = awaitAttachmentUploads([file.id]);
440 TestXmlHttpRequest.requests[0]!.complete();
441 await settled;
442​
443 expect(readAttachmentUpload(file.id)).toMatchObject({
444 status: "ready",
445 attachmentId: "pending-environment-1-recoverable.pdf",
446 });
447 });
448​
449 it("removes a persisted upload when its draft is discarded during verification", async () => {
450 const file: ComposerFileAttachment = {
451 ...makeFile("checking"),
452 file: null,
453 uploadedAttachmentId: "pending-checking-pdf",
454 uploadEnvironmentId: firstEnvironment,
455 };
456 let resolveVerification: (result: {
457 readonly _tag: "Success";
458 readonly value: object;
459 }) => void = () => {};
460 mocks.executeAtomQuery.mockReturnValueOnce(
461 new Promise((resolve) => {
462 resolveVerification = resolve;
463 }),
464 );
465​
466 startAttachmentUpload({ environmentId: firstEnvironment, image: file });
467 releaseDraftAttachment(file);
468 resolveVerification({ _tag: "Success", value: {} });
469​
470 expect(mocks.runAtomCommand).toHaveBeenCalledWith(
471 expect.anything(),
472 mocks.removeUpload,
473 {
474 environmentId: firstEnvironment,
475 input: { attachmentId: "pending-checking-pdf" },
476 },
477 expect.anything(),
478 );
479 });
480​
481 it("keeps the persisted upload when retrying after a transient verification failure", async () => {
482 const draftId = DraftId.make("draft-transient-verification");
483 const file: ComposerFileAttachment = {
484 ...makeFile("flaky"),
485 file: null,
486 uploadedAttachmentId: "pending-flaky-pdf",
487 uploadEnvironmentId: firstEnvironment,
488 };
489 mocks.executeAtomQuery.mockResolvedValueOnce({
490 _tag: "Failure",
491 error: new Error("socket closed"),
492 });
493 useComposerDraftStore.getState().addFiles(draftId, [file]);
494​
495 try {
496 startAttachmentUpload({
497 environmentId: firstEnvironment,
498 image: file,
499 draftTarget: draftId,
500 });
501 await awaitAttachmentUploads([file.id]);
502 expect(readAttachmentUpload(file.id)).toMatchObject({
503 status: "failed",
504 reason: "Uploaded file could not be verified. Retry when the server reconnects.",
505 });
506 expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.files).toMatchObject([
507 {
508 uploadedAttachmentId: "pending-flaky-pdf",
509 uploadEnvironmentId: firstEnvironment,
510 },
511 ]);
512​
513 // The persisted id is the only server copy of the bytes (`file` is null
514 // after a reload), so the retry must verify it again, not delete it.
515 retryAttachmentUpload({
516 environmentId: firstEnvironment,
517 image: file,
518 draftTarget: draftId,
519 });
520 await awaitAttachmentUploads([file.id]);
521​
522 expect(readAttachmentUpload(file.id)).toEqual({
523 status: "ready",
524 environmentId: firstEnvironment,
525 attachmentId: "pending-flaky-pdf",
526 });
527 expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.files).toMatchObject([
528 {
529 uploadedAttachmentId: "pending-flaky-pdf",
530 uploadEnvironmentId: firstEnvironment,
531 },
532 ]);
533 const removeCalls = mocks.runAtomCommand.mock.calls.filter(
534 ([, command]) => command === mocks.removeUpload,
535 );
536 expect(removeCalls).toEqual([]);
537 } finally {
538 useComposerDraftStore.getState().clearComposerContent(draftId);
539 }
540 });
541​
542 it("keeps the persisted upload when an environment switch cancels its verification", async () => {
543 const file: ComposerFileAttachment = {
544 ...makeFile("moving"),
545 file: null,
546 uploadedAttachmentId: "pending-moving-pdf",
547 uploadEnvironmentId: firstEnvironment,
548 };
549 let resolveVerification: (result: {
550 readonly _tag: "Success";
551 readonly value: object;
552 }) => void = () => {};
553 mocks.executeAtomQuery.mockReturnValueOnce(
554 new Promise((resolve) => {
555 resolveVerification = resolve;
556 }),
557 );
558​
559 startAttachmentUpload({ environmentId: firstEnvironment, image: file });
560 // Switching environments cancels the in-flight verification. The draft
561 // still references the upload in the first environment, so the cancel
562 // must not delete it.
563 startAttachmentUpload({ environmentId: secondEnvironment, image: file });
564 resolveVerification({ _tag: "Success", value: {} });
565 await awaitAttachmentUploads([file.id]);
566​
567 const persistedRemoveCalls = mocks.runAtomCommand.mock.calls.filter(
568 ([, command, target]) =>
569 command === mocks.removeUpload &&
570 (target as { readonly input: { readonly attachmentId: string } }).input.attachmentId ===
571 "pending-moving-pdf",
572 );
573 expect(persistedRemoveCalls).toEqual([]);
574 });
575​
576 it("cancels persisted-upload verification when a stash discards its file", async () => {
577 const file: ComposerFileAttachment = {
578 ...makeFile("stashed-checking"),
579 file: null,
580 uploadedAttachmentId: "pending-stashed-checking-pdf",
581 uploadEnvironmentId: firstEnvironment,
582 };
583 let resolveVerification: (result: {
584 readonly _tag: "Success";
585 readonly value: object;
586 }) => void = () => {};
587 mocks.executeAtomQuery.mockReturnValueOnce(
588 new Promise((resolve) => {
589 resolveVerification = resolve;
590 }),
591 );
592​
593 startAttachmentUpload({ environmentId: firstEnvironment, image: file });
594 releasePersistedAttachmentUpload({
595 id: file.id,
596 environmentId: firstEnvironment,
597 attachmentId: "pending-stashed-checking-pdf",
598 });
599 resolveVerification({ _tag: "Success", value: {} });
600 await Promise.resolve();
601​
602 expect(readAttachmentUpload(file.id)).toBeUndefined();
603 expect(mocks.runAtomCommand).toHaveBeenCalledWith(
604 expect.anything(),
605 mocks.removeUpload,
606 {
607 environmentId: firstEnvironment,
608 input: { attachmentId: "pending-stashed-checking-pdf" },
609 },
610 expect.anything(),
611 );
612 });
613​
614 it("releases the persisted server upload when a hydrated draft is discarded after a reload", () => {
615 // After a reload the in-memory queue is empty; the draft file only carries
616 // its persisted attachment id. Discarding it must still delete the
617 // server-side pending upload.
618 const file: ComposerFileAttachment = {
619 ...makeFile("hydrated"),
620 file: null,
621 uploadedAttachmentId: "pending-hydrated-pdf",
622 uploadEnvironmentId: firstEnvironment,
623 };
624​
625 releaseDraftAttachment(file);
626​
627 expect(mocks.runAtomCommand).toHaveBeenCalledWith(
628 expect.anything(),
629 mocks.removeUpload,
630 {
631 environmentId: firstEnvironment,
632 input: { attachmentId: "pending-hydrated-pdf" },
633 },
634 expect.anything(),
635 );
636 });
637​
638 it("routes a live persisted upload through the queue release exactly once", async () => {
639 const file: ComposerFileAttachment = {
640 ...makeFile("live"),
641 file: null,
642 uploadedAttachmentId: "pending-live-pdf",
643 uploadEnvironmentId: firstEnvironment,
644 };
645 startAttachmentUpload({ environmentId: firstEnvironment, image: file });
646 await awaitAttachmentUploads([file.id]);
647 expect(readAttachmentUpload(file.id)).toMatchObject({ status: "ready" });
648​
649 releaseDraftAttachment(file);
650​
651 expect(readAttachmentUpload(file.id)).toBeUndefined();
652 const removeCalls = mocks.runAtomCommand.mock.calls.filter(
653 ([, command]) => command === mocks.removeUpload,
654 );
655 expect(removeCalls).toEqual([
656 [
657 expect.anything(),
658 mocks.removeUpload,
659 {
660 environmentId: firstEnvironment,
661 input: { attachmentId: "pending-live-pdf" },
662 },
663 expect.anything(),
664 ],
665 ]);
666 });
667​
668 it("deletes a persisted server upload even when browser upload state is gone", () => {
669 releasePersistedAttachmentUpload({
670 id: "stashed-report",
671 environmentId: firstEnvironment,
672 attachmentId: "pending-00000000-0000-4000-8000-000000000001-pdf",
673 });
674​
675 expect(mocks.runAtomCommand).toHaveBeenCalledWith(
676 expect.anything(),
677 mocks.removeUpload,
678 {
679 environmentId: firstEnvironment,
680 input: { attachmentId: "pending-00000000-0000-4000-8000-000000000001-pdf" },
681 },
682 expect.anything(),
683 );
684 });
685​
686 it("retries rejected uploads", async () => {
687 const image = makeImage("image-retry");
688 startAttachmentUpload({ environmentId: firstEnvironment, image });
689 await Promise.resolve();
690​
691 let settled = awaitAttachmentUploads([image.id]);
692 TestXmlHttpRequest.requests[0]!.complete(500);
693 await settled;
694 expect(readAttachmentUpload(image.id)).toMatchObject({
695 status: "failed",
696 reason: "Upload rejected (500)",
697 });
698​
699 retryAttachmentUpload({ environmentId: firstEnvironment, image });
700 await Promise.resolve();
701 settled = awaitAttachmentUploads([image.id]);
702 TestXmlHttpRequest.requests[1]!.complete();
703 await settled;
704​
705 expect(readAttachmentUpload(image.id)).toMatchObject({ status: "ready" });
706 });
707​
708 it("releases an upload URL that resolves after its image was removed", async () => {
709 const image = makeImage("image-cancelled");
710 const minted = {
711 _tag: "Success" as const,
712 value: {
713 attachmentId: "pending-environment-1-image-cancelled.png",
714 relativeUrl: "/api/attachments/upload/cancelled",
715 expiresAt: 1,
716 },
717 };
718 let resolveMint: (result: typeof minted) => void = () => {};
719 const pendingMint = new Promise<typeof minted>((resolve) => {
720 resolveMint = resolve;
721 });
722 let resolveDelete: () => void = () => {};
723 const deleted = new Promise<void>((resolve) => {
724 resolveDelete = resolve;
725 });
726 mocks.runAtomCommand.mockImplementation((_registry: unknown, command: unknown) => {
727 if (command === mocks.createUploadUrl) {
728 return pendingMint;
729 }
730 resolveDelete();
731 return Promise.resolve({ _tag: "Success", value: undefined });
732 });
733​
734 startAttachmentUpload({ environmentId: firstEnvironment, image });
735 releaseAttachmentUpload(image.id);
736 resolveMint(minted);
737 await deleted;
738​
739 expect(TestXmlHttpRequest.requests).toEqual([]);
740 expect(readAttachmentUpload(image.id)).toBeUndefined();
741 expect(mocks.runAtomCommand).toHaveBeenCalledWith(
742 expect.anything(),
743 mocks.removeUpload,
744 {
745 environmentId: firstEnvironment,
746 input: { attachmentId: minted.value.attachmentId },
747 },
748 expect.anything(),
749 );
750 });
751​
752 it("restores the previous environment after a replacement upload fails", async () => {
753 const image = makeImage("image-move");
754 startAttachmentUpload({ environmentId: firstEnvironment, image });
755 await Promise.resolve();
756 let settled = awaitAttachmentUploads([image.id]);
757 TestXmlHttpRequest.requests[0]!.complete();
758 await settled;
759​
760 startAttachmentUpload({ environmentId: secondEnvironment, image });
761 await Promise.resolve();
762 settled = awaitAttachmentUploads([image.id]);
763 TestXmlHttpRequest.requests[1]!.complete(500);
764 await settled;
765​
766 startAttachmentUpload({ environmentId: firstEnvironment, image });
767 expect(readAttachmentUpload(image.id)).toMatchObject({
768 status: "ready",
769 environmentId: firstEnvironment,
770 attachmentId: "pending-environment-1-image-move.png",
771 });
772 });
773​
774 it("does not let stalled uploads block another environment", async () => {
775 const images = ["image-a", "image-b", "image-c", "image-d"].map(makeImage);
776 for (const image of images) {
777 startAttachmentUpload({ environmentId: firstEnvironment, image });
778 }
779 const otherEnvironmentImage = makeImage("image-other");
780 startAttachmentUpload({ environmentId: secondEnvironment, image: otherEnvironmentImage });
781 await Promise.resolve();
782​
783 expect(TestXmlHttpRequest.requests).toHaveLength(4);
784 const otherRequest = TestXmlHttpRequest.requests.find((request) =>
785 request.url?.includes("environment-2"),
786 );
787 expect(otherRequest).toBeDefined();
788​
789 for (const request of TestXmlHttpRequest.requests) {
790 request.complete();
791 }
792 await Promise.all([
793 ...images.slice(0, 3).map((image) => awaitAttachmentUploads([image.id])),
794 awaitAttachmentUploads([otherEnvironmentImage.id]),
795 ]);
796 await Promise.resolve();
797 TestXmlHttpRequest.requests[4]!.complete();
798 await awaitAttachmentUploads([images[3]!.id]);
799 });
800});