openvibers/openvibe.coupons Commits

Coupons: request telemetry in its own table, 30-day retention (#62)

OP OpenVibers committed 29 days ago · 568049adf0 · 5 files, +96 −2

Plan T1 step 10 (universal telemetry): this service now records its request telemetry the way Blog and Network do, using openvibe-sdk 0.46.

- **Migration** `NNNN_telemetry.sql` (expand): the `telemetry_samples` table from `telemetrySchema()`.
- **`server/app.js`**: one `createHttpTelemetry` collector, which aggregates requests per route template, method and status class per 15-second flush (one `http.request` sample per key, not one row per request). It writes through `createPgTelemetrySink` into this service's own table. `/shared`, health, readiness and `/metrics` produce no samples.
- **`server/index.js`**:
  - Every 15 s a tick flushes the collector, which has no timer of its own (only `telemetry.init()` ticks).
  - `startTelemetryRetention` deletes rows older than 30 days, a minute after start and then daily.
  - On stop, the tick and the retention timers stop and the collector flushes once before the store closes.
- **Tests**:
  - `test/telemetry.test.js`: five home-page hits flush as one sample (template `/`, 2xx, count 5); `/metrics` and `/shared` produce none; the retention keeps only rows from the last 30 days.
  - The lifecycle test's expected close order now includes the flush.

Changes

ddiff --git a/migrations/0003_telemetry.sql b/migrations/0003_telemetry.sql
nnew file mode 100644
iindex 0000000..14260fa
---- /dev/null
++++ b/migrations/0003_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 1feb117..d67593a 100644
---- a/server/app.js
++++ b/server/app.js
@@@ -43,6 +43,8 @@ const { createWebhookRouter } = require('./events/consumer');
const PUBLIC_DIR = path.join(__dirname, '..', 'public');
const VERSION = require('../package.json').version;
++const { createHttpTelemetry } = require('openvibe-sdk/service');
++const { createPgTelemetrySink } = require('openvibe-sdk/telemetry');
/**
* opts: config, store, now (clock), fetchImpl, auth (an openvibe-sdk/sso client), jwks, log,
@@@ -108,6 +110,11 @@ async function createApp(opts = {}) {
require('./render/layout').setRelease(release.release);
const metrics = require('openvibe-shared/metrics').instrument(app, { service: 'coupons', release: release.release });
app.locals.metrics = metrics.registry;
++ // Request telemetry (openvibe-sdk/service, plan T1): one aggregated sample per route template, method and status
++ // class each flush, stored in this service's telemetry_samples table; /shared, health, readiness and /metrics make
++ // none. server/index.js flushes it every 15 s and on stop, and keeps the table to 30 days.
++ ctx.telemetry = createHttpTelemetry({ service: 'coupons', sink: opts.telemetrySink || createPgTelemetrySink({ db: store.db, log }), skipPrefixes: ['/shared'] });
++ app.use(ctx.telemetry.middleware());
app.locals.ctx = ctx;
// Per-actor limits (http/actor-limits.js) for the API and the page forms, counted once each router
// resolved req.viewer; the lookup, per-address and per-person limits stay.
ddiff --git a/server/index.js b/server/index.js
iindex 5b2ab5b..b0948f9 100644
---- a/server/index.js
++++ b/server/index.js
@@@ -7,6 +7,7 @@
*/
const { createApp } = require('./app');
const { gracefulStop } = require('openvibe-sdk/service');
++const { startTelemetryRetention } = require('openvibe-sdk/telemetry');
/**
* The process stop (openvibe-sdk/service, docs/service.md's 5 s family): the worker stops taking new
@@@ -18,7 +19,7 @@ function createLifecycle({ server, ctx, exit, signals }) {
return gracefulStop({
name: 'Coupons', server, deadlineExitCode: 0, exit, signals,
stop: [() => ctx.worker.stop()],
-- close: [() => ctx.outbox.stop(), () => ctx.store.close()],
++ close: [() => ctx.outbox.stop(), async () => { clearInterval(ctx.telemetryTick); if (ctx.retention) await ctx.retention.stop(); if (ctx.telemetry) await ctx.telemetry.stop(); }, () => ctx.store.close()],
});
}
@@@ -33,6 +34,12 @@ async function start() {
server.keepAliveTimeout = 65_000;
ctx.outbox.start();
ctx.worker.start();
++ // telemetry_samples rows older than 30 days go: a minute after start, then daily (openvibe-sdk/telemetry).
++ ctx.retention = startTelemetryRetention({ db: ctx.store.db, log: console });
++ // The request collector aggregates in memory and has no timer of its own (openvibe-sdk 0.46 createHttpTelemetry):
++ // this tick writes each 15-second interval's samples; the stop clears it and flushes once more.
++ ctx.telemetryTick = setInterval(() => { ctx.telemetry.flush().catch(() => {}); }, 15_000);
++ ctx.telemetryTick.unref();
createLifecycle({ server, ctx });
return { server, ctx };
ddiff --git a/test/helpers/boot.js b/test/helpers/boot.js
iindex 697982c..324feed 100644
---- a/test/helpers/boot.js
++++ b/test/helpers/boot.js
@@@ -42,7 +42,7 @@ async function boot(opts = {}) {
let built = null;
async function start() {
const config = configLib.load(env);
-- built = await createApp({ config, store: createStore(testdb.db, { now: clock.now }), now: clock.now, log: opts.log || quiet, limitsNow: opts.limitsNow, indexnow: opts.indexnow });
++ built = await createApp({ config, telemetrySink: opts.telemetrySink, store: createStore(testdb.db, { now: clock.now }), now: clock.now, log: opts.log || quiet, limitsNow: opts.limitsNow, indexnow: opts.indexnow });
try { await built.ctx.jwks.keys(); } catch { /* started without the key: readiness reports it */ }
server = await new Promise((resolve) => { const s = http.createServer(built.app); s.listen(0, '127.0.0.1', () => resolve(s)); });
t.base = `http://127.0.0.1:${server.address().port}`;
ddiff --git a/test/telemetry.test.js b/test/telemetry.test.js
nnew file mode 100644
iindex 0000000..4506af9
---- /dev/null
++++ b/test/telemetry.test.js
@@@ -0,0 +1,52 @@
++'use strict';
++/**
++ * Request telemetry (openvibe-sdk/service, plan T1 step 10): app.js builds one collector for service 'coupons' with a
++ * PostgreSQL sink, a page hit five times flushes as ONE aggregated http.request sample (route template, 2xx, count 5),
++ * /metrics and /shared files make none, and the 30-day retention deletes only older rows.
++ */
++const assert = require('assert');
++const { pruneTelemetry } = require('openvibe-sdk/telemetry');
++const { boot, check, done } = require('./helpers/boot');
++const fs = require('fs');
++const path = require('path');
++
++(async () => {
++ await check('index.js flushes the collector every 15 s and clears that tick before the last flush on stop', () => {
++ const index = fs.readFileSync(path.join(__dirname, '..', 'server', 'index.js'), 'utf8');
++ assert.match(index, /ctx\.telemetryTick = setInterval\(\(\) => \{ ctx\.telemetry\.flush\(\)/);
++ assert.match(index, /clearInterval\(ctx\.telemetryTick\); if \(ctx\.retention\) await ctx\.retention\.stop\(\); if \(ctx\.telemetry\) await ctx\.telemetry\.stop\(\);/);
++ });
++
++ const samples = [];
++ const t = await boot({ telemetrySink: async (batch) => { samples.push(...batch); } });
++ const requests = () => samples.filter((s) => s.operation === 'http.request');
++ try {
++ await check('five hits on the home page flush as one http.request sample: template, 2xx, count 5', async () => {
++ for (let i = 0; i < 5; i++) assert.strictEqual((await t.get('/')).status, 200);
++ await t.ctx.telemetry.flush();
++ const home = requests().filter((s) => s.resource === '/' && s.status === '2xx');
++ assert.strictEqual(home.length, 1, JSON.stringify(requests()));
++ assert.strictEqual(home[0].service, 'coupons');
++ assert.strictEqual(home[0].extra.count, 5);
++ });
++
++ await check('/metrics and a /shared file make no sample', async () => {
++ samples.length = 0;
++ await t.get('/metrics');
++ await t.get('/shared/navbar.js');
++ await t.ctx.telemetry.flush();
++ assert.deepStrictEqual(requests(), []);
++ });
++
++ await check('the table exists and the retention deletes rows older than 30 days, keeping newer ones', async () => {
++ const db = t.ctx.store.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), 'coupons', 'http.request')", [days]);
++ await insert(45);
++ await insert(1);
++ assert.strictEqual(await pruneTelemetry({ db }), 1);
++ assert.strictEqual((await db.query('SELECT count(*)::int AS n FROM telemetry_samples')).rows[0].n, 1);
++ });
++ } finally { await t.close(); }
++ done();
++})().catch((e) => { console.error(e); process.exit(1); });