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

composerAttachmentUploadQueue.ts

211 lines7.2 KB

1import { EnvironmentId, type ServerConfig } from "@t3tools/contracts";
2import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";
3​
4import { parseLegacyNewTaskDraftKey } from "../state/new-task-draft-key";
5import type { DraftComposerAttachment } from "./composerImages";
6​
7export interface ComposerAttachmentUploadRequest {
8 readonly environmentId: EnvironmentId;
9 readonly attachment: DraftComposerAttachment;
11​
12export type ComposerAttachmentUploadState =
13 | { readonly status: "uploading"; readonly progress: number }
14 | { readonly status: "ready" }
15 | { readonly status: "failed"; readonly reason: string };
16​
17export function composerAttachmentUploadKey(
18 environmentId: EnvironmentId,
19 attachmentId: string,
20): string {
21 return `${environmentId}:${attachmentId}`;
23​
24export function composerDraftEnvironmentId(
25 draftKey: string,
26 queuedMessages: ReadonlyArray<{
27 readonly messageId: string;
28 readonly environmentId: EnvironmentId;
29 }>,
30 draft?: { readonly project?: { readonly environmentId: EnvironmentId } },
31): EnvironmentId | null {
32 if (draftKey.startsWith("pending-task:")) {
33 return (
34 queuedMessages.find((message) => `pending-task:${message.messageId}` === draftKey)
35 ?.environmentId ?? null
36 );
37 }
38 if (draftKey.startsWith("new-task:")) {
39 if (draft?.project) {
40 return draft.project.environmentId;
41 }
42 const legacy = parseLegacyNewTaskDraftKey(draftKey);
43 return legacy === null ? null : EnvironmentId.make(legacy.environmentId);
44 }
45 const separator = draftKey.lastIndexOf(":");
46 return separator > 0 ? EnvironmentId.make(draftKey.slice(0, separator)) : null;
48​
49type UploadServerConfig = {
50 readonly environment: {
51 readonly capabilities: Pick<
52 ServerConfig["environment"]["capabilities"],
53 "attachmentUploads" | "fileAttachments"
54 >;
55 };
56};
57​
58export function canUploadComposerAttachment(
59 attachment: DraftComposerAttachment,
60 config: UploadServerConfig | null | undefined,
61): boolean {
62 const capabilities = config?.environment.capabilities;
63 return (
64 capabilities?.attachmentUploads === true &&
65 (attachment.type === "image" ||
66 (capabilities.fileAttachments !== undefined &&
67 attachment.sizeBytes <=
68 clampFileAttachmentUploadBytes(capabilities.fileAttachments.maxUploadBytes)))
69 );
71​
72export function composerAttachmentUploadBlockReason(input: {
73 readonly environmentId: EnvironmentId;
74 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
75 readonly connected: boolean;
76 readonly serverConfig: UploadServerConfig | null;
77 readonly states: Readonly<Record<string, ComposerAttachmentUploadState>>;
78}): string | null {
79 if (!input.connected) return null;
80 for (const attachment of input.attachments) {
81 if (!canUploadComposerAttachment(attachment, input.serverConfig)) continue;
82 const state = input.states[composerAttachmentUploadKey(input.environmentId, attachment.id)];
83 if (state?.status === "failed") return "Retry or remove the failed attachment";
84 }
85 return null;
87​
88export function composerAttachmentsStillUploading(input: {
89 readonly environmentId: EnvironmentId;
90 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
91 readonly serverConfig: UploadServerConfig | null;
92 readonly states: Readonly<Record<string, ComposerAttachmentUploadState>>;
93}): boolean {
94 return input.attachments.some((attachment) => {
95 if (!canUploadComposerAttachment(attachment, input.serverConfig)) return false;
96 const state = input.states[composerAttachmentUploadKey(input.environmentId, attachment.id)];
97 return state?.status !== "ready" && state?.status !== "failed";
98 });
100​
101export function createComposerAttachmentUploadQueue(options: {
102 readonly upload: (
103 request: ComposerAttachmentUploadRequest,
104 signal: AbortSignal,
105 onProgress: (progress: number) => void,
106 ) => Promise<boolean>;
107 readonly onChange: (states: Readonly<Record<string, ComposerAttachmentUploadState>>) => void;
108}) {
109 const jobs = new Map<
110 string,
111 { readonly controller: AbortController; readonly done: Promise<void> }
112 >();
113 let desired = new Map<string, ComposerAttachmentUploadRequest>();
114 let states: Readonly<Record<string, ComposerAttachmentUploadState>> = {};
115 let disposed = false;
116​
117 function setState(key: string, state: ComposerAttachmentUploadState | undefined) {
118 const previous = states[key];
119 if (
120 previous === state ||
121 (previous?.status === "uploading" &&
122 state?.status === "uploading" &&
123 previous.progress === state.progress)
124 )
125 return;
126 const next = { ...states };
127 if (state) next[key] = state;
128 else delete next[key];
129 states = next;
130 options.onChange(states);
131 }
132​
133 function pump() {
134 if (disposed) return;
135 for (const [key, request] of desired) {
136 if (jobs.size >= 3) break;
137 if (jobs.has(key) || states[key]?.status === "ready" || states[key]?.status === "failed")
138 continue;
139 const controller = new AbortController();
140 setState(key, { status: "uploading", progress: 0 });
141 // Publish the job before starting async work, including synchronous test transports.
142 const done = Promise.resolve()
143 .then(() =>
144 options.upload(request, controller.signal, (progress) => {
145 if (controller.signal.aborted) return;
146 setState(key, {
147 status: "uploading",
148 progress: Math.floor(Math.max(0, Math.min(1, progress)) * 20) / 20,
149 });
150 }),
151 )
152 .then((persisted) => {
153 if (!controller.signal.aborted && desired.has(key)) {
154 if (!persisted) desired.delete(key);
155 setState(key, persisted ? { status: "ready" } : undefined);
156 }
157 })
158 .catch((error: unknown) => {
159 if (!controller.signal.aborted && desired.has(key)) {
160 setState(key, {
161 status: "failed",
162 reason: error instanceof Error ? error.message : "Upload failed. Tap to retry.",
163 });
164 }
165 })
166 .finally(() => {
167 jobs.delete(key);
168 pump();
169 });
170 jobs.set(key, { controller, done });
171 }
172 }
173​
174 return {
175 sync(requests: ReadonlyArray<ComposerAttachmentUploadRequest>) {
176 if (disposed) return;
177 desired = new Map(
178 requests.map((request) => [
179 composerAttachmentUploadKey(request.environmentId, request.attachment.id),
180 request,
181 ]),
182 );
183 for (const [key, job] of jobs) {
184 if (!desired.has(key)) job.controller.abort();
185 }
186 for (const key of Object.keys(states)) {
187 if (!desired.has(key)) setState(key, undefined);
188 }
189 for (const key of desired.keys()) {
190 if (!states[key]) setState(key, { status: "uploading", progress: 0 });
191 }
192 pump();
193 },
194 retry(environmentId: EnvironmentId, attachmentId: string) {
195 const key = composerAttachmentUploadKey(environmentId, attachmentId);
196 if (states[key]?.status !== "failed") return;
197 setState(key, undefined);
198 pump();
199 },
200 async settled() {
201 while (jobs.size > 0) await Promise.all([...jobs.values()].map((job) => job.done));
202 },
203 dispose() {
204 disposed = true;
205 desired.clear();
206 for (const job of jobs.values()) job.controller.abort();
207 states = {};
208 options.onChange(states);
209 },
210 };