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

ProviderSessionReaper.ts

139 lines4.6 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 const reaped = yield* providerService.stopSession({ threadId: binding.threadId }).pipe(
75 Effect.tap(() =>
76 Effect.logInfo("provider.session.reaped", {
77 threadId: binding.threadId,
78 provider: binding.provider,
79 idleDurationMs,
80 reason: "inactivity_threshold",
81 }),
82 ),
83 Effect.as(true),
84 Effect.catchCause((cause) =>
85 Effect.logWarning("provider.session.reaper.stop-failed", {
86 threadId: binding.threadId,
87 provider: binding.provider,
88 idleDurationMs,
89 cause,
90 }).pipe(Effect.as(false)),
91 ),
92 );
93​
94 if (reaped) {
95 reapedCount += 1;
96 }
97 }
98​
99 if (reapedCount > 0) {
100 yield* Effect.logInfo("provider.session.reaper.sweep-complete", {
101 reapedCount,
102 totalBindings: bindings.length,
103 });
104 }
105 });
106​
107 const start: ProviderSessionReaperShape["start"] = () =>
108 Effect.gen(function* () {
109 yield* forkParked(
110 sweep.pipe(
111 Effect.catch((error: unknown) =>
112 Effect.logWarning("provider.session.reaper.sweep-failed", {
113 error,
114 }),
115 ),
116 Effect.catchDefect((defect: unknown) =>
117 Effect.logWarning("provider.session.reaper.sweep-defect", {
118 defect,
119 }),
120 ),
121 Effect.repeat(Schedule.spaced(Duration.millis(sweepIntervalMs))),
122 ),
123 );
124​
125 yield* Effect.logInfo("provider.session.reaper.started", {
126 inactivityThresholdMs,
127 sweepIntervalMs,
128 });
129 });
130​
131 return {
132 start,
133 } satisfies ProviderSessionReaperShape;
134 });
135​
136export const makeProviderSessionReaperLive = (options?: ProviderSessionReaperLiveOptions) =>
137 Layer.effect(ProviderSessionReaper, makeProviderSessionReaper(options));
138​
139export const ProviderSessionReaperLive = makeProviderSessionReaperLive();