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

composerAttachmentUploadQueue.ts

208 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<ServerConfig["environment"]["capabilities"], "fileAttachments">;
52 };
53};
54​
55export function canUploadComposerAttachment(
56 attachment: DraftComposerAttachment,
57 config: UploadServerConfig | null | undefined,
58): boolean {
59 const capabilities = config?.environment.capabilities;
60 return (
61 capabilities !== undefined &&
62 (attachment.type === "image" ||
63 (capabilities.fileAttachments !== undefined &&
64 attachment.sizeBytes <=
65 clampFileAttachmentUploadBytes(capabilities.fileAttachments.maxUploadBytes)))
66 );
68​
69export function composerAttachmentUploadBlockReason(input: {
70 readonly environmentId: EnvironmentId;
71 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
72 readonly connected: boolean;
73 readonly serverConfig: UploadServerConfig | null;
74 readonly states: Readonly<Record<string, ComposerAttachmentUploadState>>;
75}): string | null {
76 if (!input.connected) return null;
77 for (const attachment of input.attachments) {
78 if (!canUploadComposerAttachment(attachment, input.serverConfig)) continue;
79 const state = input.states[composerAttachmentUploadKey(input.environmentId, attachment.id)];
80 if (state?.status === "failed") return "Retry or remove the failed attachment";
81 }
82 return null;
84​
85export function composerAttachmentsStillUploading(input: {
86 readonly environmentId: EnvironmentId;
87 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
88 readonly serverConfig: UploadServerConfig | null;
89 readonly states: Readonly<Record<string, ComposerAttachmentUploadState>>;
90}): boolean {
91 return input.attachments.some((attachment) => {
92 if (!canUploadComposerAttachment(attachment, input.serverConfig)) return false;
93 const state = input.states[composerAttachmentUploadKey(input.environmentId, attachment.id)];
94 return state?.status !== "ready" && state?.status !== "failed";
95 });
97​
98export function createComposerAttachmentUploadQueue(options: {
99 readonly upload: (
100 request: ComposerAttachmentUploadRequest,
101 signal: AbortSignal,
102 onProgress: (progress: number) => void,
103 ) => Promise<boolean>;
104 readonly onChange: (states: Readonly<Record<string, ComposerAttachmentUploadState>>) => void;
105}) {
106 const jobs = new Map<
107 string,
108 { readonly controller: AbortController; readonly done: Promise<void> }
109 >();
110 let desired = new Map<string, ComposerAttachmentUploadRequest>();
111 let states: Readonly<Record<string, ComposerAttachmentUploadState>> = {};
112 let disposed = false;
113​
114 function setState(key: string, state: ComposerAttachmentUploadState | undefined) {
115 const previous = states[key];
116 if (
117 previous === state ||
118 (previous?.status === "uploading" &&
119 state?.status === "uploading" &&
120 previous.progress === state.progress)
121 )
122 return;
123 const next = { ...states };
124 if (state) next[key] = state;
125 else delete next[key];
126 states = next;
127 options.onChange(states);
128 }
129​
130 function pump() {
131 if (disposed) return;
132 for (const [key, request] of desired) {
133 if (jobs.size >= 3) break;
134 if (jobs.has(key) || states[key]?.status === "ready" || states[key]?.status === "failed")
135 continue;
136 const controller = new AbortController();
137 setState(key, { status: "uploading", progress: 0 });
138 // Publish the job before starting async work, including synchronous test transports.
139 const done = Promise.resolve()
140 .then(() =>
141 options.upload(request, controller.signal, (progress) => {
142 if (controller.signal.aborted) return;
143 setState(key, {
144 status: "uploading",
145 progress: Math.floor(Math.max(0, Math.min(1, progress)) * 20) / 20,
146 });
147 }),
148 )
149 .then((persisted) => {
150 if (!controller.signal.aborted && desired.has(key)) {
151 if (!persisted) desired.delete(key);
152 setState(key, persisted ? { status: "ready" } : undefined);
153 }
154 })
155 .catch((error: unknown) => {
156 if (!controller.signal.aborted && desired.has(key)) {
157 setState(key, {
158 status: "failed",
159 reason: error instanceof Error ? error.message : "Upload failed. Tap to retry.",
160 });
161 }
162 })
163 .finally(() => {
164 jobs.delete(key);
165 pump();
166 });
167 jobs.set(key, { controller, done });
168 }
169 }
170​
171 return {
172 sync(requests: ReadonlyArray<ComposerAttachmentUploadRequest>) {
173 if (disposed) return;
174 desired = new Map(
175 requests.map((request) => [
176 composerAttachmentUploadKey(request.environmentId, request.attachment.id),
177 request,
178 ]),
179 );
180 for (const [key, job] of jobs) {
181 if (!desired.has(key)) job.controller.abort();
182 }
183 for (const key of Object.keys(states)) {
184 if (!desired.has(key)) setState(key, undefined);
185 }
186 for (const key of desired.keys()) {
187 if (!states[key]) setState(key, { status: "uploading", progress: 0 });
188 }
189 pump();
190 },
191 retry(environmentId: EnvironmentId, attachmentId: string) {
192 const key = composerAttachmentUploadKey(environmentId, attachmentId);
193 if (states[key]?.status !== "failed") return;
194 setState(key, undefined);
195 pump();
196 },
197 async settled() {
198 while (jobs.size > 0) await Promise.all([...jobs.values()].map((job) => job.done));
199 },
200 dispose() {
201 disposed = true;
202 desired.clear();
203 for (const job of jobs.values()) job.controller.abort();
204 states = {};
205 options.onChange(states);
206 },
207 };