Open History to see the last commit
1import { Duration, Effect, Layer, Schedule } from "effect";
2
3import { OrchestrationEngineService } from "../../orchestration/Services/OrchestrationEngine.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 orchestrationEngine = yield* OrchestrationEngineService;
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 readModel = yield* orchestrationEngine.getReadModel();
33 const threadsById = new Map(readModel.threads.map((thread) => [thread.id, thread] as const));
34 const bindings = yield* directory.listBindings();
35 const now = Date.now();
36 let reapedCount = 0;
37
38 for (const binding of bindings) {
39 if (binding.status === "stopped") {
40 continue;
41 }
42
43 const lastSeenMs = Date.parse(binding.lastSeenAt);
44 if (Number.isNaN(lastSeenMs)) {
45 yield* Effect.logWarning("provider.session.reaper.invalid-last-seen", {
46 threadId: binding.threadId,
47 provider: binding.provider,
48 lastSeenAt: binding.lastSeenAt,
49 });
50 continue;
51 }
52
53 const idleDurationMs = now - lastSeenMs;
54 if (idleDurationMs < inactivityThresholdMs) {
55 continue;
56 }
57
58 const thread = threadsById.get(binding.threadId);
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();