-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
228 lines (188 loc) · 8.31 KB
/
Copy pathserver.ts
File metadata and controls
228 lines (188 loc) · 8.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import http from 'node:http';
import { spawn } from 'node:child_process';
// ── Types ──────────────────────────────────────────────────────────────
interface CacheEntry {
data: unknown;
ts: number;
}
// ── Constants ──────────────────────────────────────────────────────────
const VALID_RANGES = new Set(['daily', 'monthly', 'session', 'blocks']);
const DATE_RE = /^\d{8}$/;
const CACHE_TTL = 60_000;
const SPAWN_TIMEOUT = 30_000;
// Pin to a tracked minor; ccusage made breaking schema renames between minors
// (e.g. 20.x renamed daily.date -> daily.period and dropped --project / --instances).
// Bumping this is a deliberate code change paired with type updates.
const CCUSAGE_SPEC = 'ccusage@~20.0';
// Top-level key ccusage returns per subcommand. If the parsed JSON is missing
// the expected key, the shape probably changed in a new ccusage release and the
// plugin needs updating — surface that explicitly instead of rendering blank UI.
const EXPECTED_KEY: Record<string, string> = {
daily: 'daily',
monthly: 'monthly',
session: 'session',
blocks: 'blocks',
};
// ── Cache ──────────────────────────────────────────────────────────────
const cache = new Map<string, CacheEntry>();
function getCached(key: string): unknown | null {
const entry = cache.get(key);
if (!entry) return null;
if (Date.now() - entry.ts > CACHE_TTL) {
cache.delete(key);
return null;
}
return entry.data;
}
function setCache(key: string, data: unknown): void {
cache.set(key, { data, ts: Date.now() });
}
// ── ccusage runner ─────────────────────────────────────────────────────
function runCcusage(args: string[]): Promise<{ stdout: string; stderr: string; code: number }> {
return new Promise((resolve) => {
const child = spawn('npx', [CCUSAGE_SPEC, ...args], {
stdio: ['ignore', 'pipe', 'pipe'],
timeout: SPAWN_TIMEOUT,
});
let stdout = '';
let stderr = '';
child.stdout.on('data', (d: Buffer) => { stdout += d.toString(); });
child.stderr.on('data', (d: Buffer) => { stderr += d.toString(); });
child.on('close', (code) => {
resolve({ stdout, stderr, code: code ?? 1 });
});
child.on('error', (err) => {
resolve({ stdout: '', stderr: err.message, code: 1 });
});
});
}
function validateShape(data: unknown, range: string): { ok: true } | { ok: false; keys: string[] } {
const expected = EXPECTED_KEY[range];
if (!expected) return { ok: true };
if (!data || typeof data !== 'object') return { ok: false, keys: [] };
const keys = Object.keys(data as Record<string, unknown>);
if (!keys.includes(expected)) return { ok: false, keys };
return { ok: true };
}
async function fetchCcusage(args: string[], range: string, cacheKey: string, noCache: boolean): Promise<{ status: number; body: unknown }> {
if (!noCache) {
const cached = getCached(cacheKey);
if (cached) return { status: 200, body: cached };
}
const result = await runCcusage(args);
if (result.code !== 0) {
// If stderr suggests network issue, retry with --offline
if (result.stderr.includes('fetch') || result.stderr.includes('network') || result.stderr.includes('ENOTFOUND')) {
const retryArgs = [...args, '--offline'];
const retry = await runCcusage(retryArgs);
if (retry.code === 0) {
try {
const data = { ...JSON.parse(retry.stdout), _offline: true };
const shape = validateShape(data, range);
if (!shape.ok) {
return { status: 502, body: { error: 'Unexpected ccusage output shape', range, expected: EXPECTED_KEY[range], keys: shape.keys } };
}
setCache(cacheKey, data);
return { status: 200, body: data };
} catch {
return { status: 500, body: { error: 'Failed to parse ccusage output', stderr: retry.stderr } };
}
}
}
// Check for npx not found
if (result.stderr.includes('not found') || result.stderr.includes('ENOENT')) {
return { status: 500, body: { error: 'npx not found. Please install Node.js.', stderr: result.stderr } };
}
return { status: 500, body: { error: 'ccusage failed', stderr: result.stderr } };
}
try {
const data = JSON.parse(result.stdout);
const shape = validateShape(data, range);
if (!shape.ok) {
return { status: 502, body: { error: 'Unexpected ccusage output shape', range, expected: EXPECTED_KEY[range], keys: shape.keys } };
}
setCache(cacheKey, data);
return { status: 200, body: data };
} catch {
return { status: 500, body: { error: 'Failed to parse ccusage JSON output', stderr: result.stderr, stdout: result.stdout.slice(0, 500) } };
}
}
// ── HTTP server ────────────────────────────────────────────────────────
const server = http.createServer(async (req, res) => {
res.setHeader('Content-Type', 'application/json');
const url = new URL(req.url ?? '/', `http://${req.headers.host}`);
const noCache = url.searchParams.get('nocache') === '1';
if (req.method === 'GET' && url.pathname === '/summary') {
const range = url.searchParams.get('range') ?? 'daily';
if (!VALID_RANGES.has(range)) {
res.writeHead(400);
res.end(JSON.stringify({ error: `Invalid range: ${range}. Must be one of: ${[...VALID_RANGES].join(', ')}` }));
return;
}
const args = [range, '--json'];
const cacheKey = `summary:${range}`;
const { status, body } = await fetchCcusage(args, range, cacheKey, noCache);
res.writeHead(status);
res.end(JSON.stringify(body));
return;
}
if (req.method === 'GET' && url.pathname === '/breakdown') {
const range = url.searchParams.get('range') ?? 'daily';
if (!VALID_RANGES.has(range)) {
res.writeHead(400);
res.end(JSON.stringify({ error: `Invalid range: ${range}` }));
return;
}
const args = [range, '--json', '--breakdown'];
const cacheKey = `breakdown:${range}`;
const { status, body } = await fetchCcusage(args, range, cacheKey, noCache);
res.writeHead(status);
res.end(JSON.stringify(body));
return;
}
if (req.method === 'GET' && url.pathname === '/range') {
const range = url.searchParams.get('range') ?? 'daily';
if (!VALID_RANGES.has(range)) {
res.writeHead(400);
res.end(JSON.stringify({ error: `Invalid range: ${range}` }));
return;
}
const args = [range, '--json'];
const since = url.searchParams.get('since');
const until = url.searchParams.get('until');
if (since) {
if (!DATE_RE.test(since)) {
res.writeHead(400);
res.end(JSON.stringify({ error: 'Invalid since date. Must be YYYYMMDD.' }));
return;
}
args.push('--since', since);
}
if (until) {
if (!DATE_RE.test(until)) {
res.writeHead(400);
res.end(JSON.stringify({ error: 'Invalid until date. Must be YYYYMMDD.' }));
return;
}
args.push('--until', until);
}
const cacheKey = `range:${range}:${since ?? ''}:${until ?? ''}`;
const { status, body } = await fetchCcusage(args, range, cacheKey, noCache);
res.writeHead(status);
res.end(JSON.stringify(body));
return;
}
res.writeHead(404);
res.end(JSON.stringify({ error: 'Not found' }));
});
// ── Graceful shutdown ──────────────────────────────────────────────────
process.on('SIGTERM', () => {
server.close(() => process.exit(0));
});
// ── Start ──────────────────────────────────────────────────────────────
server.listen(0, '127.0.0.1', () => {
const addr = server.address();
if (addr && typeof addr !== 'string') {
console.log(JSON.stringify({ ready: true, port: addr.port }));
}
});