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

ProviderSessionReaper.ts

152 lines5.2 KB

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