Open History to see the last commit
1import { Duration, Effect, Layer, Option, Schedule } from "effect";
2
3import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
4import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
5import {
6 ProviderSessionReaper,
7 type ProviderSessionReaperShape,
8} from "../Services/ProviderSessionReaper.ts";
9import { ProviderService } from "../Services/ProviderService.ts";
10
11const DEFAULT_INACTIVITY_THRESHOLD_MS = 30 * 60 * 1000;
12const DEFAULT_SWEEP_INTERVAL_MS = 5 * 60 * 1000;
13
14export interface ProviderSessionReaperLiveOptions {
15 readonly inactivityThresholdMs?: number;
16 readonly sweepIntervalMs?: number;
17}
18
19const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =>
20 Effect.gen(function* () {
21 const providerService = yield* ProviderService;
22 const directory = yield* ProviderSessionDirectory;
23 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
24
25 const inactivityThresholdMs = Math.max(
26 1,
27 options?.inactivityThresholdMs ?? DEFAULT_INACTIVITY_THRESHOLD_MS,
28 );
29 const sweepIntervalMs = Math.max(1, options?.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS);
30
31 const sweep = Effect.gen(function* () {
32 const bindings = yield* directory.listBindings();
33 const now = Date.now();
34 let reapedCount = 0;
35
36 for (const binding of bindings) {
37 if (binding.status === "stopped") {
38 continue;
39 }
40
41 const lastSeenMs = Date.parse(binding.lastSeenAt);
42 if (Number.isNaN(lastSeenMs)) {
43 yield* Effect.logWarning("provider.session.reaper.invalid-last-seen", {
44 threadId: binding.threadId,
45 provider: binding.provider,
46 lastSeenAt: binding.lastSeenAt,
47 });
48 continue;
49 }
50
51 const idleDurationMs = now - lastSeenMs;
52 if (idleDurationMs < inactivityThresholdMs) {
53 continue;
54 }
55
56 const thread = yield* projectionSnapshotQuery
57 .getThreadShellById(binding.threadId)
58 .pipe(Effect.map(Option.getOrUndefined));
59 if (thread?.session?.activeTurnId != null) {
60 yield* Effect.logDebug("provider.session.reaper.skipped-active-turn", {
61 threadId: binding.threadId,
62 activeTurnId: thread.session.activeTurnId,
63 idleDurationMs,
64 });
65 continue;
66 }
67
68 const reaped = yield* providerService.stopSession({ threadId: binding.threadId }).pipe(
69 Effect.tap(() =>
70 Effect.logInfo("provider.session.reaped", {
71 threadId: binding.threadId,
72 provider: binding.provider,
73 idleDurationMs,
74 reason: "inactivity_threshold",
75 }),
76 ),
77 Effect.as(true),
78 Effect.catchCause((cause) =>
79 Effect.logWarning("provider.session.reaper.stop-failed", {
80 threadId: binding.threadId,
81 provider: binding.provider,
82 idleDurationMs,
83 cause,
84 }).pipe(Effect.as(false)),
85 ),
86 );
87
88 if (reaped) {
89 reapedCount += 1;
90 }
91 }
92
93 if (reapedCount > 0) {
94 yield* Effect.logInfo("provider.session.reaper.sweep-complete", {
95 reapedCount,
96 totalBindings: bindings.length,
97 });
98 }
99 });
100
101 const start: ProviderSessionReaperShape["start"] = () =>
102 Effect.gen(function* () {
103 yield* Effect.forkScoped(
104 sweep.pipe(
105 Effect.catch((error: unknown) =>
106 Effect.logWarning("provider.session.reaper.sweep-failed", {
107 error,
108 }),
109 ),
110 Effect.catchDefect((defect: unknown) =>
111 Effect.logWarning("provider.session.reaper.sweep-defect", {
112 defect,
113 }),
114 ),
115 Effect.repeat(Schedule.spaced(Duration.millis(sweepIntervalMs))),
116 ),
117 );
118
119 yield* Effect.logInfo("provider.session.reaper.started", {
120 inactivityThresholdMs,
121 sweepIntervalMs,
122 });
123 });
124
125 return {
126 start,
127 } satisfies ProviderSessionReaperShape;
128 });
129
130export const makeProviderSessionReaperLive = (options?: ProviderSessionReaperLiveOptions) =>
131 Layer.effect(ProviderSessionReaper, makeProviderSessionReaper(options));
132
133export const ProviderSessionReaperLive = makeProviderSessionReaperLive();