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

attachmentUpload.ts

404 lines14.7 KB

1import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
2import {
3 isAssetAttachmentNotFoundFailure,
4 runAttachmentUploadCycle,
5 verifyPersistedAttachmentUpload,
6} from "@t3tools/client-runtime/state/attachments";
7import { runAtomCommand, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
8import type {
9 ChatFileAttachment,
10 ChatImageAttachment,
11 EnvironmentId,
12 UploadChatImageAttachment,
13} from "@t3tools/contracts";
14import {
15 AuthOrchestrationOperateScope,
16 PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES,
17} from "@t3tools/contracts";
18import * as Option from "effect/Option";
19​
20import { appAtomRegistry } from "../state/atom-registry";
21import { assetEnvironment } from "../state/assets";
22import { attachmentEnvironment } from "../state/attachments";
23import { environmentSession, readEnvironmentScope } from "../state/session";
24import { resolveOwnedComposerAttachmentFileUri } from "./composerAttachmentFiles";
25import { retainComposerAttachmentFileForPreview } from "./composerAttachmentPreviewRetention";
26import {
27 isComposerImageAttachment,
28 isFileBackedComposerAttachment,
29 type DraftComposerAttachment,
30 type DraftComposerImageAttachment,
31} from "./composerImages";
32import { imageMimeType } from "@t3tools/shared/image";
33import { uuidv4 } from "./uuid";
34​
35export type UploadedMobileAttachment =
36 | UploadChatImageAttachment
37 | ChatImageAttachment
38 | ChatFileAttachment;
39​
40export function withUploadedMobileAttachmentReferences(input: {
41 readonly environmentId: EnvironmentId;
42 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
43 readonly uploadedAttachments: ReadonlyArray<UploadedMobileAttachment>;
44}): ReadonlyArray<DraftComposerAttachment> {
45 return input.attachments.map((attachment, index) => {
46 const uploaded = input.uploadedAttachments[index];
47 // Files-picked images upload as images; compare wire types to retain uploaded ids and avoid re-uploading.
48 const uploadedAs = isComposerImageAttachment(attachment) ? "image" : attachment.type;
49 if (
50 !uploaded ||
51 !("id" in uploaded) ||
52 uploadedAs !== uploaded.type ||
53 (attachment.uploadedAttachmentId === uploaded.id &&
54 attachment.uploadEnvironmentId === input.environmentId)
55 ) {
56 return attachment;
57 }
58 return {
59 ...attachment,
60 uploadedAttachmentId: uploaded.id,
61 uploadEnvironmentId: input.environmentId,
62 };
63 });
65​
66export async function releasePendingAttachmentUploads(
67 environmentId: EnvironmentId,
68 attachmentIds: ReadonlyArray<string>,
69): Promise<void> {
70 const deleteOnce = async (attachmentId: string): Promise<boolean> => {
71 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) {
72 throw new Error("This connection cannot delete pending attachments.");
73 }
74 const result = await runAtomCommand(
75 appAtomRegistry,
76 attachmentEnvironment.remove,
77 { environmentId, input: { attachmentId } },
78 { reportFailure: false, reportDefect: false },
79 );
80 return (
81 result._tag === "Success" ||
82 isAssetAttachmentNotFoundFailure(squashAtomCommandFailure(result))
83 );
84 };
85​
86 const failedAttachmentIds: string[] = [];
87 for (const attachmentId of attachmentIds) {
88 if (!(await deleteOnce(attachmentId)) && !(await deleteOnce(attachmentId))) {
89 failedAttachmentIds.push(attachmentId);
90 }
91 }
92 if (failedAttachmentIds.length > 0) {
93 throw new Error(
94 `Could not delete ${failedAttachmentIds.length} pending attachment upload(s): ${failedAttachmentIds.join(", ")}.`,
95 );
96 }
98​
99async function releaseCreatedUploadsQuietly(
100 environmentId: EnvironmentId,
101 attachmentIds: ReadonlyArray<string>,
102): Promise<void> {
103 try {
104 await releasePendingAttachmentUploads(environmentId, attachmentIds);
105 } catch (error) {
106 console.warn("[attachments] could not delete abandoned pending uploads", error);
107 }
109​
110export interface PreparedTurnAttachments {
111 readonly status: "ready";
112 readonly attachments: ReadonlyArray<UploadedMobileAttachment>;
113 readonly draftAttachments: ReadonlyArray<DraftComposerAttachment>;
114 readonly pendingAttachmentIds: ReadonlyArray<string>;
116​
117export type PrepareTurnAttachmentsResult =
118 | PreparedTurnAttachments
119 | { readonly status: "abandoned" };
120​
121/** Promote Files-picked images consistently in headers, payloads and references or ChatImageAttachment rejects them. */
122function composerAttachmentWireMimeType(attachment: DraftComposerAttachment): string {
123 if (!isComposerImageAttachment(attachment)) return attachment.mimeType;
124 return supportedImageWireMimeType(attachment);
126​
127function supportedImageWireMimeType(
128 attachment: DraftComposerAttachment,
129): (typeof PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES)[number] {
130 const inferred = imageMimeType(attachment);
131 const mimeType = PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES.find(
132 (type) => type === attachment.mimeType.toLowerCase() || type === inferred,
133 );
134 if (!mimeType) throw new Error(`Unsupported image type for '${attachment.name}'.`);
135 return mimeType;
137​
138function uploadedReference(
139 attachment: DraftComposerAttachment,
140 id: string,
141): ChatImageAttachment | ChatFileAttachment {
142 const fields = {
143 id,
144 name: attachment.name,
145 mimeType: composerAttachmentWireMimeType(attachment),
146 sizeBytes: attachment.sizeBytes,
147 };
148 return isComposerImageAttachment(attachment)
149 ? { type: "image", ...fields }
150 : {
151 type: "file",
152 ...fields,
153 ...(attachment.source ? { source: attachment.source } : {}),
154 };
156​
157function attachmentUploadInput(attachment: DraftComposerAttachment) {
158 const fields = { name: attachment.name, sizeBytes: attachment.sizeBytes };
159 return isComposerImageAttachment(attachment)
160 ? { ...fields, mimeType: supportedImageWireMimeType(attachment) }
161 : { type: "file" as const, ...fields, mimeType: attachment.mimeType };
163​
164async function toUploadChatImageAttachments(
165 attachments: ReadonlyArray<DraftComposerImageAttachment>,
166): Promise<ReadonlyArray<UploadChatImageAttachment>> {
167 return Promise.all(
168 attachments.map(async (attachment) => ({
169 type: attachment.type,
170 name: attachment.name,
171 mimeType: attachment.mimeType,
172 sizeBytes: attachment.sizeBytes,
173 dataUrl: await composerImageAttachmentDataUrl(attachment),
174 })),
175 );
177​
178async function composerImageAttachmentDataUrl(
179 attachment: DraftComposerImageAttachment,
180): Promise<string> {
181 if (attachment.dataUrl !== undefined) {
182 return attachment.dataUrl;
183 }
184 if (!isFileBackedComposerAttachment(attachment)) {
185 throw new Error(`'${attachment.name}' is no longer available. Attach the image again.`);
186 }
187 const release = retainComposerAttachmentFileForPreview(attachment);
188 try {
189 const { File, Paths } = await import("expo-file-system");
190 const uri =
191 resolveOwnedComposerAttachmentFileUri(attachment.fileUri, Paths.document.uri) ??
192 attachment.fileUri;
193 const base64 = await new File(uri).base64();
194 return `data:${attachment.mimeType};base64,${base64}`;
195 } finally {
196 release();
197 }
199​
200async function uploadFileBytes(
201 environmentId: EnvironmentId,
202 attachment: DraftComposerAttachment,
203 url: string,
204 signal: AbortSignal,
205 onProgress?: (progress: number) => void,
206): Promise<void> {
207 const { File, Paths, UploadType } = await import("expo-file-system");
208 if (signal.aborted) throw new Error("Upload cancelled.");
209 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) {
210 throw new Error("This connection cannot upload attachments.");
211 }
212 const fileUri = attachment.fileUri;
213 const inlineDataUrl = attachment.type === "image" ? attachment.dataUrl : undefined;
214 if (fileUri === undefined && inlineDataUrl === undefined) {
215 throw new Error(`'${attachment.name}' is no longer available. Attach the image again.`);
216 }
217 const file =
218 fileUri === undefined
219 ? new File(Paths.cache, `t3-upload-${uuidv4()}`)
220 : new File(resolveOwnedComposerAttachmentFileUri(fileUri, Paths.document.uri) ?? fileUri);
221 try {
222 if (fileUri === undefined && inlineDataUrl !== undefined) {
223 file.create();
224 await file.write(inlineDataUrl.slice(inlineDataUrl.indexOf(",") + 1), {
225 encoding: "base64",
226 });
227 }
228 const result = await file.upload(url, {
229 httpMethod: "POST",
230 uploadType: UploadType.BINARY_CONTENT,
231 headers: { "Content-Type": composerAttachmentWireMimeType(attachment) },
232 signal,
233 ...(onProgress
234 ? {
235 onProgress: ({ bytesSent, totalBytes }) => {
236 if (totalBytes > 0) onProgress(bytesSent / totalBytes);
237 },
238 }
239 : {}),
240 });
241 if (result.status < 200 || result.status >= 300) {
242 throw new Error(`Upload failed for '${attachment.name}' (${result.status}).`);
243 }
244 } finally {
245 if (fileUri === undefined && file.exists) file.delete();
246 }
248​
249/** persistUploadedReferences runs only for new uploaded ids; save them to their owner so crash retries reuse bytes. */
250export async function prepareTurnAttachments(input: {
251 readonly environmentId: EnvironmentId;
252 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
253 readonly supportsImageUploads?: boolean;
254 readonly signal?: AbortSignal;
255 readonly onUploadProgress?: (attachmentId: string, progress: number) => void;
256 readonly persistUploadedReferences?: (
257 draftAttachments: ReadonlyArray<DraftComposerAttachment>,
258 ) => Promise<"persisted" | "abandon">;
259}): Promise<PrepareTurnAttachmentsResult> {
260 const { environmentId } = input;
261 if (input.signal?.aborted) return { status: "abandoned" };
262 const files = input.attachments.filter((attachment) => attachment.type === "file");
263 const ready = (
264 attachments: ReadonlyArray<UploadedMobileAttachment>,
265 pendingAttachmentIds: ReadonlyArray<string>,
266 draftAttachments: ReadonlyArray<DraftComposerAttachment>,
267 ): PreparedTurnAttachments => ({
268 status: "ready",
269 attachments,
270 draftAttachments,
271 pendingAttachmentIds,
272 });
273​
274 if (input.attachments.length === 0 || (files.length === 0 && !input.supportsImageUploads)) {
275 try {
276 const imageAttachments = await toUploadChatImageAttachments(
277 input.attachments.filter((attachment) => attachment.type === "image"),
278 );
279 if (input.signal?.aborted) return { status: "abandoned" };
280 return ready(imageAttachments, [], input.attachments);
281 } catch (error) {
282 if (input.signal?.aborted) return { status: "abandoned" };
283 throw error;
284 }
285 }
286​
287 const requireUploadAccess = () => {
288 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) {
289 throw new Error("This connection cannot upload attachments.");
290 }
291 };
292 requireUploadAccess();
293​
294 const connection = appAtomRegistry.get(
295 environmentSession.preparedConnectionValueAtom(environmentId),
296 );
297 if (Option.isNone(connection)) {
298 throw new Error("The environment is not connected.");
299 }
300​
301 const uploadedAttachments: UploadedMobileAttachment[] = [];
302 const pendingAttachmentIds: string[] = [];
303 const createdAttachmentIds: string[] = [];
304 const controller = new AbortController();
305 const abort = () => controller.abort();
306 input.signal?.addEventListener("abort", abort, { once: true });
307 try {
308 for (const attachment of input.attachments) {
309 if (controller.signal.aborted) throw new Error("Upload cancelled.");
310 requireUploadAccess();
311 if (attachment.type === "image" && !input.supportsImageUploads) {
312 uploadedAttachments.push(...(await toUploadChatImageAttachments([attachment])));
313 continue;
314 }
315​
316 if (
317 attachment.uploadEnvironmentId === environmentId &&
318 attachment.uploadedAttachmentId !== undefined
319 ) {
320 const verification = await verifyPersistedAttachmentUpload({
321 registry: appAtomRegistry,
322 createAssetUrl: assetEnvironment.createUrl,
323 environmentId,
324 attachmentId: attachment.uploadedAttachmentId,
325 });
326 if (verification.status === "failed") {
327 throw verification.error;
328 }
329 if (verification.status === "verified") {
330 pendingAttachmentIds.push(attachment.uploadedAttachmentId);
331 uploadedAttachments.push(uploadedReference(attachment, attachment.uploadedAttachmentId));
332 continue;
333 }
334 }
335​
336 requireUploadAccess();
337 const result = await runAttachmentUploadCycle({
338 registry: appAtomRegistry,
339 createUploadUrl: attachmentEnvironment.createUploadUrl,
340 remove: attachmentEnvironment.remove,
341 environmentId,
342 upload: attachmentUploadInput(attachment),
343 // Resolve at transfer time; reconnects may change the base URL.
344 resolveUploadUrl: (relativeUrl) => {
345 requireUploadAccess();
346 const currentConnection = appAtomRegistry.get(
347 environmentSession.preparedConnectionValueAtom(environmentId),
348 );
349 return Option.isNone(currentConnection)
350 ? null
351 : resolveAssetUrl(currentConnection.value.httpBaseUrl, relativeUrl);
352 },
353 transport: (url) => ({
354 done: uploadFileBytes(
355 environmentId,
356 attachment,
357 url,
358 controller.signal,
359 input.onUploadProgress
360 ? (progress) => input.onUploadProgress?.(attachment.id, progress)
361 : undefined,
362 ),
363 abort,
364 }),
365 onMinted: (attachmentId) => {
366 if (controller.signal.aborted) return "cancel";
367 pendingAttachmentIds.push(attachmentId);
368 createdAttachmentIds.push(attachmentId);
369 return "continue";
370 },
371 });
372 if (result.status !== "uploaded") {
373 throw result.status === "failed" && result.error !== undefined
374 ? result.error
375 : new Error(`Upload failed for '${attachment.name}'.`);
376 }
377 uploadedAttachments.push(uploadedReference(attachment, result.attachmentId));
378 }
379​
380 if (controller.signal.aborted) throw new Error("Upload cancelled.");
381​
382 const draftAttachments = withUploadedMobileAttachmentReferences({
383 environmentId,
384 attachments: input.attachments,
385 uploadedAttachments,
386 });
387 const referencesChanged = draftAttachments.some(
388 (attachment, index) => attachment !== input.attachments[index],
389 );
390 if (referencesChanged && input.persistUploadedReferences) {
391 if ((await input.persistUploadedReferences(draftAttachments)) === "abandon") {
392 await releaseCreatedUploadsQuietly(environmentId, createdAttachmentIds);
393 return { status: "abandoned" };
394 }
395 }
396 return ready(uploadedAttachments, pendingAttachmentIds, draftAttachments);
397 } catch (error) {
398 await releaseCreatedUploadsQuietly(environmentId, createdAttachmentIds);
399 if (controller.signal.aborted) return { status: "abandoned" };
400 throw error;
401 } finally {
402 input.signal?.removeEventListener("abort", abort);
403 }