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

attachments.test.ts

195 lines6.2 KB

1import { describe, expect, it } from "@effect/vitest";
2import {
3 EnvironmentId,
4 PROVIDER_SEND_TURN_MAX_FILE_BYTES,
5 type AttachmentCreateUploadUrlInput,
6 type AttachmentCreateUploadUrlResult,
7 type AttachmentDeleteInput,
8} from "@t3tools/contracts";
9import * as Effect from "effect/Effect";
10import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
11​
12import type { AtomCommand } from "./runtime.ts";
13import {
14 clampFileAttachmentUploadBytes,
15 fileAttachmentTooLargeMessage,
16 formatAttachmentSize,
17 runAttachmentUploadCycle,
18 verifyPersistedAttachmentUpload,
19} from "./attachments.ts";
20​
21const environmentId = EnvironmentId.make("environment-1");
22const registry = {} as AtomRegistry.AtomRegistry;
23​
24type CreateUploadUrlCommand = AtomCommand<
25 { readonly environmentId: EnvironmentId; readonly input: AttachmentCreateUploadUrlInput },
26 AttachmentCreateUploadUrlResult,
27 never
28>;
29​
30type RemoveCommand = AtomCommand<
31 { readonly environmentId: EnvironmentId; readonly input: AttachmentDeleteInput },
32 unknown,
33 never
34>;
35​
36function makeCreateUploadUrl(attachmentId: string): CreateUploadUrlCommand {
37 return {
38 label: "test:create-upload-url",
39 run: async () =>
40 AsyncResult.success<AttachmentCreateUploadUrlResult, never>({
41 attachmentId,
42 relativeUrl: `/api/attachments/upload/${attachmentId}`,
43 expiresAt: 1,
44 }),
45 };
47​
48const removeCalls: string[] = [];
49const remove: RemoveCommand = {
50 label: "test:remove",
51 run: async (_registry, input) => {
52 removeCalls.push(input.input.attachmentId);
53 return AsyncResult.success(undefined);
54 },
55};
56​
57const uploadInput: AttachmentCreateUploadUrlInput = {
58 type: "file",
59 name: "report.pdf",
60 mimeType: "application/pdf",
61 sizeBytes: 3,
62};
63​
64describe("runAttachmentUploadCycle", () => {
65 it("mints, transfers, and reports the attachment id", async () => {
66 const transferred: string[] = [];
67 const result = await runAttachmentUploadCycle({
68 registry,
69 createUploadUrl: makeCreateUploadUrl("pending-1"),
70 remove,
71 environmentId,
72 upload: uploadInput,
73 resolveUploadUrl: (relativeUrl) => `https://environment.test${relativeUrl}`,
74 transport: (url) => {
75 transferred.push(url);
76 return { done: Promise.resolve(), abort: () => {} };
77 },
78 });
79​
80 expect(result).toEqual({ status: "uploaded", attachmentId: "pending-1" });
81 expect(transferred).toEqual(["https://environment.test/api/attachments/upload/pending-1"]);
82 });
83​
84 it("deletes the fresh mint when the caller cancels at onMinted", async () => {
85 removeCalls.length = 0;
86 const result = await runAttachmentUploadCycle({
87 registry,
88 createUploadUrl: makeCreateUploadUrl("pending-cancelled"),
89 remove,
90 environmentId,
91 upload: uploadInput,
92 resolveUploadUrl: () => "https://environment.test/upload",
93 transport: () => {
94 throw new Error("transport must not run after cancel");
95 },
96 onMinted: () => "cancel",
97 });
98​
99 expect(result).toEqual({ status: "cancelled", attachmentId: "pending-cancelled" });
100 expect(removeCalls).toEqual(["pending-cancelled"]);
101 });
102​
103 it("keeps the minted id on transfer failure so the caller can retry or release", async () => {
104 removeCalls.length = 0;
105 const result = await runAttachmentUploadCycle({
106 registry,
107 createUploadUrl: makeCreateUploadUrl("pending-failed"),
108 remove,
109 environmentId,
110 upload: uploadInput,
111 resolveUploadUrl: () => "https://environment.test/upload",
112 transport: () => ({
113 done: Promise.reject(new Error("Upload rejected (413)")),
114 abort: () => {},
115 }),
116 });
117​
118 expect(result).toMatchObject({
119 status: "failed",
120 step: "transfer",
121 attachmentId: "pending-failed",
122 });
123 expect(removeCalls).toEqual([]);
124 });
125});
126​
127describe("verifyPersistedAttachmentUpload", () => {
128 it("hits the server on every verification instead of reusing a cached failure", async () => {
129 let lookups = 0;
130 const assetUrlAtom = Atom.make(
131 Effect.promise(() => Promise.resolve()).pipe(
132 Effect.flatMap(() => {
133 lookups += 1;
134 return lookups === 1
135 ? Effect.fail({ _tag: "TransportError" } as const)
136 : Effect.succeed({ url: "/api/assets/pending-1" });
137 }),
138 ),
139 ).pipe(Atom.swr({ staleTime: 60_000 }), Atom.keepAlive);
140 const liveRegistry = AtomRegistry.make();
141​
142 const verify = () =>
143 verifyPersistedAttachmentUpload({
144 registry: liveRegistry,
145 createAssetUrl: () => assetUrlAtom,
146 environmentId,
147 attachmentId: "pending-1",
148 });
149​
150 const first = await verify();
151 expect(first).toMatchObject({ status: "failed" });
152​
153 const second = await verify();
154 expect(second).toEqual({ status: "verified" });
155 expect(lookups).toBe(2);
156 });
157});
158​
159describe("file attachment limits", () => {
160 it("clamps the advertised limit to the turn contract cap", () => {
161 expect(clampFileAttachmentUploadBytes(1024)).toBe(1024);
162 expect(clampFileAttachmentUploadBytes(PROVIDER_SEND_TURN_MAX_FILE_BYTES * 2)).toBe(
163 PROVIDER_SEND_TURN_MAX_FILE_BYTES,
164 );
165 });
166​
167 it("formats attachment row sizes", () => {
168 expect(formatAttachmentSize(3 * 1024 * 1024)).toBe("3.0 MB");
169 expect(formatAttachmentSize(1)).toBe("1 KB");
170 });
171​
172 it("formats small upload limits without rounding them to zero MB", () => {
173 expect(fileAttachmentTooLargeMessage("tiny.txt", 1)).toBe(
174 "'tiny.txt' exceeds the 1 byte attachment limit.",
175 );
176 expect(fileAttachmentTooLargeMessage("small.txt", 1024)).toBe(
177 "'small.txt' exceeds the 1 KB attachment limit.",
178 );
179 expect(fileAttachmentTooLargeMessage("exact.txt", 1025)).toBe(
180 "'exact.txt' exceeds the 1025 bytes attachment limit.",
181 );
182 expect(fileAttachmentTooLargeMessage("medium.zip", 512 * 1024)).toBe(
183 "'medium.zip' exceeds the 512 KB attachment limit.",
184 );
185 });
186​
187 it("keeps whole-MB upload limits for standard server caps", () => {
188 expect(fileAttachmentTooLargeMessage("one.bin", 1024 * 1024)).toBe(
189 "'one.bin' exceeds the 1 MB attachment limit.",
190 );
191 expect(fileAttachmentTooLargeMessage("big.zip", 50 * 1024 * 1024)).toBe(
192 "'big.zip' exceeds the 50 MB attachment limit.",
193 );
194 });
195});