Open History to see the last commit
1import type { ProviderInstanceId } from "@t3tools/contracts";
2import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
3import type { ProviderUsageScan } from "@t3tools/provider-core/server/usage";
4import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
5import * as Clock from "effect/Clock";
6import * as Context from "effect/Context";
7import * as Digest from "effect/crypto/Digest";
8import * as Deferred from "effect/Deferred";
9import * as Effect from "effect/Effect";
10import * as Hex from "effect/encoding/Hex";
11import * as Fiber from "effect/Fiber";
12import * as FileSystem from "effect/FileSystem";
13import * as Layer from "effect/Layer";
14import * as Path from "effect/Path";
15import * as Schema from "effect/Schema";
16import * as Semaphore from "effect/Semaphore";
17
18import {
19 CURSOR_ACCOUNT_CACHE_FILE_NAME,
20 CURSOR_ACCOUNT_TTL_MS,
21 cursorFetchRange,
22 decodeCursorAccountCaches,
23 encodeCursorAccountCaches,
24 isCursorCacheFresh,
25 mergeCursorFetch,
26 type CursorAccountCache,
27 type CursorCredentialSource,
28} from "./accountCache.ts";
29import * as CursorAccountReader from "./CursorAccountReader.ts";
30import { readStoredCursorApiKey } from "./credentialStore.ts";
31
32const CURSOR_ACCOUNT_READ_ERROR = "Cursor account usage could not be read.";
33
34const decodeCacheFile = Schema.decodeUnknownEffect(
35 Schema.fromJsonString(Schema.Unknown as unknown as Schema.Codec<unknown>),
36);
37
38export class CursorUsageAccounts extends Context.Service<
39 CursorUsageAccounts,
40 {
41 readonly scan: (input: {
42 readonly instances: ReadonlyArray<{
43 readonly instanceId: ProviderInstanceId;
44 readonly environment: NodeJS.ProcessEnv;
45 }>;
46 readonly windowStartMs: number;
47 readonly retentionCutoffMs: number;
48 readonly awaitRefresh: boolean;
49 }) => Effect.Effect<ReadonlyArray<ProviderUsageScan>>;
50 readonly awaitPersisted: Effect.Effect<void>;
51 }
52>()("@t3tools/provider-cursor/server/CursorUsageAccounts") {}
53
54const make = Effect.gen(function* () {
55 const fileSystem = yield* FileSystem.FileSystem;
56 const path = yield* Path.Path;
57 const host = yield* ProviderHost.ProviderHost;
58 const accountReader = yield* CursorAccountReader.CursorAccountReader;
59 const digest = yield* Digest.Digest;
60
61 const cachePath = path.join(host.paths.stateDir, CURSOR_ACCOUNT_CACHE_FILE_NAME);
62 const caches = new Map<string, CursorAccountCache>();
63 let cacheDirty = false;
64 /** Failed refreshes share the cache TTL to prevent repeated requests; null means no login. */
65 const failures = new Map<string, { readonly atMs: number; readonly error: string | null }>();
66 const refreshes = new Map<string, Deferred.Deferred<void>>();
67
68 const ensureLoaded = yield* Effect.cached(
69 fileSystem.readFileString(cachePath).pipe(
70 Effect.flatMap((raw) => decodeCacheFile(raw)),
71 Effect.catchCause(() => Effect.succeed(null)),
72 Effect.map((document) => {
73 for (const [key, cache] of decodeCursorAccountCaches(document)) caches.set(key, cache);
74 }),
75 ),
76 );
77
78 // Serialize snapshots; clear dirty before encoding and restore it on failure so changes retry.
79 const persistLock = yield* Semaphore.make(1);
80 const persist = Effect.gen(function* () {
81 if (!cacheDirty) return;
82 cacheDirty = false;
83 yield* Effect.sync(() => encodeCursorAccountCaches(caches)).pipe(
84 Effect.flatMap((contents) => writeFileStringAtomically({ filePath: cachePath, contents })),
85 Effect.provideService(FileSystem.FileSystem, fileSystem),
86 Effect.provideService(Path.Path, path),
87 Effect.catchCause(() =>
88 Effect.sync(() => {
89 cacheDirty = true;
90 }),
91 ),
92 );
93 }).pipe(persistLock.withPermit, Effect.withSpan("CursorUsageAccounts.persist"));
94
95 const pendingPersists = new Set<Fiber.Fiber<void>>();
96 const schedulePersist = Effect.forkDetach(persist).pipe(
97 Effect.map((fiber) => {
98 pendingPersists.add(fiber);
99 fiber.addObserver(() => pendingPersists.delete(fiber));
100 }),
101 );
102 const awaitPersisted = Effect.suspend(() => Fiber.awaitAll([...pendingPersists])).pipe(
103 Effect.asVoid,
104 );
105 yield* Effect.addFinalizer(() => awaitPersisted);
106
107 const refreshLock = yield* Semaphore.make(2);
108 const refreshAccount = Effect.fn("CursorUsageAccounts.refreshAccount")(function* (
109 credential: CursorCredentialSource,
110 credentialKey: string,
111 retentionStartMs: number,
112 ) {
113 const nowMs = yield* Clock.currentTimeMillis;
114 const fetchMissing = (cache: CursorAccountCache | undefined) => {
115 const range = cursorFetchRange(cache, retentionStartMs, nowMs);
116 return accountReader
117 .read(credential, range.sinceMs, range.untilMs)
118 .pipe(Effect.map((result) => ({ range, result })));
119 };
120 let base = caches.get(credentialKey);
121 let fetched = yield* fetchMissing(base);
122 if (
123 base !== undefined &&
124 fetched.result.accountKey !== null &&
125 fetched.result.accountKey !== base.accountKey
126 ) {
127 caches.delete(credentialKey);
128 cacheDirty = true;
129 base = undefined;
130 fetched = yield* fetchMissing(base);
131 }
132 const { range, result } = fetched;
133 if (result.missing || result.error !== null || result.accountKey === null) {
134 failures.set(credentialKey, {
135 atMs: nowMs,
136 error: result.missing || result.error !== null ? result.error : CURSOR_ACCOUNT_READ_ERROR,
137 });
138 yield* schedulePersist;
139 return;
140 }
141 const merged = mergeCursorFetch(
142 base,
143 result.accountKey,
144 range,
145 result.records,
146 nowMs,
147 retentionStartMs,
148 );
149 caches.set(credentialKey, merged.cache);
150 failures.delete(credentialKey);
151 if (merged.changed) cacheDirty = true;
152 yield* schedulePersist;
153 }, refreshLock.withPermit);
154
155 const startRefresh = (
156 credential: CursorCredentialSource,
157 credentialKey: string,
158 retentionStartMs: number,
159 ) =>
160 // Enroll and fork atomically so interruption cannot strand a registered refresh.
161 Effect.uninterruptible(
162 Effect.gen(function* () {
163 const current = refreshes.get(credentialKey);
164 if (current !== undefined) return current;
165 const done = Deferred.makeUnsafe<void>();
166 refreshes.set(credentialKey, done);
167 // Detached: a departing client must not cancel a fetch later reads reuse.
168 yield* refreshAccount(credential, credentialKey, retentionStartMs).pipe(
169 Effect.catchCause(() =>
170 Clock.currentTimeMillis.pipe(
171 Effect.map((atMs) =>
172 failures.set(credentialKey, { atMs, error: CURSOR_ACCOUNT_READ_ERROR }),
173 ),
174 ),
175 ),
176 Effect.ensuring(
177 Effect.suspend(() => {
178 refreshes.delete(credentialKey);
179 return Deferred.succeed(done, undefined);
180 }),
181 ),
182 Effect.forkDetach,
183 );
184 return done;
185 }),
186 );
187
188 const accountSource = Effect.fn("CursorUsageAccounts.accountSource")(function* (
189 credential: CursorCredentialSource,
190 windowStartMs: number,
191 retentionStartMs: number,
192 awaitRefresh: boolean,
193 ) {
194 yield* ensureLoaded;
195 const credentialKey = `api-key:${Hex.encode(yield* digest.digest(Digest.sha256, new TextEncoder().encode(credential.apiKey)))}`;
196 const nowMs = yield* Clock.currentTimeMillis;
197 const recentFailure = failures.get(credentialKey);
198 let refreshing = false;
199 if (
200 (recentFailure === undefined || nowMs - recentFailure.atMs >= CURSOR_ACCOUNT_TTL_MS) &&
201 !isCursorCacheFresh(caches.get(credentialKey), nowMs)
202 ) {
203 const refresh = yield* startRefresh(credential, credentialKey, retentionStartMs);
204 if (awaitRefresh) yield* Deferred.await(refresh);
205 else refreshing = true;
206 }
207
208 const cache = caches.get(credentialKey);
209 const failure = refreshing ? undefined : failures.get(credentialKey);
210 const failureMessage = failure === undefined ? undefined : failure.error;
211 if (failureMessage === null) return null;
212 if (cache === undefined) {
213 return {
214 dir: "cursor-account",
215 ...(refreshing
216 ? { files: [], refreshing: true }
217 : { files: null, message: failureMessage ?? CURSOR_ACCOUNT_READ_ERROR }),
218 } satisfies ProviderUsageScan;
219 }
220 // Account history spans machines; a stable fingerprint prevents duplicate environment counts.
221 const source = `cursor-account:${cache.accountKey}`;
222 return {
223 dir: source,
224 hostId: "cursor.com",
225 volumeId: cache.accountKey,
226 files: [
227 {
228 path: source,
229 records: cache.records.filter((record) => record.timestampMs >= windowStartMs),
230 },
231 ],
232 ...(failureMessage === undefined
233 ? { status: "ok" }
234 : { status: "partial", message: failureMessage }),
235 ...(refreshing ? { refreshing: true } : {}),
236 } satisfies ProviderUsageScan;
237 });
238
239 const scan: CursorUsageAccounts["Service"]["scan"] = Effect.fn("CursorUsageAccounts.scan")(
240 function* ({ instances, windowStartMs, retentionCutoffMs, awaitRefresh }) {
241 const apiKeys = yield* Effect.forEach(instances, ({ instanceId, environment }) =>
242 environment.CURSOR_API_KEY?.trim()
243 ? Effect.succeed(environment.CURSOR_API_KEY.trim())
244 : readStoredCursorApiKey(instanceId).pipe(
245 Effect.provideService(ProviderHost.ProviderHost, host),
246 Effect.orElseSucceed(() => undefined),
247 ),
248 );
249 const uniqueApiKeys = [...new Set(apiKeys.filter((apiKey) => apiKey !== undefined))];
250 if (uniqueApiKeys.length > 0) {
251 const sources: ReadonlyArray<ProviderUsageScan | null> = yield* Effect.forEach(
252 uniqueApiKeys,
253 (apiKey) =>
254 accountSource(
255 { kind: "apiKey", apiKey },
256 windowStartMs,
257 retentionCutoffMs,
258 awaitRefresh,
259 ),
260 { concurrency: 2 },
261 );
262 // Keys for one account share its source, and a repeated source would count sessions twice.
263 // A failed key can hold older records, so a current read wins, then a refresh the client
264 // must follow up on.
265 const rank = (source: ProviderUsageScan) =>
266 source.status === "ok" ? 2 : source.refreshing ? 1 : 0;
267 const byAccount = new Map<string, ProviderUsageScan>();
268 for (const source of sources) {
269 if (source === null) continue;
270 const kept = byAccount.get(source.dir);
271 if (kept === undefined || rank(source) > rank(kept)) {
272 byAccount.set(source.dir, source);
273 }
274 }
275 return [...byAccount.values()];
276 }
277 return [];
278 },
279 );
280
281 return CursorUsageAccounts.of({ scan, awaitPersisted });
282});
283
284export const layer = Layer.effect(CursorUsageAccounts, make);