Open History to see the last commit
1import { EnvironmentId } from "@t3tools/contracts";
2import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
3
4import type { ComposerImageAttachment } from "../composerDraftStore";
5
6const mocks = vi.hoisted(() => ({
7 createUploadUrl: Symbol("create-upload-url"),
8 removeUpload: Symbol("remove-upload"),
9 runAtomCommand: vi.fn(),
10 readPreparedConnection: vi.fn(),
11}));
12
13vi.mock("@t3tools/client-runtime/state/runtime", () => ({
14 runAtomCommand: mocks.runAtomCommand,
15}));
16
17vi.mock("../rpc/atomRegistry", () => ({ appAtomRegistry: {} }));
18
19vi.mock("../state/attachments", () => ({
20 attachmentEnvironment: {
21 createUploadUrl: mocks.createUploadUrl,
22 remove: mocks.removeUpload,
23 },
24}));
25
26vi.mock("../state/session", () => ({
27 readPreparedConnection: mocks.readPreparedConnection,
28}));
29
30import {
31 awaitAttachmentUploads,
32 getUploadedAttachments,
33 readAttachmentUpload,
34 releaseAttachmentUpload,
35 releaseAttachmentUploads,
36 retryAttachmentUpload,
37 startAttachmentUpload,
38 useAttachmentUploadStore,
39} from "./attachmentUploadQueue";
40
41type ProgressListener = (event: {
42 readonly lengthComputable: boolean;
43 readonly loaded: number;
44 readonly total: number;
45}) => void;
46
47class TestXmlHttpRequest {
48 static requests: TestXmlHttpRequest[] = [];
49
50 status = 0;
51 timeout = 0;
52 method: string | null = null;
53 url: string | null = null;
54 readonly headers = new Map<string, string>();
55 readonly listeners = new Map<string, () => void>();
56 progressListener: ProgressListener | null = null;
57
58 readonly upload = {
59 addEventListener: (_event: string, listener: ProgressListener) => {
60 this.progressListener = listener;
61 },
62 };
63
64 constructor() {
65 TestXmlHttpRequest.requests.push(this);
66 }
67
68 open(method: string, url: string): void {
69 this.method = method;
70 this.url = url;
71 }
72
73 setRequestHeader(name: string, value: string): void {
74 this.headers.set(name, value);
75 }
76
77 addEventListener(event: string, listener: () => void): void {
78 this.listeners.set(event, listener);
79 }
80
81 send(): void {}
82
83 abort(): void {
84 this.listeners.get("abort")?.();
85 }
86
87 progress(loaded: number, total: number): void {
88 this.progressListener?.({ lengthComputable: true, loaded, total });
89 }
90
91 complete(status = 204): void {
92 this.status = status;
93 this.listeners.get("load")?.();
94 }
95}
96
97const firstEnvironment = EnvironmentId.make("environment-1");
98const secondEnvironment = EnvironmentId.make("environment-2");
99
100function makeImage(id: string): ComposerImageAttachment {
101 const file = new File([new Uint8Array([1, 2, 3])], `${id}.png`, { type: "image/png" });
102 return {
103 type: "image",
104 id,
105 name: file.name,
106 mimeType: file.type,
107 sizeBytes: file.size,
108 previewUrl: `blob:${id}`,
109 file,
110 };
111}
112
113describe("attachmentUploadQueue", () => {
114 beforeEach(() => {
115 TestXmlHttpRequest.requests = [];
116 mocks.runAtomCommand.mockReset();
117 mocks.readPreparedConnection.mockReset();
118 mocks.readPreparedConnection.mockReturnValue({ httpBaseUrl: "https://environment.test/" });
119 mocks.runAtomCommand.mockImplementation(
120 async (
121 _registry: unknown,
122 command: unknown,
123 target: {
124 readonly environmentId: EnvironmentId;
125 readonly input: { readonly name?: string };
126 },
127 ) => {
128 if (command === mocks.createUploadUrl) {
129 const attachmentId = `pending-${target.environmentId}-${target.input.name}`;
130 return {
131 _tag: "Success",
132 value: {
133 attachmentId,
134 relativeUrl: `/api/attachments/upload/${attachmentId}`,
135 expiresAt: 1,
136 },
137 };
138 }
139 return { _tag: "Success", value: undefined };
140 },
141 );
142 vi.stubGlobal("XMLHttpRequest", TestXmlHttpRequest);
143 });
144
145 afterEach(() => {
146 for (const imageId of Object.keys(useAttachmentUploadStore.getState().uploadsByImageId)) {
147 releaseAttachmentUpload(imageId);
148 }
149 vi.unstubAllGlobals();
150 });
151
152 it("uploads images immediately and sends attachment references", async () => {
153 const image = makeImage("image-1");
154 startAttachmentUpload({ environmentId: firstEnvironment, image });
155 await Promise.resolve();
156
157 const request = TestXmlHttpRequest.requests[0]!;
158 expect(request.method).toBe("POST");
159 expect(request.url).toBe(
160 "https://environment.test/api/attachments/upload/pending-environment-1-image-1.png",
161 );
162 request.progress(1, 3);
163 expect(readAttachmentUpload(image.id)).toMatchObject({ status: "uploading", progress: 1 / 3 });
164
165 const settled = awaitAttachmentUploads([image.id]);
166 request.complete();
167 await settled;
168
169 expect(getUploadedAttachments({ environmentId: firstEnvironment, images: [image] })).toEqual([
170 {
171 type: "image",
172 id: "pending-environment-1-image-1.png",
173 name: "image-1.png",
174 mimeType: "image/png",
175 sizeBytes: 3,
176 },
177 ]);
178
179 releaseAttachmentUploads([image]);
180 expect(readAttachmentUpload(image.id)).toBeUndefined();
181 expect(mocks.runAtomCommand).toHaveBeenCalledWith(
182 expect.anything(),
183 mocks.removeUpload,
184 {
185 environmentId: firstEnvironment,
186 input: { attachmentId: "pending-environment-1-image-1.png" },
187 },
188 expect.anything(),
189 );
190 });
191
192 it("retries rejected uploads", async () => {
193 const image = makeImage("image-retry");
194 startAttachmentUpload({ environmentId: firstEnvironment, image });
195 await Promise.resolve();
196
197 let settled = awaitAttachmentUploads([image.id]);
198 TestXmlHttpRequest.requests[0]!.complete(500);
199 await settled;
200 expect(readAttachmentUpload(image.id)).toMatchObject({
201 status: "failed",
202 reason: "Upload rejected (500)",
203 });
204
205 retryAttachmentUpload({ environmentId: firstEnvironment, image });
206 await Promise.resolve();
207 settled = awaitAttachmentUploads([image.id]);
208 TestXmlHttpRequest.requests[1]!.complete();
209 await settled;
210
211 expect(readAttachmentUpload(image.id)).toMatchObject({ status: "ready" });
212 });
213
214 it("releases an upload URL that resolves after its image was removed", async () => {
215 const image = makeImage("image-cancelled");
216 const minted = {
217 _tag: "Success" as const,
218 value: {
219 attachmentId: "pending-environment-1-image-cancelled.png",
220 relativeUrl: "/api/attachments/upload/cancelled",
221 expiresAt: 1,
222 },
223 };
224 let resolveMint: (result: typeof minted) => void = () => {};
225 const pendingMint = new Promise<typeof minted>((resolve) => {
226 resolveMint = resolve;
227 });
228 let resolveDelete: () => void = () => {};
229 const deleted = new Promise<void>((resolve) => {
230 resolveDelete = resolve;
231 });
232 mocks.runAtomCommand.mockImplementation((_registry: unknown, command: unknown) => {
233 if (command === mocks.createUploadUrl) {
234 return pendingMint;
235 }
236 resolveDelete();
237 return Promise.resolve({ _tag: "Success", value: undefined });
238 });
239
240 startAttachmentUpload({ environmentId: firstEnvironment, image });
241 releaseAttachmentUpload(image.id);
242 resolveMint(minted);
243 await deleted;
244
245 expect(TestXmlHttpRequest.requests).toEqual([]);
246 expect(readAttachmentUpload(image.id)).toBeUndefined();
247 expect(mocks.runAtomCommand).toHaveBeenCalledWith(
248 expect.anything(),
249 mocks.removeUpload,
250 {
251 environmentId: firstEnvironment,
252 input: { attachmentId: minted.value.attachmentId },
253 },
254 expect.anything(),
255 );
256 });
257
258 it("restores the previous environment after a replacement upload fails", async () => {
259 const image = makeImage("image-move");
260 startAttachmentUpload({ environmentId: firstEnvironment, image });
261 await Promise.resolve();
262 let settled = awaitAttachmentUploads([image.id]);
263 TestXmlHttpRequest.requests[0]!.complete();
264 await settled;
265
266 startAttachmentUpload({ environmentId: secondEnvironment, image });
267 await Promise.resolve();
268 settled = awaitAttachmentUploads([image.id]);
269 TestXmlHttpRequest.requests[1]!.complete(500);
270 await settled;
271
272 startAttachmentUpload({ environmentId: firstEnvironment, image });
273 expect(readAttachmentUpload(image.id)).toMatchObject({
274 status: "ready",
275 environmentId: firstEnvironment,
276 attachmentId: "pending-environment-1-image-move.png",
277 });
278 });
279
280 it("does not let stalled uploads block another environment", async () => {
281 const images = ["image-a", "image-b", "image-c", "image-d"].map(makeImage);
282 for (const image of images) {
283 startAttachmentUpload({ environmentId: firstEnvironment, image });
284 }
285 const otherEnvironmentImage = makeImage("image-other");
286 startAttachmentUpload({ environmentId: secondEnvironment, image: otherEnvironmentImage });
287 await Promise.resolve();
288
289 expect(TestXmlHttpRequest.requests).toHaveLength(4);
290 const otherRequest = TestXmlHttpRequest.requests.find((request) =>
291 request.url?.includes("environment-2"),
292 );
293 expect(otherRequest).toBeDefined();
294
295 for (const request of TestXmlHttpRequest.requests) {
296 request.complete();
297 }
298 await Promise.all([
299 ...images.slice(0, 3).map((image) => awaitAttachmentUploads([image.id])),
300 awaitAttachmentUploads([otherEnvironmentImage.id]),
301 ]);
302 await Promise.resolve();
303 TestXmlHttpRequest.requests[4]!.complete();
304 await awaitAttachmentUploads([images[3]!.id]);
305 });
306});