openvibers/openvibe.host Commits
Host: request telemetry in its own table, 30-day retention (#110)
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);@@@ -93,6 +93,7 @@ async function createApp(opts = {}) {app.locals.metrics = registry;app.locals.ctx = ctx;app.use(sharedMetrics.httpMetrics(registry).middleware);++ app.use(require('openvibe-sdk/service').telemetryMiddleware); // request telemetry: a no-op until server/index.js calls telemetry.init()const catalogHost = new URL(config.baseUrl).hostname.toLowerCase();app.use((req, res, next) => {let hostname;@@@ -2,7 +2,8 @@/** OpenVibe.Host catalog service entry point. */const { createApp } = require('./app');--const { gracefulStop } = require('openvibe-sdk/service');++const { gracefulStop, telemetry } = require('openvibe-sdk/service');++const { createPgTelemetrySink, startTelemetryRetention } = require('openvibe-sdk/telemetry');async function main() {const { app, ctx } = await createApp();@@@ -13,6 +14,10 @@ const server = app.listen(config.port, config.host, () => {console.log(`[Host] events relay ${ctx.outbox.enabled ? `on → ${config.events.url}` : 'off (events wait in event_outbox)'}; worker ${config.worker.enabled ? 'on' : 'off'}`);});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 this service's telemetry_samples table; rows older than 14 days go daily.++telemetry.init({ service: 'host', sink: createPgTelemetrySink({ db: ctx.store.db, log: console }), skipPrefixes: ['/shared'], intervalMs: 60_000 });++const telemetryRetention = startTelemetryRetention({ db: ctx.store.db, log: console, olderThanDays: 14 });server.requestTimeout = 30_000;ctx.outbox.start();ctx.worker.start();@@@ -28,6 +33,7 @@ const { stop } = gracefulStop({close: [() => ctx.outbox.stop(),() => ctx.stopMetrics(),++ async () => { if (telemetryRetention) await telemetryRetention.stop(); await telemetry.stop(); },() => ctx.store.close(),],drainMs: 4000,nnew file mode 100644@@@ -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 'host' 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/boot');++(async () => {++ const read = (p) => fs.readFileSync(path.join(__dirname, '..', p), 'utf8');++ assert.match(read('server/index.js'), /telemetry\.init\(\{ service: 'host', 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: 'host', 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.api('GET', '/catalog')).status, 200);++ await telemetry.flush();++ const hit = requests().filter((s) => s.resource === '/catalog/' && s.status === '2xx');++ assert.strictEqual(hit.length, 1, JSON.stringify(requests()));++ assert.strictEqual(hit[0].service, 'host');++ assert.strictEqual(hit[0].extra.count, 5);++++ samples.length = 0;++ await await t.api('GET', '/metrics');++ await await t.api('GET', '/shared/navbar.js');++ await telemetry.flush();++ assert.deepStrictEqual(requests(), [], '/metrics and /shared make no sample');++++ 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), 'host', '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); });
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);
@@ -93,6 +93,7 @@ async function createApp(opts = {}) {
@@ -93,6 +93,7 @@ async function createApp(opts = {}) {
app.locals.metrics = registry;
app.locals.metrics = registry;
app.locals.ctx = ctx;
app.locals.ctx = ctx;
app.use(sharedMetrics.httpMetrics(registry).middleware);
app.use(sharedMetrics.httpMetrics(registry).middleware);
+ app.use(require('openvibe-sdk/service').telemetryMiddleware); // request telemetry: a no-op until server/index.js calls telemetry.init()
const catalogHost = new URL(config.baseUrl).hostname.toLowerCase();
const catalogHost = new URL(config.baseUrl).hostname.toLowerCase();
app.use((req, res, next) => {
app.use((req, res, next) => {
let hostname;
let hostname;
@@ -2,7 +2,8 @@
@@ -2,7 +2,8 @@
/** OpenVibe.Host catalog service entry point. */
/** OpenVibe.Host catalog service entry point. */
const { createApp } = require('./app');
const { createApp } = require('./app');
-const { gracefulStop } = require('openvibe-sdk/service');
+const { gracefulStop, telemetry } = require('openvibe-sdk/service');
+const { createPgTelemetrySink, startTelemetryRetention } = require('openvibe-sdk/telemetry');
async function main() {
async function main() {
const { app, ctx } = await createApp();
const { app, ctx } = await createApp();
@@ -13,6 +14,10 @@ const server = app.listen(config.port, config.host, () => {
@@ -13,6 +14,10 @@ const server = app.listen(config.port, config.host, () => {
console.log(`[Host] events relay ${ctx.outbox.enabled ? `on → ${config.events.url}` : 'off (events wait in event_outbox)'}; worker ${config.worker.enabled ? 'on' : 'off'}`);
console.log(`[Host] events relay ${ctx.outbox.enabled ? `on → ${config.events.url}` : 'off (events wait in event_outbox)'}; worker ${config.worker.enabled ? 'on' : 'off'}`);
});
});
server.keepAliveTimeout = 65_000;
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 this service's telemetry_samples table; rows older than 14 days go daily.
+telemetry.init({ service: 'host', sink: createPgTelemetrySink({ db: ctx.store.db, log: console }), skipPrefixes: ['/shared'], intervalMs: 60_000 });
+const telemetryRetention = startTelemetryRetention({ db: ctx.store.db, log: console, olderThanDays: 14 });
server.requestTimeout = 30_000;
server.requestTimeout = 30_000;
ctx.outbox.start();
ctx.outbox.start();
ctx.worker.start();
ctx.worker.start();
@@ -28,6 +33,7 @@ const { stop } = gracefulStop({
@@ -28,6 +33,7 @@ const { stop } = gracefulStop({
close: [
close: [
() => ctx.outbox.stop(),
() => ctx.outbox.stop(),
() => ctx.stopMetrics(),
() => ctx.stopMetrics(),
+ async () => { if (telemetryRetention) await telemetryRetention.stop(); await telemetry.stop(); },
() => ctx.store.close(),
() => ctx.store.close(),
],
],
drainMs: 4000,
drainMs: 4000,
new file mode 100644
new file mode 100644
@@ -0,0 +1,50 @@
@@ -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 'host' 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/boot');
+(async () => {
+ const read = (p) => fs.readFileSync(path.join(__dirname, '..', p), 'utf8');
+ assert.match(read('server/index.js'), /telemetry\.init\(\{ service: 'host', 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: 'host', 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.api('GET', '/catalog')).status, 200);
+ await telemetry.flush();
+ const hit = requests().filter((s) => s.resource === '/catalog/' && s.status === '2xx');
+ assert.strictEqual(hit.length, 1, JSON.stringify(requests()));
+ assert.strictEqual(hit[0].service, 'host');
+ assert.strictEqual(hit[0].extra.count, 5);
+
+ samples.length = 0;
+ await await t.api('GET', '/metrics');
+ await await t.api('GET', '/shared/navbar.js');
+ await telemetry.flush();
+ assert.deepStrictEqual(requests(), [], '/metrics and /shared make no sample');
+
+ 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), 'host', '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); });