@obzerver/server 0.15.0 → 0.17.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.
@@ -0,0 +1,32 @@
1
+ import * as queries from './queries.js';
2
+ import * as simple from './simple.js';
3
+ import * as history from './history.js';
4
+ import { retention } from './db.js';
5
+ import { pruneSpanTrees } from './usage.js';
6
+ export interface Job {
7
+ id: number;
8
+ file: string;
9
+ module: keyof typeof MODULES;
10
+ fn: string;
11
+ args: unknown[];
12
+ }
13
+ export type Reply = {
14
+ id: number;
15
+ ok: true;
16
+ value: unknown;
17
+ } | {
18
+ id: number;
19
+ ok: false;
20
+ error: string;
21
+ stack?: string;
22
+ };
23
+ declare const MODULES: {
24
+ readonly queries: typeof queries;
25
+ readonly simple: typeof simple;
26
+ readonly history: typeof history;
27
+ readonly maintenance: {
28
+ readonly retention: typeof retention;
29
+ readonly pruneSpanTrees: typeof pruneSpanTrees;
30
+ };
31
+ };
32
+ export {};
@@ -0,0 +1,35 @@
1
+ // The background worker's side: its own connections to the project databases, and the read queries and
2
+ // roll-ups it runs on them, so they never hold up ingest on the server's event loop.
3
+ import { parentPort } from 'node:worker_threads';
4
+ import * as queries from './queries.js';
5
+ import * as simple from './simple.js';
6
+ import * as history from './history.js';
7
+ import { Db, retention } from './db.js';
8
+ import { pruneSpanTrees } from './usage.js';
9
+ const MODULES = { queries, simple, history, maintenance: { retention, pruneSpanTrees } };
10
+ const open = new Map();
11
+ const dbFor = (file) => {
12
+ let d = open.get(file);
13
+ if (!d)
14
+ open.set(file, (d = Db.attach(file)));
15
+ return d;
16
+ };
17
+ parentPort?.on('message', (job) => {
18
+ if ('close' in job) {
19
+ open.get(job.close)?.close();
20
+ open.delete(job.close);
21
+ return;
22
+ }
23
+ let reply;
24
+ try {
25
+ const fn = MODULES[job.module][job.fn];
26
+ if (typeof fn !== 'function')
27
+ throw new Error(`No ${job.module}.${job.fn}`);
28
+ reply = { id: job.id, ok: true, value: fn(dbFor(job.file), ...job.args) };
29
+ }
30
+ catch (e) {
31
+ reply = { id: job.id, ok: false, error: e.message, stack: e.stack };
32
+ }
33
+ parentPort.postMessage(reply);
34
+ });
35
+ //# sourceMappingURL=readworker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"readworker.js","sourceRoot":"","sources":["../src/readworker.ts"],"names":[],"mappings":"AAAA,uGAAuG;AACvG,qFAAqF;AACrF,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,KAAK,OAAO,MAAM,cAAc,CAAC;AACxC,OAAO,KAAK,MAAM,MAAM,aAAa,CAAC;AACtC,OAAO,KAAK,OAAO,MAAM,cAAc,CAAC;AACxC,OAAO,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACxC,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAK5C,MAAM,OAAO,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE,EAAE,SAAS,EAAE,cAAc,EAAE,EAAW,CAAC;AAClG,MAAM,IAAI,GAAG,IAAI,GAAG,EAAc,CAAC;AACnC,MAAM,KAAK,GAAG,CAAC,IAAY,EAAM,EAAE;IACjC,IAAI,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IACvB,IAAI,CAAC,CAAC;QAAE,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAC9C,OAAO,CAAC,CAAC;AACX,CAAC,CAAC;AAEF,UAAU,EAAE,EAAE,CAAC,SAAS,EAAE,CAAC,GAA4B,EAAE,EAAE;IACzD,IAAI,OAAO,IAAI,GAAG,EAAE,CAAC;QAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,CAAC;QAAC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QAAC,OAAO;IAAC,CAAC;IACrF,IAAI,KAAY,CAAC;IACjB,IAAI,CAAC;QACH,MAAM,EAAE,GAAI,OAAO,CAAC,GAAG,CAAC,MAAM,CAA6B,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QACpE,IAAI,OAAO,EAAE,KAAK,UAAU;YAAE,MAAM,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,MAAM,IAAI,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC;QAC5E,KAAK,GAAG,EAAE,EAAE,EAAE,GAAG,CAAC,EAAE,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,EAAG,EAA2C,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,GAAG,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;IACtH,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,KAAK,GAAG,EAAE,EAAE,EAAE,GAAG,CAAC,EAAE,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAG,CAAW,CAAC,OAAO,EAAE,KAAK,EAAG,CAAW,CAAC,KAAK,EAAE,CAAC;IAC5F,CAAC;IACD,UAAW,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;AACjC,CAAC,CAAC,CAAC"}
package/dist/server.d.ts CHANGED
@@ -26,6 +26,8 @@ export interface ServerOptions {
26
26
  ingestQueue?: number | string;
27
27
  /** Event-loop delay (ms) past which new batches get "busy, retry later". OBZERVER_SHED_LAG_MS, default 500. */
28
28
  shedLagMs?: number | string;
29
+ /** Threads that run dashboard reads and roll-ups off the event loop; 0 runs them inline. OBZERVER_READ_THREADS, default 1. */
30
+ readThreads?: number | string;
29
31
  /** Which proxies may set X-Forwarded-For: true, false, or addresses/CIDRs. OBZERVER_TRUST_PROXY, default private networks. */
30
32
  trustProxy?: boolean | string;
31
33
  retentionDays?: number | string;
@@ -64,6 +66,7 @@ export interface ServerConfig {
64
66
  ingestRate: number;
65
67
  ingestQueue: number;
66
68
  shedLagMs: number;
69
+ readThreads: number;
67
70
  trustProxy: boolean | string;
68
71
  }
69
72
  export interface ObzerverServer {
package/dist/server.js CHANGED
@@ -7,7 +7,7 @@ import fs from 'node:fs';
7
7
  import path from 'node:path';
8
8
  import { fileURLToPath } from 'node:url';
9
9
  import { openSecretCount, secretFindings, secretGroups } from './secrets.js';
10
- import { baseline, history, historyInfo, historyTick, typical } from './history.js';
10
+ import { baseline, history, historyInfo, typical } from './history.js';
11
11
  import { getSetting, setSetting, retention, hashSecret, newMcpToken } from './db.js';
12
12
  import { createKey, listKeys, revokeKey, rotateKey, KeyError } from './keys.js';
13
13
  import { RateLimiter } from './ratelimit.js';
@@ -19,12 +19,17 @@ import { mcpHandler, MCP_TOOL_NAMES } from './mcp.js';
19
19
  import { issueRow, verifyFix, runVerification, MEASURABLE } from './issues.js';
20
20
  import { PROVIDERS, PROVIDER_LABEL, TrackerError, createTicket, syncTickets, onIssueResolved, onVerification, publicTrackerSettings, saveTrackerSettings, testTracker, trackerSettings, verifyGithubSignature, verifyLinearSignature, handleGithubEvent, handleLinearEvent, } from './trackers.js';
21
21
  import * as Q from './queries.js';
22
- import { simpleHome, simpleAlerts, saveSimpleAlerts, simpleTestRule, simpleReleases } from './simple.js';
22
+ import { simpleAlerts, saveSimpleAlerts, simpleTestRule } from './simple.js';
23
23
  import { listSlos, sloStatus, sloHistory, saveSlo, deleteSlo, validateSlo, toSlo, burnRulesFor } from './slos.js';
24
24
  import { slugify as slugifyPage, toPage, toIncident, validatePage, savePage, deletePage, createIncident, updateIncident, pageView, publicView, renderStatusHtml, runAutoIncidents } from './status.js';
25
25
  import { mailConfig, maskSmtpUrl, parseRecipients, sendMail, resetMailTransports, alertEmail } from './mailer.js';
26
26
  import { AiMeter } from './aiusage.js';
27
27
  import { IngestQueue } from './ingestqueue.js';
28
+ import { Reader } from './reader.js';
29
+ import { OtlpConverter, decodeJson, decodeProtobuf, partialSuccess } from './otlp.js';
30
+ import { walStats } from './checkpoint.js';
31
+ import * as S from './simple.js';
32
+ import * as H from './history.js';
28
33
  import { UsageMeter, pruneSpanTrees, SPAN_TREE_DAYS } from './usage.js';
29
34
  const here = path.dirname(fileURLToPath(import.meta.url));
30
35
  const isLoopback = (host) => ['127.0.0.1', '::1', 'localhost'].includes(host) || host.startsWith('127.');
@@ -58,6 +63,7 @@ export async function createServer(opts = {}) {
58
63
  ingestRate: (() => { const v = Number(opts.ingestRate ?? env.OBZERVER_INGEST_RATE ?? 20); return Number.isFinite(v) && v >= 0 ? v : 20; })(),
59
64
  ingestQueue: (() => { const v = Number(opts.ingestQueue ?? env.OBZERVER_INGEST_QUEUE ?? 100); return Number.isFinite(v) && v >= 1 ? v : 100; })(),
60
65
  shedLagMs: (() => { const v = Number(opts.shedLagMs ?? env.OBZERVER_SHED_LAG_MS ?? 500); return Number.isFinite(v) && v >= 50 ? v : 500; })(),
66
+ readThreads: (() => { const v = Number(opts.readThreads ?? env.OBZERVER_READ_THREADS ?? 1); return Number.isInteger(v) && v >= 0 && v <= 16 ? v : 1; })(),
61
67
  trustProxy: (() => {
62
68
  const v = opts.trustProxy ?? env.OBZERVER_TRUST_PROXY;
63
69
  if (v === undefined)
@@ -129,12 +135,41 @@ export async function createServer(opts = {}) {
129
135
  const ingestQueue = new IngestQueue({
130
136
  runInTx: (slug, fn) => projects.run(slug, () => projects.db(slug).tx(fn)),
131
137
  maxQueued: config.ingestQueue, maxLagMs: config.shedLagMs,
138
+ isPaused: (slug) => projects.db(slug).paused,
132
139
  });
133
140
  const toolOpts = { usage: () => ({ ...usage.report(), askObzeri: aiMeter.report() }), locked: lockedText };
134
141
  const mcp = mcpHandler(db, toolOpts);
135
142
  const secret = getSetting(root, 'session_secret') ?? crypto.randomBytes(32).toString('hex');
136
143
  const app = Fastify({ logger: config.logger, bodyLimit: 25 * 1024 * 1024, trustProxy: config.trustProxy });
137
144
  app.addHook('onClose', async () => { ingestQueue.close(); });
145
+ // Dashboard reads and roll-ups: in the read worker for databases on disk (the current project's).
146
+ const reader = new Reader(config.readThreads);
147
+ /** OpenTelemetry span assembly, per project (spans can arrive before their request's span). */
148
+ const otlp = new Map();
149
+ const otlpRefused = new Map();
150
+ /** Writes the OpenTelemetry requests whose grace period is over (see otlp.ts), through the ingest queue. */
151
+ const flushOtlp = async (all = false) => {
152
+ for (const [slug, conv] of otlp) {
153
+ const payloads = conv.take(Date.now(), all);
154
+ if (!payloads.length)
155
+ continue;
156
+ try {
157
+ const rs = await ingestQueue.submit(slug, () => projects.db(slug).tx(() => payloads.map((p) => meteredIngest(slug, p))));
158
+ const stop = rs.find((r) => r.refuse);
159
+ if (stop?.refuse)
160
+ otlpRefused.set(slug, { until: Date.now() + stop.seconds * 1000, error: stop.error });
161
+ }
162
+ catch (e) {
163
+ app.log.warn({ err: e, slug }, 'OpenTelemetry spans could not be written');
164
+ }
165
+ }
166
+ };
167
+ const otlpTimer = setInterval(() => { void flushOtlp(); }, 500);
168
+ otlpTimer.unref();
169
+ app.addHook('onClose', async () => { await reader.close(); });
170
+ app.addHook('preClose', async () => { clearInterval(otlpTimer); await flushOtlp(true); });
171
+ const MODULES = { queries: Q, simple: S, history: H, maintenance: { retention, pruneSpanTrees } };
172
+ const read = (module, fn, ...args) => reader.run(db.path, db, module, fn, args, () => MODULES[module][fn](db, ...args));
138
173
  // ---------------------------------------------------------------- auth
139
174
  // The dashboard password is kept only as a hash. Sessions are signed with it too, so changing the password
140
175
  // signs everyone out.
@@ -225,7 +260,7 @@ export async function createServer(opts = {}) {
225
260
  app.get('/healthz', async (_req, reply) => {
226
261
  try {
227
262
  db.get('SELECT 1');
228
- return { ok: true, version: VERSION, uptime: Math.round((Date.now() - started) / 1000), ingest: { queued: ingestQueue.queued, lagMs: Math.round(ingestQueue.lagMs), shed: ingestQueue.shed } };
263
+ return { ok: true, version: VERSION, uptime: Math.round((Date.now() - started) / 1000), ingest: { queued: ingestQueue.queued, lagMs: Math.round(ingestQueue.lagMs), shed: ingestQueue.shed }, reads: reader.stats(), wal: walStats, otlp: { waiting: [...otlp.values()].reduce((a, c) => a + c.waiting, 0), dropped: [...otlp.values()].reduce((a, c) => a + c.dropped, 0), lastDropped: [...otlp.values()].flatMap((c) => c.lastDropped).slice(-10) } };
229
264
  }
230
265
  catch (e) {
231
266
  return reply.code(503).send({ ok: false, version: VERSION, error: e.message });
@@ -281,6 +316,9 @@ export async function createServer(opts = {}) {
281
316
  });
282
317
  app.delete('/api/projects/:slug', async (req, reply) => {
283
318
  try {
319
+ const file = projects.has(req.params.slug) ? projects.db(req.params.slug).path : null;
320
+ if (file)
321
+ reader.forget(file);
284
322
  projects.remove(req.params.slug);
285
323
  ingests.delete(req.params.slug);
286
324
  usage.invalidate();
@@ -357,6 +395,47 @@ export async function createServer(opts = {}) {
357
395
  return reply.code(429).header('retry-after', String(r.seconds)).send({ error: r.error, usage: 'refused' });
358
396
  return { ok: true, project: slug, accepted: r.accepted, usage: r.state };
359
397
  });
398
+ // ------------------------------------------------------------ OpenTelemetry (OTLP/HTTP)
399
+ // Apps in any language report with the official OpenTelemetry SDKs: set OTEL_EXPORTER_OTLP_ENDPOINT to this
400
+ // server and OTEL_EXPORTER_OTLP_HEADERS to x-obzerver-key=<ingest key>. Protobuf (their default) or JSON.
401
+ scope.addContentTypeParser(['application/x-protobuf', 'application/protobuf'], { parseAs: 'buffer' }, (_req, body, done) => done(null, body));
402
+ const isProto = (req) => String(req.headers['content-type'] || '').includes('protobuf');
403
+ const answer = (req, reply, message) => {
404
+ const proto = isProto(req);
405
+ reply.header('content-type', proto ? 'application/x-protobuf' : 'application/json');
406
+ return message ? partialSuccess(message, proto) : proto ? Buffer.alloc(0) : {};
407
+ };
408
+ scope.post('/v1/traces', async (req, reply) => {
409
+ const k = req.ingestKey ?? null;
410
+ let resources;
411
+ try {
412
+ resources = isProto(req) ? decodeProtobuf(req.body) : decodeJson(req.body);
413
+ }
414
+ catch (e) {
415
+ return reply.code(400).send({ error: `Not an OTLP trace export: ${e.message}` });
416
+ }
417
+ const slug = k?.slug ?? DEFAULT_PROJECT;
418
+ if (k)
419
+ markUsed(k);
420
+ // Over the plan's allowance (seen when the last spans were written): tell the exporter to wait.
421
+ const stop = otlpRefused.get(slug);
422
+ if (stop && stop.until > Date.now())
423
+ return reply.code(429).header('retry-after', String(Math.ceil((stop.until - Date.now()) / 1000))).send({ error: stop.error, usage: 'refused' });
424
+ // A key limited to one environment takes only that environment's apps.
425
+ const envOf = (r) => { const e = r.attrs['deployment.environment.name'] ?? r.attrs['deployment.environment']; return typeof e === 'string' && e ? e : null; };
426
+ const refused = k?.environment ? resources.filter((r) => envOf(r) !== k.environment) : [];
427
+ let conv = otlp.get(slug);
428
+ if (!conv)
429
+ otlp.set(slug, (conv = new OtlpConverter()));
430
+ conv.add(refused.length ? resources.filter((r) => !refused.includes(r)) : resources);
431
+ return answer(req, reply, refused.length
432
+ ? `This key only accepts the "${k.environment}" environment; spans from ${refused.map((r) => `"${String(r.attrs['service.name'] ?? 'unknown_service')}" (${envOf(r) ?? 'no environment'})`).join(', ')} were not stored.`
433
+ : null);
434
+ });
435
+ // Metrics and logs aren't stored yet: accepted with a warning, so exporters don't keep retrying them.
436
+ for (const what of ['metrics', 'logs']) {
437
+ scope.post(`/v1/${what}`, async (req, reply) => answer(req, reply, `Obzerver stores OpenTelemetry traces only for now; ${what} were not stored. Set OTEL_${what.toUpperCase()}_EXPORTER=none to stop sending them.`));
438
+ }
360
439
  });
361
440
  // ---------------------------------------------------------------- MCP
362
441
  app.post('/mcp', async (req, reply) => {
@@ -407,8 +486,8 @@ export async function createServer(opts = {}) {
407
486
  });
408
487
  app.post('/api/usage/resume', async () => { usage.resume(); return usage.report(); });
409
488
  // Simple mode: health, what broke, what changed and what to do, in plain words.
410
- app.get('/api/simple', async (req) => simpleHome(db, w(req.query)));
411
- app.get('/api/simple/releases', async (req) => simpleReleases(db, w(req.query)));
489
+ app.get('/api/simple', async (req) => await read('simple', 'simpleHome', w(req.query)));
490
+ app.get('/api/simple/releases', async (req) => await read('simple', 'simpleReleases', w(req.query)));
412
491
  app.get('/api/simple/alerts', async () => simpleAlerts(db, { emailReady: !!mailConfig(root).url }));
413
492
  app.put('/api/simple/alerts', async (req) => {
414
493
  saveSimpleAlerts(db, req.body || {});
@@ -434,14 +513,14 @@ export async function createServer(opts = {}) {
434
513
  const r = db.run('UPDATE secret_groups SET status = ?, resolved_at = ? WHERE fingerprint = ?', status, status === 'open' ? null : Date.now(), req.params.fp);
435
514
  return r.changes ? { ok: true } : reply.code(404).send({ error: 'not found' });
436
515
  });
437
- app.get('/api/overview', async (req) => Q.overview(db, w(req.query)));
438
- app.get('/api/operations', async (req) => Q.operationsBy(db, w(req.query), req.query.kind || 'http', req.query.protocol));
439
- app.get('/api/operations/series', async (req) => Q.protocolSeries(db, w(req.query), req.query.protocol || 'http'));
516
+ app.get('/api/overview', async (req) => await read('queries', 'overview', w(req.query)));
517
+ app.get('/api/operations', async (req) => await read('queries', 'operationsBy', w(req.query), req.query.kind || 'http', req.query.protocol));
518
+ app.get('/api/operations/series', async (req) => await read('queries', 'protocolSeries', w(req.query), req.query.protocol || 'http'));
440
519
  app.get('/api/operation', async (req, reply) => {
441
520
  const { name, kind, service, sort, filter, limit, offset } = req.query;
442
521
  if (!name)
443
522
  return reply.code(400).send({ error: 'name required' });
444
- return Q.operation(db, w(req.query), { name, kind: kind || 'http', service, sort, filter, limit, offset });
523
+ return read('queries', 'operation', w(req.query), { name, kind: kind || 'http', service, sort, filter, limit, offset });
445
524
  });
446
525
  app.get('/api/history', async (req) => {
447
526
  const { kind, service, name, days } = req.query;
@@ -453,34 +532,34 @@ export async function createServer(opts = {}) {
453
532
  const t = Number(at) || Date.now();
454
533
  return { thisHour: baseline(db, f, t), last4Weeks: typical(db, f, t) };
455
534
  });
456
- app.get('/api/executions/:id', async (req, reply) => Q.execution(db, req.params.id) ?? notFound(reply));
535
+ app.get('/api/executions/:id', async (req, reply) => await read('queries', 'execution', req.params.id) ?? notFound(reply));
457
536
  app.get('/api/executions/:id/prompt', async (req, reply) => {
458
537
  const prompt = Q.agentPrompt(db, req.params.id);
459
538
  return prompt ? { prompt } : notFound(reply);
460
539
  });
461
- app.get('/api/traces', async (req) => Q.traces(db, w(req.query), { q: req.query.q, failed: req.query.failed, minDuration: req.query.minDuration, kind: req.query.kind, limit: req.query.limit }));
462
- app.get('/api/traces/:traceId', async (req, reply) => Q.traceById(db, req.params.traceId) ?? notFound(reply));
463
- app.get('/api/errors', async (req) => Q.errorGroups(db, w(req.query), { handled: req.query.handled ?? '0', status: req.query.status }));
464
- app.get('/api/errors/:fp', async (req, reply) => Q.errorGroup(db, w(req.query), req.params.fp) ?? notFound(reply));
540
+ app.get('/api/traces', async (req) => await read('queries', 'traces', w(req.query), { q: req.query.q, failed: req.query.failed, minDuration: req.query.minDuration, kind: req.query.kind, limit: req.query.limit }));
541
+ app.get('/api/traces/:traceId', async (req, reply) => await read('queries', 'traceById', req.params.traceId) ?? notFound(reply));
542
+ app.get('/api/errors', async (req) => await read('queries', 'errorGroups', w(req.query), { handled: req.query.handled ?? '0', status: req.query.status }));
543
+ app.get('/api/errors/:fp', async (req, reply) => await read('queries', 'errorGroup', w(req.query), req.params.fp) ?? notFound(reply));
465
544
  app.patch('/api/errors/:fp', async (req) => {
466
545
  const status = ['open', 'resolved', 'ignored'].includes(req.body?.status ?? '') ? req.body.status : 'open';
467
546
  db.run('UPDATE error_groups SET status = ?, resolved_at = ? WHERE fingerprint = ?', status, status === 'resolved' ? Date.now() : null, req.params.fp);
468
547
  return { ok: true };
469
548
  });
470
- app.get('/api/logs', async (req) => Q.logs(db, w(req.query), { level: req.query.level, q: req.query.q, traceId: req.query.traceId, before: req.query.before, limit: req.query.limit }));
471
- app.get('/api/functions', async (req) => Q.functions(db, w(req.query)));
472
- app.get('/api/queries', async (req) => Q.queries(db, w(req.query)));
473
- app.get('/api/outbound', async (req) => Q.outbound(db, w(req.query)));
474
- app.get('/api/users', async (req) => Q.users(db, w(req.query), { groupBy: req.query.groupBy }));
475
- app.get('/api/users/:id', async (req) => Q.user(db, w(req.query), req.params.id));
476
- app.get('/api/runtime', async (req) => Q.runtime(db, w(req.query)));
477
- app.get('/api/runtime/view', async (req, reply) => req.query.service ? Q.runtimeView(db, w(req.query), { service: req.query.service, instance: req.query.instance || null }) : reply.code(400).send({ error: 'service required' }));
478
- app.get('/api/runtime/spike', async (req) => Q.runtimeSpike(db, { service: req.query.service || '', instance: req.query.instance, ts: Number(req.query.ts), windowMs: Number(req.query.windowMs) || 60000 }));
479
- app.get('/api/metrics', async (req) => Q.metricsList(db, w(req.query)));
480
- app.get('/api/metrics/:name', async (req) => Q.metricSeries(db, w(req.query), req.params.name));
481
- app.get('/api/releases', async (req) => Q.releases(db, w(req.query)));
482
- app.get('/api/releases/:service/:version', async (req, reply) => Q.releaseVerdict(db, req.params.service, req.params.version) ?? notFound(reply));
483
- app.get('/api/map', async (req) => Q.serviceMap(db, w(req.query)));
549
+ app.get('/api/logs', async (req) => await read('queries', 'logs', w(req.query), { level: req.query.level, q: req.query.q, traceId: req.query.traceId, before: req.query.before, limit: req.query.limit }));
550
+ app.get('/api/functions', async (req) => await read('queries', 'functions', w(req.query)));
551
+ app.get('/api/queries', async (req) => await read('queries', 'queries', w(req.query)));
552
+ app.get('/api/outbound', async (req) => await read('queries', 'outbound', w(req.query)));
553
+ app.get('/api/users', async (req) => await read('queries', 'users', w(req.query), { groupBy: req.query.groupBy }));
554
+ app.get('/api/users/:id', async (req) => await read('queries', 'user', w(req.query), req.params.id));
555
+ app.get('/api/runtime', async (req) => await read('queries', 'runtime', w(req.query)));
556
+ app.get('/api/runtime/view', async (req, reply) => req.query.service ? await read('queries', 'runtimeView', w(req.query), { service: req.query.service, instance: req.query.instance || null }) : reply.code(400).send({ error: 'service required' }));
557
+ app.get('/api/runtime/spike', async (req) => await read('queries', 'runtimeSpike', { service: req.query.service || '', instance: req.query.instance, ts: Number(req.query.ts), windowMs: Number(req.query.windowMs) || 60000 }));
558
+ app.get('/api/metrics', async (req) => await read('queries', 'metricsList', w(req.query)));
559
+ app.get('/api/metrics/:name', async (req) => await read('queries', 'metricSeries', w(req.query), req.params.name));
560
+ app.get('/api/releases', async (req) => await read('queries', 'releases', w(req.query)));
561
+ app.get('/api/releases/:service/:version', async (req, reply) => await read('queries', 'releaseVerdict', req.params.service, req.params.version) ?? notFound(reply));
562
+ app.get('/api/map', async (req) => await read('queries', 'serviceMap', w(req.query)));
484
563
  // ---------------------------------------------------------------- alerts
485
564
  const ruleRow = (r) => ({ ...r, ...toRule(r) });
486
565
  app.get('/api/alerts', async () => ({ types: RULE_TYPES, rules: db.all('SELECT * FROM alert_rules ORDER BY id').map(ruleRow) }));
@@ -942,12 +1021,12 @@ export async function createServer(opts = {}) {
942
1021
  app.addHook('onClose', async () => { for (const t of timers)
943
1022
  clearInterval(t); projects.close(); });
944
1023
  /** Retention for the current project: the plan's window, and on plans past 7 days, span trees of fast successes go at 7. */
945
- const runRetention = () => {
946
- historyTick(db, historyCfg());
1024
+ const runRetention = async () => {
1025
+ await read('history', 'historyTick', historyCfg());
947
1026
  const days = usage.retentionDays(config.retentionDays);
948
- retention(db, days);
1027
+ await read('maintenance', 'retention', days);
949
1028
  if (days > SPAN_TREE_DAYS && usage.plan().retentionDays != null)
950
- pruneSpanTrees(db);
1029
+ await read('maintenance', 'pruneSpanTrees');
951
1030
  };
952
1031
  // Background passes run once per project, each against its own database.
953
1032
  const perProject = (label, fn) => () => projects.each(fn, (slug, e) => log(`${label} [${slug}]: ${e.message}`));
@@ -960,10 +1039,10 @@ export async function createServer(opts = {}) {
960
1039
  every(config.ticketSyncMs, perProject('tickets', () => syncTickets(db, log)), 'tickets');
961
1040
  every(60000, perProject('status', () => runAutoIncidents(db, Date.now(), log)), 'status');
962
1041
  // Roll-ups first, so raw data is summarised before retention removes it.
963
- every(5 * 60000, perProject('history', () => historyTick(db, historyCfg())), 'history');
1042
+ every(5 * 60000, perProject('history', () => read('history', 'historyTick', historyCfg())), 'history');
964
1043
  every(3600e3, perProject('retention', () => runRetention()), 'retention');
965
1044
  // On first start after an upgrade, roll up the raw days already stored in one go.
966
- const first = setTimeout(perProject('history', () => historyTick(db, historyCfg(), Date.now(), Math.ceil(config.retentionDays * 24) + 2)), 1500);
1045
+ const first = setTimeout(perProject('history', () => read('history', 'historyTick', historyCfg(), Date.now(), Math.ceil(config.retentionDays * 24) + 2)), 1500);
967
1046
  first.unref();
968
1047
  timers.push(first);
969
1048
  return app;