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

attachmentUpload.ts

442 lines16.4 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 {
17 AuthOrchestrationOperateScope,
18 PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES,
19} from "@t3tools/contracts";
20import * as Option from "effect/Option";
21​
22import { appAtomRegistry } from "../state/atom-registry";
23import { assetEnvironment } from "../state/assets";
24import { attachmentEnvironment } from "../state/attachments";
25import { environmentSession, readEnvironmentScope } from "../state/session";
26import { resolveOwnedComposerAttachmentFileUri } from "./composerAttachmentFiles";
27import { retainComposerAttachmentFileForPreview } from "./composerAttachmentPreviewRetention";
28import {
29 isComposerImageAttachment,
30 isFileBackedComposerAttachment,
31 type DraftComposerAttachment,
32 type DraftComposerImageAttachment,
33} from "./composerImages";
34import { imageMimeType } from "@t3tools/shared/image";
35import { uuidv4 } from "./uuid";
36​
37export type UploadedMobileAttachment =
38 | UploadChatImageAttachment
39 | ChatImageAttachment
40 | ChatFileAttachment;
41​
42export function validateDraftFileAttachments(input: {
43 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
44 readonly serverConfig: {
45 readonly environment: {
46 readonly capabilities: {
47 readonly attachmentUploads?: boolean;
48 readonly fileAttachments?: { readonly maxUploadBytes: number };
49 };
50 };
51 } | null;
52}): string | null {
53 const files = input.attachments.filter((attachment) => attachment.type === "file");
54 if (files.length === 0) return null;
55 if (input.serverConfig === null) return "Server attachment support is still loading.";
56 const capabilities = input.serverConfig.environment.capabilities;
57 if (capabilities.attachmentUploads !== true || capabilities.fileAttachments === undefined) {
58 return "This server does not support file attachments.";
59 }
60 const maxBytes = clampFileAttachmentUploadBytes(capabilities.fileAttachments.maxUploadBytes);
61 const oversized = files.find((attachment) => attachment.sizeBytes > maxBytes);
62 return oversized ? fileAttachmentTooLargeMessage(oversized.name, maxBytes) : null;
64​
65export function withUploadedMobileAttachmentReferences(input: {
66 readonly environmentId: EnvironmentId;
67 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
68 readonly uploadedAttachments: ReadonlyArray<UploadedMobileAttachment>;
69}): ReadonlyArray<DraftComposerAttachment> {
70 return input.attachments.map((attachment, index) => {
71 const uploaded = input.uploadedAttachments[index];
72 // A picture picked through Files stays `type: "file"` in the draft while it uploads as an
73 // image, so compare against the type it was actually sent under: comparing draft types
74 // drops the id, and the next send re-uploads bytes the server already holds.
75 const uploadedAs = isComposerImageAttachment(attachment) ? "image" : attachment.type;
76 if (
77 !uploaded ||
78 !("id" in uploaded) ||
79 uploadedAs !== uploaded.type ||
80 (attachment.uploadedAttachmentId === uploaded.id &&
81 attachment.uploadEnvironmentId === input.environmentId)
82 ) {
83 return attachment;
84 }
85 return {
86 ...attachment,
87 uploadedAttachmentId: uploaded.id,
88 uploadEnvironmentId: input.environmentId,
89 };
90 });
92​
93export async function releasePendingAttachmentUploads(
94 environmentId: EnvironmentId,
95 attachmentIds: ReadonlyArray<string>,
96): Promise<void> {
97 const deleteOnce = async (attachmentId: string): Promise<boolean> => {
98 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) {
99 throw new Error("This connection cannot delete pending attachments.");
100 }
101 const result = await runAtomCommand(
102 appAtomRegistry,
103 attachmentEnvironment.remove,
104 { environmentId, input: { attachmentId } },
105 { reportFailure: false, reportDefect: false },
106 );
107 return (
108 result._tag === "Success" ||
109 isAssetAttachmentNotFoundFailure(squashAtomCommandFailure(result))
110 );
111 };
112​
113 const failedAttachmentIds: string[] = [];
114 for (const attachmentId of attachmentIds) {
115 if (!(await deleteOnce(attachmentId)) && !(await deleteOnce(attachmentId))) {
116 failedAttachmentIds.push(attachmentId);
117 }
118 }
119 if (failedAttachmentIds.length > 0) {
120 throw new Error(
121 `Could not delete ${failedAttachmentIds.length} pending attachment upload(s): ${failedAttachmentIds.join(", ")}.`,
122 );
123 }
125​
126async function releaseCreatedUploadsQuietly(
127 environmentId: EnvironmentId,
128 attachmentIds: ReadonlyArray<string>,
129): Promise<void> {
130 try {
131 await releasePendingAttachmentUploads(environmentId, attachmentIds);
132 } catch (error) {
133 console.warn("[attachments] could not delete abandoned pending uploads", error);
134 }
136​
137export interface PreparedTurnAttachments {
138 readonly status: "ready";
139 readonly attachments: ReadonlyArray<UploadedMobileAttachment>;
140 readonly draftAttachments: ReadonlyArray<DraftComposerAttachment>;
141 readonly pendingAttachmentIds: ReadonlyArray<string>;
143​
144export type PrepareTurnAttachmentsResult =
145 | PreparedTurnAttachments
146 | { readonly status: "abandoned" };
147​
148/**
149 * A picture picked through Files arrives typed as a plain file, often with no usable mime, so it is
150 * promoted to the type the provider accepts. Every place that names the attachment on the wire —
151 * the upload header, the upload input, and the message reference — has to agree on this one value,
152 * or the turn describes bytes that are not what was actually sent and `ChatImageAttachment` rejects
153 * it.
154 */
155export function composerAttachmentWireMimeType(attachment: DraftComposerAttachment): string {
156 if (!isComposerImageAttachment(attachment)) return attachment.mimeType;
157 return supportedImageWireMimeType(attachment);
159​
160function supportedImageWireMimeType(
161 attachment: DraftComposerAttachment,
162): (typeof PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES)[number] {
163 const inferred = imageMimeType(attachment);
164 const mimeType = PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES.find(
165 (type) => type === attachment.mimeType.toLowerCase() || type === inferred,
166 );
167 if (!mimeType) throw new Error(`Unsupported image type for '${attachment.name}'.`);
168 return mimeType;
170​
171function uploadedReference(
172 attachment: DraftComposerAttachment,
173 id: string,
174): ChatImageAttachment | ChatFileAttachment {
175 const fields = {
176 id,
177 name: attachment.name,
178 mimeType: composerAttachmentWireMimeType(attachment),
179 sizeBytes: attachment.sizeBytes,
180 };
181 return isComposerImageAttachment(attachment)
182 ? { type: "image", ...fields }
183 : {
184 type: "file",
185 ...fields,
186 ...(attachment.source ? { source: attachment.source } : {}),
187 };
189​
190function attachmentUploadInput(attachment: DraftComposerAttachment) {
191 const fields = { name: attachment.name, sizeBytes: attachment.sizeBytes };
192 return isComposerImageAttachment(attachment)
193 ? { ...fields, mimeType: supportedImageWireMimeType(attachment) }
194 : { type: "file" as const, ...fields, mimeType: attachment.mimeType };
196​
197async function toUploadChatImageAttachments(
198 attachments: ReadonlyArray<DraftComposerImageAttachment>,
199): Promise<ReadonlyArray<UploadChatImageAttachment>> {
200 return Promise.all(
201 attachments.map(async (attachment) => ({
202 type: attachment.type,
203 name: attachment.name,
204 mimeType: attachment.mimeType,
205 sizeBytes: attachment.sizeBytes,
206 dataUrl: await composerImageAttachmentDataUrl(attachment),
207 })),
208 );
210​
211async function composerImageAttachmentDataUrl(
212 attachment: DraftComposerImageAttachment,
213): Promise<string> {
214 if (attachment.dataUrl !== undefined) {
215 return attachment.dataUrl;
216 }
217 if (!isFileBackedComposerAttachment(attachment)) {
218 throw new Error(`'${attachment.name}' is no longer available. Attach the image again.`);
219 }
220 const release = retainComposerAttachmentFileForPreview(attachment);
221 try {
222 const { File, Paths } = await import("expo-file-system");
223 const uri =
224 resolveOwnedComposerAttachmentFileUri(attachment.fileUri, Paths.document.uri) ??
225 attachment.fileUri;
226 const base64 = await new File(uri).base64();
227 return `data:${attachment.mimeType};base64,${base64}`;
228 } finally {
229 release();
230 }
232​
233async function uploadFileBytes(
234 environmentId: EnvironmentId,
235 attachment: DraftComposerAttachment,
236 url: string,
237 signal: AbortSignal,
238 onProgress?: (progress: number) => void,
239): Promise<void> {
240 const { File, Paths, UploadType } = await import("expo-file-system");
241 if (signal.aborted) throw new Error("Upload cancelled.");
242 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) {
243 throw new Error("This connection cannot upload attachments.");
244 }
245 const fileUri = attachment.fileUri;
246 const inlineDataUrl = attachment.type === "image" ? attachment.dataUrl : undefined;
247 if (fileUri === undefined && inlineDataUrl === undefined) {
248 throw new Error(`'${attachment.name}' is no longer available. Attach the image again.`);
249 }
250 const file =
251 fileUri === undefined
252 ? new File(Paths.cache, `t3-upload-${uuidv4()}`)
253 : new File(resolveOwnedComposerAttachmentFileUri(fileUri, Paths.document.uri) ?? fileUri);
254 try {
255 if (fileUri === undefined && inlineDataUrl !== undefined) {
256 file.create();
257 await file.write(inlineDataUrl.slice(inlineDataUrl.indexOf(",") + 1), {
258 encoding: "base64",
259 });
260 }
261 const result = await file.upload(url, {
262 httpMethod: "POST",
263 uploadType: UploadType.BINARY_CONTENT,
264 headers: { "Content-Type": composerAttachmentWireMimeType(attachment) },
265 signal,
266 ...(onProgress
267 ? {
268 onProgress: ({ bytesSent, totalBytes }) => {
269 if (totalBytes > 0) onProgress(bytesSent / totalBytes);
270 },
271 }
272 : {}),
273 });
274 if (result.status < 200 || result.status >= 300) {
275 throw new Error(`Upload failed for '${attachment.name}' (${result.status}).`);
276 }
277 } finally {
278 if (fileUri === undefined && file.exists) file.delete();
279 }
281​
282/**
283 * `persistUploadedReferences` runs once the bytes are on the server and only when new ids appeared.
284 * It must write the annotated attachments into the owner (queued message or draft) so a retry after
285 * a crash reuses the bytes.
286 */
287export async function prepareTurnAttachments(input: {
288 readonly environmentId: EnvironmentId;
289 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
290 readonly supportsImageUploads?: boolean;
291 readonly signal?: AbortSignal;
292 readonly onUploadProgress?: (attachmentId: string, progress: number) => void;
293 readonly persistUploadedReferences?: (
294 draftAttachments: ReadonlyArray<DraftComposerAttachment>,
295 ) => Promise<"persisted" | "abandon">;
296}): Promise<PrepareTurnAttachmentsResult> {
297 const { environmentId } = input;
298 if (input.signal?.aborted) return { status: "abandoned" };
299 const files = input.attachments.filter((attachment) => attachment.type === "file");
300 const ready = (
301 attachments: ReadonlyArray<UploadedMobileAttachment>,
302 pendingAttachmentIds: ReadonlyArray<string>,
303 draftAttachments: ReadonlyArray<DraftComposerAttachment>,
304 ): PreparedTurnAttachments => ({
305 status: "ready",
306 attachments,
307 draftAttachments,
308 pendingAttachmentIds,
309 });
310​
311 if (input.attachments.length === 0 || (files.length === 0 && !input.supportsImageUploads)) {
312 try {
313 const imageAttachments = await toUploadChatImageAttachments(
314 input.attachments.filter((attachment) => attachment.type === "image"),
315 );
316 if (input.signal?.aborted) return { status: "abandoned" };
317 return ready(imageAttachments, [], input.attachments);
318 } catch (error) {
319 if (input.signal?.aborted) return { status: "abandoned" };
320 throw error;
321 }
322 }
323​
324 const requireUploadAccess = () => {
325 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) {
326 throw new Error("This connection cannot upload attachments.");
327 }
328 };
329 requireUploadAccess();
330​
331 const connection = appAtomRegistry.get(
332 environmentSession.preparedConnectionValueAtom(environmentId),
333 );
334 if (Option.isNone(connection)) {
335 throw new Error("The environment is not connected.");
336 }
337​
338 const uploadedAttachments: UploadedMobileAttachment[] = [];
339 const pendingAttachmentIds: string[] = [];
340 const createdAttachmentIds: string[] = [];
341 const controller = new AbortController();
342 const abort = () => controller.abort();
343 input.signal?.addEventListener("abort", abort, { once: true });
344 try {
345 for (const attachment of input.attachments) {
346 if (controller.signal.aborted) throw new Error("Upload cancelled.");
347 requireUploadAccess();
348 if (attachment.type === "image" && !input.supportsImageUploads) {
349 uploadedAttachments.push(...(await toUploadChatImageAttachments([attachment])));
350 continue;
351 }
352​
353 if (
354 attachment.uploadEnvironmentId === environmentId &&
355 attachment.uploadedAttachmentId !== undefined
356 ) {
357 const verification = await verifyPersistedAttachmentUpload({
358 registry: appAtomRegistry,
359 createAssetUrl: assetEnvironment.createUrl,
360 environmentId,
361 attachmentId: attachment.uploadedAttachmentId,
362 });
363 if (verification.status === "failed") {
364 throw verification.error;
365 }
366 if (verification.status === "verified") {
367 pendingAttachmentIds.push(attachment.uploadedAttachmentId);
368 uploadedAttachments.push(uploadedReference(attachment, attachment.uploadedAttachmentId));
369 continue;
370 }
371 }
372​
373 requireUploadAccess();
374 const result = await runAttachmentUploadCycle({
375 registry: appAtomRegistry,
376 createUploadUrl: attachmentEnvironment.createUploadUrl,
377 remove: attachmentEnvironment.remove,
378 environmentId,
379 upload: attachmentUploadInput(attachment),
380 // Read the connection at transfer time: the environment may have
381 // reconnected on a new base URL since this cycle started.
382 resolveUploadUrl: (relativeUrl) => {
383 requireUploadAccess();
384 const currentConnection = appAtomRegistry.get(
385 environmentSession.preparedConnectionValueAtom(environmentId),
386 );
387 return Option.isNone(currentConnection)
388 ? null
389 : resolveAssetUrl(currentConnection.value.httpBaseUrl, relativeUrl);
390 },
391 transport: (url) => ({
392 done: uploadFileBytes(
393 environmentId,
394 attachment,
395 url,
396 controller.signal,
397 input.onUploadProgress
398 ? (progress) => input.onUploadProgress?.(attachment.id, progress)
399 : undefined,
400 ),
401 abort,
402 }),
403 onMinted: (attachmentId) => {
404 if (controller.signal.aborted) return "cancel";
405 pendingAttachmentIds.push(attachmentId);
406 createdAttachmentIds.push(attachmentId);
407 return "continue";
408 },
409 });
410 if (result.status !== "uploaded") {
411 throw result.status === "failed" && result.error !== undefined
412 ? result.error
413 : new Error(`Upload failed for '${attachment.name}'.`);
414 }
415 uploadedAttachments.push(uploadedReference(attachment, result.attachmentId));
416 }
417​
418 if (controller.signal.aborted) throw new Error("Upload cancelled.");
419​
420 const draftAttachments = withUploadedMobileAttachmentReferences({
421 environmentId,
422 attachments: input.attachments,
423 uploadedAttachments,
424 });
425 const referencesChanged = draftAttachments.some(
426 (attachment, index) => attachment !== input.attachments[index],
427 );
428 if (referencesChanged && input.persistUploadedReferences) {
429 if ((await input.persistUploadedReferences(draftAttachments)) === "abandon") {
430 await releaseCreatedUploadsQuietly(environmentId, createdAttachmentIds);
431 return { status: "abandoned" };
432 }
433 }
434 return ready(uploadedAttachments, pendingAttachmentIds, draftAttachments);
435 } catch (error) {
436 await releaseCreatedUploadsQuietly(environmentId, createdAttachmentIds);
437 if (controller.signal.aborted) return { status: "abandoned" };
438 throw error;
439 } finally {
440 input.signal?.removeEventListener("abort", abort);
441 }