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

attachmentUploadQueue.ts

609 lines20.1 KB

1import {
2 PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES,
3 type ChatAttachment,
4 type EnvironmentId,
5} from "@t3tools/contracts";
6import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
7import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
8import {
9 deletePendingAttachmentUpload,
10 runAttachmentUploadCycle,
11 verifyPersistedAttachmentUpload,
12 type PersistedAttachmentVerification,
13} from "@t3tools/client-runtime/state/attachments";
14import { create } from "zustand";
15​
16import {
17 DraftId,
18 useComposerDraftStore,
19 type ComposerFileAttachment,
20 type ComposerImageAttachment,
21 type ComposerThreadTarget,
22} from "../composerDraftStore";
23import { appAtomRegistry } from "../rpc/atomRegistry";
24import { assetEnvironment } from "../state/assets";
25import { attachmentEnvironment } from "../state/attachments";
26import { readPreparedConnection } from "../state/session";
27import type { AttachmentUploadState, ReadyAttachmentUpload } from "./attachmentUploadState";
28​
29const MAX_UPLOADS_PER_ENVIRONMENT = 3;
30const UPLOAD_TIMEOUT_MS = 5 * 60_000;
31​
32interface AttachmentUploadStore {
33 readonly uploadsByImageId: Readonly<Record<string, AttachmentUploadState>>;
35​
36export const useAttachmentUploadStore = create<AttachmentUploadStore>(() => ({
37 uploadsByImageId: {},
38}));
39​
40interface UploadJob {
41 readonly image: ComposerImageAttachment | ComposerFileAttachment;
42 readonly environmentId: EnvironmentId;
43 /**
44 * The draft that owned this file when the job started. Completion resolves
45 * the current owner because the file can move while the upload is pending.
46 */
47 readonly draftTarget?: ComposerThreadTarget;
48 readonly previous?: ReadyAttachmentUpload;
49 /**
50 * The draft's persisted server-side upload, to verify instead of re-upload.
51 * The draft owns this id; the queue never deletes it on cancel or retry.
52 * Deleting it goes through `releasePersistedAttachmentUpload` only.
53 */
54 readonly persistedAttachmentId?: string;
55 readonly settled: Promise<void>;
56 resolveSettled: () => void;
57 /** Only ids this queue minted itself. Cancel and retry may delete these. */
58 attachmentId: string | null;
59 cancelled: boolean;
60 abort: (() => void) | null;
62​
63const jobsByImageId = new Map<string, UploadJob>();
64const queue: UploadJob[] = [];
65const activeUploadsByEnvironment = new Map<EnvironmentId, number>();
66​
67function setUploadState(imageId: string, upload: AttachmentUploadState): void {
68 useAttachmentUploadStore.setState((state) => ({
69 uploadsByImageId: { ...state.uploadsByImageId, [imageId]: upload },
70 }));
72​
73function clearUploadState(imageId: string): void {
74 useAttachmentUploadStore.setState((state) => {
75 if (!(imageId in state.uploadsByImageId)) {
76 return state;
77 }
78 const uploadsByImageId = { ...state.uploadsByImageId };
79 delete uploadsByImageId[imageId];
80 return { uploadsByImageId };
81 });
83​
84export function readAttachmentUpload(imageId: string): AttachmentUploadState | undefined {
85 return useAttachmentUploadStore.getState().uploadsByImageId[imageId];
87​
88/** Finds the file's current same-environment draft after any in-flight move. */
89function resolveCurrentFileDraftTarget(job: UploadJob): ComposerThreadTarget | undefined {
90 if (job.draftTarget === undefined || job.image.type !== "file") {
91 return undefined;
92 }
93 const store = useComposerDraftStore.getState();
94 for (const [key, draft] of Object.entries(store.draftsByThreadKey)) {
95 if (!draft.files.some((file) => file.id === job.image.id)) {
96 continue;
97 }
98 const draftSession = store.draftThreadsByThreadKey[key];
99 if (draftSession !== undefined) {
100 if (draftSession.environmentId === job.environmentId) {
101 return DraftId.make(key);
102 }
103 continue;
104 }
105 // Tests and legacy callers can use a DraftId without session metadata.
106 // Only its original job supplies enough environment identity to trust it.
107 if (typeof job.draftTarget === "string" && job.draftTarget === key) {
108 return DraftId.make(key);
109 }
110 const threadRef = parseScopedThreadKey(key);
111 if (threadRef?.environmentId === job.environmentId) {
112 return threadRef;
113 }
114 }
115 return undefined;
117​
118/**
119 * Persists a finished upload's ids onto the draft that owns the file. The
120 * mounted composer effect performs the same write for live UI updates, but a
121 * background completion (user navigated away, upload finished, reload) must
122 * not depend on a mounted composer to survive. `setFileUpload` no-ops when
123 * the draft row is gone or already carries these ids.
124 */
125function stampDraftFileUpload(job: UploadJob, attachmentId: string): void {
126 const draftTarget = resolveCurrentFileDraftTarget(job);
127 if (draftTarget === undefined) {
128 return;
129 }
130 useComposerDraftStore
131 .getState()
132 .setFileUpload(draftTarget, job.image.id, job.environmentId, attachmentId);
134​
135function deletePendingUpload(environmentId: EnvironmentId, attachmentId: string): void {
136 deletePendingAttachmentUpload({
137 registry: appAtomRegistry,
138 remove: attachmentEnvironment.remove,
139 environmentId,
140 attachmentId,
141 });
143​
144function uploadBytes(input: {
145 readonly url: string;
146 readonly file: File;
147 readonly mimeType: string;
148 readonly onProgress: (progress: number) => void;
149}): { readonly done: Promise<void>; readonly abort: () => void } {
150 const xhr = new XMLHttpRequest();
151 const done = new Promise<void>((resolve, reject) => {
152 xhr.open("POST", input.url, true);
153 xhr.timeout = UPLOAD_TIMEOUT_MS;
154 xhr.setRequestHeader("Content-Type", input.mimeType);
155 xhr.upload.addEventListener("progress", (event) => {
156 if (event.lengthComputable && event.total > 0) {
157 input.onProgress(event.loaded / event.total);
158 }
159 });
160 xhr.addEventListener("load", () => {
161 if (xhr.status >= 200 && xhr.status < 300) {
162 resolve();
163 } else {
164 reject(new Error(`Upload rejected (${xhr.status})`));
165 }
166 });
167 xhr.addEventListener("error", () => reject(new Error("Upload failed")));
168 xhr.addEventListener("timeout", () => reject(new Error("Upload timed out")));
169 xhr.addEventListener("abort", () => reject(new Error("Upload cancelled")));
170 xhr.send(input.file);
171 });
172​
173 return { done, abort: () => xhr.abort() };
175​
176async function runUpload(job: UploadJob): Promise<void> {
177 if (job.persistedAttachmentId) {
178 const verification = await verifyPersistedAttachmentUpload({
179 registry: appAtomRegistry,
180 createAssetUrl: assetEnvironment.createUrl,
181 environmentId: job.environmentId,
182 attachmentId: job.persistedAttachmentId,
183 });
184 if (job.cancelled) {
185 return;
186 }
187 if (verification.status === "verified") {
188 setUploadState(job.image.id, {
189 status: "ready",
190 environmentId: job.environmentId,
191 attachmentId: job.persistedAttachmentId,
192 });
193 stampDraftFileUpload(job, job.persistedAttachmentId);
194 return;
195 }
196 if (verification.status === "missing" && !job.image.file && job.image.type === "file") {
197 const draftTarget = resolveCurrentFileDraftTarget(job);
198 if (
199 draftTarget !== undefined &&
200 useComposerDraftStore
201 .getState()
202 .markFileUploadMissing(
203 draftTarget,
204 job.image.id,
205 job.environmentId,
206 job.persistedAttachmentId,
207 )
208 ) {
209 clearUploadState(job.image.id);
210 return;
211 }
212 }
213 if (verification.status === "failed" || !job.image.file) {
214 // No `attachmentId` here: a failed state's id marks a pending upload
215 // this queue minted, which retry and release then delete. The persisted
216 // id is the only server copy of a hydrated file, so a transient
217 // verification failure must leave it in place for the next retry.
218 setUploadState(job.image.id, {
219 status: "failed",
220 environmentId: job.environmentId,
221 reason:
222 verification.status === "missing"
223 ? "Uploaded file expired. Remove it and attach it again."
224 : "Uploaded file could not be verified. Retry when the server reconnects.",
225 ...(job.previous ? { previous: job.previous } : {}),
226 });
227 return;
228 }
229 }
230​
231 const mimeType =
232 job.image.type === "file"
233 ? job.image.mimeType.toLowerCase()
234 : PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES.find(
235 (supportedMimeType) => supportedMimeType === job.image.mimeType.toLowerCase(),
236 );
237 if (!mimeType) {
238 setUploadState(job.image.id, {
239 status: "failed",
240 environmentId: job.environmentId,
241 reason: "Unsupported image type",
242 ...(job.previous ? { previous: job.previous } : {}),
243 });
244 return;
245 }
246 const file = job.image.file;
247 if (!file) {
248 setUploadState(job.image.id, {
249 status: "failed",
250 environmentId: job.environmentId,
251 reason: "Original file is no longer available",
252 ...(job.previous ? { previous: job.previous } : {}),
253 });
254 return;
255 }
256​
257 let lastStep = -1;
258 const result = await runAttachmentUploadCycle({
259 registry: appAtomRegistry,
260 createUploadUrl: attachmentEnvironment.createUploadUrl,
261 remove: attachmentEnvironment.remove,
262 environmentId: job.environmentId,
263 upload: {
264 ...(job.image.type === "file" ? { type: "file" as const } : {}),
265 name: job.image.name,
266 mimeType,
267 sizeBytes: file.size,
268 },
269 resolveUploadUrl: (relativeUrl) => {
270 const connection = readPreparedConnection(job.environmentId);
271 return connection ? resolveAssetUrl(connection.httpBaseUrl, relativeUrl) : null;
272 },
273 transport: (url) =>
274 uploadBytes({
275 url,
276 file,
277 mimeType,
278 onProgress: (progress) => {
279 const step = Math.floor(progress * 20);
280 if (step === lastStep || job.cancelled) {
281 return;
282 }
283 lastStep = step;
284 setUploadState(job.image.id, {
285 status: "uploading",
286 environmentId: job.environmentId,
287 progress,
288 ...(job.previous ? { previous: job.previous } : {}),
289 });
290 },
291 }),
292 onMinted: (attachmentId) => {
293 if (job.cancelled) {
294 return "cancel";
295 }
296 job.attachmentId = attachmentId;
297 return "continue";
298 },
299 onTransferStart: (abort) => {
300 job.abort = abort;
301 },
302 });
303 job.abort = null;
304 if (result.status === "cancelled" || job.cancelled) {
305 return;
306 }
307 if (result.status === "uploaded") {
308 setUploadState(job.image.id, {
309 status: "ready",
310 environmentId: job.environmentId,
311 attachmentId: result.attachmentId,
312 });
313 stampDraftFileUpload(job, result.attachmentId);
314 if (job.previous) {
315 deletePendingUpload(job.previous.environmentId, job.previous.attachmentId);
316 }
317 return;
318 }
319 setUploadState(job.image.id, {
320 status: "failed",
321 environmentId: job.environmentId,
322 reason:
323 result.step === "mint"
324 ? "Upload could not start"
325 : result.step === "resolve-url"
326 ? "Not connected"
327 : result.error instanceof Error
328 ? result.error.message
329 : "Upload failed",
330 ...(result.attachmentId ? { attachmentId: result.attachmentId } : {}),
331 ...(job.previous ? { previous: job.previous } : {}),
332 });
334​
335function pumpUploads(): void {
336 for (let index = 0; index < queue.length; ) {
337 const job = queue[index]!;
338 const active = activeUploadsByEnvironment.get(job.environmentId) ?? 0;
339 if (active >= MAX_UPLOADS_PER_ENVIRONMENT) {
340 index += 1;
341 continue;
342 }
343​
344 queue.splice(index, 1);
345 if (job.cancelled) {
346 continue;
347 }
348 activeUploadsByEnvironment.set(job.environmentId, active + 1);
349 void runUpload(job)
350 .catch(() => {
351 if (!job.cancelled) {
352 setUploadState(job.image.id, {
353 status: "failed",
354 environmentId: job.environmentId,
355 reason: "Upload failed",
356 ...(job.previous ? { previous: job.previous } : {}),
357 });
358 }
359 })
360 .finally(() => {
361 if (jobsByImageId.get(job.image.id) === job) {
362 jobsByImageId.delete(job.image.id);
363 }
364 const remaining = (activeUploadsByEnvironment.get(job.environmentId) ?? 1) - 1;
365 if (remaining > 0) {
366 activeUploadsByEnvironment.set(job.environmentId, remaining);
367 } else {
368 activeUploadsByEnvironment.delete(job.environmentId);
369 }
370 job.resolveSettled();
371 pumpUploads();
372 });
373 }
375​
376export function startAttachmentUpload(input: {
377 readonly environmentId: EnvironmentId;
378 readonly image: ComposerImageAttachment | ComposerFileAttachment;
379 /** Draft that owns the file; lets a background completion persist its ids. */
380 readonly draftTarget?: ComposerThreadTarget;
381}): void {
382 const existingJob = jobsByImageId.get(input.image.id);
383 if (existingJob?.environmentId === input.environmentId) {
384 return;
385 }
386​
387 const existing = readAttachmentUpload(input.image.id);
388 if (existing?.status === "ready" && existing.environmentId === input.environmentId) {
389 return;
390 }
391 if (existing?.status === "failed" && existing.environmentId === input.environmentId) {
392 return;
393 }
394 if (
395 existing &&
396 "previous" in existing &&
397 existing.previous?.environmentId === input.environmentId
398 ) {
399 cancelAttachmentUpload(input.image.id);
400 if (existing.status === "failed" && existing.attachmentId) {
401 deletePendingUpload(existing.environmentId, existing.attachmentId);
402 }
403 setUploadState(input.image.id, existing.previous);
404 return;
405 }
406​
407 if (existingJob) {
408 cancelAttachmentUpload(input.image.id);
409 }
410 const previous = existing?.status === "ready" ? existing : existing?.previous;
411 let resolveSettled: () => void = () => {};
412 const settled = new Promise<void>((resolve) => {
413 resolveSettled = resolve;
414 });
415 const job: UploadJob = {
416 image: input.image,
417 environmentId: input.environmentId,
418 ...(input.draftTarget !== undefined ? { draftTarget: input.draftTarget } : {}),
419 ...(previous ? { previous } : {}),
420 ...(input.image.type === "file" &&
421 input.image.uploadEnvironmentId === input.environmentId &&
422 input.image.uploadedAttachmentId
423 ? { persistedAttachmentId: input.image.uploadedAttachmentId }
424 : {}),
425 settled,
426 resolveSettled,
427 attachmentId: null,
428 cancelled: false,
429 abort: null,
430 };
431​
432 jobsByImageId.set(input.image.id, job);
433 queue.push(job);
434 setUploadState(input.image.id, {
435 status: "uploading",
436 environmentId: input.environmentId,
437 progress: 0,
438 ...(previous ? { previous } : {}),
439 });
440 pumpUploads();
442​
443/**
444 * Stops the job and deletes only the pending upload it minted itself. A
445 * persisted draft upload survives cancellation (an environment switch cancels
446 * the old job, and the draft still references that server copy).
447 */
448export function cancelAttachmentUpload(imageId: string): void {
449 const job = jobsByImageId.get(imageId);
450 if (!job) {
451 return;
452 }
453 job.cancelled = true;
454 jobsByImageId.delete(imageId);
455 const queuedIndex = queue.indexOf(job);
456 if (queuedIndex !== -1) {
457 queue.splice(queuedIndex, 1);
458 }
459 job.abort?.();
460 if (job.attachmentId) {
461 deletePendingUpload(job.environmentId, job.attachmentId);
462 }
463 job.resolveSettled();
465​
466export function releaseAttachmentUpload(imageId: string): void {
467 const upload = readAttachmentUpload(imageId);
468 cancelAttachmentUpload(imageId);
469 if (upload?.status === "ready") {
470 deletePendingUpload(upload.environmentId, upload.attachmentId);
471 } else if (upload) {
472 if (upload.status === "failed" && upload.attachmentId) {
473 deletePendingUpload(upload.environmentId, upload.attachmentId);
474 }
475 if (upload.previous) {
476 deletePendingUpload(upload.previous.environmentId, upload.previous.attachmentId);
477 }
478 }
479 clearUploadState(imageId);
481​
482export function releasePersistedAttachmentUpload(input: {
483 readonly id: string;
484 readonly environmentId: EnvironmentId;
485 readonly attachmentId: string;
486}): void {
487 const upload = readAttachmentUpload(input.id);
488 if (
489 upload?.status === "ready" &&
490 upload.environmentId === input.environmentId &&
491 upload.attachmentId === input.attachmentId
492 ) {
493 releaseAttachmentUpload(input.id);
494 return;
495 }
496 const job = jobsByImageId.get(input.id);
497 if (
498 job?.environmentId === input.environmentId &&
499 job.persistedAttachmentId === input.attachmentId
500 ) {
501 // Tears down the in-flight verification or re-upload. The queue only
502 // deletes ids it minted, so the persisted id still needs the delete below.
503 releaseAttachmentUpload(input.id);
504 }
505 deletePendingUpload(input.environmentId, input.attachmentId);
507​
508export function retryAttachmentUpload(input: {
509 readonly environmentId: EnvironmentId;
510 readonly image: ComposerImageAttachment | ComposerFileAttachment;
511 readonly draftTarget?: ComposerThreadTarget;
512}): void {
513 const previous = readAttachmentUpload(input.image.id);
514 cancelAttachmentUpload(input.image.id);
515 // A failed state's `attachmentId` is always one this queue minted, so this
516 // never deletes a persisted draft upload. Retrying a hydrated file whose
517 // verification failed leaves the server copy alone and verifies it again.
518 if (previous?.status === "failed" && previous.attachmentId) {
519 deletePendingUpload(previous.environmentId, previous.attachmentId);
520 }
521 if (previous && "previous" in previous && previous.previous) {
522 setUploadState(input.image.id, previous.previous);
523 } else {
524 clearUploadState(input.image.id);
525 }
526 startAttachmentUpload(input);
528​
529/**
530 * Checks that a stashed upload still exists on the server. Pending uploads
531 * are swept after 24 hours, so a stash restore asks first instead of handing
532 * the composer a dead reference.
533 */
534export function verifyStashedAttachmentUpload(input: {
535 readonly environmentId: EnvironmentId;
536 readonly attachmentId: string;
537}): Promise<PersistedAttachmentVerification> {
538 return verifyPersistedAttachmentUpload({
539 registry: appAtomRegistry,
540 createAssetUrl: assetEnvironment.createUrl,
541 environmentId: input.environmentId,
542 attachmentId: input.attachmentId,
543 });
545​
546export async function awaitAttachmentUploads(imageIds: ReadonlyArray<string>): Promise<void> {
547 await Promise.all(imageIds.map((imageId) => jobsByImageId.get(imageId)?.settled));
549​
550export function getUploadedAttachments(input: {
551 readonly environmentId: EnvironmentId;
552 readonly images: ReadonlyArray<ComposerImageAttachment | ComposerFileAttachment>;
553}): ChatAttachment[] | null {
554 const attachments: ChatAttachment[] = [];
555 for (const image of input.images) {
556 const upload = readAttachmentUpload(image.id);
557 if (upload?.status !== "ready" || upload.environmentId !== input.environmentId) {
558 return null;
559 }
560 attachments.push({
561 type: image.type,
562 id: upload.attachmentId,
563 name: image.name,
564 mimeType: image.mimeType,
565 sizeBytes: image.sizeBytes,
566 });
567 }
568 return attachments;
570​
571/**
572 * The one owner for discarding a draft attachment's server-side upload. The
573 * queue-keyed release only sees in-memory state, so after a reload it finds
574 * nothing and the pending upload leaks. When the draft carries a persisted
575 * `uploadedAttachmentId` (which survives reloads), route through the persisted
576 * release; it still prefers the queue path when the queue owns that same
577 * attachment. Every draft discard path must funnel through here.
578 */
579export function releaseDraftAttachment(
580 attachment: ComposerImageAttachment | ComposerFileAttachment,
581): void {
582 if (
583 attachment.type === "file" &&
584 attachment.uploadedAttachmentId !== undefined &&
585 attachment.uploadEnvironmentId !== undefined
586 ) {
587 releasePersistedAttachmentUpload({
588 id: attachment.id,
589 environmentId: attachment.uploadEnvironmentId,
590 attachmentId: attachment.uploadedAttachmentId,
591 });
592 // A failed re-upload after verification can hold a newer minted
593 // attachment under the queue key. Release whatever is left so neither
594 // copy stays behind. (The pending delete is idempotent server-side.)
595 if (jobsByImageId.has(attachment.id) || readAttachmentUpload(attachment.id)) {
596 releaseAttachmentUpload(attachment.id);
597 }
598 return;
599 }
600 releaseAttachmentUpload(attachment.id);
602​
603export function releaseDraftAttachments(
604 attachments: ReadonlyArray<ComposerImageAttachment | ComposerFileAttachment>,
605): void {
606 for (const attachment of attachments) {
607 releaseDraftAttachment(attachment);
608 }