opencode-statboard 1.0.13 → 1.1.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-statboard",
3
- "version": "1.0.13",
3
+ "version": "1.1.0",
4
4
  "description": "Real-time dashboard for opencode token usage and cost statistics",
5
5
  "main": "server.js",
6
6
  "bin": {
@@ -21,5 +21,8 @@
21
21
  "repository": {
22
22
  "type": "git",
23
23
  "url": "https://github.com/thumb2086/opencode-usage-dashboard"
24
+ },
25
+ "dependencies": {
26
+ "better-sqlite3": "^13.0.3"
24
27
  }
25
28
  }
package/public/index.html CHANGED
@@ -224,6 +224,9 @@ function applyI18n() {
224
224
  function toggleLang() {
225
225
  lang = lang === 'en' ? 'zh-TW' : 'en';
226
226
  localStorage.setItem('lang', lang);
227
+ applyI18n();
228
+ }
229
+
227
230
  async function backupDb() {
228
231
  const btn = $('backupBtn');
229
232
  btn.classList.add('busy');
@@ -246,9 +249,6 @@ async function backupDb() {
246
249
  setTimeout(() => { btn.textContent = t('backup'); }, 5000);
247
250
  }
248
251
 
249
- applyI18n();
250
- }
251
-
252
252
  const $ = (id) => document.getElementById(id);
253
253
  let currentDays = parseInt(localStorage.getItem('trendDays') || '7', 10);
254
254
 
package/server.js CHANGED
@@ -4,10 +4,14 @@ const http = require('http');
4
4
  const fs = require('fs');
5
5
  const path = require('path');
6
6
 
7
+ let Database;
8
+ try { Database = require('better-sqlite3'); } catch (_) { Database = null; }
9
+
7
10
  const PORT = 4868;
8
11
  const REFRESH_MS = 15000;
9
12
  const TREND_MS = 10 * 60 * 1000;
10
13
  const REPORT_TTL = 10 * 60 * 1000;
14
+ const STATS_TTL = 10 * 60 * 1000;
11
15
  const CACHE_CLEANUP_MS = 5 * 60 * 1000;
12
16
  const BACKUP_DIR = path.join(__dirname, 'backups');
13
17
  const BACKUP_RETENTION = parseInt(process.env.OPENCODE_BACKUP_RETENTION || '0', 10) || 0;
@@ -25,6 +29,18 @@ const EXE = (() => {
25
29
  return 'opencode';
26
30
  })();
27
31
 
32
+ let db = null;
33
+ function getDb() {
34
+ if (db) return db;
35
+ if (!Database) return null;
36
+ if (!fs.existsSync(BACKUP_SRC)) return null;
37
+ try {
38
+ db = new Database(BACKUP_SRC, { readonly: true, fileMustExist: true });
39
+ db.pragma('journal_mode = WAL');
40
+ return db;
41
+ } catch (_) { return null; }
42
+ }
43
+
28
44
  const state = { data: null, busy: false, error: null, updatedAt: 0, models: null, modelsBusy: false, loading: true };
29
45
 
30
46
  let indexHtmlCache = null;
@@ -50,6 +66,18 @@ function run(args, timeout = 120000) {
50
66
  });
51
67
  }
52
68
 
69
+ function dbQuery(sql) {
70
+ const d = getDb();
71
+ if (!d) return null;
72
+ try { return d.prepare(sql).all(); } catch (_) { return null; }
73
+ }
74
+
75
+ function dbGet(sql) {
76
+ const d = getDb();
77
+ if (!d) return null;
78
+ try { return d.prepare(sql).get(); } catch (_) { return null; }
79
+ }
80
+
53
81
  const trendCache = {};
54
82
  const trendBusy = {};
55
83
  const trendPending = {};
@@ -63,57 +91,40 @@ function cleanExpiredCache(cache, ttl) {
63
91
  }
64
92
  }
65
93
 
