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

attachmentUpload.ts

432 lines16.5 KB

1import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
2import {
3 clampFileAttachmentUploadBytes,
4 fileAttachmentTooLargeMessage,
5 isAssetAttachmentNotFoundFailure,
6 runAttachmentUploadCycle,
7 verifyPersistedAttachmentUpload,
8} from "@t3tools/client-runtime/state/attachments";
9import { runAtomCommand, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
10import type {
11 ChatFileAttachment,
12 ChatImageAttachment,
13 EnvironmentId,
14 UploadChatImageAttachment,
15} from "@t3tools/contracts";
16import { PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES } from "@t3tools/contracts";
17import * as Option from "effect/Option";
18​
19import { appAtomRegistry } from "../state/atom-registry";
20import { assetEnvironment } from "../state/assets";
21import { attachmentEnvironment } from "../state/attachments";
22import { environmentSession } from "../state/session";
23import { retainComposerAttachmentFileForPreview } from "../state/use-composer-drafts";
24import { resolveOwnedComposerAttachmentFileUri } from "./composerAttachmentFiles";
25import {
26 isFileBackedComposerAttachment,
27 type DraftComposerAttachment,
28 type DraftComposerImageAttachment,
29} from "./composerImages";
30import { uuidv4 } from "./uuid";
31​
32/**
33 * This module owns the server side of a composer attachment's lifecycle.
34 * `prepareTurnAttachments` acquires pending uploads (verifying and reusing
35 * persisted ones), hands the uploaded ids back to the attachment's durable
36 * owner (queued outbox message or composer draft), and leaves their cleanup
37 * to that owner after it checks shared references. Nothing outside this module
38 * mints or deletes pending uploads. The local-file side of the lifecycle is
39 * owned by `removeThreadOutboxMessage` / the composer draft mutators, which
40 * release files through `releaseUnusedComposerAttachmentFiles`.
41 */
42export type UploadedMobileAttachment =
43 | UploadChatImageAttachment
44 | ChatImageAttachment
45 | ChatFileAttachment;
46​
47export function validateDraftFileAttachments(input: {
48 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
49 readonly serverConfig: {
50 readonly environment: {
51 readonly capabilities: {
52 readonly attachmentUploads?: boolean;
53 readonly fileAttachments?: { readonly maxUploadBytes: number };
54 };
55 };
56 } | null;
57}): string | null {
58 const files = input.attachments.filter((attachment) => attachment.type === "file");
59 if (files.length === 0) return null;
60 if (input.serverConfig === null) return "Server attachment support is still loading.";
61 const capabilities = input.serverConfig.environment.capabilities;
62 if (capabilities.attachmentUploads !== true || capabilities.fileAttachments === undefined) {
63 return "This server does not support file attachments.";
64 }
65 const maxBytes = clampFileAttachmentUploadBytes(capabilities.fileAttachments.maxUploadBytes);
66 const oversized = files.find((attachment) => attachment.sizeBytes > maxBytes);
67 return oversized ? fileAttachmentTooLargeMessage(oversized.name, maxBytes) : null;
69​
70/** Keep uploaded ids alongside the local bytes so a later send can reuse them. */
71export function withUploadedMobileAttachmentReferences(input: {
72 readonly environmentId: EnvironmentId;
73 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
74 readonly uploadedAttachments: ReadonlyArray<UploadedMobileAttachment>;
75}): ReadonlyArray<DraftComposerAttachment> {
76 return input.attachments.map((attachment, index) => {
77 const uploaded = input.uploadedAttachments[index];
78 if (
79 !uploaded ||
80 !("id" in uploaded) ||
81 attachment.type !== uploaded.type ||
82 (attachment.uploadedAttachmentId === uploaded.id &&
83 attachment.uploadEnvironmentId === input.environmentId)
84 ) {
85 return attachment;
86 }
87 return {
88 ...attachment,
89 uploadedAttachmentId: uploaded.id,
90 uploadEnvironmentId: input.environmentId,
91 };
92 });
94​
95/**
96 * Deletes pending uploads the client no longer references. Every delete result
97 * is inspected; failed deletes are retried once and a persistent failure
98 * throws, so a caller can never silently leak the outcome. (The server also
99 * expires pending uploads, so a leaked id self-heals eventually.)
100 */
101export async function releasePendingAttachmentUploads(
102 environmentId: EnvironmentId,
103 attachmentIds: ReadonlyArray<string>,
104): Promise<void> {
105 const deleteOnce = async (attachmentId: string): Promise<boolean> => {
106 const result = await runAtomCommand(
107 appAtomRegistry,
108 attachmentEnvironment.remove,
109 { environmentId, input: { attachmentId } },
110 { reportFailure: false, reportDefect: false },
111 );
112 return (
113 result._tag === "Success" ||
114 isAssetAttachmentNotFoundFailure(squashAtomCommandFailure(result))
115 );
116 };
117​
118 const failedAttachmentIds: string[] = [];
119 for (const attachmentId of attachmentIds) {
120 if (!(await deleteOnce(attachmentId)) && !(await deleteOnce(attachmentId))) {
121 failedAttachmentIds.push(attachmentId);
122 }
123 }
124 if (failedAttachmentIds.length > 0) {
125 throw new Error(
126 `Could not delete ${failedAttachmentIds.length} pending attachment upload(s): ${failedAttachmentIds.join(", ")}.`,
127 );
128 }
130​
131async function releaseCreatedUploadsQuietly(
132 environmentId: EnvironmentId,
133 attachmentIds: ReadonlyArray<string>,
134): Promise<void> {
135 try {
136 await releasePendingAttachmentUploads(environmentId, attachmentIds);
137 } catch (error) {
138 // The original failure must propagate; the leaked pending uploads expire
139 // on the server.
140 console.warn("[attachments] could not delete abandoned pending uploads", error);
141 }
143​
144export interface PreparedTurnAttachments {
145 readonly status: "ready";
146 /** Wire attachments for `startTurn`, in the original composer order. */
147 readonly attachments: ReadonlyArray<UploadedMobileAttachment>;
148 /** Composer attachments annotated with the uploaded pending ids. */
149 readonly draftAttachments: ReadonlyArray<DraftComposerAttachment>;
150 /** Every pending upload backing this turn (reused and newly minted). */
151 readonly pendingAttachmentIds: ReadonlyArray<string>;
153​
154export type PrepareTurnAttachmentsResult =
155 | PreparedTurnAttachments
156 | { readonly status: "abandoned" };
157​
158function uploadedReference(
159 attachment: DraftComposerAttachment,
160 id: string,
161): ChatImageAttachment | ChatFileAttachment {
162 const fields = {
163 id,
164 name: attachment.name,
165 mimeType: attachment.mimeType,
166 sizeBytes: attachment.sizeBytes,
167 };
168 return attachment.type === "image" ? { type: "image", ...fields } : { type: "file", ...fields };
170​
171function attachmentUploadInput(attachment: DraftComposerAttachment) {
172 const fields = {
173 name: attachment.name,
174 mimeType: attachment.mimeType,
175 sizeBytes: attachment.sizeBytes,
176 };
177 if (attachment.type === "file") return { type: "file" as const, ...fields };
178 const mimeType = PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES.find(
179 (type) => type === attachment.mimeType.toLowerCase(),
180 );
181 if (!mimeType) throw new Error(`Unsupported image type for '${attachment.name}'.`);
182 return { ...fields, mimeType };
184​
185/**
186 * Wire shape for startTurn on servers without attachment uploads: pure inline
187 * uploads without client draft id / previewUri. File-backed images read their
188 * base64 from disk lazily, only when this legacy path is actually taken.
189 */
190async function toUploadChatImageAttachments(
191 attachments: ReadonlyArray<DraftComposerImageAttachment>,
192): Promise<ReadonlyArray<UploadChatImageAttachment>> {
193 return Promise.all(
194 attachments.map(async (attachment) => ({
195 type: attachment.type,
196 name: attachment.name,
197 mimeType: attachment.mimeType,
198 sizeBytes: attachment.sizeBytes,
199 dataUrl: await composerImageAttachmentDataUrl(attachment),
200 })),
201 );
203​
204/** Inline bytes for one image: legacy drafts carry them, file-backed ones read them from disk. */
205async function composerImageAttachmentDataUrl(
206 attachment: DraftComposerImageAttachment,
207): Promise<string> {
208 if (attachment.dataUrl !== undefined) {
209 return attachment.dataUrl;
210 }
211 if (!isFileBackedComposerAttachment(attachment)) {
212 throw new Error(`'${attachment.name}' is no longer available. Attach the image again.`);
213 }
214 const release = retainComposerAttachmentFileForPreview(attachment);
215 try {
216 const { File, Paths } = await import("expo-file-system");
217 const uri =
218 resolveOwnedComposerAttachmentFileUri(attachment.fileUri, Paths.document.uri) ??
219 attachment.fileUri;
220 const base64 = await new File(uri).base64();
221 return `data:${attachment.mimeType};base64,${base64}`;
222 } finally {
223 release();
224 }
226​
227async function uploadFileBytes(
228 attachment: DraftComposerAttachment,
229 url: string,
230 signal: AbortSignal,
231 onProgress?: (progress: number) => void,
232): Promise<void> {
233 const { File, Paths, UploadType } = await import("expo-file-system");
234 if (signal.aborted) throw new Error("Upload cancelled.");
235 // Legacy image drafts persisted inline bytes and stage them in a temp cache
236 // file for the native uploader. Everything else uploads its owned copy.
237 const fileUri = attachment.fileUri;
238 const inlineDataUrl = attachment.type === "image" ? attachment.dataUrl : undefined;
239 if (fileUri === undefined && inlineDataUrl === undefined) {
240 throw new Error(`'${attachment.name}' is no longer available. Attach the image again.`);
241 }
242 const file =
243 fileUri === undefined
244 ? new File(Paths.cache, `t3-upload-${uuidv4()}`)
245 : new File(resolveOwnedComposerAttachmentFileUri(fileUri, Paths.document.uri) ?? fileUri);
246 try {
247 if (fileUri === undefined && inlineDataUrl !== undefined) {
248 file.create();
249 file.write(inlineDataUrl.slice(inlineDataUrl.indexOf(",") + 1), {
250 encoding: "base64",
251 });
252 }
253 const result = await file.upload(url, {
254 httpMethod: "POST",
255 uploadType: UploadType.BINARY_CONTENT,
256 headers: { "Content-Type": attachment.mimeType },
257 signal,
258 ...(onProgress
259 ? {
260 onProgress: ({ bytesSent, totalBytes }) => {
261 if (totalBytes > 0) onProgress(bytesSent / totalBytes);
262 },
263 }
264 : {}),
265 });
266 if (result.status < 200 || result.status >= 300) {
267 throw new Error(`Upload failed for '${attachment.name}' (${result.status}).`);
268 }
269 } finally {
270 if (fileUri === undefined && file.exists) file.delete();
271 }
273​
274/**
275 * Acquires server-side uploads for one turn's attachments and persists the
276 * uploaded ids into the attachments' durable owner.
277 *
278 * `persistUploadedReferences` runs once the bytes are on the server and only
279 * when new ids appeared. It must write the annotated attachments into the
280 * owner (queued message or draft) so a retry after a crash reuses the bytes.
281 * Returning `"abandon"` (owner no longer wants the send) or throwing deletes
282 * the pending uploads this call minted, so the owner cannot leak them.
283 */
284export async function prepareTurnAttachments(input: {
285 readonly environmentId: EnvironmentId;
286 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
287 /** Older environments continue to receive inline images. */
288 readonly supportsImageUploads?: boolean;
289 readonly signal?: AbortSignal;
290 readonly onUploadProgress?: (attachmentId: string, progress: number) => void;
291 readonly persistUploadedReferences?: (
292 draftAttachments: ReadonlyArray<DraftComposerAttachment>,
293 ) => Promise<"persisted" | "abandon">;
294}): Promise<PrepareTurnAttachmentsResult> {
295 const { environmentId } = input;
296 if (input.signal?.aborted) return { status: "abandoned" };
297 const files = input.attachments.filter((attachment) => attachment.type === "file");
298 const ready = (
299 attachments: ReadonlyArray<UploadedMobileAttachment>,
300 pendingAttachmentIds: ReadonlyArray<string>,
301 draftAttachments: ReadonlyArray<DraftComposerAttachment>,
302 ): PreparedTurnAttachments => ({
303 status: "ready",
304 attachments,
305 draftAttachments,
306 pendingAttachmentIds,
307 });
308​
309 if (input.attachments.length === 0 || (files.length === 0 && !input.supportsImageUploads)) {
310 try {
311 const imageAttachments = await toUploadChatImageAttachments(
312 input.attachments.filter((attachment) => attachment.type === "image"),
313 );
314 if (input.signal?.aborted) return { status: "abandoned" };
315 return ready(imageAttachments, [], input.attachments);
316 } catch (error) {
317 if (input.signal?.aborted) return { status: "abandoned" };
318 throw error;
319 }
320 }
321​
322 const connection = appAtomRegistry.get(
323 environmentSession.preparedConnectionValueAtom(environmentId),
324 );
325 if (Option.isNone(connection)) {
326 throw new Error("The environment is not connected.");
327 }
328​
329 const uploadedAttachments: UploadedMobileAttachment[] = [];
330 const pendingAttachmentIds: string[] = [];
331 const createdAttachmentIds: string[] = [];
332 const controller = new AbortController();
333 const abort = () => controller.abort();
334 input.signal?.addEventListener("abort", abort, { once: true });
335 try {
336 for (const attachment of input.attachments) {
337 if (controller.signal.aborted) throw new Error("Upload cancelled.");
338 if (attachment.type === "image" && !input.supportsImageUploads) {
339 uploadedAttachments.push(...(await toUploadChatImageAttachments([attachment])));
340 continue;
341 }
342​
343 // Reuse the bytes from a previous attempt when their pending upload is
344 // still alive on this environment.
345 if (
346 attachment.uploadEnvironmentId === environmentId &&
347 attachment.uploadedAttachmentId !== undefined
348 ) {
349 const verification = await verifyPersistedAttachmentUpload({
350 registry: appAtomRegistry,
351 createAssetUrl: assetEnvironment.createUrl,
352 environmentId,
353 attachmentId: attachment.uploadedAttachmentId,
354 });
355 if (verification.status === "failed") {
356 throw verification.error;
357 }
358 if (verification.status === "verified") {
359 pendingAttachmentIds.push(attachment.uploadedAttachmentId);
360 uploadedAttachments.push(uploadedReference(attachment, attachment.uploadedAttachmentId));
361 continue;
362 }
363 // "missing": the pending upload expired, upload the bytes again.
364 }
365​
366 const result = await runAttachmentUploadCycle({
367 registry: appAtomRegistry,
368 createUploadUrl: attachmentEnvironment.createUploadUrl,
369 remove: attachmentEnvironment.remove,
370 environmentId,
371 upload: attachmentUploadInput(attachment),
372 // Read the connection at transfer time: the environment may have
373 // reconnected on a new base URL since this cycle started.
374 resolveUploadUrl: (relativeUrl) => {
375 const currentConnection = appAtomRegistry.get(
376 environmentSession.preparedConnectionValueAtom(environmentId),
377 );
378 return Option.isNone(currentConnection)
379 ? null
380 : resolveAssetUrl(currentConnection.value.httpBaseUrl, relativeUrl);
381 },
382 transport: (url) => ({
383 done: uploadFileBytes(
384 attachment,
385 url,
386 controller.signal,
387 input.onUploadProgress
388 ? (progress) => input.onUploadProgress?.(attachment.id, progress)
389 : undefined,
390 ),
391 abort,
392 }),
393 onMinted: (attachmentId) => {
394 if (controller.signal.aborted) return "cancel";
395 pendingAttachmentIds.push(attachmentId);
396 createdAttachmentIds.push(attachmentId);
397 return "continue";
398 },
399 });
400 if (result.status !== "uploaded") {
401 throw result.status === "failed" && result.error !== undefined
402 ? result.error
403 : new Error(`Upload failed for '${attachment.name}'.`);
404 }
405 uploadedAttachments.push(uploadedReference(attachment, result.attachmentId));
406 }
407​
408 if (controller.signal.aborted) throw new Error("Upload cancelled.");
409​
410 const draftAttachments = withUploadedMobileAttachmentReferences({
411 environmentId,
412 attachments: input.attachments,
413 uploadedAttachments,
414 });
415 const referencesChanged = draftAttachments.some(
416 (attachment, index) => attachment !== input.attachments[index],
417 );
418 if (referencesChanged && input.persistUploadedReferences) {
419 if ((await input.persistUploadedReferences(draftAttachments)) === "abandon") {
420 await releaseCreatedUploadsQuietly(environmentId, createdAttachmentIds);
421 return { status: "abandoned" };
422 }
423 }
424 return ready(uploadedAttachments, pendingAttachmentIds, draftAttachments);
425 } catch (error) {
426 await releaseCreatedUploadsQuietly(environmentId, createdAttachmentIds);
427 if (controller.signal.aborted) return { status: "abandoned" };
428 throw error;
429 } finally {
430 input.signal?.removeEventListener("abort", abort);
431 }