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

UsageLimitRecoveryWorker.ts

112 lines3.9 KB

1import { CommandId, MessageId, type OrchestrationV2Command } from "@t3tools/contracts";
2import * as DateTime from "effect/DateTime";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Scheduler from "../scheduling/Scheduler.ts";
6import * as ServerSettings from "../serverSettings.ts";
7import * as ProjectionStore from "./ProjectionStore.ts";
8import * as ThreadManagement from "./ThreadManagementService.ts";
9​
10export function limitRecoveryCommand(
11 thread: ProjectionStore.ProjectionLimitRecoveryCandidate,
12 autoResume: boolean,
13 nowMs: number,
14 snooze = false,
15): OrchestrationV2Command | null {
16 if (
17 thread.status !== "failed" ||
18 thread.lastErrorClass !== "usage_limit" ||
19 !thread.latestRunId ||
20 !thread.usageLimitResetAt ||
21 thread.archivedAt !== null ||
22 thread.settledOverride === "settled" ||
23 thread.pendingRuntimeRequest !== null
24 )
25 return null;
26 const resetMs = Date.parse(thread.usageLimitResetAt);
27 // An already-expired window reported with a fresh failure cannot start a retry loop.
28 if (
29 !Number.isFinite(resetMs) ||
30 resetMs <= DateTime.toEpochMillis(thread.latestRunCompletedAt ?? thread.updatedAt)
31 )
32 return null;
33 const identity = `${thread.id}:${thread.latestRunId}:${resetMs}`;
34 const recovery = thread.limitRecovery;
35 if (recovery?.runId !== thread.latestRunId || recovery.resetAt !== thread.usageLimitResetAt) {
36 if (!autoResume && (!snooze || resetMs <= nowMs)) return null;
37 return {
38 type: "thread.metadata.update",
39 commandId: CommandId.make(`limit-arm:${identity}`),
40 threadId: thread.id,
41 limitRecovery: {
42 runId: thread.latestRunId,
43 resetAt: thread.usageLimitResetAt,
44 autoResume,
45 snooze: snooze && resetMs > nowMs,
46 },
47 };
48 }
49 if (
50 !recovery.autoResume ||
51 resetMs > nowMs ||
52 (thread.snoozedUntil != null && DateTime.toEpochMillis(thread.snoozedUntil) > nowMs)
53 )
54 return null;
55 const deliveryIdentity = `${identity}:${recovery.requestId ?? "legacy"}`;
56 return {
57 type: "message.dispatch",
58 commandId: CommandId.make(`limit-resume:${deliveryIdentity}`),
59 messageId: MessageId.make(`limit-resume:${deliveryIdentity}`),
60 threadId: thread.id,
61 usageLimitContinuationOfRunId: thread.latestRunId,
62 ...(recovery.requestId === undefined
63 ? {}
64 : { usageLimitRecoveryRequestId: recovery.requestId }),
65 text: "Continue where you left off.",
66 attachments: [],
67 dispatchMode: { type: "start_immediately" },
68 createdBy: "user",
69 creationSource: "server",
70 };
72​
73const makeSweep = Effect.gen(function* () {
74 const projections = yield* ProjectionStore.ProjectionStoreV2;
75 const threads = yield* ThreadManagement.ThreadManagementService;
76 const settings = yield* ServerSettings.ServerSettingsService;
77 return Effect.fn("UsageLimitRecoveryWorker.sweep")(function* () {
78 const preferences = yield* settings.getSettings;
79 const now = yield* DateTime.now;
80 const candidates = yield* projections.getLimitRecoveryCandidates({
81 now,
82 autoResume: preferences.autoResumeLimitedThreads,
83 snooze: preferences.snoozeLimitedThreads,
84 });
85 const nowMs = DateTime.toEpochMillis(now);
86 for (const thread of candidates) {
87 const command = limitRecoveryCommand(
88 thread,
89 preferences.autoResumeLimitedThreads,
90 nowMs,
91 preferences.snoozeLimitedThreads,
92 );
93 if (command === null) continue;
94 yield* threads.dispatch(command).pipe(
95 Effect.catchCause((cause) =>
96 Effect.logWarning("orchestration-v2.limit-recovery.dispatch-failed", {
97 threadId: thread.id,
98 cause,
99 }),
100 ),
101 );
102 }
103 });
104});
105​
106export const layer = Layer.effectDiscard(
107 Effect.gen(function* () {
108 const sweep = yield* makeSweep;
109 const scheduler = yield* Scheduler.Scheduler;
110 yield* scheduler.register("usage-limit-recovery", sweep());
111 }),
112);