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

attachmentUploadQueue.ts

649 lines21.0 KB

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