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

attachments.ts

238 lines8.3 KB

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