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

attachmentStore.ts

226 lines6.9 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_PATTERN = new RegExp(
19 `^(${ATTACHMENT_ID_THREAD_SEGMENT_PATTERN})-(${ATTACHMENT_ID_UUID_PATTERN})$`,
20 "i",
21);
22​
23export const PENDING_ATTACHMENT_THREAD_SEGMENT = "pending";
24export const PENDING_ATTACHMENT_MAX_AGE_MS = 24 * 60 * 60 * 1000;
25const PARTIAL_UPLOAD_MAX_AGE_MS = 60 * 60 * 1000;
26​
27export function toSafeThreadAttachmentSegment(threadId: string): string | null {
28 const segment = threadId
29 .trim()
30 .toLowerCase()
31 .replace(/[^a-z0-9_-]+/gi, "-")
32 .replace(/-+/g, "-")
33 .replace(/^[-_]+|[-_]+$/g, "")
34 .slice(0, ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS)
35 .replace(/[-_]+$/g, "");
36 if (segment.length === 0) {
37 return null;
38 }
39 return segment === PENDING_ATTACHMENT_THREAD_SEGMENT ? "_pending" : segment;
41​
42export function createPendingAttachmentId(): string {
43 return `${PENDING_ATTACHMENT_THREAD_SEGMENT}-${NodeCrypto.randomUUID()}`;
45​
46export function parseAttachmentUuid(attachmentId: string): string | null {
47 const normalizedId = normalizeAttachmentRelativePath(attachmentId);
48 if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
49 return null;
50 }
51 return normalizedId.match(ATTACHMENT_ID_PATTERN)?.[2]?.toLowerCase() ?? null;
53​
54export function createAttachmentId(threadId: string): string | null {
55 const threadSegment = toSafeThreadAttachmentSegment(threadId);
56 if (!threadSegment) {
57 return null;
58 }
59 return `${threadSegment}-${NodeCrypto.randomUUID()}`;
61​
62export function parseThreadSegmentFromAttachmentId(attachmentId: string): string | null {
63 const normalizedId = normalizeAttachmentRelativePath(attachmentId);
64 if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
65 return null;
66 }
67 const match = normalizedId.match(ATTACHMENT_ID_PATTERN);
68 if (!match) {
69 return null;
70 }
71 return match[1]?.toLowerCase() ?? null;
73​
74export function attachmentRelativePath(attachment: ChatAttachment): string {
75 switch (attachment.type) {
76 case "image": {
77 const extension = inferImageExtension({
78 mimeType: attachment.mimeType,
79 fileName: attachment.name,
80 });
81 return `${attachment.id}${extension}`;
82 }
83 }
85​
86export function resolveAttachmentPath(input: {
87 readonly attachmentsDir: string;
88 readonly attachment: ChatAttachment;
89}): string | null {
90 return resolveAttachmentRelativePath({
91 attachmentsDir: input.attachmentsDir,
92 relativePath: attachmentRelativePath(input.attachment),
93 });
95​
96export function resolveAttachmentPathById(input: {
97 readonly attachmentsDir: string;
98 readonly attachmentId: string;
99}): string | null {
100 const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);
101 if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
102 return null;
103 }
104 for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {
105 const maybePath = resolveAttachmentRelativePath({
106 attachmentsDir: input.attachmentsDir,
107 relativePath: `${normalizedId}${extension}`,
108 });
109 if (maybePath && NodeFS.existsSync(maybePath)) {
110 return maybePath;
111 }
112 }
113 return null;
115​
116export type AttachmentClaimPlan =
117 | {
118 readonly ok: true;
119 readonly finalId: string;
120 readonly currentPath: string;
121 readonly finalPath: string;
122 }
123 | { readonly ok: false; readonly reason: string };
124​
125export function planAttachmentClaim(input: {
126 readonly attachmentsDir: string;
127 readonly threadId: string;
128 readonly attachmentId: string;
129}): AttachmentClaimPlan {
130 const uuid = parseAttachmentUuid(input.attachmentId);
131 const requestedSegment = parseThreadSegmentFromAttachmentId(input.attachmentId);
132 if (!uuid || !requestedSegment) {
133 return { ok: false, reason: "invalid attachment id" };
134 }
135​
136 if (!toSafeThreadAttachmentSegment(input.threadId)) {
137 return { ok: false, reason: "invalid thread id" };
138 }
139 if (requestedSegment !== PENDING_ATTACHMENT_THREAD_SEGMENT) {
140 return { ok: false, reason: "attachment must be a pending upload" };
141 }
142​
143 const currentPath = resolveAttachmentPathById({
144 attachmentsDir: input.attachmentsDir,
145 attachmentId: input.attachmentId,
146 });
147 if (!currentPath) {
148 return { ok: false, reason: "attachment not found (removed or expired)" };
149 }
150 const finalId = createAttachmentId(input.threadId);
151 if (!finalId) {
152 return { ok: false, reason: "failed to create attachment id" };
153 }
154​
155 const expectedFinalPath = resolveAttachmentRelativePath({
156 attachmentsDir: input.attachmentsDir,
157 relativePath: `${finalId}${NodePath.extname(currentPath)}`,
158 });
159 if (!expectedFinalPath) {
160 return { ok: false, reason: "failed to resolve attachment path" };
161 }
162 return {
163 ok: true,
164 finalId,
165 currentPath,
166 finalPath: expectedFinalPath,
167 };
169​
170export function sweepStalePendingAttachments(input: {
171 readonly attachmentsDir: string;
172 readonly nowMs: number;
173}): { readonly deleted: number } {
174 let entries: string[];
175 try {
176 entries = NodeFS.readdirSync(input.attachmentsDir);
177 } catch {
178 return { deleted: 0 };
179 }
180​
181 let deleted = 0;
182 for (const entry of entries) {
183 const isPartial = entry.endsWith(".part");
184 if (!isPartial) {
185 const attachmentId = parseAttachmentIdFromRelativePath(entry);
186 if (
187 !attachmentId ||
188 parseThreadSegmentFromAttachmentId(attachmentId) !== PENDING_ATTACHMENT_THREAD_SEGMENT
189 ) {
190 continue;
191 }
192 }
193​
194 const resolved = resolveAttachmentRelativePath({
195 attachmentsDir: input.attachmentsDir,
196 relativePath: entry,
197 });
198 if (!resolved) {
199 continue;
200 }
201 try {
202 const maxAgeMs = isPartial ? PARTIAL_UPLOAD_MAX_AGE_MS : PENDING_ATTACHMENT_MAX_AGE_MS;
203 if (input.nowMs - NodeFS.statSync(resolved).mtimeMs > maxAgeMs) {
204 NodeFS.unlinkSync(resolved);
205 deleted += 1;
206 }
207 } catch {
208 continue;
209 }
210 }
211​
212 return { deleted };
214​
215export function parseAttachmentIdFromRelativePath(relativePath: string): string | null {
216 const normalized = normalizeAttachmentRelativePath(relativePath);
217 if (!normalized || normalized.includes("/")) {
218 return null;
219 }
220 const extensionIndex = normalized.lastIndexOf(".");
221 if (extensionIndex <= 0) {
222 return null;
223 }
224 const id = normalized.slice(0, extensionIndex);
225 return id.length > 0 && !id.includes(".") ? id : null;