pi-cliproxyapi 0.4.3 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/ui-usage.ts CHANGED
@@ -3,8 +3,37 @@
3
3
  // Lines are wrapped pre-render so they never reflow inside the overlay box —
4
4
  // long errors get truncated with an ellipsis on the same line. Progress bars
5
5
  // are colored by remaining capacity: green ≥40%, yellow 15–40%, red <15%.
6
+ //
7
+ // One row per account window answers "how fast and until when":
8
+ //
9
+ // [██████░░░░░░░░░░░░] 31% 5h Session ↻4:40 2.1x 20%/h out 14:20
10
+ // [██████████████░░░░] 81% 7d Weekly ↻2д4ч 0.4x 2%/h lasts
11
+ // [██████████████░░░░] 81% 7d Fable ↻2д4ч pace: collecting
12
+ //
13
+ // Pace comes from the bridge; without it the row says it is still collecting.
14
+ //
15
+ // Account headers carry the router's view: `prio N`, `w N` when weights
16
+ // matter, and `▶` (with the share when the tier is shared) on the accounts a
17
+ // new request goes to. Accounts are listed by priority, highest first:
18
+ //
19
+ // ● ▶ artem@example.com prio 100 75% ✓12 ✗0 ◆ this session
20
+ // ● koza@example.com prio 50 ✓3 ✗0
21
+
22
+ import { visibleWidth } from "@earendil-works/pi-tui";
6
23
 
7
- import type { UsageAccount, UsageDocument, UsageGroup } from "./fetch-usage.ts";
24
+ import type {
25
+ RoutingStrategy,
26
+ UsageAccount,
27
+ UsageDocument,
28
+ UsageGroup,
29
+ } from "./fetch-usage.ts";
30
+ import { boundAccount } from "./status-quota.ts";
31
+ import {
32
+ formatClock,
33
+ formatCountdown,
34
+ formatMultiplier,
35
+ paceLevel,
36
+ } from "./quota-format.ts";
8
37
 
9
38
  // 256-color palette codes (truecolor and 256color terminals both render).