66
- async function generateTrend(days, retries = 2) {
67
- const step = days > 30 ? 3 : 1;
68
- const points = Math.ceil(days / step);
94
+ async function generateTrend(days) {
69
95
  const now = Date.now();
70
-
71
- async function getDailyStats(dayOffset) {
72
- const startOfDay = new Date();
73
- startOfDay.setHours(0, 0, 0, 0);
74
- startOfDay.setDate(startOfDay.getDate() - dayOffset);
75
- const startMs = startOfDay.getTime();
76
-
77
- const endOfDay = new Date(startOfDay);
78
- endOfDay.setDate(endOfDay.getDate() + 1);
79
- const endMs = endOfDay.getTime();
80
-
81
- const r = await run(['db', `SELECT COUNT(*) AS sessions, COALESCE(SUM(tokens_input),0) AS input, COALESCE(SUM(tokens_output),0) AS output, COALESCE(SUM(tokens_cache_read),0) AS cacheRead, COALESCE(SUM(cost),0) AS total FROM session WHERE time_updated >= ${startMs} AND time_updated < ${endMs};`, '--format', 'tsv']);
82
- if (!r.ok) return null;
83
- const rows = parseTSV(r.out);
84
- if (!rows.length) return null;
85
- const row = rows[0];
86
- return {
87
- sessions: parseInt(row.sessions) || 0,
88
- input: parseFloat(row.input) || 0,
89
- output: parseFloat(row.output) || 0,
90
- cacheRead: parseFloat(row.cacheRead) || 0,
91
- total: parseFloat(row.total) || 0,
92
- };
93
- }
94
-
95
- const results = new Array(points);
96
- let next = 0;
97
- const worker = async () => {
98
- while (next < points) {
99
- const i = next++;
100
- results[i] = await getDailyStats(i * step);
101
- }
102
- };
103
- await Promise.all(Array.from({ length: 4 }, worker));
104
- if (results.some((r) => !r)) {
105
- if (retries > 0) {
106
- await new Promise((r) => setTimeout(r, 1000));
107
- return generateTrend(days, retries - 1);
96
+ const startMs = now - days * 86400000;
97
+
98
+ const rows = dbQuery(`SELECT CAST((time_updated / 86400000) AS INTEGER) AS day_key, COUNT(*) AS sessions, COALESCE(SUM(tokens_input),0) AS input, COALESCE(SUM(tokens_output),0) AS output, COALESCE(SUM(tokens_cache_read),0) AS cacheRead, COALESCE(SUM(cost),0) AS total FROM session WHERE time_updated >= ${startMs} GROUP BY day_key ORDER BY day_key ASC;`);
99
+
100
+ const byDay = {};
101
+ if (rows) {
102
+ for (const row of rows) {
103
+ const key = parseInt(row.day_key);
104
+ if (!isNaN(key)) {
105
+ byDay[key] = {
106
+ sessions: parseInt(row.sessions) || 0,
107
+ input: parseFloat(row.input) || 0,
108
+ output: parseFloat(row.output) || 0,
109
+ cacheRead: parseFloat(row.cacheRead) || 0,
110
+ total: parseFloat(row.total) || 0,
111
+ };
112
+ }
108
113
  }
109
- return null;
110
114
  }
111
-
115
+
116
+ const startKey = Math.floor(startMs / 86400000);
117
+ const todayKey = Math.floor(now / 86400000);
118
+ const results = [];
119
+ for (let k = todayKey; k >= startKey; k--) {
120
+ results.push(byDay[k] || { sessions: 0, input: 0, output: 0, cacheRead: 0, total: 0 });
121
+ }
122
+
112
123
  return {
113
124
  generatedAt: now,
114
- step,
125
+ step: 1,
115
126
  labels: results.map((_, i) => {
116
- const d = new Date(now - (i * step) * 86400000);
127
+ const d = new Date(now - i * 86400000);
117
128
  return (d.getMonth() + 1) + '/' + d.getDate();
118
129
  }),
119
130
  sessions: results.map((b) => b.sessions),
@@ -143,105 +154,104 @@ function refreshTrend(days) {
143
154
  return { trend: hit ? Object.assign({}, hit, { stale: true }) : null, pending };
144
155
  }
145
156
 
146
- const clean = (s) => String(s).replace(/[^\x20-\x7E\n]/g, '');
147
-
148
- function toNum(s) {
149
- const t = String(s).replace(/,/g, '').trim();
150
- const m = /^([\d.]+)([KMB])?$/i.exec(t);
151
- if (!m) return NaN;
152
- let v = parseFloat(m[1]);
153
- if (m[2]) v *= { K: 1e3, M: 1e6, B: 1e9 }[m[2].toUpperCase()];
154
- return v;
157
+ function computeMedian(arr) {
158
+ if (!arr.length) return 0;
159
+ const sorted = arr.slice().sort((a, b) => a - b);
160
+ const mid = Math.floor(sorted.length / 2);
161
+ return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
155
162
  }
156
163
 
157
- const money = (s) => {
158
- const m = /([\d.]+)/.exec(String(s));
159
- return m ? parseFloat(m[1]) : NaN;
160
- };
164
+ function getStatsFromDb(days) {
165
+ const now = Date.now();
166
+ const startMs = days > 0 ? now - days * 86400000 : 0;
167
+ const timeFilter = startMs ? `AND s.time_updated >= ${startMs}` : '';
168
+ const timeFilterPart = startMs ? `AND p.time_updated >= ${startMs}` : '';
169
+ const timeFilterWhere = startMs ? `WHERE s.time_updated >= ${startMs}` : '';
170
+
171
+ const overview = dbGet(`SELECT COUNT(*) AS sessions, COUNT(DISTINCT CAST(s.time_updated / 86400000 AS INTEGER)) AS days FROM session s ${timeFilterWhere};`);
172
+ const msgCount = dbGet(`SELECT COUNT(*) AS messages FROM message m ${startMs ? `WHERE m.time_updated >= ${startMs}` : ''};`);
173
+ const costRow = dbGet(`SELECT COALESCE(SUM(tokens_input),0) AS input, COALESCE(SUM(tokens_output),0) AS output, COALESCE(SUM(tokens_cache_read),0) AS cacheRead, COALESCE(SUM(tokens_cache_write),0) AS cacheWrite, COALESCE(SUM(cost),0) AS total FROM session s ${timeFilterWhere};`);
174
+
175
+ const toolRows = dbQuery(`SELECT json_extract(p.data, '$.tool') AS tool FROM part p WHERE json_extract(p.data, '$.type') = 'tool' ${timeFilterPart};`) || [];
176
+ const toolCounts = {};
177
+ for (const row of toolRows) {
178
+ if (row.tool) toolCounts[row.tool] = (toolCounts[row.tool] || 0) + 1;
179
+ }
180
+ const totalToolUse = Object.values(toolCounts).reduce((s, v) => s + v, 0) || 1;
181
+ const tools = Object.entries(toolCounts)
182
+ .map(([name, count]) => ({ name, count, pct: Math.round((count / totalToolUse) * 1000) / 10 }))
183
+ .sort((a, b) => b.count - a.count);
184
+
185
+ const tokenRows = dbQuery(`SELECT tokens_input + tokens_output AS tokens FROM session s ${timeFilterWhere};`) || [];
186
+ const tokenVals = tokenRows.map((r) => r.tokens).filter(Number.isFinite);
187
+ const avgTokens = tokenVals.length ? tokenVals.reduce((s, v) => s + v, 0) / tokenVals.length : 0;
188
+ const medianTokens = computeMedian(tokenVals);
189
+ const activeDays = overview ? (overview.days || 1) : 1;
190
+ const sessions = overview ? (overview.sessions || 0) : 0;
191
+ const avgDayCost = costRow && costRow.total ? costRow.total / activeDays : 0;
161
192
 
162
- function parseStats(text) {
163
- const c = clean(text);
164
- const grab = (re) => { const m = re.exec(c); return m ? m[1] : null; };
165
- const out = {
193
+ const models = dbQuery(`SELECT COALESCE(json_extract(model,'$.providerID'), 'unknown') || '/' || COALESCE(json_extract(model,'$.id'), 'unknown') AS name, COUNT(*) AS messages, COALESCE(SUM(tokens_input),0) AS input, COALESCE(SUM(tokens_output),0) AS output, COALESCE(SUM(tokens_cache_read),0) AS cacheRead, COALESCE(SUM(tokens_cache_write),0) AS cacheWrite, COALESCE(SUM(cost),0) AS cost FROM session s ${timeFilterWhere} GROUP BY name ORDER BY COALESCE(SUM(cost),0) DESC;`) || [];
194
+
195
+ return {
196
+ ok: true,
166
197
  overview: {
167
- sessions: toNum(grab(/Sessions\s+([\d,]+)/)),
168
- messages: toNum(grab(/Messages\s+([\d,]+)/)),
169
- days: toNum(grab(/Days\s+([\d,]+)/)),
198
+ sessions: sessions,
199
+ messages: msgCount ? (msgCount.messages || 0) : 0,
200
+ days: activeDays,
170
201
  },
171
202
  cost: {
172
- total: money(grab(/Total Cost\s*\$([\d.]+)/)),
173
- avgDay: money(grab(/Avg Cost\/Day\s*\$([\d.]+)/)),
174
- avgTokensSession: toNum(grab(/Avg Tokens\/Session\s+([\d.]+[KMB]?)/)),
175
- medianTokensSession: toNum(grab(/Median Tokens\/Session\s+([\d.]+[KMB]?)/)),
176
- input: toNum(grab(/^Input\s+([\d.]+[KMB]?)/m)),
177
- output: toNum(grab(/^Output\s+([\d.]+[KMB]?)/m)),
178
- cacheRead: toNum(grab(/^Cache Read\s+([\d.]+[KMB]?)/m)),
179
- cacheWrite: toNum(grab(/^Cache Write\s+([\d.]+[KMB]?)/m)),
203
+ total: costRow ? costRow.total : 0,
204
+ avgDay: avgDayCost,
205
+ avgTokensSession: Math.round(avgTokens),
206
+ medianTokensSession: Math.round(medianTokens),
207
+ input: costRow ? costRow.input : 0,
208
+ output: costRow ? costRow.output : 0,
209
+ cacheRead: costRow ? costRow.cacheRead : 0,
210
+ cacheWrite: costRow ? costRow.cacheWrite : 0,
180
211
  },
181
- tools: [],
182
- models: [],
183
- };
184
-
185
- for (const line of c.split('\n')) {
186
- const m = /^\s*([\w.\-]+)\s+([\d,]+)\s*\(\s*([\d.]+)%\)/.exec(line);
187
- if (m) out.tools.push({ name: m[1], count: parseInt(m[2].replace(/,/g, ''), 10), pct: parseFloat(m[3]) });
188
- }
189
-
190
- let cur = null;
191
- const setv = (cur, line, re, key, isMoney) => {
192
- const m = re.exec(line);
193
- if (m) cur[key] = isMoney ? money(m[1]) : toNum(m[1]);
212
+ tools,
213
+ models,
194
214
  };
195
- for (const line of c.split('\n')) {
196
- const name = /^\s*([a-zA-Z0-9_.\-]+\/[a-zA-Z0-9_.\-]+)\s*$/.exec(line);
197
- if (name) {
198
- cur = { name: name[1], messages: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
199
- out.models.push(cur);
200
- continue;
201
- }
202
- if (!cur) continue;
203
- setv(cur, line, /Messages\s+([\d,]+)/, 'messages', false);
204
- setv(cur, line, /Input Tokens\s+([\d.]+[KMB]?)/, 'input', false);
205
- setv(cur, line, /Output Tokens\s+([\d.]+[KMB]?)/, 'output', false);
206
- setv(cur, line, /Cache Read\s+([\d.]+[KMB]?)/, 'cacheRead', false);
207
- setv(cur, line, /Cache Write\s+([\d.]+[KMB]?)/, 'cacheWrite', false);
208
- setv(cur, line, /Cost\s+(\$[\d.]+)/, 'cost', true);
209
- }
210
- return out;
211
- }
212
-
213
- function validRow(p) {
214
- return Number.isFinite(p.overview.sessions) && Number.isFinite(p.overview.messages);
215
- }
216
-
217
- async function runStats(args) {
218
- const r = await run(args);
219
- if (!r.ok) return null;
220
- const p = parseStats(r.out);
221
- if (!validRow(p)) return null;
222
- return Object.assign({ ok: true }, p);
223
215
  }
224
216
 
225
217
  async function refresh() {
226
218
  if (state.busy) return;
227
219
  state.busy = true;
228
- const p = await runStats(['stats']);
229
- if (p) {
230
- state.data = p;
231
- state.error = null;
232
- state.updatedAt = Date.now();
233
- } else {
234
- state.error = state.error || 'opencode stats failed';
220
+ try {
221
+ const p = getStatsFromDb(0);
222
+ if (p && p.ok) {
223
+ state.data = p;
224
+ state.error = null;
225
+ state.updatedAt = Date.now();
226
+ } else {
227
+ state.error = state.error || 'failed to read database';
228
+ }
229
+ } catch (e) {
230
+ state.error = e.message;
235
231
  }
236
232
  state.loading = false;
237
233
  state.busy = false;
238
234
  }
239
235
 
236
+ function getModelsFromDb() {
237
+ const rows = dbQuery(`SELECT COALESCE(json_extract(model,'$.providerID'), 'unknown') AS provider, COALESCE(json_extract(model,'$.id'), 'unknown') AS model, COUNT(*) AS messages, COALESCE(SUM(tokens_input),0) AS input, COALESCE(SUM(tokens_output),0) AS output, COALESCE(SUM(tokens_cache_read),0) AS cacheRead, COALESCE(SUM(cost),0) AS cost FROM session GROUP BY provider, model ORDER BY COALESCE(SUM(cost),0) DESC LIMIT 10;`) || [];
238
+ return rows.map((r) => ({
239
+ name: r.provider + '/' + r.model,
240
+ messages: r.messages || 0,
241
+ input: r.input || 0,
242
+ output: r.output || 0,
243
+ cacheRead: r.cacheRead || 0,
244
+ cacheWrite: 0,
245
+ cost: r.cost || 0,
246
+ }));
247
+ }
248
+
240
249
  async function refreshModels() {
241
250
  if (state.modelsBusy) return;
242
251
  state.modelsBusy = true;
243
- const p = await runStats(['stats', '--models', '10']);
244
- if (p) state.models = p.models;
252
+ try {
253
+ state.models = getModelsFromDb();
254
+ } catch (_) {}
245
255
  state.modelsBusy = false;
246
256
  }
247
257
 
@@ -300,70 +310,28 @@ async function autoBackupIfDue() {
300
310
  await performBackup(true);
301
311
  }
302
312
 
303
- function clamp(n) {
304
- return Number.isFinite(n) && n > 0 ? n : 0;
305
- }
306
-
307
- function safeNum(v) {
308
- return Number.isFinite(v) ? v : 0;
309
- }
310
-
311
- function sub(a, b) {
312
- return {
313
- sessions: clamp(safeNum(a.overview.sessions) - safeNum(b.overview.sessions)),
314
- messages: clamp(safeNum(a.overview.messages) - safeNum(b.overview.messages)),
315
- total: clamp(safeNum(a.cost.total) - safeNum(b.cost.total)),
316
- input: clamp(safeNum(a.cost.input) - safeNum(b.cost.input)),
317
- output: clamp(safeNum(a.cost.output) - safeNum(b.cost.output)),
318
- cacheRead: clamp(safeNum(a.cost.cacheRead) - safeNum(b.cost.cacheRead)),
319
- };
320
- }
321
-
322
313
  const reportCache = {};
323
314
  const reportBusy = {};
324
315
 
325
- function parseTSV(text) {
326
- if (!text) return [];
327
- const cleaned = text.replace(/[^\x20-\x7E\n\t]/g, '');
328
- const lines = cleaned.trim().split('\n');
329
- if (lines.length < 2) return [];
330
- const headers = lines[0].split('\t');
331
- return lines.slice(1).map((line) => {
332
- const cols = line.split('\t');
333
- const obj = {};
334
- headers.forEach((h, i) => { obj[h.trim()] = (cols[i] || '').trim(); });
335
- return obj;
336
- });
337
- }
338
-
339
- async function buildReport(days) {
316
+ function buildReportFromDb(days) {
317
+ const now = Date.now();
318
+ const startMs = days === -1 ? 0 : days <= 1 ? now - 86400000 : days <= 7 ? now - days * 86400000 : (() => {
319
+ const d = new Date(); d.setDate(1); d.setHours(0, 0, 0, 0); return d.getTime();
320
+ })();
340
321
  const label = days === -1 ? 'All' : days <= 1 ? 'Daily' : days <= 7 ? 'Weekly' : 'Monthly';
341
- const timeFilter = days === -1
342
- ? '1=1'
343
- : days <= 1
344
- ? `(strftime('%s','now','start of day') * 1000)`
345
- : days <= 7
346
- ? `(strftime('%s','now','start of day', '-${days - 1} day') * 1000)`
347
- : `(strftime('%s','now','start of month') * 1000)`;
348
- let statsR = days === -1
349
- ? await runStats(['stats', '--models', '20'])
350
- : await runStats(['stats', '--days', String(Math.max(days, 1)), '--models', '20']);
351
- if (!statsR) {
352
- await new Promise((r) => setTimeout(r, 2000));
353
- statsR = days === -1
354
- ? await runStats(['stats', '--models', '20'])
355
- : await runStats(['stats', '--days', String(Math.max(days, 1)), '--models', '20']);
356
- }
357
- const [agentR, modelR] = await Promise.all([
358
- run(['db', `SELECT agent, COUNT(*) AS sessions, ROUND(SUM(cost),4) AS cost, SUM(tokens_input) AS tok_in, SUM(tokens_output) AS tok_out, SUM(tokens_cache_read) AS cache_read FROM session WHERE agent IS NOT NULL AND time_updated >= ${timeFilter} GROUP BY 1 ORDER BY cost DESC;`, '--format', 'tsv']),
359
- run(['db', `SELECT COALESCE(json_extract(model,'$.providerID'), 'unknown') AS provider, COALESCE(json_extract(model,'$.id'), 'unknown') AS model, COUNT(*) AS sessions, ROUND(SUM(cost),4) AS cost, SUM(tokens_input) AS tok_in, SUM(tokens_output) AS tok_out, SUM(tokens_cache_read) AS cache_read FROM session WHERE time_updated >= ${timeFilter} GROUP BY 1, 2 ORDER BY cost DESC;`, '--format', 'tsv']),
360
- ]);
322
+ const where = startMs ? `WHERE time_updated >= ${startMs}` : '';
323
+
324
+ const statsR = getStatsFromDb(days);
325
+ const agentRows = dbQuery(`SELECT agent, COUNT(*) AS sessions, ROUND(SUM(cost),4) AS cost, SUM(tokens_input) AS tok_in, SUM(tokens_output) AS tok_out, SUM(tokens_cache_read) AS cache_read FROM session WHERE agent IS NOT NULL ${startMs ? `AND time_updated >= ${startMs}` : ''} GROUP BY agent ORDER BY cost DESC;`) || [];
326
+ const providerRows = dbQuery(`SELECT COALESCE(json_extract(model,'$.providerID'), 'unknown') AS provider, COALESCE(json_extract(model,'$.id'), 'unknown') AS model, COUNT(*) AS sessions, ROUND(SUM(cost),4) AS cost, SUM(tokens_input) AS tok_in, SUM(tokens_output) AS tok_out, SUM(tokens_cache_read) AS cache_read FROM session ${where} GROUP BY provider, model ORDER BY cost DESC;`) || [];
327
+
361
328
  return {
362
- label: label,
363
- days: days,
329
+ label,
330
+ days,
364
331
  stats: statsR,
365
- agents: parseTSV(agentR.out),
366
- providers: parseTSV(modelR.out),
332
+ agents: agentRows,
333
+ providers: providerRows,
334
+ generatedAt: now,
367
335
  };
368
336
  }
369
337
 
@@ -374,13 +342,13 @@ function refreshReport(days) {
374
342
  if (fresh) return { report: hit, ready: true };
375
343
  if (!reportBusy[key]) {
376
344
  reportBusy[key] = true;
377
- buildReport(days).then((r) => {
345
+ try {
346
+ const r = buildReportFromDb(days);
378
347
  if (r && r.stats && r.stats.ok) {
379
- reportCache[key] = Object.assign({}, r, { generatedAt: Date.now() });
348
+ reportCache[key] = r;
380
349
  }
381
- }).catch(() => {}).finally(() => {
382
- delete reportBusy[key];
383
- });
350
+ } catch (_) {}
351
+ delete reportBusy[key];
384
352
  }
385
353
  return hit ? { report: Object.assign({}, hit, { stale: true }), ready: true } : { report: null, ready: false };
386
354
  }
@@ -437,9 +405,8 @@ const server = http.createServer(async (req, res) => {
437
405
 
438
406
  function gracefulShutdown() {
439
407
  console.log('\nShutting down...');
440
- server.close(() => {
441
- process.exit(0);
442
- });
408
+ if (db) try { db.close(); } catch (_) {}
409
+ server.close(() => { process.exit(0); });
443
410
  setTimeout(() => process.exit(1), 5000);
444
411
  }
445
412
 
@@ -461,12 +428,16 @@ setInterval(() => {
461
428
  await refresh();
462
429
  await refreshModels();
463
430
  for (const d of [1, 7, 30]) {
464
- const r = await buildReport(d);
465
- if (r && r.stats && r.stats.ok) reportCache[String(d)] = Object.assign({}, r, { generatedAt: Date.now() });
431
+ try {
432
+ const r = buildReportFromDb(d);
433
+ if (r && r.stats && r.stats.ok) reportCache[String(d)] = r;
434
+ } catch (_) {}
466
435
  }
467
436
  for (const d of [7, 30, 90]) {
468
- const t = await generateTrend(d);
469
- if (t) trendCache[String(d)] = t;
437
+ try {
438
+ const t = await generateTrend(d);
439
+ if (t) trendCache[String(d)] = t;
440
+ } catch (_) {}
470
441
  }
471
442
  await autoBackupIfDue();
472
443
  })();