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