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

ResourceCleanupService.ts

84 lines3.0 KB

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