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

AttachmentClaims.ts

139 lines5.3 KB

1import * as FileSystem from "effect/FileSystem";
2import {
3 ChatAttachmentId,
4 getProviderAttachmentLimitError,
5 type ChatAttachment,
6} from "@t3tools/contracts";
7import * as Effect from "effect/Effect";
8import * as Schema from "effect/Schema";
9​
10import {
11 parseThreadSegmentFromAttachmentId,
12 PENDING_ATTACHMENT_THREAD_SEGMENT,
13 planAttachmentClaim,
14 resolveAttachmentPath,
15} from "../attachmentStore.ts";
16import * as ServerConfig from "../config.ts";
17​
18export class AttachmentClaimError extends Schema.TaggedError<AttachmentClaimError>()(
19 "AttachmentClaimError",
20 {
21 message: Schema.String,
22 cause: Schema.optional(Schema.Defect()),
23 },
24) {}
25​
26export const validateAttachmentLimits = Effect.fn("AttachmentClaims.validateAttachmentLimits")(
27 function* (attachments: ReadonlyArray<ChatAttachment>) {
28 const error = getProviderAttachmentLimitError(attachments);
29 if (error) return yield* new AttachmentClaimError({ message: error });
30 },
31);
32​
33export interface ClaimedAttachments {
34 readonly attachments: ReadonlyArray<ChatAttachment>;
35 readonly claimedPaths: ReadonlyArray<string>;
37​
38export function attachmentIsPendingUpload(attachment: ChatAttachment): boolean {
39 return parseThreadSegmentFromAttachmentId(attachment.id) === PENDING_ATTACHMENT_THREAD_SEGMENT;
41​
42/** Remove partial claims only before dispatch, or after proving they were not accepted. */
43export const releaseClaimedAttachments = Effect.fn("AttachmentClaims.releaseClaimedAttachments")(
44 function* (claimedPaths: ReadonlyArray<string>) {
45 if (claimedPaths.length === 0) return;
46 const fileSystem = yield* FileSystem.FileSystem;
47 yield* Effect.forEach(claimedPaths, (path) => fileSystem.remove(path).pipe(Effect.ignore), {
48 concurrency: 1,
49 discard: true,
50 }).pipe(Effect.uninterruptible);
51 },
52);
53​
54/** Copies preserve the pending retry source after failed bootstrap; the pending sweep reclaims it. */
55export const claimPendingAttachments = Effect.fn("AttachmentClaims.claimPendingAttachments")(
56 function* (input: {
57 readonly threadId: string;
58 readonly attachments: ReadonlyArray<ChatAttachment>;
59 }) {
60 yield* validateAttachmentLimits(input.attachments);
61 if (
62 new Set(input.attachments.map((attachment) => attachment.id)).size !==
63 input.attachments.length
64 ) {
65 return yield* new AttachmentClaimError({
66 message: "Duplicate attachment ids are not allowed.",
67 });
68 }
69 if (!input.attachments.some(attachmentIsPendingUpload)) {
70 return { attachments: input.attachments, claimedPaths: [] } satisfies ClaimedAttachments;
71 }
72 const serverConfig = yield* ServerConfig.ServerConfig;
73 const fileSystem = yield* FileSystem.FileSystem;
74 const claimedPaths: string[] = [];
75 const attachments = yield* Effect.forEach(
76 input.attachments,
77 (attachment) =>
78 Effect.gen(function* () {
79 if (!attachmentIsPendingUpload(attachment)) {
80 return attachment;
81 }
82 const claim = planAttachmentClaim({
83 attachmentsDir: serverConfig.attachmentsDir,
84 threadId: input.threadId,
85 attachmentId: attachment.id,
86 });
87 if (!claim.ok) {
88 return yield* new AttachmentClaimError({
89 message: `Attachment '${attachment.name}' cannot be sent: ${claim.reason}.`,
90 });
91 }
92 const info = yield* fileSystem.stat(claim.currentPath).pipe(
93 Effect.mapError(
94 (cause) =>
95 new AttachmentClaimError({
96 message: `Attachment '${attachment.name}' cannot be sent: attachment not found.`,
97 cause,
98 }),
99 ),
100 );
101 if (Number(info.size) !== attachment.sizeBytes) {
102 return yield* new AttachmentClaimError({
103 message: `Attachment '${attachment.name}' cannot be sent: stored size does not match.`,
104 });
105 }
106 const normalized: ChatAttachment = {
107 ...attachment,
108 id: ChatAttachmentId.make(claim.finalId),
109 mimeType: attachment.mimeType.toLowerCase(),
110 };
111 const expectedPath = resolveAttachmentPath({
112 attachmentsDir: serverConfig.attachmentsDir,
113 attachment: normalized,
114 });
115 if (expectedPath !== claim.finalPath) {
116 return yield* new AttachmentClaimError({
117 message: `Attachment '${attachment.name}' cannot be sent: attachment type does not match the upload.`,
118 });
119 }
120 // Copies isolate edits from the retry source. Keep the uncancellable copy and rollback registration
121 // uninterruptible so cleanup always sees completed writes.
122 yield* fileSystem.copyFile(claim.currentPath, claim.finalPath).pipe(
123 Effect.mapError(
124 (cause) =>
125 new AttachmentClaimError({
126 message: `Failed to claim attachment '${attachment.name}' for this thread.`,
127 cause,
128 }),
129 ),
130 Effect.andThen(Effect.sync(() => claimedPaths.push(claim.finalPath))),
131 Effect.uninterruptible,
132 );
133 return normalized;
134 }),
135 { concurrency: 1 },
136 ).pipe(Effect.onError(() => releaseClaimedAttachments(claimedPaths)));
137 return { attachments, claimedPaths } satisfies ClaimedAttachments;
138 },
139);