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

attachmentUpload.ts

318 lines12.1 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 EnvironmentId,
13 UploadChatImageAttachment,
14} from "@t3tools/contracts";
15import * as Option from "effect/Option";
16​
17import { appAtomRegistry } from "../state/atom-registry";
18import { assetEnvironment } from "../state/assets";
19import { attachmentEnvironment } from "../state/attachments";
20import { environmentSession } from "../state/session";
21import { resolveOwnedComposerAttachmentFileUri } from "./composerAttachmentFiles";
22import { toUploadChatImageAttachments, type DraftComposerAttachment } from "./composerImages";
23​
24/**
25 * This module owns the server side of a composer attachment's lifecycle.
26 * `prepareTurnAttachments` acquires pending uploads (verifying and reusing
27 * persisted ones), hands the uploaded ids back to the attachment's durable
28 * owner (queued outbox message or composer draft), and returns a release
29 * handle for after the turn consumed the bytes. Nothing outside this module
30 * mints or deletes pending uploads. The local-file side of the lifecycle is
31 * owned by `removeThreadOutboxMessage` / the composer draft mutators, which
32 * release files through `releaseUnusedComposerAttachmentFiles`.
33 */
34export type UploadedMobileAttachment = UploadChatImageAttachment | ChatFileAttachment;
35​
36export function validateDraftFileAttachments(input: {
37 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
38 readonly serverConfig: {
39 readonly environment: {
40 readonly capabilities: {
41 readonly attachmentUploads?: boolean;
42 readonly fileAttachments?: { readonly maxUploadBytes: number };
43 };
44 };
45 } | null;
46}): string | null {
47 const files = input.attachments.filter((attachment) => attachment.type === "file");
48 if (files.length === 0) return null;
49 if (input.serverConfig === null) return "Server attachment support is still loading.";
50 const capabilities = input.serverConfig.environment.capabilities;
51 if (capabilities.attachmentUploads !== true || capabilities.fileAttachments === undefined) {
52 return "This server does not support file attachments.";
53 }
54 const maxBytes = clampFileAttachmentUploadBytes(capabilities.fileAttachments.maxUploadBytes);
55 const oversized = files.find((attachment) => attachment.sizeBytes > maxBytes);
56 return oversized ? fileAttachmentTooLargeMessage(oversized.name, maxBytes) : null;
58​
59/** Keep uploaded file ids on durable drafts so a later send can reuse their bytes. */
60export function withUploadedMobileAttachmentReferences(input: {
61 readonly environmentId: EnvironmentId;
62 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
63 readonly uploadedAttachments: ReadonlyArray<UploadedMobileAttachment>;
64}): ReadonlyArray<DraftComposerAttachment> {
65 return input.attachments.map((attachment, index) => {
66 const uploaded = input.uploadedAttachments[index];
67 if (
68 attachment.type !== "file" ||
69 uploaded?.type !== "file" ||
70 (attachment.uploadedAttachmentId === uploaded.id &&
71 attachment.uploadEnvironmentId === input.environmentId)
72 ) {
73 return attachment;
74 }
75 return {
76 ...attachment,
77 uploadedAttachmentId: uploaded.id,
78 uploadEnvironmentId: input.environmentId,
79 };
80 });
82​
83/**
84 * Deletes pending uploads the client no longer references. Every delete result
85 * is inspected; failed deletes are retried once and a persistent failure
86 * throws, so a caller can never silently leak the outcome. (The server also
87 * expires pending uploads, so a leaked id self-heals eventually.)
88 */
89export async function releasePendingAttachmentUploads(
90 environmentId: EnvironmentId,
91 attachmentIds: ReadonlyArray<string>,
92): Promise<void> {
93 const deleteOnce = async (attachmentId: string): Promise<boolean> => {
94 const result = await runAtomCommand(
95 appAtomRegistry,
96 attachmentEnvironment.remove,
97 { environmentId, input: { attachmentId } },
98 { reportFailure: false, reportDefect: false },
99 );
100 return (
101 result._tag === "Success" ||
102 isAssetAttachmentNotFoundFailure(squashAtomCommandFailure(result))
103 );
104 };
105​
106 const failedAttachmentIds: string[] = [];
107 for (const attachmentId of attachmentIds) {
108 if (!(await deleteOnce(attachmentId)) && !(await deleteOnce(attachmentId))) {
109 failedAttachmentIds.push(attachmentId);
110 }
111 }
112 if (failedAttachmentIds.length > 0) {
113 throw new Error(
114 `Could not delete ${failedAttachmentIds.length} pending attachment upload(s): ${failedAttachmentIds.join(", ")}.`,
115 );
116 }
118​
119async function releaseCreatedUploadsQuietly(
120 environmentId: EnvironmentId,
121 attachmentIds: ReadonlyArray<string>,
122): Promise<void> {
123 try {
124 await releasePendingAttachmentUploads(environmentId, attachmentIds);
125 } catch (error) {
126 // The original failure must propagate; the leaked pending uploads expire
127 // on the server.
128 console.warn("[attachments] could not delete abandoned pending uploads", error);
129 }
131​
132export interface PreparedTurnAttachments {
133 readonly status: "ready";
134 /** Wire attachments for `startTurn`, in the original composer order. */
135 readonly attachments: ReadonlyArray<UploadedMobileAttachment>;
136 /** Composer attachments annotated with the uploaded pending ids. */
137 readonly draftAttachments: ReadonlyArray<DraftComposerAttachment>;
138 /** Every pending upload backing this turn (reused and newly minted). */
139 readonly pendingAttachmentIds: ReadonlyArray<string>;
140 /** Deletes all pending uploads once the delivered turn holds the bytes. */
141 readonly releaseUploads: () => Promise<void>;
143​
144export type PrepareTurnAttachmentsResult =
145 | PreparedTurnAttachments
146 | { readonly status: "abandoned" };
147​
148async function uploadFileBytes(
149 attachment: Extract<DraftComposerAttachment, { readonly type: "file" }>,
150 url: string,
151): Promise<void> {
152 const { File, Paths, UploadType } = await import("expo-file-system");
153 const fileUri =
154 resolveOwnedComposerAttachmentFileUri(attachment.fileUri, Paths.document.uri) ??
155 attachment.fileUri;
156 const result = await new File(fileUri).upload(url, {
157 httpMethod: "POST",
158 uploadType: UploadType.BINARY_CONTENT,
159 headers: { "Content-Type": attachment.mimeType },
160 });
161 if (result.status < 200 || result.status >= 300) {
162 throw new Error(`Upload failed for '${attachment.name}' (${result.status}).`);
163 }
165​
166/**
167 * Acquires server-side uploads for one turn's attachments and persists the
168 * uploaded ids into the attachments' durable owner.
169 *
170 * `persistUploadedReferences` runs once the bytes are on the server and only
171 * when new ids appeared. It must write the annotated attachments into the
172 * owner (queued message or draft) so a retry after a crash reuses the bytes.
173 * Returning `"abandon"` (owner no longer wants the send) or throwing deletes
174 * the pending uploads this call minted, so the owner cannot leak them.
175 */
176export async function prepareTurnAttachments(input: {
177 readonly environmentId: EnvironmentId;
178 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
179 readonly persistUploadedReferences?: (
180 draftAttachments: ReadonlyArray<DraftComposerAttachment>,
181 ) => Promise<"persisted" | "abandon">;
182}): Promise<PrepareTurnAttachmentsResult> {
183 const { environmentId } = input;
184 const files = input.attachments.filter((attachment) => attachment.type === "file");
185 const ready = (
186 attachments: ReadonlyArray<UploadedMobileAttachment>,
187 pendingAttachmentIds: ReadonlyArray<string>,
188 draftAttachments: ReadonlyArray<DraftComposerAttachment>,
189 ): PreparedTurnAttachments => ({
190 status: "ready",
191 attachments,
192 draftAttachments,
193 pendingAttachmentIds,
194 releaseUploads: () => releasePendingAttachmentUploads(environmentId, pendingAttachmentIds),
195 });
196​
197 if (files.length === 0) {
198 return ready(
199 toUploadChatImageAttachments(
200 input.attachments.filter((attachment) => attachment.type === "image"),
201 ),
202 [],
203 input.attachments,
204 );
205 }
206​
207 const connection = appAtomRegistry.get(
208 environmentSession.preparedConnectionValueAtom(environmentId),
209 );
210 if (Option.isNone(connection)) {
211 throw new Error("The environment is not connected.");
212 }
213​
214 const uploadedAttachments: UploadedMobileAttachment[] = [];
215 const pendingAttachmentIds: string[] = [];
216 const createdAttachmentIds: string[] = [];
217 try {
218 for (const attachment of input.attachments) {
219 if (attachment.type === "image") {
220 uploadedAttachments.push(...toUploadChatImageAttachments([attachment]));
221 continue;
222 }
223​
224 // Reuse the bytes from a previous attempt when their pending upload is
225 // still alive on this environment.
226 if (
227 attachment.uploadEnvironmentId === environmentId &&
228 attachment.uploadedAttachmentId !== undefined
229 ) {
230 const verification = await verifyPersistedAttachmentUpload({
231 registry: appAtomRegistry,
232 createAssetUrl: assetEnvironment.createUrl,
233 environmentId,
234 attachmentId: attachment.uploadedAttachmentId,
235 });
236 if (verification.status === "failed") {
237 throw verification.error;
238 }
239 if (verification.status === "verified") {
240 pendingAttachmentIds.push(attachment.uploadedAttachmentId);
241 uploadedAttachments.push({
242 type: "file",
243 id: attachment.uploadedAttachmentId,
244 name: attachment.name,
245 mimeType: attachment.mimeType,
246 sizeBytes: attachment.sizeBytes,
247 });
248 continue;
249 }
250 // "missing": the pending upload expired, upload the bytes again.
251 }
252​
253 const result = await runAttachmentUploadCycle({
254 registry: appAtomRegistry,
255 createUploadUrl: attachmentEnvironment.createUploadUrl,
256 remove: attachmentEnvironment.remove,
257 environmentId,
258 upload: {
259 type: "file",
260 name: attachment.name,
261 mimeType: attachment.mimeType,
262 sizeBytes: attachment.sizeBytes,
263 },
264 // Read the connection at transfer time: the environment may have
265 // reconnected on a new base URL since this cycle started.
266 resolveUploadUrl: (relativeUrl) => {
267 const currentConnection = appAtomRegistry.get(
268 environmentSession.preparedConnectionValueAtom(environmentId),
269 );
270 return Option.isNone(currentConnection)
271 ? null
272 : resolveAssetUrl(currentConnection.value.httpBaseUrl, relativeUrl);
273 },
274 transport: (url) => ({
275 done: uploadFileBytes(attachment, url),
276 // expo-file-system uploads cannot abort mid-flight.
277 abort: () => {},
278 }),
279 onMinted: (attachmentId) => {
280 pendingAttachmentIds.push(attachmentId);
281 createdAttachmentIds.push(attachmentId);
282 return "continue";
283 },
284 });
285 if (result.status !== "uploaded") {
286 throw result.status === "failed" && result.error !== undefined
287 ? result.error
288 : new Error(`Upload failed for '${attachment.name}'.`);
289 }
290 uploadedAttachments.push({
291 type: "file",
292 id: result.attachmentId,
293 name: attachment.name,
294 mimeType: attachment.mimeType,
295 sizeBytes: attachment.sizeBytes,
296 });
297 }
298​
299 const draftAttachments = withUploadedMobileAttachmentReferences({
300 environmentId,
301 attachments: input.attachments,
302 uploadedAttachments,
303 });
304 const referencesChanged = draftAttachments.some(
305 (attachment, index) => attachment !== input.attachments[index],
306 );
307 if (referencesChanged && input.persistUploadedReferences) {
308 if ((await input.persistUploadedReferences(draftAttachments)) === "abandon") {
309 await releaseCreatedUploadsQuietly(environmentId, createdAttachmentIds);
310 return { status: "abandoned" };
311 }
312 }
313 return ready(uploadedAttachments, pendingAttachmentIds, draftAttachments);
314 } catch (error) {
315 await releaseCreatedUploadsQuietly(environmentId, createdAttachmentIds);
316 throw error;
317 }