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

attachmentStore.ts

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