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

attachmentUploadQueue.ts

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