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 * as Effect from "effect/Effect";
10import { mFallback, msg } from "gt-i18n";
11import type { MFunctionType } from "gt-i18n/types";
12import type { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
13
14import type { EnvironmentRegistry } from "../connection/registry.ts";
15import {
16 createEnvironmentRpcCommand,
17 executeAtomQuery,
18 runAtomCommand,
19 squashAtomCommandFailure,
20 type AtomCommand,
21} from "./runtime.ts";
22
23export function createAttachmentEnvironmentAtoms<R, E>(
24 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
25) {
26 return {
27 createUploadUrl: createEnvironmentRpcCommand(runtime, {
28 label: "environment-command:attachments:create-upload-url",
29 tag: WS_METHODS.attachmentsCreateUploadUrl,
30 }),
31 remove: createEnvironmentRpcCommand(runtime, {
32 label: "environment-command:attachments:delete",
33 tag: WS_METHODS.attachmentsDelete,
34 }),
35 };
36}
37
38/**
39 * Pending uploads expire, so this is the signal to upload the bytes again rather than retry the
40 * lookup. A structural `_tag` check rather than a schema check: the squashed cause of a failed
41 * RPC is not guaranteed to be a decoded error class instance, only a tagged value.
42 */
43export function isAssetAttachmentNotFoundFailure(error: unknown): boolean {
44 return (
45 typeof error === "object" &&
46 error !== null &&
47 "_tag" in error &&
48 error._tag === "AssetAttachmentNotFoundError"
49 );
50}
51
52export type PersistedAttachmentVerification =
53 | { readonly status: "verified" }
54 | { readonly status: "missing" }
55 | { readonly status: "failed"; readonly error: unknown };
56
57export function verifyPersistedAttachmentUpload<A, E>(input: {
58 readonly registry: AtomRegistry.AtomRegistry;
59 readonly createAssetUrl: (query: {
60 readonly environmentId: EnvironmentId;
61 readonly input: {
62 readonly resource: { readonly _tag: "attachment"; readonly attachmentId: string };
63 };
64 }) => Atom.Atom<AsyncResult.AsyncResult<A, E>>;
65 readonly environmentId: EnvironmentId;
66 readonly attachmentId: string;
67}): Effect.Effect<PersistedAttachmentVerification> {
68 return Effect.promise(() =>
69 executeAtomQuery(
70 input.registry,
71 input.createAssetUrl({
72 environmentId: input.environmentId,
73 input: { resource: { _tag: "attachment", attachmentId: input.attachmentId } },
74 }),
75 // `refresh` forces a server round trip: the asset URL query atom caches
76 // results (SWR), so a retry right after a transient failure would
77 // otherwise re-observe the cached failure and never ask the server.
78 { reportFailure: false, reportDefect: false, refresh: true },
79 ),
80 ).pipe(
81 Effect.map((result): PersistedAttachmentVerification => {
82 if (result._tag === "Success") return { status: "verified" };
83 const error = squashAtomCommandFailure(result);
84 return isAssetAttachmentNotFoundFailure(error)
85 ? { status: "missing" }
86 : { status: "failed", error };
87 }),
88 Effect.withSpan("Attachments.verifyPersistedUpload"),
89 );
90}
91
92type AttachmentCreateUploadUrlCommand<E> = AtomCommand<
93 { readonly environmentId: EnvironmentId; readonly input: AttachmentCreateUploadUrlInput },
94 AttachmentCreateUploadUrlResult,
95 E
96>;
97
98type AttachmentRemoveCommand<E> = AtomCommand<
99 { readonly environmentId: EnvironmentId; readonly input: AttachmentDeleteInput },
100 unknown,
101 E
102>;
103
104export function deletePendingAttachmentUpload<E>(input: {
105 readonly registry: AtomRegistry.AtomRegistry;
106 readonly remove: AttachmentRemoveCommand<E>;
107 readonly environmentId: EnvironmentId;
108 readonly attachmentId: string;
109}): void {
110 void runAtomCommand(
111 input.registry,
112 input.remove,
113 { environmentId: input.environmentId, input: { attachmentId: input.attachmentId } },
114 { reportFailure: false, reportDefect: false },
115 );
116}
117
118export type AttachmentUploadCycleResult =
119 | { readonly status: "uploaded"; readonly attachmentId: string }
120 | {
121 readonly status: "failed";
122 readonly step: "mint" | "resolve-url" | "transfer";
123 readonly attachmentId: string | null;
124 readonly error: unknown;
125 };
126
127/**
128 * Mints an upload slot and sends the bytes. A failure keeps the minted id in the result so the
129 * caller decides between retry and release. Interrupting the cycle aborts the transfer and
130 * deletes the fresh mint, including when the interruption arrives while minting.
131 */
132export function runAttachmentUploadCycle<E, RE, TE>(input: {
133 readonly registry: AtomRegistry.AtomRegistry;
134 readonly createUploadUrl: AttachmentCreateUploadUrlCommand<E>;
135 readonly remove: AttachmentRemoveCommand<RE>;
136 readonly environmentId: EnvironmentId;
137 readonly upload: AttachmentCreateUploadUrlInput;
138 readonly resolveUploadUrl: (relativeUrl: string) => string | null;
139 /** Sends the bytes; interrupting it aborts the transfer. */
140 readonly transport: (url: string) => Effect.Effect<void, TE>;
141}): Effect.Effect<AttachmentUploadCycleResult> {
142 return Effect.uninterruptibleMask((restore) =>
143 Effect.gen(function* () {
144 const minted = yield* Effect.promise(() =>
145 runAtomCommand(
146 input.registry,
147 input.createUploadUrl,
148 { environmentId: input.environmentId, input: input.upload },
149 { reportFailure: false },
150 ),
151 );
152 if (minted._tag !== "Success") {
153 return {
154 status: "failed",
155 step: "mint",
156 attachmentId: null,
157 error: squashAtomCommandFailure(minted),
158 } as const;
159 }
160 const attachmentId = minted.value.attachmentId;
161 return yield* restore(
162 Effect.suspend(() => {
163 const url = input.resolveUploadUrl(minted.value.relativeUrl);
164 if (!url) {
165 return Effect.succeed<AttachmentUploadCycleResult>({
166 status: "failed",
167 step: "resolve-url",
168 attachmentId,
169 error: new Error("The environment is not connected."),
170 });
171 }
172 return input.transport(url).pipe(
173 Effect.as<AttachmentUploadCycleResult>({ status: "uploaded", attachmentId }),
174 Effect.catch((error) =>
175 Effect.succeed<AttachmentUploadCycleResult>({
176 status: "failed",
177 step: "transfer",
178 attachmentId,
179 error,
180 }),
181 ),
182 );
183 }),
184 ).pipe(
185 Effect.onInterrupt(() =>
186 Effect.sync(() =>
187 deletePendingAttachmentUpload({
188 registry: input.registry,
189 remove: input.remove,
190 environmentId: input.environmentId,
191 attachmentId,
192 }),
193 ),
194 ),
195 );
196 }),
197 ).pipe(Effect.withSpan("Attachments.runUploadCycle"));
198}
199
200/**
201 * The contract caps what a turn may reference, so a larger advertised value must not admit
202 * files the send would then refuse.
203 */
204export function clampFileAttachmentUploadBytes(advertisedMaxUploadBytes: number): number {
205 return Math.min(advertisedMaxUploadBytes, PROVIDER_SEND_TURN_MAX_FILE_BYTES);
206}
207
208export function formatAttachmentSize(
209 sizeBytes: number,
210 resolve: MFunctionType = mFallback,
211): string {
212 const kilobytes = Math.max(1, Math.ceil(sizeBytes / 1024));
213 // Pick the unit after rounding, so 1023.5 KB reads "1.0 MB", not "1024 KB".
214 return kilobytes >= 1024
215 ? resolve(msg("{size} MB", { size: (sizeBytes / (1024 * 1024)).toFixed(1) }))
216 : resolve(msg("{size} KB", { size: kilobytes }));
217}
218
219export function fileAttachmentTooLargeMessage(
220 name: string,
221 maxUploadBytes: number,
222 resolve: MFunctionType = mFallback,
223): string {
224 const size =
225 maxUploadBytes >= 1024 * 1024 && maxUploadBytes % (1024 * 1024) === 0
226 ? resolve(msg("{count} MB", { count: maxUploadBytes / (1024 * 1024) }))
227 : maxUploadBytes >= 1024 && maxUploadBytes % 1024 === 0
228 ? resolve(msg("{count} KB", { count: maxUploadBytes / 1024 }))
229 : resolve(
230 msg("{count, plural, one {{count} byte} other {{count} bytes}}", {
231 count: maxUploadBytes,
232 }),
233 );
234 return resolve(msg("''{name}'' exceeds the {size} attachment limit.", { name, size }));
235}