openvibers/openvibe.events Commits

Events: request telemetry in its own table, 30-day retention (#85)

OP OpenVibers committed 29 days ago · 032eb9f033 · 5 files, +87 −3

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/0009_telemetry.sql b/migrations/0009_telemetry.sql
nnew file mode 100644
iindex 0000000..14260fa
---- /dev/null
++++ b/migrations/0009_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 88b5d3c..d78c422 100644
---- a/server/app.js
++++ b/server/app.js
@@@ -29,6 +29,7 @@ function createApp({ config, store, auth, keys, worker, realtime, metrics, dnsLo
// HTTP golden signals by route template + GET /metrics (direct loopback callers only). An SSE
// connection is a session, not a request, so it is counted by events_realtime_connections instead.
const instrumented = instrument(app, { service: 'events', release: release.release, registry: metrics && metrics.registry, skip: (req) => req.path === '/realtime/stream' });
++ app.use(require('openvibe-sdk/service').telemetryMiddleware); // request telemetry: a no-op until server/index.js calls telemetry.init()
app.use(http.middleware());
// GET /release.json (ADR-016) and POST /release-metrics (open tabs' update reports into /metrics).
release.mount(app, { registry: instrumented.registry });
ddiff --git a/server/index.js b/server/index.js
iindex 875013b..4368e7e 100644
---- a/server/index.js
++++ b/server/index.js
@@@ -22,7 +22,8 @@ const { createGuardedPost } = require('./egress');
const { createBillingReadings } = require('./billing');
const { createIndexNow } = require('openvibe-shared/indexnow');
const indexnowNotify = require('./indexnow-notify');
--const { gracefulStop } = require('openvibe-sdk/service');
++const { gracefulStop, telemetry } = require('openvibe-sdk/service');
++const { createPgTelemetrySink, startTelemetryRetention } = require('openvibe-sdk/telemetry');
async function start({
config, db: givenDb = null, clock = { now: () => Date.now() }, fetchImpl = globalThis.fetch, deliveryFetch = fetchImpl,
@@@ -166,7 +167,11 @@ if (require.main === module) {
// SIGTERM/SIGINT (openvibe-sdk/service, docs/service.md's handles family): requests in flight get 8 s,
// then handles.close() (the timers stopped, the carriers/realtime/worker stopped, the server closed, the
// database closed; a rejection exits 1); past 10 s the process exits 1.
-- gracefulStop({ name: 'events', server: handles.server, handles, drainMs: 8000, deadlineMs: 10000 });
++ // Request telemetry (openvibe-sdk/service, plan T1): one aggregated sample per route template, method and status
++ // class each minute, stored in this service's telemetry_samples table; rows older than 14 days go daily.
++ telemetry.init({ service: 'events', sink: createPgTelemetrySink({ db: handles.db, log: console }), skipPrefixes: ['/shared'], intervalMs: 60_000 });
++ const telemetryRetention = startTelemetryRetention({ db: handles.db, log: console, olderThanDays: 14 });
++ gracefulStop({ name: 'events', server: handles.server, handles, drainMs: 8000, deadlineMs: 10000, stop: [async () => { if (telemetryRetention) await telemetryRetention.stop(); await telemetry.stop(); }] });
}).catch((err) => {
console.error(`[events] failed to start: ${err.stack || err}`);
process.exit(1);
ddiff --git a/test/service-kit.test.js b/test/service-kit.test.js
iindex fc1c976..5ccc77d 100644
---- a/test/service-kit.test.js
++++ b/test/service-kit.test.js
@@@ -18,7 +18,7 @@ const quiet = { log() {}, warn() {}, error() {} };
const source = fs.readFileSync(path.join(__dirname, '../server/index.js'), 'utf8');
t("server/index.js imports gracefulStop from openvibe-sdk/service and owns no signal handler", () => {
-- assert.match(source, /const \{ gracefulStop \} = require\('openvibe-sdk\/service'\)/);
++ assert.match(source, /const \{ gracefulStop(, [A-Za-z]+)* \} = require\('openvibe-sdk\/service'\)/);
assert.doesNotMatch(source, /process\.on\('SIGTERM'/);
assert.doesNotMatch(source, /process\.on\('SIGINT'/);
assert.doesNotMatch(source, /setTimeout\(\(\) => process\.exit\(1\), 10000\)/, 'the old 10 s exit-1 timer is gone');
ddiff --git a/test/telemetry.test.js b/test/telemetry.test.js
nnew file mode 100644
iindex 0000000..05f6427
---- /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 'events' 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, request } = require('./helpers');
++(async () => {
++ const read = (p) => fs.readFileSync(path.join(__dirname, '..', p), 'utf8');
++ assert.match(read('server/index.js'), /telemetry\.init\(\{ service: 'events', 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: 'events', 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 request(t.base, 'GET', '/')).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, 'events');
++ assert.strictEqual(hit[0].extra.count, 5);
++
++ samples.length = 0;
++ await await request(t.base, 'GET', '/metrics');
++ await await request(t.base, 'GET', '/shared/navbar.js');
++ await telemetry.flush();
++ assert.deepStrictEqual(requests(), [], '/metrics and /shared make no sample');
++
++ const db = t.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), 'events', '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.stop || t.close)();
++ }
++})().catch((err) => { console.error(err); process.exit(1); });