Open History to see the last commit
1import {
2 PROVIDER_SEND_TURN_MAX_FILE_BYTES,
3 WS_METHODS,
4 type AttachmentCreateUploadUrlInput,
5 type AttachmentCreateUploadUrlResult,
6 type AttachmentDeleteInput,
7 type EnvironmentId,
8} from "@t3tools/contracts";
9import type { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
10
11import type { EnvironmentRegistry } from "../connection/registry.ts";
12import {
13 createEnvironmentRpcCommand,
14 executeAtomQuery,
15 runAtomCommand,
16 squashAtomCommandFailure,
17 type AtomCommand,
18} from "./runtime.ts";
19
20/**
21 * RPC commands for pending chat attachment uploads. Mirrors
22 * `createAssetEnvironmentAtoms`: each client instantiates it with its own
23 * connection runtime (`attachmentEnvironment` in web and mobile).
24 */
25export function createAttachmentEnvironmentAtoms<R, E>(
26 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
27) {
28 return {
29 createUploadUrl: createEnvironmentRpcCommand(runtime, {
30 label: "environment-command:attachments:create-upload-url",
31 tag: WS_METHODS.attachmentsCreateUploadUrl,
32 }),
33 remove: createEnvironmentRpcCommand(runtime, {
34 label: "environment-command:attachments:delete",
35 tag: WS_METHODS.attachmentsDelete,
36 }),
37 };
38}
39
40/**
41 * Whether a failed asset lookup means the attachment no longer exists on the
42 * server, as opposed to a transient transport failure. Pending uploads expire,
43 * so this is the signal to upload the bytes again rather than retry the lookup.
44 *
45 * A structural `_tag` check rather than a schema check: the squashed cause of
46 * a failed RPC is not guaranteed to be a decoded error class instance, only a
47 * tagged value.
48 */
49export function isAssetAttachmentNotFoundFailure(error: unknown): boolean {
50 return (
51 typeof error === "object" &&
52 error !== null &&
53 "_tag" in error &&
54 error._tag === "AssetAttachmentNotFoundError"
55 );
56}
57
58export type PersistedAttachmentVerification =
59 | { readonly status: "verified" }
60 | { readonly status: "missing" }
61 | { readonly status: "failed"; readonly error: unknown };
62
63/**
64 * Checks that a previously uploaded pending attachment still exists on the
65 * server by minting an asset URL for it. `verified` means the send can reuse
66 * the stored bytes, `missing` means the upload expired and the bytes must be
67 * uploaded again, `failed` means the server could not be asked.
68 */
69export async function verifyPersistedAttachmentUpload<A, E>(input: {
70 readonly registry: AtomRegistry.AtomRegistry;
71 readonly createAssetUrl: (query: {
72 readonly environmentId: EnvironmentId;
73 readonly input: {
74 readonly resource: { readonly _tag: "attachment"; readonly attachmentId: string };
75 };
76 }) => Atom.Atom<AsyncResult.AsyncResult<A, E>>;
77 readonly environmentId: EnvironmentId;
78 readonly attachmentId: string;
79}): Promise<PersistedAttachmentVerification> {
80 const result = await executeAtomQuery(
81 input.registry,
82 input.createAssetUrl({
83 environmentId: input.environmentId,
84 input: { resource: { _tag: "attachment", attachmentId: input.attachmentId } },
85 }),
86 // `refresh` forces a server round trip: the asset URL query atom caches
87 // results (SWR), so a retry right after a transient failure would
88 // otherwise re-observe the cached failure and never ask the server.
89 { reportFailure: false, reportDefect: false, refresh: true },
90 );
91 if (result._tag === "Success") {
92 return { status: "verified" };
93 }
94 const error = squashAtomCommandFailure(result);
95 return isAssetAttachmentNotFoundFailure(error)
96 ? { status: "missing" }
97 : { status: "failed", error };
98}
99
100type AttachmentCreateUploadUrlCommand<E> = AtomCommand<
101 { readonly environmentId: EnvironmentId; readonly input: AttachmentCreateUploadUrlInput },
102 AttachmentCreateUploadUrlResult,
103 E
104>;
105
106type AttachmentRemoveCommand<E> = AtomCommand<
107 { readonly environmentId: EnvironmentId; readonly input: AttachmentDeleteInput },
108 unknown,
109 E
110>;
111
112/** Fire-and-forget delete of a pending upload the client no longer references. */
113export function deletePendingAttachmentUpload<E>(input: {
114 readonly registry: AtomRegistry.AtomRegistry;
115 readonly remove: AttachmentRemoveCommand<E>;
116 readonly environmentId: EnvironmentId;
117 readonly attachmentId: string;
118}): void {
119 void runAtomCommand(
120 input.registry,
121 input.remove,
122 { environmentId: input.environmentId, input: { attachmentId: input.attachmentId } },
123 { reportFailure: false, reportDefect: false },
124 );
125}
126
127/** A running byte transfer: resolves when the server accepted the bytes. */
128export interface AttachmentByteUpload {
129 readonly done: Promise<void>;
130 readonly abort: () => void;
131}
132
133export type AttachmentUploadCycleResult =
134 | { readonly status: "uploaded"; readonly attachmentId: string }
135 | { readonly status: "cancelled"; readonly attachmentId: string | null }
136 | {
137 readonly status: "failed";
138 readonly step: "mint" | "resolve-url" | "transfer";
139 readonly attachmentId: string | null;
140 readonly error: unknown;
141 };
142
143/**
144 * The platform-neutral upload cycle: mint a signed upload URL, resolve it
145 * against the environment's HTTP base, and hand the bytes to a
146 * platform-specific transport (XHR on web, `expo-file-system` on mobile).
147 *
148 * The cycle never deletes the minted pending upload on failure: callers keep
149 * the returned `attachmentId` and decide between retry and release. The one
150 * exception is `onMinted` returning `"cancel"`, where the caller already
151 * abandoned the upload and the fresh mint is deleted before returning.
152 */
153export async function runAttachmentUploadCycle<E, RE>(input: {
154 readonly registry: AtomRegistry.AtomRegistry;
155 readonly createUploadUrl: AttachmentCreateUploadUrlCommand<E>;
156 readonly remove: AttachmentRemoveCommand<RE>;
157 readonly environmentId: EnvironmentId;
158 readonly upload: AttachmentCreateUploadUrlInput;
159 readonly resolveUploadUrl: (relativeUrl: string) => string | null;
160 readonly transport: (url: string) => AttachmentByteUpload;
161 /** Observe the minted id (for cancellation bookkeeping) before bytes move. */
162 readonly onMinted?: (attachmentId: string) => "continue" | "cancel";
163 readonly onTransferStart?: (abort: () => void) => void;
164}): Promise<AttachmentUploadCycleResult> {
165 const minted = await runAtomCommand(
166 input.registry,
167 input.createUploadUrl,
168 { environmentId: input.environmentId, input: input.upload },
169 { reportFailure: false },
170 );
171 if (minted._tag !== "Success") {
172 return {
173 status: "failed",
174 step: "mint",
175 attachmentId: null,
176 error: squashAtomCommandFailure(minted),
177 };
178 }
179 const attachmentId = minted.value.attachmentId;
180 if (input.onMinted?.(attachmentId) === "cancel") {
181 deletePendingAttachmentUpload({
182 registry: input.registry,
183 remove: input.remove,
184 environmentId: input.environmentId,
185 attachmentId,
186 });
187 return { status: "cancelled", attachmentId };
188 }
189
190 const url = input.resolveUploadUrl(minted.value.relativeUrl);
191 if (!url) {
192 return {
193 status: "failed",
194 step: "resolve-url",
195 attachmentId,
196 error: new Error("The environment is not connected."),
197 };
198 }
199
200 const transfer = input.transport(url);
201 input.onTransferStart?.(transfer.abort);
202 try {
203 await transfer.done;
204 } catch (error) {
205 return { status: "failed", step: "transfer", attachmentId, error };
206 }
207 return { status: "uploaded", attachmentId };
208}
209
210/**
211 * The effective per-file byte limit for a server that advertises
212 * `capabilities.fileAttachments.maxUploadBytes`. The contract caps what a
213 * turn may reference, so a larger advertised value must not admit files the
214 * send would then refuse.
215 */
216export function clampFileAttachmentUploadBytes(advertisedMaxUploadBytes: number): number {
217 return Math.min(advertisedMaxUploadBytes, PROVIDER_SEND_TURN_MAX_FILE_BYTES);
218}
219
220/** "3.2 MB" / "48 KB" label for attachment rows. Never shows "0 KB". */
221export function formatAttachmentSize(sizeBytes: number): string {
222 return sizeBytes >= 1024 * 1024
223 ? `${(sizeBytes / (1024 * 1024)).toFixed(1)} MB`
224 : `${Math.max(1, Math.ceil(sizeBytes / 1024))} KB`;
225}
226
227/** User-facing rejection for a file over the effective upload limit. */
228export function fileAttachmentTooLargeMessage(name: string, maxUploadBytes: number): string {
229 const maxUploadSize =
230 maxUploadBytes >= 1024 * 1024 && maxUploadBytes % (1024 * 1024) === 0
231 ? `${maxUploadBytes / (1024 * 1024)} MB`
232 : maxUploadBytes >= 1024 && maxUploadBytes % 1024 === 0
233 ? `${maxUploadBytes / 1024} KB`
234 : `${maxUploadBytes} ${maxUploadBytes === 1 ? "byte" : "bytes"}`;
235 return `'${name}' exceeds the ${maxUploadSize} attachment limit.`;
236}