openvibers/openvibe.coupons Commits
Coupons: request telemetry in its own table, 30-day retention (#62)
Changes
nnew file mode 100644@@@ -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);@@@ -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.@@@ -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 };@@@ -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}`;nnew file mode 100644@@@ -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); });
new file mode 100644
new file mode 100644
@@ -0,0 +1,28 @@
@@ -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);
@@ -43,6 +43,8 @@ const { createWebhookRouter } = require('./events/consumer');
@@ -43,6 +43,8 @@ const { createWebhookRouter } = require('./events/consumer');
const PUBLIC_DIR = path.join(__dirname, '..', 'public');
const PUBLIC_DIR = path.join(__dirname, '..', 'public');
const VERSION = require('../package.json').version;
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,
* opts: config, store, now (clock), fetchImpl, auth (an openvibe-sdk/sso client), jwks, log,
@@ -108,6 +110,11 @@ async function createApp(opts = {}) {
@@ -108,6 +110,11 @@ async function createApp(opts = {}) {
require('./render/layout').setRelease(release.release);
require('./render/layout').setRelease(release.release);
const metrics = require('openvibe-shared/metrics').instrument(app, { service: 'coupons', release: release.release });
const metrics = require('openvibe-shared/metrics').instrument(app, { service: 'coupons', release: release.release });
app.locals.metrics = metrics.registry;
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;
app.locals.ctx = ctx;
// Per-actor limits (http/actor-limits.js) for the API and the page forms, counted once each router
// 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.
// resolved req.viewer; the lookup, per-address and per-person limits stay.
@@ -7,6 +7,7 @@
@@ -7,6 +7,7 @@
*/
*/
const { createApp } = require('./app');
const { createApp } = require('./app');
const { gracefulStop } = require('openvibe-sdk/service');
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
* 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 }) {
@@ -18,7 +19,7 @@ function createLifecycle({ server, ctx, exit, signals }) {
return gracefulStop({
return gracefulStop({
name: 'Coupons', server, deadlineExitCode: 0, exit, signals,
name: 'Coupons', server, deadlineExitCode: 0, exit, signals,
stop: [() => ctx.worker.stop()],
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() {
@@ -33,6 +34,12 @@ async function start() {
server.keepAliveTimeout = 65_000;
server.keepAliveTimeout = 65_000;
ctx.outbox.start();
ctx.outbox.start();
ctx.worker.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 });
createLifecycle({ server, ctx });
return { server, ctx };
return { server, ctx };
@@ -42,7 +42,7 @@ async function boot(opts = {}) {
@@ -42,7 +42,7 @@ async function boot(opts = {}) {
let built = null;
let built = null;
async function start() {
async function start() {
const config = configLib.load(env);
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 */ }
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)); });
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}`;
t.base = `http://127.0.0.1:${server.address().port}`;
new file mode 100644
new file mode 100644
@@ -0,0 +1,52 @@
@@ -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); });