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

accountCache.ts

235 lines7.1 KB

1// Occurrence indices are fetch-local; replace entire refetched ranges to prevent key collisions.
2import { cursorRateModel } from "./accountUsage.ts";
3import type { UsageRecord } from "@t3tools/provider-core/server/usage";
4​
5export type CursorCredentialSource = string | { readonly kind: "keychain" };
6​
7export const CURSOR_ACCOUNT_TTL_MS = 60 * 1000;
8​
9/** Dashboard events can be finalized after they were first read. */
10const REFETCH_OVERLAP_MS = 60 * 60 * 1000;
11​
12export interface CursorAccountCache {
13 readonly accountKey: string;
14 readonly sinceMs: number;
15 readonly untilMs: number;
16 readonly fetchedAtMs: number;
17 readonly records: readonly UsageRecord[];
19​
20interface CursorFetchRange {
21 readonly sinceMs: number;
22 readonly untilMs: number;
24​
25export function isCursorCacheFresh(
26 cache: CursorAccountCache | undefined,
27 nowMs: number,
28): cache is CursorAccountCache {
29 return cache !== undefined && nowMs - cache.fetchedAtMs < CURSOR_ACCOUNT_TTL_MS;
31​
32export function cursorFetchRange(
33 cache: CursorAccountCache | undefined,
34 retentionStartMs: number,
35 nowMs: number,
36): CursorFetchRange {
37 return cache === undefined ||
38 cache.sinceMs > retentionStartMs ||
39 cache.untilMs - REFETCH_OVERLAP_MS < retentionStartMs
40 ? { sinceMs: retentionStartMs, untilMs: nowMs }
41 : { sinceMs: cache.untilMs - REFETCH_OVERLAP_MS, untilMs: nowMs };
43​
44export function mergeCursorFetch(
45 cache: CursorAccountCache | undefined,
46 accountKey: string,
47 range: CursorFetchRange,
48 fetched: readonly UsageRecord[],
49 nowMs: number,
50 retentionStartMs: number,
51) {
52 const inRange = (record: UsageRecord) =>
53 record.timestampMs >= range.sinceMs && record.timestampMs <= range.untilMs;
54 const previous = cache?.records ?? [];
55 const added = fetched.filter(inRange);
56 const replacedKeys = new Set(previous.filter(inRange).map((record) => record.dedupeKey));
57 const changed =
58 cache === undefined ||
59 replacedKeys.size !== added.length ||
60 added.some((record) => !replacedKeys.has(record.dedupeKey));
61 return {
62 changed,
63 cache: {
64 accountKey,
65 sinceMs: retentionStartMs,
66 untilMs: range.untilMs,
67 fetchedAtMs: nowMs,
68 records: [
69 ...previous.filter((record) => !inRange(record) && record.timestampMs >= retentionStartMs),
70 ...added,
71 ],
72 } satisfies CursorAccountCache,
73 };
75​
76/** Versioned files isolate caches for different server versions sharing a state directory. */
77export const CURSOR_ACCOUNT_CACHE_FILE_NAME = "usage-cursor-account-cache-v1.json";
78const CURSOR_ACCOUNT_CACHE_VERSION = 1;
79​
80type SerializedRecord = readonly [
81 timestampMs: number,
82 modelIndex: number,
83 sessionIndex: number,
84 uncachedInputTokens: number,
85 cachedInputTokens: number,
86 cacheCreationTokens: number,
87 outputTokens: number,
88 reportedCostUsd: number | null,
89 dedupeKey: string | null,
90];
91​
92interface SerializedAccount {
93 readonly accountKey: string;
94 readonly sinceMs: number;
95 readonly untilMs: number;
96 readonly fetchedAtMs: number;
97 readonly records: readonly SerializedRecord[];
99​
100export function encodeCursorAccountCaches(caches: ReadonlyMap<string, CursorAccountCache>): string {
101 const strings: string[] = [];
102 const indexes = new Map<string, number>();
103 const intern = (value: string) => {
104 let index = indexes.get(value);
105 if (index === undefined) {
106 index = strings.length;
107 strings.push(value);
108 indexes.set(value, index);
109 }
110 return index;
111 };
112 const accounts: Record<string, SerializedAccount> = {};
113 for (const [credentialKey, cache] of caches) {
114 accounts[credentialKey] = {
115 accountKey: cache.accountKey,
116 sinceMs: cache.sinceMs,
117 untilMs: cache.untilMs,
118 fetchedAtMs: cache.fetchedAtMs,
119 records: cache.records.map((record) => [
120 record.timestampMs,
121 intern(record.model),
122 intern(record.sessionId),
123 record.totals.uncachedInputTokens,
124 record.totals.cachedInputTokens,
125 record.totals.cacheCreationTokens,
126 record.totals.outputTokens,
127 record.reportedCostUsd,
128 record.dedupeKey,
129 ]),
130 };
131 }
132 return JSON.stringify({ version: CURSOR_ACCOUNT_CACHE_VERSION, strings, accounts });
134​
135const isFiniteNumber = (value: unknown): value is number =>
136 typeof value === "number" && Number.isFinite(value);
137​
138/** Drop a malformed account whole; surviving records would leave gaps in a range marked complete. */
139export function decodeCursorAccountCaches(document: unknown): Map<string, CursorAccountCache> {
140 const caches = new Map<string, CursorAccountCache>();
141 if (typeof document !== "object" || document === null) return caches;
142 const root = document as {
143 readonly version?: unknown;
144 readonly strings?: unknown;
145 readonly accounts?: unknown;
146 };
147 const strings = root.strings;
148 if (
149 root.version !== CURSOR_ACCOUNT_CACHE_VERSION ||
150 !Array.isArray(strings) ||
151 !strings.every((value): value is string => typeof value === "string") ||
152 typeof root.accounts !== "object" ||
153 root.accounts === null
154 ) {
155 return caches;
156 }
157 const stringAt = (index: unknown): string | undefined =>
158 typeof index === "number" ? strings[index] : undefined;
159​
160 const decodeRecord = (row: unknown): UsageRecord | null => {
161 if (!Array.isArray(row)) return null;
162 const [
163 timestampMs,
164 modelIndex,
165 sessionIndex,
166 uncached,
167 cached,
168 creation,
169 output,
170 cost,
171 key,
172 ]: readonly unknown[] = row;
173 const model = stringAt(modelIndex);
174 const sessionId = stringAt(sessionIndex);
175 if (
176 !isFiniteNumber(timestampMs) ||
177 model === undefined ||
178 sessionId === undefined ||
179 !isFiniteNumber(uncached) ||
180 !isFiniteNumber(cached) ||
181 !isFiniteNumber(creation) ||
182 !isFiniteNumber(output) ||
183 (cost !== null && !isFiniteNumber(cost)) ||
184 (key !== null && typeof key !== "string")
185 ) {
186 return null;
187 }
188 return {
189 provider: "cursor",
190 timestampMs,
191 model,
192 rateModel: cursorRateModel(model),
193 sessionId,
194 totals: {
195 uncachedInputTokens: uncached,
196 cachedInputTokens: cached,
197 cacheCreationTokens: creation,
198 outputTokens: output,
199 reasoningTokens: 0,
200 },
201 reportedCostUsd: cost,
202 speed: "standard",
203 dedupeKey: key,
204 };
205 };
206​
207 for (const [credentialKey, raw] of Object.entries(root.accounts)) {
208 if (typeof raw !== "object" || raw === null) continue;
209 const account = raw as Partial<Record<keyof SerializedAccount, unknown>>;
210 if (
211 typeof account.accountKey !== "string" ||
212 !isFiniteNumber(account.sinceMs) ||
213 !isFiniteNumber(account.untilMs) ||
214 !isFiniteNumber(account.fetchedAtMs) ||
215 !Array.isArray(account.records)
216 ) {
217 continue;
218 }
219 const records: UsageRecord[] = [];
220 for (const row of account.records) {
221 const record = decodeRecord(row);
222 if (record === null) break;
223 records.push(record);
224 }
225 if (records.length !== account.records.length) continue;
226 caches.set(credentialKey, {
227 accountKey: account.accountKey,
228 sinceMs: account.sinceMs,
229 untilMs: account.untilMs,
230 fetchedAtMs: account.fetchedAtMs,
231 records,
232 });
233 }
234 return caches;