10
39
  const C = {
@@ -22,21 +51,41 @@ const C = {
22
51
  redBg: "\x1b[48;5;52m",
23
52
  };
24
53
 
25
- const BAR_WIDTH = 18;
26
- const MAX_LABEL_WIDTH = 28;
54
+ /** Column widths; the narrow layout keeps a full row inside 80 columns. */
55
+ interface Layout {
56
+ bar: number;
57
+ label: number;
58
+ /** Account label in headers. */
59
+ account: number;
60
+ }
61
+ const WIDE: Layout = { bar: 18, label: 28, account: 36 };
62
+ const NARROW: Layout = { bar: 10, label: 16, account: 24 };
63
+ /** Below this many columns the narrow layout is used. */
64
+ const WIDE_MIN_WIDTH = 100;
27
65
 
28
66
  export interface RenderUsageOptions {
29
67
  /** Include accounts with `disabled` flag in the output. */
30
68
  showDisabled?: boolean;
31
69
  /** Print the raw backend error string on a second line (instead of just the short [err 401] marker). */
32
70
  verbose?: boolean;
71
+ /** Columns available for each line; picks the wide or narrow layout. */
72
+ width?: number;
73
+ /** Clock for countdowns and projections (tests pass a fixed one). */
74
+ now?: number;
33
75
  }
34
76
 
77
+ const SESSION_MARKER = `${C.accent}◆ this session${C.reset}`;
78
+
35
79
  export function renderUsage(
36
80
  doc: UsageDocument,
37
81
  opts: RenderUsageOptions = {},
38
82
  ): string[] {
39
83
  const lines: string[] = [];
84
+ const layout =
85
+ opts.width !== undefined && opts.width < WIDE_MIN_WIDTH ? NARROW : WIDE;
86
+ const now = opts.now ?? Date.now();
87
+ const sessionAuth =
88
+ doc.session?.status === "bound" ? doc.session.authIndex : undefined;
40
89
  const byProvider = new Map<string, UsageAccount[]>();
41
90
  let hiddenDisabled = 0;
42
91
  for (const a of doc.accounts) {
@@ -61,11 +110,27 @@ export function renderUsage(
61
110
  );
62
111
  }
63
112
 
64
- for (const [provider, accounts] of Array.from(byProvider.entries()).sort()) {
113
+ for (const [provider, unordered] of Array.from(byProvider.entries()).sort()) {
65
114
  lines.push("");
66
115
  lines.push(`${C.bold}${C.accent}▌ ${provider}${C.reset}`);
116
+ // Highest priority first; the sort is stable, so ties keep bridge order.
117
+ const accounts = [...unordered].sort(
118
+ (x, y) => (y.priority ?? 0) - (x.priority ?? 0),
119
+ );
120
+ const serving =
121
+ boundAccount(doc, accounts)?.authIndex ?? sessionAuth;
122
+ const tierSize = accounts.filter((a) => a.routing?.active).length;
123
+ const anyActive = tierSize > 0;
67
124
  for (const a of accounts) {
68
- lines.push(formatAccountHeader(a));
125
+ lines.push(
126
+ formatAccountHeader(a, {
127
+ servesSession: serving !== undefined && a.authIndex === serving,
128
+ strategy: doc.routing?.strategy,
129
+ anyActive,
130
+ sharedTier: tierSize > 1,
131
+ labelWidth: layout.account,
132
+ }),
133
+ );
69
134
  if (!a.supported) {
70
135
  lines.push(` ${C.dim2}(provider not quota-aware)${C.reset}`);
71
136
  continue;
@@ -83,7 +148,7 @@ export function renderUsage(
83
148
  lines.push(` ${C.dim2}(no active quota windows)${C.reset}`);
84
149
  continue;
85
150
  }
86
- for (const g of groups) lines.push(formatGroup(g));
151
+ for (const g of groups) lines.push(formatGroup(g, layout, now, opts.width));
87
152
  }
88
153
  }
89
154
 
@@ -95,9 +160,19 @@ export function renderUsage(
95
160
  `${ICON_OK_DOT} ok ` +
96
161
  `${ICON_WARN} error/unavailable ` +
97
162
  `${ICON_DISABLED} disabled ` +
98
- `${C.green}✓N${C.reset}/${C.red}✗N${C.reset} request counters ` +
99
- `${C.dim}v = verbose, d = show disabled${C.reset}`,
163
+ `${C.green}✓N${C.reset}/${C.red}✗N${C.reset} requests`,
164
+ );
165
+ lines.push(
166
+ `${C.dim} ↻ resets in · Nx pace vs sustainable (≥1.0 runs out first) · %/h burn${C.reset}`,
167
+ );
168
+ lines.push(
169
+ ` ${C.accent}◆${C.reset} ${C.dim}serves this session · v verbose · d disabled${C.reset}`,
100
170
  );
171
+ if (doc.accounts.some((a) => a.routing || a.priority !== undefined)) {
172
+ lines.push(
173
+ ` ${C.accent}▶${C.reset} ${C.dim}routes new requests (share) · prio/w routing priority/weight${C.reset}`,
174
+ );
175
+ }
101
176
  return lines;
102
177
  }
103
178
 
@@ -115,11 +190,39 @@ function wrapText(s: string, max: number): string[] {
115
190
  return out;
116
191
  }
117
192
 
118
- function formatAccountHeader(a: UsageAccount): string {
193
+ interface HeaderContext {
194
+ servesSession: boolean;
195
+ strategy?: RoutingStrategy;
196
+ /** Some account of the provider is in the active tier: reserve the `▶` column. */
197
+ anyActive: boolean;
198
+ /** The active tier has more than one account: show each one's share. */
199
+ sharedTier: boolean;
200
+ labelWidth: number;
201
+ }
202
+
203
+ function formatAccountHeader(a: UsageAccount, h: HeaderContext): string {
119
204
  const status = accountStatus(a);
120
205
  const counters = `${C.green}✓${a.success}${C.reset} ${C.red}✗${a.failed}${C.reset}`;
121
- const label = truncate(a.label, 36);
122
- return ` ${status} ${C.bold}${label}${C.reset} ${counters}`;
206
+ const label = truncate(a.label, h.labelWidth);
207
+ const marker = h.servesSession ? ` ${SESSION_MARKER}` : "";
208
+ const active = a.routing?.active === true;
209
+ const tier = h.anyActive ? (active ? `${C.accent}▶${C.reset} ` : " ") : "";
210
+ const routing: string[] = [];
211
+ if (a.priority !== undefined) routing.push(`prio ${fmtNumber(a.priority)}`);
212
+ const weight = a.weight ?? 1;
213
+ if (a.weight !== undefined && (h.strategy === "weighted-round-robin" || weight !== 1)) {
214
+ routing.push(`w ${fmtNumber(weight)}`);
215
+ }
216
+ if (active && h.sharedTier) {
217
+ routing.push(`${C.accent}${Math.round((a.routing?.share ?? 0) * 100)}%${C.reset}`);
218
+ }
219
+ const route = routing.length > 0 ? ` ${C.dim}${routing.join(" ")}${C.reset}` : "";
220
+ return ` ${status} ${tier}${C.bold}${label}${C.reset}${route} ${counters}${marker}`;
221
+ }
222
+
223
+ /** Integers as is, fractions with up to two decimals. */
224
+ function fmtNumber(n: number): string {
225
+ return Number.isInteger(n) ? String(n) : String(Math.round(n * 100) / 100);
123
226
  }
124
227
 
125
228
  // Status icons — distinct from the ✓/✗ request counters so the user
@@ -136,24 +239,78 @@ function accountStatus(a: UsageAccount): string {
136
239
  return ICON_OK_DOT;
137
240
  }
138
241
 
139
- function formatGroup(g: UsageGroup): string {
242
+ /** Narrowest a window label is squeezed to so the forecast stays visible. */
243
+ const MIN_LABEL_CELLS = 4;
244
+
245
+ /**
246
+ * One window row. Widths are terminal cells, not string length, so wide
247
+ * (e.g. CJK) labels line up; when the row would not fit `width`, the label
248
+ * is shortened first so the pace forecast is never the part that is cut.
249
+ */
250
+ function formatGroup(
251
+ g: UsageGroup,
252
+ layout: Layout,
253
+ now: number,
254
+ width?: number,
255
+ ): string {
140
256
  const f = clamp(g.remainingFraction);
141
257
  const pct = Math.round(f * 100);
142
- const bar = renderBar(f);
143
- const reset = g.resetTime
144
- ? ` ${C.dim}reset ${humanizeReset(g.resetTime)}${C.reset}`
145
- : "";
146
- const label = truncate(g.label, MAX_LABEL_WIDTH).padEnd(MAX_LABEL_WIDTH, " ");
147
- return ` ${bar} ${formatPct(pct, f)} ${label}${reset}`;
258
+ const bar = renderBar(f, layout.bar);
259
+ const countdown = formatCountdown(g.resetTime, now);
260
+ const reset = `${C.dim}${(countdown ? `↻${countdown}` : "").padEnd(7)}${C.reset}`;
261
+ const pace = formatPace(g, now);
262
+ const row = (labelCells: number) =>
263
+ ` ${bar} ${formatPct(pct, f)} ${fitCells(g.label, labelCells)} ${reset} ${pace}`;
264
+ const full = row(layout.label);
265
+ const excess = width === undefined ? 0 : visibleWidth(full) - width;
266
+ if (excess <= 0) return full;
267
+ return row(Math.max(MIN_LABEL_CELLS, layout.label - excess));
268
+ }
269
+
270
+ /** `s` cut (with `…`) or padded to exactly `cells` terminal cells. */
271
+ function fitCells(s: string, cells: number): string {
272
+ if (visibleWidth(s) <= cells) return s + " ".repeat(cells - visibleWidth(s));
273
+ let out = "";
274
+ let used = 0;
275
+ for (const ch of s) {
276
+ const w = visibleWidth(ch);
277
+ if (used + w > cells - 1) break;
278
+ out += ch;
279
+ used += w;
280
+ }
281
+ return `${out}…${" ".repeat(cells - 1 - used)}`;
282
+ }
283
+
284
+ /**
285
+ * Pace columns: multiplier, burn per hour, then when the window runs out —
286
+ * or `lasts` when the pace is sustainable. Without bridge pace data the
287
+ * window is still being sampled.
288
+ */
289
+ function formatPace(g: UsageGroup, now: number): string {
290
+ const p = g.pace;
291
+ if (!p || !Number.isFinite(p.multiplier) || !Number.isFinite(p.burnPerHour)) {
292
+ return ` ${C.dim2}pace: collecting${C.reset}`;
293
+ }
294
+ const level = paceLevel(p.multiplier);
295
+ const color = { ok: C.green, warning: C.yellow, error: C.red }[level];
296
+ const mult = `${color}${formatMultiplier(p.multiplier).padStart(5)}${C.reset}`;
297
+ const burn = `${C.dim}${`${Math.round(Math.max(0, p.burnPerHour) * 100)}%/h`.padStart(6)}${C.reset}`;
298
+ let outcome = "";
299
+ if (level === "ok") outcome = `${C.green}lasts${C.reset}`;
300
+ else {
301
+ const clock = p.exhaustAt ? formatClock(p.exhaustAt, now) : null;
302
+ if (clock) outcome = `${color}out ${clock}${C.reset}`;
303
+ }
304
+ return `${mult} ${burn} ${outcome}`.trimEnd();
148
305
  }
149
306
 
150
- function renderBar(fraction: number): string {
307
+ function renderBar(fraction: number, width: number): string {
151
308
  const f = clamp(fraction);
152
- const filled = Math.round(f * BAR_WIDTH);
309
+ const filled = Math.round(f * width);
153
310
  const color = colorForFraction(f);
154
311
  const dimColor = C.dim2;
155
312
  const full = "█".repeat(filled);
156
- const empty = "░".repeat(BAR_WIDTH - filled);
313
+ const empty = "░".repeat(width - filled);
157
314
  return `${dimColor}[${color}${full}${dimColor}${empty}]${C.reset}`;
158
315
  }
159
316
 
@@ -168,19 +325,6 @@ function colorForFraction(f: number): string {
168
325
  return C.red;
169
326
  }
170
327
 
171
- function humanizeReset(iso: string): string {
172
- const t = Date.parse(iso);
173
- if (!Number.isFinite(t)) return iso;
174
- const ms = t - Date.now();
175
- if (ms <= 0) return "now";
176
- const min = Math.round(ms / 60_000);
177
- if (min < 60) return `${min}m`;
178
- const hr = Math.round(min / 60);
179
- if (hr < 48) return `${hr}h`;
180
- const d = Math.round(hr / 24);
181
- return `${d}d`;
182
- }
183
-
184
328
  function clamp(f: number): number {
185
329
  return Math.max(0, Math.min(1, f));
186
330
  }
@@ -7,6 +7,10 @@
7
7
  // 3. if stale or missing → tryAcquireLock()
8
8
  // a. lock acquired → fetchUsage(force) → writeUsageCache → releaseLock
9
9
  // b. lock NOT acquired (another instance fetching) → use stale doc or null
10
+ // c. lock refused by the filesystem → fetch without the shared cache
11
+ //
12
+ // Nothing here may stall Pi: lock waits are asynchronous and bounded, and a
13
+ // filesystem error gives up on the cache instead of retrying.
10
14
  //
11
15
  // Lock: O_EXCL create (atomic on POSIX). Contains pid + timestamp. Stale locks
12
16
  // (older than LOCK_STALE_MS) are removed to recover from crashed processes.
@@ -15,18 +19,38 @@ import {
15
19
  existsSync,
16
20
  mkdirSync,
17
21
  readFileSync,
22
+ renameSync,
18
23
  statSync,
19
24
  unlinkSync,
20
25
  writeFileSync,
21
26
  } from "node:fs";
22
27
  import { join } from "node:path";
28
+ import { randomUUID } from "node:crypto";
23
29
 
24
30
  import { CONFIG_DIR } from "./config.ts";
25
- import type { UsageDocument } from "./fetch-usage.ts";
31
+ import type {
32
+ UsageDocument,
33
+ UsageSession,
34
+ UsageSessionQuery,
35
+ } from "./fetch-usage.ts";
36
+ import {
37
+ sanitizeUsageDocument,
38
+ sanitizeUsageSession,
39
+ } from "./fetch-usage.ts";
26
40
  import { log } from "./log.ts";
27
41
 
28
42
  export const USAGE_CACHE_PATH = join(CONFIG_DIR, "usage-cache.json");
29
43
  export const USAGE_LOCK_PATH = join(CONFIG_DIR, "usage-cache.lock");
44
+ /**
45
+ * Short lock around a cache write's read-merge-publish, separate from the
46
+ * fetch lease above: a fetcher whose lease went stale must still never
47
+ * publish over a document another instance wrote after it read the file.
48
+ */
49
+ export const USAGE_PUBLISH_LOCK_PATH = join(CONFIG_DIR, "usage-cache.publish.lock");
50
+ /** A publish lock older than this belongs to a writer that died mid-write. */
51
+ const PUBLISH_LOCK_STALE_MS = 2_000;
52
+ /** How long a writer waits for the publish lock before skipping its write. */
53
+ const PUBLISH_LOCK_WAIT_MS = 250;
30
54
 
31
55
  /**
32
56
  * Minimum interval between network fetches, shared across all Pi instances.
@@ -40,32 +64,128 @@ export const USAGE_CACHE_TTL_MS = 15_000;
40
64
  /** A lock file older than this is considered stale (process crashed). */
41
65
  const LOCK_STALE_MS = 30_000;
42
66
 
67
+ /**
68
+ * How long a session binding read from the bridge is trusted. The document is
69
+ * shared by every Pi instance, but its `session` field only describes the
70
+ * session that fetched it, so bindings are kept per session in a side map and
71
+ * refreshed by the owning instance on its own fetches.
72
+ */
73
+ export const SESSION_BINDING_TTL_MS = 120_000;
74
+ /**
75
+ * A binding older than this is expired: it is no longer attached to the
76
+ * document, so a busy lock or a bridge outage shows the aggregate ("unknown")
77
+ * instead of an account the session may have left. Between the TTL and this
78
+ * point the binding is still shown while the owning instance refreshes it.
79
+ */
80
+ export const SESSION_BINDING_EXPIRY_MS = 5 * 60_000;
81
+ /** Bindings older than this are dropped from the file. */
82
+ const SESSION_BINDING_PRUNE_MS = 30 * 60_000;
83
+
84
+ interface SessionEntry {
85
+ at: number; // epoch ms
86
+ /** null: the bridge answered without a binding (e.g. it predates them). */
87
+ session: UsageSession | null;
88
+ }
89
+
43
90
  interface CacheEnvelope {
91
+ /** Proxy origin + key digest this file was fetched for (cache-namespace.ts). */
92
+ namespace: string;
44
93
  fetchedAt: number; // epoch ms
94
+ /** Shared document, always stored without its `session` field. */
45
95
  doc: UsageDocument;
96
+ /** Per-session bindings, keyed by {@link sessionCacheKey}. */
97
+ sessions?: Record<string, SessionEntry>;
46
98
  }
47
99
 
48
100
  export interface CachedUsage {
101
+ /** The document, carrying `session` only for the asking session. */
49
102
  doc: UsageDocument;
50
103
  ageMs: number;
104
+ /**
105
+ * True when the asking session has a binding younger than the TTL. The
106
+ * document carries the binding only until it expires.
107
+ */
108
+ sessionFresh: boolean;
109
+ }
110
+
111
+ /** Key a binding by session and model: the bridge resolves it for both. */
112
+ export function sessionCacheKey(session: UsageSessionQuery): string {
113
+ return `${session.id}\u0000${session.model ?? ""}`;
51
114
  }
52
115
 
53
- /** Read the shared cache file. Returns null if missing/corrupt. */
54
- export function readUsageCache(): CachedUsage | null {
116
+ /** The last envelope read successfully, served when the file turns invalid. */
117
+ let lastGoodEnvelope: CacheEnvelope | null = null;
118
+
119
+ /**
120
+ * Read and sanitize the file. Another process writes it, so nothing in it is
121
+ * trusted: an invalid envelope yields the last good one, invalid entries are
122
+ * dropped (see sanitizeUsageDocument).
123
+ */
124
+ function readEnvelope(namespace: string): CacheEnvelope | null {
125
+ const lastGood = lastGoodEnvelope?.namespace === namespace ? lastGoodEnvelope : null;
55
126
  if (!existsSync(USAGE_CACHE_PATH)) return null;
127
+ let raw: unknown;
56
128
  try {
57
- const env = JSON.parse(
58
- readFileSync(USAGE_CACHE_PATH, "utf8"),
59
- ) as CacheEnvelope;
60
- if (
61
- !env ||
62
- typeof env.fetchedAt !== "number" ||
63
- !env.doc ||
64
- !Array.isArray(env.doc.accounts)
65
- ) {
66
- return null;
129
+ raw = JSON.parse(readFileSync(USAGE_CACHE_PATH, "utf8"));
130
+ } catch (err) {
131
+ log.debug("usage cache unreadable:", (err as Error).message);
132
+ return lastGood;
133
+ }
134
+ const env = raw as {
135
+ namespace?: unknown;
136
+ fetchedAt?: unknown;
137
+ doc?: unknown;
138
+ sessions?: unknown;
139
+ };
140
+ // Another proxy/key (or a legacy file without a namespace): a miss, never
141
+ // shown as this client's data.
142
+ if (env?.namespace !== namespace) return null;
143
+ const doc = sanitizeUsageDocument(env?.doc);
144
+ if (
145
+ !doc ||
146
+ typeof env.fetchedAt !== "number" ||
147
+ !Number.isFinite(env.fetchedAt)
148
+ ) {
149
+ return lastGood;
150
+ }
151
+ const sessions: Record<string, SessionEntry> = {};
152
+ if (env.sessions && typeof env.sessions === "object") {
153
+ for (const [key, e] of Object.entries(env.sessions as Record<string, unknown>)) {
154
+ const entry = e as { at?: unknown; session?: unknown } | null;
155
+ if (typeof entry?.at !== "number" || !Number.isFinite(entry.at)) continue;
156
+ sessions[key] = {
157
+ at: entry.at,
158
+ session: sanitizeUsageSession(entry.session) ?? null,
159
+ };
67
160
  }
68
- return { doc: env.doc, ageMs: Date.now() - env.fetchedAt };
161
+ }
162
+ lastGoodEnvelope = { namespace, fetchedAt: env.fetchedAt, doc, sessions };
163
+ return lastGoodEnvelope;
164
+ }
165
+
166
+ /**
167
+ * Read the shared cache file. Returns null if missing/corrupt. With a session,
168
+ * the returned document carries that session's binding when one is known.
169
+ */
170
+ export function readUsageCache(
171
+ namespace: string,
172
+ session?: UsageSessionQuery,
173
+ ): CachedUsage | null {
174
+ try {
175
+ const env = readEnvelope(namespace);
176
+ if (!env) return null;
177
+ const { session: _ignored, ...doc } = env.doc;
178
+ const entry = session
179
+ ? env.sessions?.[sessionCacheKey(session)]
180
+ : undefined;
181
+ const now = Date.now();
182
+ const live = entry !== undefined && now - entry.at < SESSION_BINDING_EXPIRY_MS;
183
+ return {
184
+ doc: live && entry.session ? { ...doc, session: entry.session } : doc,
185
+ ageMs: now - env.fetchedAt,
186
+ sessionFresh:
187
+ entry !== undefined && now - entry.at < SESSION_BINDING_TTL_MS,
188
+ };
69
189
  } catch (err) {
70
190
  log.warn("failed to read usage cache:", (err as Error).message);
71
191
  return null;
@@ -77,13 +197,154 @@ export function isUsageFresh(ageMs: number): boolean {
77
197
  return ageMs < USAGE_CACHE_TTL_MS;
78
198
  }
79
199
 
80
- /** Write fresh usage data + timestamp to the shared cache file. */
81
- export function writeUsageCache(doc: UsageDocument): void {
200
+ /**
201
+ * Write fresh usage data + timestamp to the shared cache file. The document's
202
+ * `session` field is moved into the per-session map under the session that
203
+ * fetched it; other sessions' bindings are kept until they age out.
204
+ *
205
+ * `fetchStartedAt` is when the caller started the request. A fetcher whose
206
+ * lock went stale can finish after another instance already published a
207
+ * newer document; that newer document is kept and only this session's
208
+ * binding is merged in (unless a newer one is already there).
209
+ *
210
+ * The file is replaced by renaming a sibling temp file, so a reader in
211
+ * another process sees the old or the new content, never a partial write.
212
+ *
213
+ * Never blocks the event loop and never rejects: when the publish lock is
214
+ * free the write completes before this returns; a held lock is waited for
215
+ * asynchronously for at most PUBLISH_LOCK_WAIT_MS; any filesystem error
216
+ * skips the write (the caller continues without the cache).
217
+ */
218
+ export function writeUsageCache(
219
+ namespace: string,
220
+ doc: UsageDocument,
221
+ session?: UsageSessionQuery,
222
+ fetchStartedAt?: number,
223
+ ): Promise<void> {
82
224
  try {
83
225
  mkdirSync(CONFIG_DIR, { recursive: true });
84
- const env: CacheEnvelope = { fetchedAt: Date.now(), doc };
85
- writeFileSync(USAGE_CACHE_PATH, JSON.stringify(env), "utf8");
86
226
  } catch (err) {
227
+ log.debug("usage cache write skipped:", (err as Error).message);
228
+ return Promise.resolve();
229
+ }
230
+ const publish = (token: string) => {
231
+ try {
232
+ publishUsageCache(namespace, doc, session, fetchStartedAt);
233
+ } finally {
234
+ releasePublishLock(token);
235
+ }
236
+ };
237
+ const token = `${process.pid}@${randomUUID()}`;
238
+ const first = attemptPublishLock(token);
239
+ if (first === "taken") {
240
+ publish(token);
241
+ return Promise.resolve();
242
+ }
243
+ if (first === "failed") return Promise.resolve();
244
+ return (async () => {
245
+ const deadline = Date.now() + PUBLISH_LOCK_WAIT_MS;
246
+ while (Date.now() < deadline) {
247
+ await sleep(5);
248
+ const r = attemptPublishLock(token);
249
+ if (r === "taken") return publish(token);
250
+ if (r === "failed") return;
251
+ }
252
+ log.debug("usage cache write skipped: another instance is publishing");
253
+ })().catch((err) => {
254
+ log.debug("usage cache write failed:", (err as Error).message);
255
+ });
256
+ }
257
+
258
+ /** Resolve after `ms` without keeping the process alive. */
259
+ function sleep(ms: number): Promise<void> {
260
+ return new Promise((resolve) => {
261
+ const t = setTimeout(resolve, ms);
262
+ (t as { unref?: () => void }).unref?.();
263
+ });
264
+ }
265
+
266
+ const errCode = (err: unknown) => (err as NodeJS.ErrnoException)?.code;
267
+
268
+ /**
269
+ * One attempt at the publish lock: "taken", "busy" (another live writer
270
+ * holds it, or a stale one was just removed — try again later), or "failed"
271
+ * (the filesystem refuses: give up on the cache for this write).
272
+ */
273
+ function attemptPublishLock(token: string): "taken" | "busy" | "failed" {
274
+ try {
275
+ writeFileSync(USAGE_PUBLISH_LOCK_PATH, token, { flag: "wx" });
276
+ return "taken";
277
+ } catch (err) {
278
+ // Only an existing lock is contention; anything else will not heal by waiting.
279
+ if (errCode(err) !== "EEXIST") {
280
+ log.debug("usage cache publish lock unavailable:", (err as Error).message);
281
+ return "failed";
282
+ }
283
+ }
284
+ try {
285
+ // Held: take it over only when its writer is long gone.
286
+ if (Date.now() - statSync(USAGE_PUBLISH_LOCK_PATH).mtimeMs > PUBLISH_LOCK_STALE_MS) {
287
+ unlinkSync(USAGE_PUBLISH_LOCK_PATH);
288
+ }
289
+ } catch (err) {
290
+ // ENOENT: released meanwhile, retried on the next attempt.
291
+ if (errCode(err) !== "ENOENT") return "failed";
292
+ }
293
+ return "busy";
294
+ }
295
+
296
+ /** Remove the publish lock only while it is still ours. */
297
+ function releasePublishLock(token: string): void {
298
+ try {
299
+ if (readFileSync(USAGE_PUBLISH_LOCK_PATH, "utf8") === token) {
300
+ unlinkSync(USAGE_PUBLISH_LOCK_PATH);
301
+ }
302
+ } catch {
303
+ // Already gone.
304
+ }
305
+ }
306
+
307
+ function publishUsageCache(
308
+ namespace: string,
309
+ doc: UsageDocument,
310
+ session?: UsageSessionQuery,
311
+ fetchStartedAt?: number,
312
+ ): void {
313
+ const tmp = `${USAGE_CACHE_PATH}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
314
+ try {
315
+ const now = Date.now();
316
+ const fetchedAt = fetchStartedAt ?? now;
317
+ const sessions: Record<string, SessionEntry> = {};
318
+ let previous: CacheEnvelope | null = null;
319
+ try {
320
+ previous = readEnvelope(namespace);
321
+ } catch {
322
+ // A corrupt file is simply replaced.
323
+ }
324
+ for (const [key, entry] of Object.entries(previous?.sessions ?? {})) {
325
+ if (now - entry.at < SESSION_BINDING_PRUNE_MS) sessions[key] = entry;
326
+ }
327
+ const { session: binding, ...shared } = doc;
328
+ if (session) {
329
+ // Recorded even when absent, so an old bridge does not make every
330
+ // refresh look like a missing binding worth refetching for.
331
+ const key = sessionCacheKey(session);
332
+ if (!sessions[key] || sessions[key].at <= fetchedAt) {
333
+ sessions[key] = { at: fetchedAt, session: binding ?? null };
334
+ }
335
+ }
336
+ const superseded = previous !== null && previous.fetchedAt > fetchedAt;
337
+ const env: CacheEnvelope = superseded
338
+ ? { namespace, fetchedAt: previous!.fetchedAt, doc: previous!.doc, sessions }
339
+ : { namespace, fetchedAt, doc: shared, sessions };
340
+ writeFileSync(tmp, JSON.stringify(env), "utf8");
341
+ renameSync(tmp, USAGE_CACHE_PATH);
342
+ } catch (err) {
343
+ try {
344
+ unlinkSync(tmp);
345
+ } catch {
346
+ // Nothing was written.
347
+ }
87
348
  log.warn("failed to write usage cache:", (err as Error).message);
88
349
  }
89
350
  }
@@ -96,6 +357,21 @@ export function writeUsageCache(doc: UsageDocument): void {
96
357
  * lock we still own.
97
358
  */
98
359
  export function tryAcquireUsageLock(): string | null {
360
+ const lock = acquireUsageLock();
361
+ return lock.state === "taken" ? lock.token : null;
362
+ }
363
+
364
+ export type UsageLock =
365
+ | { state: "taken"; token: string }
366
+ | { state: "busy" }
367
+ | { state: "unavailable" };
368
+
369
+ /**
370
+ * Like {@link tryAcquireUsageLock}, but tells contention ("busy": another
371
+ * instance is fetching) from a filesystem that refuses the lock
372
+ * ("unavailable": the caller fetches without the shared cache).
373
+ */
374
+ export function acquireUsageLock(): UsageLock {
99
375
  const token = `${process.pid}@${Date.now()}`;
100
376
  // Clean up stale lock from a crashed process
101
377
  if (existsSync(USAGE_LOCK_PATH)) {
@@ -105,20 +381,23 @@ export function tryAcquireUsageLock(): string | null {
105
381
  log.debug("removing stale usage lock");
106
382
  unlinkSync(USAGE_LOCK_PATH);
107
383
  } else {
108
- return null; // someone else holds a live lock
384
+ return { state: "busy" }; // someone else holds a live lock
109
385
  }
110
386
  } catch {
111
387
  // stat/unlink race — treat as locked to be safe
112
- return null;
388
+ return { state: "busy" };
113
389
  }
114
390
  }
115
391
  // O_EXCL ("wx") — atomically creates only if the file does not exist
116
392
  try {
117
393
  writeFileSync(USAGE_LOCK_PATH, token, { flag: "wx" });
118
- return token;
119
- } catch {
120
- // race: another instance created the lock between our check and create
121
- return null;
394
+ return { state: "taken", token };
395
+ } catch (err) {
396
+ // EEXIST: another instance created the lock between our check and
397
+ // create. Anything else: the directory refuses files altogether.
398
+ if (errCode(err) === "EEXIST") return { state: "busy" };
399
+ log.debug("usage lock unavailable:", (err as Error).message);
400
+ return { state: "unavailable" };
122
401
  }
123
402
  }
124
403