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

attachmentStore.ts

307 lines10.1 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeCrypto from "node:crypto";
3import * as NodeFS from "node:fs";
4import * as NodePath from "node:path";
5​
6import type { ChatAttachment } from "@t3tools/contracts";
7import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput";
8​
9import {
10 normalizeAttachmentRelativePath,
11 resolveAttachmentRelativePath,
12} from "./attachmentPaths.ts";
13import { inferImageExtension, SAFE_IMAGE_FILE_EXTENSIONS } from "./imageMime.ts";
14​
15const ATTACHMENT_FILENAME_EXTENSIONS = [...SAFE_IMAGE_FILE_EXTENSIONS, ".bin"];
16const ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS = 80;
17const ATTACHMENT_ID_THREAD_SEGMENT_PATTERN = "[a-z0-9_]+(?:-[a-z0-9_]+)*";
18const ATTACHMENT_ID_UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
19const ATTACHMENT_ID_FILE_EXTENSION_PATTERN = "[a-z0-9]{1,10}";
20const ATTACHMENT_ID_PATTERN = new RegExp(
21 `^(${ATTACHMENT_ID_THREAD_SEGMENT_PATTERN})-(${ATTACHMENT_ID_UUID_PATTERN})(?:-(${ATTACHMENT_ID_FILE_EXTENSION_PATTERN}))?$`,
22 "i",
23);
24​
25export const PENDING_ATTACHMENT_THREAD_SEGMENT = "pending";
26const PENDING_ATTACHMENT_MAX_AGE_MS = 24 * 60 * 60 * 1000;
27const PARTIAL_UPLOAD_MAX_AGE_MS = 60 * 60 * 1000;
28​
29export function toSafeThreadAttachmentSegment(threadId: string): string | null {
30 const segment = threadId
31 .trim()
32 .toLowerCase()
33 .replace(/[^a-z0-9_-]+/gi, "-")
34 .replace(/-+/g, "-")
35 .replace(/^[-_]+|[-_]+$/g, "")
36 .slice(0, ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS)
37 .replace(/[-_]+$/g, "");
38 if (segment.length === 0) {
39 return null;
40 }
41 return segment === PENDING_ATTACHMENT_THREAD_SEGMENT ? "_pending" : segment;
43​
44export function attachmentFileExtension(fileName: string): string {
45 const extension = NodePath.extname(fileName).toLowerCase();
46 // ".part" is reserved for in-flight uploads; a stored "archive.part" would
47 // look stale to sweepStalePendingAttachments and get deleted.
48 if (extension === ".part" || !/^\.[a-z0-9]{1,10}$/.test(extension)) {
49 return ".bin";
50 }
51 return extension;
53​
54function attachmentIdExtensionSuffix(extension: string | undefined): string {
55 if (!extension) {
56 return "";
57 }
58 const normalized = extension.replace(/^\./, "").toLowerCase();
59 return new RegExp(`^${ATTACHMENT_ID_FILE_EXTENSION_PATTERN}$`).test(normalized)
60 ? `-${normalized}`
61 : "-bin";
63​
64export function createPendingAttachmentId(extension?: string): string {
65 return `${PENDING_ATTACHMENT_THREAD_SEGMENT}-${NodeCrypto.randomUUID()}${attachmentIdExtensionSuffix(extension)}`;
67​
68export function parseAttachmentUuid(attachmentId: string): string | null {
69 const normalizedId = normalizeAttachmentRelativePath(attachmentId);
70 if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
71 return null;
72 }
73 return normalizedId.match(ATTACHMENT_ID_PATTERN)?.[2]?.toLowerCase() ?? null;
75​
76export function parseAttachmentFileExtension(attachmentId: string): string | null {
77 const normalizedId = normalizeAttachmentRelativePath(attachmentId);
78 if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
79 return null;
80 }
81 return normalizedId.match(ATTACHMENT_ID_PATTERN)?.[3]?.toLowerCase() ?? null;
83​
84export function createAttachmentId(threadId: string, extension?: string): string | null {
85 const threadSegment = toSafeThreadAttachmentSegment(threadId);
86 if (!threadSegment) {
87 return null;
88 }
89 return `${threadSegment}-${NodeCrypto.randomUUID()}${attachmentIdExtensionSuffix(extension)}`;
91​
92export function createDeterministicAttachmentId(
93 threadId: string,
94 stableKey: string,
95): string | null {
96 const threadSegment = toSafeThreadAttachmentSegment(threadId);
97 if (!threadSegment) return null;
98 const hash = NodeCrypto.createHash("sha256")
99 .update(JSON.stringify([threadId, stableKey]))
100 .digest("hex")
101 .slice(0, 32);
102 const uuid = `${hash.slice(0, 8)}-${hash.slice(8, 12)}-${hash.slice(12, 16)}-${hash.slice(16, 20)}-${hash.slice(20)}`;
103 return `${threadSegment}-${uuid}`;
105​
106export function parseThreadSegmentFromAttachmentId(attachmentId: string): string | null {
107 const normalizedId = normalizeAttachmentRelativePath(attachmentId);
108 if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
109 return null;
110 }
111 const match = normalizedId.match(ATTACHMENT_ID_PATTERN);
112 if (!match) {
113 return null;
114 }
115 return match[1]?.toLowerCase() ?? null;
117​
118/**
119 * Attachments a thread's `html_render` tool calls published. Only ids minted
120 * for this thread count, so deleting a fork never removes its source's pages.
121 */
122export function threadHtmlRenderAttachmentIds(
123 threadId: string,
124 items: Iterable<{ readonly toolName: string | null | undefined; readonly output?: unknown }>,
125) {
126 const segment = toSafeThreadAttachmentSegment(threadId);
127 if (segment === null) return [];
128 return Array.from(items).flatMap((item) => {
129 const attachmentId = htmlRenderFromToolItem(item)?.attachmentId;
130 return attachmentId !== undefined &&
131 parseThreadSegmentFromAttachmentId(attachmentId) === segment
132 ? [attachmentId]
133 : [];
134 });
136​
137/** Null for attachment types this build does not know; callers skip those. */
138export function attachmentRelativePath(attachment: ChatAttachment): string | null {
139 switch (attachment.type) {
140 case "image": {
141 const extension = inferImageExtension({
142 mimeType: attachment.mimeType,
143 fileName: attachment.name,
144 });
145 return `${attachment.id}${extension}`;
146 }
147 case "file":
148 return `${attachment.id}${attachmentFileExtension(attachment.name)}`;
149 default:
150 return null;
151 }
153​
154export function resolveAttachmentPath(input: {
155 readonly attachmentsDir: string;
156 readonly attachment: ChatAttachment;
157}): string | null {
158 const relativePath = attachmentRelativePath(input.attachment);
159 if (!relativePath) {
160 return null;
161 }
162 return resolveAttachmentRelativePath({
163 attachmentsDir: input.attachmentsDir,
164 relativePath,
165 });
167​
168export function resolveAttachmentPathById(input: {
169 readonly attachmentsDir: string;
170 readonly attachmentId: string;
171}): string | null {
172 const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);
173 if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
174 return null;
175 }
176 const fileExtension = parseAttachmentFileExtension(normalizedId);
177 if (fileExtension) {
178 const filePath = resolveAttachmentRelativePath({
179 attachmentsDir: input.attachmentsDir,
180 relativePath: `${normalizedId}.${fileExtension.toLowerCase()}`,
181 });
182 return filePath && NodeFS.existsSync(filePath) ? filePath : null;
183 }
184 for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {
185 const maybePath = resolveAttachmentRelativePath({
186 attachmentsDir: input.attachmentsDir,
187 relativePath: `${normalizedId}${extension}`,
188 });
189 if (maybePath && NodeFS.existsSync(maybePath)) {
190 return maybePath;
191 }
192 }
193 return null;
195​
196export type AttachmentClaimPlan =
197 | {
198 readonly ok: true;
199 readonly finalId: string;
200 readonly currentPath: string;
201 readonly finalPath: string;
202 }
203 | { readonly ok: false; readonly reason: string };
204​
205export function planAttachmentClaim(input: {
206 readonly attachmentsDir: string;
207 readonly threadId: string;
208 readonly attachmentId: string;
209}): AttachmentClaimPlan {
210 const uuid = parseAttachmentUuid(input.attachmentId);
211 const requestedSegment = parseThreadSegmentFromAttachmentId(input.attachmentId);
212 if (!uuid || !requestedSegment) {
213 return { ok: false, reason: "invalid attachment id" };
214 }
215​
216 if (!toSafeThreadAttachmentSegment(input.threadId)) {
217 return { ok: false, reason: "invalid thread id" };
218 }
219 if (requestedSegment !== PENDING_ATTACHMENT_THREAD_SEGMENT) {
220 return { ok: false, reason: "attachment must be a pending upload" };
221 }
222​
223 const currentPath = resolveAttachmentPathById({
224 attachmentsDir: input.attachmentsDir,
225 attachmentId: input.attachmentId,
226 });
227 if (!currentPath) {
228 return { ok: false, reason: "attachment not found (removed or expired)" };
229 }
230 const fileExtension = parseAttachmentFileExtension(input.attachmentId) ?? undefined;
231 const finalId = createAttachmentId(input.threadId, fileExtension);
232 if (!finalId) {
233 return { ok: false, reason: "failed to create attachment id" };
234 }
235​
236 const expectedFinalPath = resolveAttachmentRelativePath({
237 attachmentsDir: input.attachmentsDir,
238 relativePath: `${finalId}${NodePath.extname(currentPath)}`,
239 });
240 if (!expectedFinalPath) {
241 return { ok: false, reason: "failed to resolve attachment path" };
242 }
243 return {
244 ok: true,
245 finalId,
246 currentPath,
247 finalPath: expectedFinalPath,
248 };
250​
251export function sweepStalePendingAttachments(input: {
252 readonly attachmentsDir: string;
253 readonly nowMs: number;
254}): { readonly deleted: number } {
255 let entries: string[];
256 try {
257 entries = NodeFS.readdirSync(input.attachmentsDir);
258 } catch {
259 return { deleted: 0 };
260 }
261​
262 let deleted = 0;
263 for (const entry of entries) {
264 const isPartial = entry.endsWith(".part");
265 if (!isPartial) {
266 const attachmentId = parseAttachmentIdFromRelativePath(entry);
267 if (
268 !attachmentId ||
269 parseThreadSegmentFromAttachmentId(attachmentId) !== PENDING_ATTACHMENT_THREAD_SEGMENT
270 ) {
271 continue;
272 }
273 }
274​
275 const resolved = resolveAttachmentRelativePath({
276 attachmentsDir: input.attachmentsDir,
277 relativePath: entry,
278 });
279 if (!resolved) {
280 continue;
281 }
282 try {
283 const maxAgeMs = isPartial ? PARTIAL_UPLOAD_MAX_AGE_MS : PENDING_ATTACHMENT_MAX_AGE_MS;
284 if (input.nowMs - NodeFS.statSync(resolved).mtimeMs > maxAgeMs) {
285 NodeFS.unlinkSync(resolved);
286 deleted += 1;
287 }
288 } catch {
289 continue;
290 }
291 }
292​
293 return { deleted };
295​
296function parseAttachmentIdFromRelativePath(relativePath: string): string | null {
297 const normalized = normalizeAttachmentRelativePath(relativePath);
298 if (!normalized || normalized.includes("/")) {
299 return null;
300 }
301 const extensionIndex = normalized.lastIndexOf(".");
302 if (extensionIndex <= 0) {
303 return null;
304 }
305 const id = normalized.slice(0, extensionIndex);
306 return id.length > 0 && !id.includes(".") ? id : null;