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

attachmentUploadQueue.ts

654 lines22.9 KB

1import {
2 AuthOrchestrationOperateScope,
3 AuthOrchestrationReadScope,
4 PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES,
5 type ChatAttachment,
6 type EnvironmentId,
7} from "@t3tools/contracts";
8import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
9import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
10import {
11 attachmentUploadError,
12 createAttachmentUploadRegistry,
13} from "@t3tools/client-runtime/state/attachment-uploads";
14import {
15 deletePendingAttachmentUpload,
16 runAttachmentUploadCycle,
17 verifyPersistedAttachmentUpload,
18 type PersistedAttachmentVerification,
19} from "@t3tools/client-runtime/state/attachments";
20import { create } from "zustand";
21import * as Effect from "effect/Effect";
22import * as Fiber from "effect/Fiber";
23import * as Option from "effect/Option";
24import { AsyncResult } from "effect/reactivity";
25​
26import {
27 DraftId,
28 useComposerDraftStore,
29 type ComposerFileAttachment,
30 type ComposerImageAttachment,
31 type ComposerThreadTarget,
32} from "../composerDraftStore";
33import { appAtomRegistry } from "../rpc/atomRegistry";
34import { environmentCatalog } from "../connection/catalog";
35import { assetEnvironment } from "../state/assets";
36import { attachmentEnvironment } from "../state/attachments";
37import { readEnvironmentScope, readPreparedConnection } from "../state/session";
38import type { AttachmentUploadState, ReadyAttachmentUpload } from "./attachmentUploadState";
39​
40const MAX_UPLOADS_PER_ENVIRONMENT = 3;
41const UPLOAD_TIMEOUT_MS = 5 * 60_000;
42​
43interface AttachmentUploadStore {
44 readonly uploadsByImageId: Readonly<Record<string, AttachmentUploadState>>;
46​
47export const useAttachmentUploadStore = create<AttachmentUploadStore>(() => ({
48 uploadsByImageId: {},
49}));
50​
51interface UploadJob {
52 readonly image: ComposerImageAttachment | ComposerFileAttachment;
53 readonly environmentId: EnvironmentId;
54 /** Original owner; completion resolves the current owner because uploads can outlive draft moves. */
55 readonly draftTarget?: ComposerThreadTarget;
56 readonly previous?: ReadyAttachmentUpload;
57 /** Draft-owned; delete only through releasePersistedAttachmentUpload, never queue cancel/retry. */
58 readonly persistedAttachmentId?: string;
60​
61type DraftFileOwner = Pick<UploadJob, "image" | "environmentId" | "draftTarget">;
62​
63/** The upload each image holds; a failed one stays held for its retry. */
64interface HeldUpload {
65 readonly job: UploadJob;
66 readonly release: () => void;
67 readonly stopWatchingConnection: () => void;
69​
70const heldUploads = new Map<string, HeldUpload>();
71const jobKey = (job: UploadJob) => `${job.environmentId}:${job.image.id}`;
72​
73function setUploadState(imageId: string, upload: AttachmentUploadState): void {
74 useAttachmentUploadStore.setState((state) => ({
75 uploadsByImageId: { ...state.uploadsByImageId, [imageId]: upload },
76 }));
78​
79function clearUploadState(imageId: string): void {
80 useAttachmentUploadStore.setState((state) => {
81 if (!(imageId in state.uploadsByImageId)) {
82 return state;
83 }
84 const uploadsByImageId = { ...state.uploadsByImageId };
85 delete uploadsByImageId[imageId];
86 return { uploadsByImageId };
87 });
89​
90export function readAttachmentUpload(imageId: string): AttachmentUploadState | undefined {
91 return useAttachmentUploadStore.getState().uploadsByImageId[imageId];
93​
94function resolveCurrentFileDraftTarget(job: DraftFileOwner): 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 if (typeof job.draftTarget === "string" && job.draftTarget === key) {
111 return DraftId.make(key);
112 }
113 const threadRef = parseScopedThreadKey(key);
114 if (threadRef?.environmentId === job.environmentId) {
115 return threadRef;
116 }
117 }
118 return undefined;
120​
121/** Persist background completions even when no composer is mounted. */
122function stampDraftFileUpload(job: DraftFileOwner, attachmentId: string): void {
123 const draftTarget = resolveCurrentFileDraftTarget(job);
124 if (draftTarget === undefined) {
125 return;
126 }
127 useComposerDraftStore
128 .getState()
129 .setFileUpload(draftTarget, job.image.id, job.environmentId, attachmentId);
131​
132function deletePendingUpload(environmentId: EnvironmentId, attachmentId: string): void {
133 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return;
134 deletePendingAttachmentUpload({
135 registry: appAtomRegistry,
136 remove: attachmentEnvironment.remove,
137 environmentId,
138 attachmentId,
139 });
141​
142function uploadBytes(input: {
143 readonly url: string;
144 readonly file: File;
145 readonly mimeType: string;
146 readonly signal: AbortSignal;
147 readonly onProgress: (progress: number) => void;
148}): Promise<void> {
149 const xhr = new XMLHttpRequest();
150 return 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 input.signal.addEventListener("abort", () => xhr.abort(), { once: true });
170 xhr.send(input.file);
171 });
173​
174const canOperate = (environmentId: EnvironmentId) =>
175 readEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
176​
177/** Records the failure the composer shows, then fails the upload with it. */
178const failUpload = (job: UploadJob, reason: string, attachmentId?: string) =>
179 Effect.sync(() =>
180 setUploadState(job.image.id, {
181 status: "failed",
182 environmentId: job.environmentId,
183 reason,
184 ...(attachmentId ? { attachmentId } : {}),
185 ...(job.previous ? { previous: job.previous } : {}),
186 }),
187 ).pipe(Effect.andThen(Effect.fail(attachmentUploadError(new Error(reason)))));
188​
189/** Uploads one composer attachment, writing the state its composer shows as it goes. */
190const uploadJob = Effect.fn("WebAttachmentUploads.upload")(function* (job: UploadJob) {
191 if (!canOperate(job.environmentId)) {
192 return yield* failUpload(job, "This connection cannot upload attachments.");
193 }
194 if (job.persistedAttachmentId) {
195 const verification = yield* verifyPersistedAttachmentUpload({
196 registry: appAtomRegistry,
197 createAssetUrl: assetEnvironment.createUrl,
198 environmentId: job.environmentId,
199 attachmentId: job.persistedAttachmentId,
200 });
201 if (verification.status === "verified") {
202 setUploadState(job.image.id, {
203 status: "ready",
204 environmentId: job.environmentId,
205 attachmentId: job.persistedAttachmentId,
206 });
207 stampDraftFileUpload(job, job.persistedAttachmentId);
208 return job.persistedAttachmentId;
209 }
210 if (verification.status === "missing" && !job.image.file && job.image.type === "file") {
211 const draftTarget = resolveCurrentFileDraftTarget(job);
212 if (
213 draftTarget !== undefined &&
214 useComposerDraftStore
215 .getState()
216 .markFileUploadMissing(
217 draftTarget,
218 job.image.id,
219 job.environmentId,
220 job.persistedAttachmentId,
221 )
222 ) {
223 // The draft now shows the file as missing, so the composer has no upload to show.
224 clearUploadState(job.image.id);
225 return yield* attachmentUploadError(new Error("Uploaded file expired."));
226 }
227 }
228 if (verification.status === "failed" || !job.image.file) {
229 // Failed-state ids get deleted on retry/release; exclude persisted ids after transient verification failure.
230 return yield* failUpload(
231 job,
232 verification.status === "missing"
233 ? "Uploaded file expired. Remove it and attach it again."
234 : "Uploaded file could not be verified. Retry when the server reconnects.",
235 );
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) return yield* failUpload(job, "Unsupported image type");
246 const file = job.image.file;
247 if (!file) return yield* failUpload(job, "Original file is no longer available");
248 if (!canOperate(job.environmentId)) {
249 return yield* failUpload(job, "This connection cannot upload attachments.");
250 }
251​
252 let lastStep = -1;
253 const result = yield* runAttachmentUploadCycle({
254 registry: appAtomRegistry,
255 createUploadUrl: attachmentEnvironment.createUploadUrl,
256 remove: attachmentEnvironment.remove,
257 environmentId: job.environmentId,
258 upload: {
259 ...(job.image.type === "file" ? { type: "file" as const } : {}),
260 name: job.image.name,
261 mimeType,
262 sizeBytes: file.size,
263 },
264 resolveUploadUrl: (relativeUrl) => {
265 if (!canOperate(job.environmentId)) return null;
266 const connection = readPreparedConnection(job.environmentId);
267 return connection ? resolveAssetUrl(connection.httpBaseUrl, relativeUrl) : null;
268 },
269 transport: (url) =>
270 Effect.tryPromise({
271 try: (signal) =>
272 uploadBytes({
273 url,
274 file,
275 mimeType,
276 signal,
277 onProgress: (progress) => {
278 const step = Math.floor(progress * 20);
279 if (step === lastStep || signal.aborted) return;
280 lastStep = step;
281 setUploadState(job.image.id, {
282 status: "uploading",
283 environmentId: job.environmentId,
284 progress,
285 ...(job.previous ? { previous: job.previous } : {}),
286 });
287 },
288 }),
289 catch: attachmentUploadError,
290 }),
291 });
292 if (result.status === "uploaded") {
293 setUploadState(job.image.id, {
294 status: "ready",
295 environmentId: job.environmentId,
296 attachmentId: result.attachmentId,
297 });
298 stampDraftFileUpload(job, result.attachmentId);
299 if (job.previous) {
300 deletePendingUpload(job.previous.environmentId, job.previous.attachmentId);
301 }
302 return result.attachmentId;
303 }
304 return yield* failUpload(
305 job,
306 result.step === "mint"
307 ? "Upload could not start"
308 : result.step === "resolve-url"
309 ? canOperate(job.environmentId)
310 ? "Not connected"
311 : "This connection cannot upload attachments."
312 : result.error instanceof Error
313 ? result.error.message
314 : "Upload failed",
315 result.attachmentId ?? undefined,
316 );
317});
318​
319const uploads = createAttachmentUploadRegistry<UploadJob>({
320 key: jobKey,
321 environmentId: (job) => job.environmentId,
322 concurrencyPerEnvironment: MAX_UPLOADS_PER_ENVIRONMENT,
323 upload: (job) =>
324 uploadJob(job).pipe(
325 Effect.catchDefect((defect) =>
326 failUpload(job, "Upload failed").pipe(
327 Effect.ensuring(Effect.logWarning("Composer attachment upload threw", defect)),
328 ),
329 ),
330 ),
331});
332​
333/** Waits for an image's held upload to finish, without keeping it running. */
334function awaitHeldUpload(imageId: string): Effect.Effect<void> {
335 const held = heldUploads.get(imageId);
336 const fiber = held === undefined ? undefined : uploads.current(jobKey(held.job));
337 return fiber === undefined ? Effect.void : Effect.asVoid(Fiber.await(fiber));
339​
340export function startAttachmentUpload(input: {
341 readonly environmentId: EnvironmentId;
342 readonly image: ComposerImageAttachment | ComposerFileAttachment;
343 readonly draftTarget?: ComposerThreadTarget;
344 readonly force?: boolean;
345}): void {
346 if (!canOperate(input.environmentId)) return;
347 const existingHold = heldUploads.get(input.image.id);
348 if (existingHold?.job.environmentId === input.environmentId) {
349 return;
350 }
351​
352 const existing = readAttachmentUpload(input.image.id);
353 if (
354 !input.force &&
355 existing?.status === "ready" &&
356 existing.environmentId === input.environmentId
357 ) {
358 // A file restored into a draft after its upload finished (stash, failed send) missed the
359 // completion stamp; stamping here keeps it from re-uploading after a reload.
360 stampDraftFileUpload(input, existing.attachmentId);
361 return;
362 }
363 if (existing?.status === "failed" && existing.environmentId === input.environmentId) {
364 return;
365 }
366 if (
367 existing &&
368 "previous" in existing &&
369 existing.previous?.environmentId === input.environmentId
370 ) {
371 cancelAttachmentUpload(input.image.id);
372 if (existing.status === "failed" && existing.attachmentId) {
373 deletePendingUpload(existing.environmentId, existing.attachmentId);
374 }
375 setUploadState(input.image.id, existing.previous);
376 // Retargeting a scratch draft cleared the file's upload stamp; restore it for reloads.
377 stampDraftFileUpload(input, existing.previous.attachmentId);
378 return;
379 }
380​
381 if (existingHold) {
382 cancelAttachmentUpload(input.image.id);
383 }
384 const previous = existing?.status === "ready" ? existing : existing?.previous;
385 const job: UploadJob = {
386 image: input.image,
387 environmentId: input.environmentId,
388 ...(input.draftTarget !== undefined ? { draftTarget: input.draftTarget } : {}),
389 ...(previous ? { previous } : {}),
390 ...(!input.force &&
391 input.image.type === "file" &&
392 input.image.uploadEnvironmentId === input.environmentId &&
393 input.image.uploadedAttachmentId
394 ? { persistedAttachmentId: input.image.uploadedAttachmentId }
395 : {}),
396 };
397​
398 setUploadState(input.image.id, {
399 status: "uploading",
400 environmentId: input.environmentId,
401 progress: 0,
402 ...(previous ? { previous } : {}),
403 });
404 const connectionAtom = environmentCatalog.stateAtom(job.environmentId);
405 const isConnected = () =>
406 Option.exists(
407 AsyncResult.value(appAtomRegistry.get(connectionAtom)),
408 (state) => state.phase === "connected",
409 );
410 const ownsImage = () => heldUploads.get(input.image.id)?.job === job;
411 let wasConnected = isConnected();
412 const stopWatchingConnection = appAtomRegistry.subscribe(connectionAtom, () => {
413 const connected = isConnected();
414 const reconnected = connected && !wasConnected;
415 wasConnected = connected;
416 if (!reconnected) return;
417 // HTTP failures can follow reconnection; await the attempt and retry only if this job still owns the file.
418 Effect.runFork(
419 awaitHeldUpload(input.image.id).pipe(
420 Effect.andThen(
421 Effect.sync(() => {
422 if (
423 ownsImage() &&
424 readAttachmentUpload(input.image.id)?.status === "failed" &&
425 isConnected()
426 ) {
427 retryAttachmentUpload(input);
428 }
429 }),
430 ),
431 ),
432 );
433 });
434 heldUploads.set(input.image.id, {
435 job,
436 release: uploads.hold(job),
437 stopWatchingConnection,
438 });
439 // A finished upload lets go of its image; a failed one stays held for its retry.
440 uploads.current(jobKey(job))?.addObserver((exit) => {
441 if (exit._tag !== "Success" || !ownsImage()) return;
442 const held = heldUploads.get(input.image.id)!;
443 heldUploads.delete(input.image.id);
444 held.stopWatchingConnection();
445 held.release();
446 });
448​
449function cancelAttachmentUpload(imageId: string): void {
450 const held = heldUploads.get(imageId);
451 if (!held) {
452 return;
453 }
454 heldUploads.delete(imageId);
455 held.stopWatchingConnection();
456 // Releasing interrupts a running upload, which aborts its transfer and deletes its mint.
457 held.release();
459​
460export function releaseAttachmentUpload(imageId: string): void {
461 const upload = readAttachmentUpload(imageId);
462 cancelAttachmentUpload(imageId);
463 if (upload?.status === "ready") {
464 deletePendingUpload(upload.environmentId, upload.attachmentId);
465 } else if (upload) {
466 if (upload.status === "failed" && upload.attachmentId) {
467 deletePendingUpload(upload.environmentId, upload.attachmentId);
468 }
469 if (upload.previous) {
470 deletePendingUpload(upload.previous.environmentId, upload.previous.attachmentId);
471 }
472 }
473 clearUploadState(imageId);
475​
476export function releasePersistedAttachmentUpload(input: {
477 readonly id: string;
478 readonly environmentId: EnvironmentId;
479 readonly attachmentId: string;
480}): void {
481 const upload = readAttachmentUpload(input.id);
482 if (
483 upload?.status === "ready" &&
484 upload.environmentId === input.environmentId &&
485 upload.attachmentId === input.attachmentId
486 ) {
487 releaseAttachmentUpload(input.id);
488 return;
489 }
490 const held = heldUploads.get(input.id);
491 if (
492 held?.job.environmentId === input.environmentId &&
493 held.job.persistedAttachmentId === input.attachmentId
494 ) {
495 releaseAttachmentUpload(input.id);
496 }
497 deletePendingUpload(input.environmentId, input.attachmentId);
499​
500export function retryAttachmentUpload(input: {
501 readonly environmentId: EnvironmentId;
502 readonly image: ComposerImageAttachment | ComposerFileAttachment;
503 readonly draftTarget?: ComposerThreadTarget;
504}): void {
505 if (!canOperate(input.environmentId)) return;
506 const previous = readAttachmentUpload(input.image.id);
507 const held = heldUploads.get(input.image.id);
508 cancelAttachmentUpload(input.image.id);
509 // The failed upload stays cached until dropped, and the retry must start a fresh one.
510 if (held) uploads.invalidate(jobKey(held.job));
511 if (previous?.status === "failed" && previous.attachmentId) {
512 deletePendingUpload(previous.environmentId, previous.attachmentId);
513 }
514 if (previous && "previous" in previous && previous.previous) {
515 setUploadState(input.image.id, previous.previous);
516 } else {
517 clearUploadState(input.image.id);
518 }
519 startAttachmentUpload(input);
521​
522/** Verifies uploads before stash restore; pending uploads expire after 24 hours. */
523export function verifyStashedAttachmentUpload(input: {
524 readonly environmentId: EnvironmentId;
525 readonly attachmentId: string;
526}): Promise<PersistedAttachmentVerification> {
527 return Effect.runPromise(
528 verifyPersistedAttachmentUpload({
529 registry: appAtomRegistry,
530 createAssetUrl: assetEnvironment.createUrl,
531 environmentId: input.environmentId,
532 attachmentId: input.attachmentId,
533 }),
534 );
536​
537/** Resolves once these images' uploads finish, fail or are cancelled. */
538export function awaitAttachmentUploads(imageIds: ReadonlyArray<string>): Promise<void> {
539 return Effect.runPromise(
540 Effect.forEach(imageIds, awaitHeldUpload, { concurrency: "unbounded", discard: true }),
541 );
543​
544/** Revalidate ready uploads at send time; a long-lived draft can outlive server cleanup. */
545export async function refreshExpiredAttachmentUploads(input: {
546 readonly environmentId: EnvironmentId;
547 readonly images: ReadonlyArray<ComposerImageAttachment | ComposerFileAttachment>;
548 readonly draftTarget?: ComposerThreadTarget;
549}): Promise<void> {
550 const canVerify = readEnvironmentScope(input.environmentId, AuthOrchestrationReadScope);
551 await Promise.all(
552 input.images.map(async (image) => {
553 const upload = readAttachmentUpload(image.id);
554 if (upload?.status !== "ready" || upload.environmentId !== input.environmentId) return;
555 if (!canVerify) {
556 if (image.file) {
557 startAttachmentUpload({
558 environmentId: input.environmentId,
559 image,
560 force: true,
561 ...(input.draftTarget !== undefined ? { draftTarget: input.draftTarget } : {}),
562 });
563 } else {
564 setUploadState(image.id, {
565 status: "failed",
566 environmentId: input.environmentId,
567 previous: upload,
568 reason: "Uploaded attachment could not be verified. Attach the file again.",
569 });
570 }
571 return;
572 }
573 const verification = await verifyStashedAttachmentUpload({
574 environmentId: input.environmentId,
575 attachmentId: upload.attachmentId,
576 }).catch((error: unknown): PersistedAttachmentVerification => ({ status: "failed", error }));
577 // The user may have removed or replaced the attachment while verification was in flight.
578 if (readAttachmentUpload(image.id) !== upload) return;
579 if (verification.status === "verified") return;
580 if (verification.status === "missing" && image.file) {
581 clearUploadState(image.id);
582 startAttachmentUpload({
583 environmentId: input.environmentId,
584 image,
585 force: true,
586 ...(input.draftTarget !== undefined ? { draftTarget: input.draftTarget } : {}),
587 });
588 return;
589 }
590 setUploadState(image.id, {
591 status: "failed",
592 environmentId: input.environmentId,
593 previous: upload,
594 reason:
595 verification.status === "missing"
596 ? "Uploaded attachment expired. Remove it and attach it again."
597 : "Uploaded attachment could not be verified. Retry when the server reconnects.",
598 });
599 }),
600 );
601 await awaitAttachmentUploads(input.images.map((image) => image.id));
603​
604export function getUploadedAttachments(input: {
605 readonly environmentId: EnvironmentId;
606 readonly images: ReadonlyArray<ComposerImageAttachment | ComposerFileAttachment>;
607}): ChatAttachment[] | null {
608 const attachments: ChatAttachment[] = [];
609 for (const image of input.images) {
610 const upload = readAttachmentUpload(image.id);
611 if (upload?.status !== "ready" || upload.environmentId !== input.environmentId) {
612 return null;
613 }
614 attachments.push({
615 type: image.type,
616 id: upload.attachmentId,
617 name: image.name,
618 mimeType: image.mimeType,
619 sizeBytes: image.sizeBytes,
620 ...(image.source ? { source: image.source } : {}),
621 });
622 }
623 return attachments;
625​
626/** In-memory queue releases miss uploads after reload; every draft discard must use this path. */
627export function releaseDraftAttachment(
628 attachment: ComposerImageAttachment | ComposerFileAttachment,
629): void {
630 if (
631 attachment.type === "file" &&
632 attachment.uploadedAttachmentId !== undefined &&
633 attachment.uploadEnvironmentId !== undefined
634 ) {
635 releasePersistedAttachmentUpload({
636 id: attachment.id,
637 environmentId: attachment.uploadEnvironmentId,
638 attachmentId: attachment.uploadedAttachmentId,
639 });
640 if (heldUploads.has(attachment.id) || readAttachmentUpload(attachment.id)) {
641 releaseAttachmentUpload(attachment.id);
642 }
643 return;
644 }
645 releaseAttachmentUpload(attachment.id);
647​
648export function releaseDraftAttachments(
649 attachments: ReadonlyArray<ComposerImageAttachment | ComposerFileAttachment>,
650): void {
651 for (const attachment of attachments) {
652 releaseDraftAttachment(attachment);
653 }