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

ProviderSessionReaper.ts

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