openvibers/openvibe.vip Commits

VIP: request telemetry in its own table, 30-day retention (#58)

OP OpenVibers committed 29 days ago · dfb4729db4 · 4 files, +86 −2

Plan T1 step 10 (universal telemetry): this service now records its request telemetry using openvibe-sdk 0.46's process-wide collector, the same shape Network uses.

- **Migration** `NNNN_telemetry.sql` (expand): the `telemetry_samples` table from `telemetrySchema()`.
- **`server/app.js`** mounts `telemetryMiddleware` before any route. It does nothing until `init()`, so tests and tools that build the app are unaffected.
- **`server/index.js`** (production start):
  - `telemetry.init({ service, sink: createPgTelemetrySink(...) })` aggregates requests per route template, method and status class. Every minute (the singleton's own timer, `intervalMs: 60_000`) it writes one `http.request` sample per key plus the active-request, p95 and event-loop-lag gauges. `/shared`, health, readiness and `/metrics` produce no samples.
  - `startTelemetryRetention` deletes rows older than 14 days, a minute after start and then daily. At this interval and retention a service holds about 55k rows (about 15 MB with indexes); at 15 s and 30 days it would be about 125 MB, roughly 4.4 GB across the estate.
  - On stop, the retention stops and the collector flushes once before the database closes.
- **`test/telemetry.test.js`**:
  - checks that wiring in the source;
  - checks that five hits on one route flush as one sample (count 5) and that `/metrics` and `/shared` produce none;
  - checks that the migration's table works with the retention (only rows from the last 14 days are kept).

Changes

ddiff --git a/migrations/0004_telemetry.sql b/migrations/0004_telemetry.sql
nnew file mode 100644
iindex 0000000..14260fa
---- /dev/null
++++ b/migrations/0004_telemetry.sql
@@@ -0,0 +1,28 @@
++-- phase: expand
++-- Request telemetry (openvibe-sdk/telemetry telemetrySchema()): one row per aggregated sample, pruned after 30 days (server/index.js).
++CREATE TABLE IF NOT EXISTS telemetry_samples (
++ id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
++ at timestamptz NOT NULL,
++ service text NOT NULL,
++ project text,
++ subject text,
++ resource text,
++ provider text,
++ node text,
++ cell text,
++ region text,
++ operation text NOT NULL,
++ latency_ms double precision,
++ queue_delay_ms double precision,
++ ttfb_ms double precision,
++ throughput_per_second double precision,
++ bytes bigint,
++ status text,
++ cache_status text,
++ cost_estimate double precision,
++ route_epoch bigint,
++ trace_id text,
++ extra jsonb NOT NULL DEFAULT '{}'::jsonb
++);
++CREATE INDEX IF NOT EXISTS telemetry_samples_at_idx ON telemetry_samples (at);
++CREATE INDEX IF NOT EXISTS telemetry_samples_service_idx ON telemetry_samples (service, operation, at);
ddiff --git a/server/app.js b/server/app.js
iindex 79780eb..25aac2a 100644
---- a/server/app.js
++++ b/server/app.js
@@@ -72,6 +72,7 @@ async function createApp(opts = {}) {
// HTTP golden signals by route template, process metrics, release_info; GET /metrics answers
// direct loopback callers only (Track O). Gauges: outbox backlog and projection staleness.
const metrics = require('openvibe-shared/metrics').instrument(app, { service: 'vip', release: release.release });
++ app.use(require('openvibe-sdk/service').telemetryMiddleware); // request telemetry: a no-op until server/index.js calls telemetry.init()
metrics.registry.gauge({ name: 'vip_outbox_pending', help: 'Events waiting in the outbox', collect: async () => await outbox.outbox.pending() });
metrics.registry.gauge({
name: 'vip_projection_rows', help: 'Entitlement projection rows by freshness', labelNames: ['state'],
ddiff --git a/server/index.js b/server/index.js
iindex 6f1936e..c9221de 100644
---- a/server/index.js
++++ b/server/index.js
@@@ -10,7 +10,8 @@
*/
const { loadConfig } = require('./config');
const { createApp } = require('./app');
--const { gracefulStop } = require('openvibe-sdk/service');
++const { gracefulStop, telemetry } = require('openvibe-sdk/service');
++const { createPgTelemetrySink, startTelemetryRetention } = require('openvibe-sdk/telemetry');
const { startSubscriptions } = require('openvibe-sdk/account-data');
/**
@@@ -30,7 +31,7 @@ function createLifecycle({ server, app, timers = [], exit, signals, extra = [] }
() => { if (metrics && metrics.stop) metrics.stop(); },
...extra,
],
-- close: [() => domain.db.close()],
++ close: [async () => { if (app.locals.telemetryRetention) await app.locals.telemetryRetention.stop(); await telemetry.stop(); }, () => domain.db.close()],
});
}
@@@ -61,6 +62,10 @@ async function start() {
console.log(`[VIP] billing ${config.billing.url}; events relay ${outbox.enabled ? `→ ${config.events.url}` : 'off (outbox accumulates)'}; billing events ${config.events.webhookSecrets.length ? 'accepted' : 'not accepted (VIP_EVENTS_SECRET unset)'}`);
});
server.keepAliveTimeout = 65_000;
++ // Request telemetry (openvibe-sdk/service, plan T1): one aggregated sample per route template, method and status
++ // class each minute, stored in telemetry_samples; rows older than 14 days go daily.
++ telemetry.init({ service: 'vip', sink: createPgTelemetrySink({ db: domain.db, log: console }), skipPrefixes: ['/shared'], intervalMs: 60_000 });
++ app.locals.telemetryRetention = startTelemetryRetention({ db: domain.db, log: console, olderThanDays: 14 });
// The two account subscriptions at OpenVibe.Events (ADR-033), created when missing; off without EVENTS_URL,
// VIP_EVENTS_SECRET or the client secret. The billing.* ones stay scripts/subscribe.js's.
ddiff --git a/test/telemetry.test.js b/test/telemetry.test.js
nnew file mode 100644
iindex 0000000..f70fe24
---- /dev/null
++++ b/test/telemetry.test.js
@@@ -0,0 +1,50 @@
++'use strict';
++/**
++ * Request telemetry (openvibe-sdk/service, plan T1 step 10): app.js mounts the process-wide telemetryMiddleware (a no-op
++ * until init), server/index.js calls telemetry.init() for service 'vip' with a PostgreSQL sink, starts the 14-day
++ * retention and flushes on stop. Five hits on one route flush as ONE aggregated http.request sample; /metrics and
++ * /shared make none; the retention deletes only rows older than 14 days.
++ */
++const assert = require('assert');
++const fs = require('fs');
++const path = require('path');
++const { telemetry } = require('openvibe-sdk/service');
++const { pruneTelemetry } = require('openvibe-sdk/telemetry');
++const { boot } = require('./helpers/app');
++(async () => {
++ const read = (p) => fs.readFileSync(path.join(__dirname, '..', p), 'utf8');
++ assert.match(read('server/index.js'), /telemetry\.init\(\{ service: 'vip', sink: createPgTelemetrySink\(/, 'index.js starts the collector');
++ assert.match(read('server/index.js'), /startTelemetryRetention\(/, 'index.js starts the retention');
++ assert.match(read('server/index.js'), /[Rr]etention\.stop\(\); await telemetry\.stop\(\);/, 'the stop flushes');
++
++ const t = await boot();
++ const samples = [];
++ telemetry.init({ service: 'vip', sink: async (batch) => { samples.push(...batch); }, intervalMs: 3600e3 });
++ const requests = () => samples.filter((s) => s.operation === 'http.request');
++ try {
++ for (let i = 0; i < 5; i++) assert.strictEqual((await t.call('GET', '/', { token: null })).status, 200);
++ await telemetry.flush();
++ const hit = requests().filter((s) => s.resource === '/' && s.status === '2xx');
++ assert.strictEqual(hit.length, 1, JSON.stringify(requests()));
++ assert.strictEqual(hit[0].service, 'vip');
++ assert.strictEqual(hit[0].extra.count, 5);
++
++ samples.length = 0;
++ await await t.call('GET', '/metrics', { token: null });
++ await await t.call('GET', '/shared/navbar.js', { token: null });
++ await telemetry.flush();
++ assert.deepStrictEqual(requests(), [], '/metrics and /shared make no sample');
++
++ const db = t.domain.db;
++ await db.query('DELETE FROM telemetry_samples');
++ const insert = (days) => db.query("INSERT INTO telemetry_samples (at, service, operation) VALUES (now() - make_interval(days => $1), 'vip', 'http.request')", [days]);
++ await insert(20);
++ await insert(1);
++ assert.strictEqual(await pruneTelemetry({ db, olderThanDays: 14 }), 1);
++ assert.strictEqual((await db.query('SELECT count(*)::int AS n FROM telemetry_samples')).rows[0].n, 1);
++ console.log('telemetry ok');
++ } finally {
++ await telemetry.stop();
++ await t.close();
++ }
++})().catch((err) => { console.error(err); process.exit(1); });