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

attachmentUpload.ts

451 lines16.2 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 { msg } from "gt-react-native";
9import { m } from "../i18n/messages";
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 Effect from "effect/Effect";
21import * as Option from "effect/Option";
22​
23import { appAtomRegistry } from "../state/atom-registry";
24import { assetEnvironment } from "../state/assets";
25import { attachmentEnvironment } from "../state/attachments";
26import { environmentSession, readEnvironmentScope } from "../state/session";
27import { resolveOwnedComposerAttachmentFileUri } from "./composerAttachmentFiles";
28import { retainComposerAttachmentFileForPreview } from "./composerAttachmentPreviewRetention";
29import {
30 isComposerImageAttachment,
31 isFileBackedComposerAttachment,
32 type DraftComposerAttachment,
33 type DraftComposerImageAttachment,
34} from "./composerImages";
35import { imageMimeType } from "@t3tools/shared/image";
36import { uuidv4 } from "./uuid";
37import {
38 attachmentUploadError,
39 type AttachmentUploadError,
40} from "@t3tools/client-runtime/state/attachment-uploads";
41​
42export type UploadedMobileAttachment =
43 | UploadChatImageAttachment
44 | ChatImageAttachment
45 | ChatFileAttachment;
46​
47export function withUploadedMobileAttachmentReferences(input: {
48 readonly environmentId: EnvironmentId;
49 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
50 readonly uploadedAttachments: ReadonlyArray<UploadedMobileAttachment>;
51}): ReadonlyArray<DraftComposerAttachment> {
52 return input.attachments.map((attachment, index) => {
53 const uploaded = input.uploadedAttachments[index];
54 // Files-picked images upload as images; compare wire types to retain uploaded ids and avoid re-uploading.
55 const uploadedAs = isComposerImageAttachment(attachment) ? "image" : attachment.type;
56 if (
57 !uploaded ||
58 !("id" in uploaded) ||
59 uploadedAs !== uploaded.type ||
60 (attachment.uploadedAttachmentId === uploaded.id &&
61 attachment.uploadEnvironmentId === input.environmentId)
62 ) {
63 return attachment;
64 }
65 return {
66 ...attachment,
67 uploadedAttachmentId: uploaded.id,
68 uploadEnvironmentId: input.environmentId,
69 };
70 });
72​
73export async function releasePendingAttachmentUploads(
74 environmentId: EnvironmentId,
75 attachmentIds: ReadonlyArray<string>,
76): Promise<void> {
77 const deleteOnce = async (attachmentId: string): Promise<boolean> => {
78 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) {
79 throw new Error("This connection cannot delete pending attachments.");
80 }
81 const result = await runAtomCommand(
82 appAtomRegistry,
83 attachmentEnvironment.remove,
84 { environmentId, input: { attachmentId } },
85 { reportFailure: false, reportDefect: false },
86 );
87 return (
88 result._tag === "Success" ||
89 isAssetAttachmentNotFoundFailure(squashAtomCommandFailure(result))
90 );
91 };
92​
93 const failedAttachmentIds: string[] = [];
94 for (const attachmentId of attachmentIds) {
95 if (!(await deleteOnce(attachmentId)) && !(await deleteOnce(attachmentId))) {
96 failedAttachmentIds.push(attachmentId);
97 }
98 }
99 if (failedAttachmentIds.length > 0) {
100 throw new Error(
101 `Could not delete ${failedAttachmentIds.length} pending attachment upload(s): ${failedAttachmentIds.join(", ")}.`,
102 );
103 }
105​
106async function releaseCreatedUploadsQuietly(
107 environmentId: EnvironmentId,
108 attachmentIds: ReadonlyArray<string>,
109): Promise<void> {
110 try {
111 await releasePendingAttachmentUploads(environmentId, attachmentIds);
112 } catch (error) {
113 console.warn("[attachments] could not delete abandoned pending uploads", error);
114 }
116​
117export interface PreparedTurnAttachments {
118 readonly status: "ready";
119 readonly attachments: ReadonlyArray<UploadedMobileAttachment>;
120 readonly draftAttachments: ReadonlyArray<DraftComposerAttachment>;
121 readonly pendingAttachmentIds: ReadonlyArray<string>;
123​
124export type PrepareTurnAttachmentsResult =
125 | PreparedTurnAttachments
126 | { readonly status: "abandoned" };
127​
128/** Promote Files-picked images consistently in headers, payloads and references or ChatImageAttachment rejects them. */
129function composerAttachmentWireMimeType(attachment: DraftComposerAttachment): string {
130 if (!isComposerImageAttachment(attachment)) return attachment.mimeType;
131 return supportedImageWireMimeType(attachment);
133​
134function supportedImageWireMimeType(
135 attachment: DraftComposerAttachment,
136): (typeof PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES)[number] {
137 const inferred = imageMimeType(attachment);
138 const mimeType = PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES.find(
139 (type) => type === attachment.mimeType.toLowerCase() || type === inferred,
140 );
141 if (!mimeType) {
142 throw new Error(m(msg`Unsupported image type for '${{ name: attachment.name }}'.`));
143 }
144 return mimeType;
146​
147function uploadedReference(
148 attachment: DraftComposerAttachment,
149 id: string,
150): ChatImageAttachment | ChatFileAttachment {
151 const fields = {
152 id,
153 name: attachment.name,
154 mimeType: composerAttachmentWireMimeType(attachment),
155 sizeBytes: attachment.sizeBytes,
156 };
157 return isComposerImageAttachment(attachment)
158 ? { type: "image", ...fields }
159 : {
160 type: "file",
161 ...fields,
162 ...(attachment.source ? { source: attachment.source } : {}),
163 };
165​
166function attachmentUploadInput(attachment: DraftComposerAttachment) {
167 const fields = { name: attachment.name, sizeBytes: attachment.sizeBytes };
168 return isComposerImageAttachment(attachment)
169 ? { ...fields, mimeType: supportedImageWireMimeType(attachment) }
170 : { type: "file" as const, ...fields, mimeType: attachment.mimeType };
172​
173async function toUploadChatImageAttachments(
174 attachments: ReadonlyArray<DraftComposerImageAttachment>,
175): Promise<ReadonlyArray<UploadChatImageAttachment>> {
176 return Promise.all(
177 attachments.map(async (attachment) => ({
178 type: attachment.type,
179 name: attachment.name,
180 mimeType: attachment.mimeType,
181 sizeBytes: attachment.sizeBytes,
182 dataUrl: await composerImageAttachmentDataUrl(attachment),
183 })),
184 );
186​
187async function composerImageAttachmentDataUrl(
188 attachment: DraftComposerImageAttachment,
189): Promise<string> {
190 if (attachment.dataUrl !== undefined) {
191 return attachment.dataUrl;
192 }
193 if (!isFileBackedComposerAttachment(attachment)) {
194 throw new Error(`'${attachment.name}' is no longer available. Attach the image again.`);
195 }
196 const release = retainComposerAttachmentFileForPreview(attachment);
197 try {
198 const { File, Paths } = await import("expo-file-system");
199 const uri =
200 resolveOwnedComposerAttachmentFileUri(attachment.fileUri, Paths.document.uri) ??
201 attachment.fileUri;
202 const base64 = await new File(uri).base64();
203 return `data:${attachment.mimeType};base64,${base64}`;
204 } finally {
205 release();
206 }
208​
209const UPLOAD_STALL_CHECK_MS = 10_000;
210​
211async function uploadFileBytes(
212 environmentId: EnvironmentId,
213 attachment: DraftComposerAttachment,
214 url: string,
215 signal: AbortSignal,
216 onProgress?: (progress: number) => void,
217 onTransportFailure?: () => void,
218): Promise<void> {
219 const { File, Paths, UploadType } = await import("expo-file-system");
220 if (signal.aborted) throw new Error("Upload cancelled.");
221 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) {
222 throw new Error(m(msg("This connection cannot upload attachments.")));
223 }
224 const fileUri = attachment.fileUri;
225 const inlineDataUrl = attachment.type === "image" ? attachment.dataUrl : undefined;
226 if (fileUri === undefined && inlineDataUrl === undefined) {
227 throw new Error(`'${attachment.name}' is no longer available. Attach the image again.`);
228 }
229 const file =
230 fileUri === undefined
231 ? new File(Paths.cache, `t3-upload-${uuidv4()}`)
232 : new File(resolveOwnedComposerAttachmentFileUri(fileUri, Paths.document.uri) ?? fileUri);
233 try {
234 if (fileUri === undefined && inlineDataUrl !== undefined) {
235 file.create();
236 await file.write(inlineDataUrl.slice(inlineDataUrl.indexOf(",") + 1), {
237 encoding: "base64",
238 });
239 }
240 // Native uploads to an origin that stopped accepting connections can hang without rejecting.
241 let stallTimer: ReturnType<typeof setTimeout> | undefined;
242 const armStallCheck = () => {
243 clearTimeout(stallTimer);
244 stallTimer = setTimeout(() => {
245 onTransportFailure?.();
246 armStallCheck();
247 }, UPLOAD_STALL_CHECK_MS);
248 };
249 armStallCheck();
250 let result: Awaited<ReturnType<typeof file.upload>>;
251 try {
252 result = await file.upload(url, {
253 httpMethod: "POST",
254 uploadType: UploadType.BINARY_CONTENT,
255 headers: { "Content-Type": composerAttachmentWireMimeType(attachment) },
256 signal,
257 // Native events carry Int64 counts, which expo-modules-jsi delivers as BigInt despite the `number` type.
258 onProgress: ({ bytesSent, totalBytes }) => {
259 armStallCheck();
260 const total = Number(totalBytes);
261 if (total > 0) onProgress?.(Number(bytesSent) / total);
262 },
263 });
264 } catch (cause) {
265 if (!signal.aborted && file.exists) {
266 onTransportFailure?.();
267 }
268 throw cause;
269 } finally {
270 clearTimeout(stallTimer);
271 }
272 if (result.status < 200 || result.status >= 300) {
273 throw new Error(
274 m(
275 msg`Upload failed for '${{ name: attachment.name }}' (${{ status: String(result.status) }}).`,
276 ),
277 );
278 }
279 } finally {
280 if (fileUri === undefined && file.exists) file.delete();
281 }
283​
284function requireUploadAccess(environmentId: EnvironmentId): void {
285 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) {
286 throw new Error(m(msg("This connection cannot upload attachments.")));
287 }
289​
290/**
291 * Uploads one attachment and returns its uploaded id, reusing an earlier upload the server
292 * still has. Interrupting it aborts the native transfer and deletes the pending upload it minted;
293 * a failed transfer deletes it too.
294 */
295export const uploadComposerAttachment = Effect.fn("uploadComposerAttachment")(function* (
296 environmentId: EnvironmentId,
297 attachment: DraftComposerAttachment,
298 onProgress?: (progress: number) => void,
299) {
300 yield* Effect.try({
301 try: () => requireUploadAccess(environmentId),
302 catch: attachmentUploadError,
303 });
304 if (
305 attachment.uploadEnvironmentId === environmentId &&
306 attachment.uploadedAttachmentId !== undefined
307 ) {
308 const verification = yield* verifyPersistedAttachmentUpload({
309 registry: appAtomRegistry,
310 createAssetUrl: assetEnvironment.createUrl,
311 environmentId,
312 attachmentId: attachment.uploadedAttachmentId,
313 });
314 if (verification.status === "failed") {
315 return yield* attachmentUploadError(verification.error);
316 }
317 if (verification.status === "verified") return attachment.uploadedAttachmentId;
318 }
319 yield* Effect.try({
320 try: () => requireUploadAccess(environmentId),
321 catch: attachmentUploadError,
322 });
323 if (
324 Option.isNone(
325 appAtomRegistry.get(environmentSession.preparedConnectionValueAtom(environmentId)),
326 )
327 ) {
328 return yield* attachmentUploadError(new Error(m(msg("The environment is not connected."))));
329 }
330 const checkHttpOrigin = () => {
331 void runAtomCommand(appAtomRegistry, attachmentEnvironment.checkHttpOrigin, environmentId, {
332 reportFailure: false,
333 reportDefect: false,
334 });
335 };
336 const result = yield* runAttachmentUploadCycle({
337 registry: appAtomRegistry,
338 createUploadUrl: attachmentEnvironment.createUploadUrl,
339 remove: attachmentEnvironment.remove,
340 environmentId,
341 upload: attachmentUploadInput(attachment),
342 // Resolve at transfer time; reconnects may change the base URL.
343 resolveUploadUrl: (relativeUrl) => {
344 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return null;
345 const connection = appAtomRegistry.get(
346 environmentSession.preparedConnectionValueAtom(environmentId),
347 );
348 return Option.isNone(connection)
349 ? null
350 : resolveAssetUrl(connection.value.httpBaseUrl, relativeUrl);
351 },
352 transport: (url) =>
353 Effect.tryPromise({
354 try: (signal) =>
355 uploadFileBytes(environmentId, attachment, url, signal, onProgress, checkHttpOrigin),
356 catch: attachmentUploadError,
357 }),
358 });
359 if (result.status === "uploaded") return result.attachmentId;
360 if (result.attachmentId !== null) {
361 yield* Effect.promise(() =>
362 releaseCreatedUploadsQuietly(environmentId, [result.attachmentId!]),
363 );
364 }
365 return yield* attachmentUploadError(
366 result.step === "resolve-url" &&
367 !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)
368 ? new Error(m(msg("This connection cannot upload attachments.")))
369 : result.error instanceof Error
370 ? result.error
371 : new Error(m(msg`Upload failed for '${{ name: attachment.name }}'.`)),
372 );
373});
374​
375/**
376 * Turns a message's attachments into wire references. `uploadAttachment` is the shared upload
377 * registry, so a send joins an upload the composer already started; interrupting this stops
378 * waiting without cancelling that shared upload. persistUploadedReferences runs only for new
379 * uploaded ids; save them to their owner so crash retries reuse bytes.
380 */
381export const prepareTurnAttachments = Effect.fn("prepareTurnAttachments")(function* (input: {
382 readonly environmentId: EnvironmentId;
383 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
384 readonly supportsImageUploads?: boolean;
385 readonly uploadAttachment: (
386 attachment: DraftComposerAttachment,
387 ) => Effect.Effect<string, AttachmentUploadError>;
388 readonly persistUploadedReferences?: (
389 draftAttachments: ReadonlyArray<DraftComposerAttachment>,
390 ) => Effect.Effect<"persisted" | "abandon">;
391}) {
392 const { environmentId } = input;
393 const inlineImages = (attachments: ReadonlyArray<DraftComposerAttachment>) =>
394 Effect.tryPromise({
395 try: () =>
396 toUploadChatImageAttachments(
397 attachments.filter(
398 (attachment): attachment is DraftComposerImageAttachment => attachment.type === "image",
399 ),
400 ),
401 catch: attachmentUploadError,
402 });
403 const files = input.attachments.filter((attachment) => attachment.type === "file");
404 if (input.attachments.length === 0 || (files.length === 0 && !input.supportsImageUploads)) {
405 const imageAttachments = yield* inlineImages(input.attachments);
406 return {
407 status: "ready",
408 attachments: imageAttachments,
409 draftAttachments: input.attachments,
410 pendingAttachmentIds: [],
411 } satisfies PreparedTurnAttachments as PrepareTurnAttachmentsResult;
412 }
413​
414 yield* Effect.try({
415 try: () => requireUploadAccess(environmentId),
416 catch: attachmentUploadError,
417 });
418 const uploadedAttachments: UploadedMobileAttachment[] = [];
419 const pendingAttachmentIds: string[] = [];
420 for (const attachment of input.attachments) {
421 if (attachment.type === "image" && !input.supportsImageUploads) {
422 uploadedAttachments.push(...(yield* inlineImages([attachment])));
423 continue;
424 }
425 const uploadedId = yield* input.uploadAttachment(attachment);
426 pendingAttachmentIds.push(uploadedId);
427 uploadedAttachments.push(uploadedReference(attachment, uploadedId));
428 }
429​
430 const draftAttachments = withUploadedMobileAttachmentReferences({
431 environmentId,
432 attachments: input.attachments,
433 uploadedAttachments,
434 });
435 const referencesChanged = draftAttachments.some(
436 (attachment, index) => attachment !== input.attachments[index],
437 );
438 if (
439 referencesChanged &&
440 input.persistUploadedReferences &&
441 (yield* input.persistUploadedReferences(draftAttachments)) === "abandon"
442 ) {
443 return { status: "abandoned" } as PrepareTurnAttachmentsResult;
444 }
445 return {
446 status: "ready",
447 attachments: uploadedAttachments,
448 draftAttachments,
449 pendingAttachmentIds,
450 } satisfies PreparedTurnAttachments as PrepareTurnAttachmentsResult;
451});