Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Layer from "effect/Layer";
5import * as Schema from "effect/Schema";
6
7import { resolveAttachmentPathById } from "../attachmentStore.ts";
8import * as ServerConfig from "../config.ts";
9import * as TerminalManager from "../terminal/Manager.ts";
10
11export class ResourceCleanupError extends Schema.TaggedError<ResourceCleanupError>()(
12 "ResourceCleanupError",
13 {
14 operation: Schema.Literals(["terminal", "attachment"]),
15 threadId: Schema.optional(Schema.String),
16 attachmentId: Schema.optional(Schema.String),
17 cause: Schema.Defect(),
18 },
19) {}
20
21export class ResourceCleanupService extends Context.Reference<{
22 readonly cleanupTerminals: (threadId: string) => Effect.Effect<void, ResourceCleanupError>;
23 readonly cleanupAttachments: (
24 attachmentIds: ReadonlyArray<string>,
25 ) => Effect.Effect<void, ResourceCleanupError>;
26}>("t3/orchestration-v2/ResourceCleanupService", {
27 defaultValue: () => ({
28 cleanupTerminals: () => Effect.void,
29 cleanupAttachments: () => Effect.void,
30 }),
31}) {}
32
33export const live = Layer.effect(
34 ResourceCleanupService,
35 Effect.gen(function* () {
36 const terminals = yield* TerminalManager.TerminalManager;
37 const fileSystem = yield* FileSystem.FileSystem;
38 const config = yield* ServerConfig.ServerConfig;
39 return {
40 cleanupTerminals: (threadId: string) =>
41 terminals
42 .close({ threadId, deleteHistory: true })
43 .pipe(
44 Effect.mapError(
45 (cause) => new ResourceCleanupError({ operation: "terminal", threadId, cause }),
46 ),
47 ),
48 cleanupAttachments: (attachmentIds: ReadonlyArray<string>) =>
49 Effect.forEach(
50 attachmentIds,
51 (attachmentId) => {
52 const path = resolveAttachmentPathById({
53 attachmentsDir: config.attachmentsDir,
54 attachmentId,
55 });
56 return path === null
57 ? Effect.void
58 : fileSystem
59 .remove(path, { force: true })
60 .pipe(
61 Effect.mapError(
62 (cause) =>
63 new ResourceCleanupError({ operation: "attachment", attachmentId, cause }),
64 ),
65 );
66 },
67 { discard: true, concurrency: 4 },
68 ),
69 };
70 }),
71);