openvibers/openvibe.tips Commits
Tips: request telemetry in its own table, 30-day retention (#58)
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);@@@ -80,6 +80,9 @@ function createApp(opts = {}) {const metrics = require('openvibe-shared/metrics').instrument(app, {service: 'tips', release: release.release, registry, skip: (req) => /^\/overlay\/[^/]+\/events$/.test(req.path),});++ // Request telemetry (openvibe-sdk/service): a no-op until server/index.js calls telemetry.init(); an overlay's event++ // stream lasts as long as the overlay is open, so it is not a request latency (as for the metrics above).++ { const { telemetry } = require('openvibe-sdk/service'); app.use((req, res, next) => (/^\/overlay\/[^/]+\/events$/.test(req.path) ? next() : telemetry.middleware(req, res, next))); }app.use(http.middleware());app.use((req, res, next) => {res.setHeader('X-Content-Type-Options', 'nosniff');@@@ -21,7 +21,8 @@ const { openDb, migrate } = require('./db');const { createApp } = require('./app');const { createValkey } = require('openvibe-sdk/valkey');const { createRegistry } = require('openvibe-shared/metrics');--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');/**@@@ -41,7 +42,7 @@ function createLifecycle({ server, app, timers = [], exit, signals, extra = [] }() => outbox.stop(),...extra,],-- close: [() => db.close(), () => { if (valkey) return valkey.close(); }],++ close: [async () => { if (app.locals.telemetryRetention) await app.locals.telemetryRetention.stop(); await telemetry.stop(); }, () => db.close(), () => { if (valkey) return valkey.close(); }],});}@@@ -73,6 +74,10 @@ async function start() {console.log(`[Tips] billing ${config.billing.url}; chat adapter ${config.chat.adapter}; events relay ${outbox.enabled ? `→ ${config.events.url}` : 'off (outbox accumulates)'}; billing events ${config.events.webhookSecrets.length ? 'accepted' : 'not accepted (TIPS_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: 'tips', sink: createPgTelemetrySink({ db: db, log: console }), skipPrefixes: ['/shared'], intervalMs: 60_000 });++ app.locals.telemetryRetention = startTelemetryRetention({ db: db, log: console, olderThanDays: 14 });// The two account subscriptions at OpenVibe.Events (ADR-033), created when missing; off without EVENTS_URL,// TIPS_EVENTS_SECRET or the client secret. The billing.* ones stay scripts/subscribe.js's.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 'tips' 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: 'tips', 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: 'tips', 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, 'tips');++ 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), 'tips', '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);
@@ -80,6 +80,9 @@ function createApp(opts = {}) {
@@ -80,6 +80,9 @@ function createApp(opts = {}) {
const metrics = require('openvibe-shared/metrics').instrument(app, {
const metrics = require('openvibe-shared/metrics').instrument(app, {
service: 'tips', release: release.release, registry, skip: (req) => /^\/overlay\/[^/]+\/events$/.test(req.path),
service: 'tips', release: release.release, registry, skip: (req) => /^\/overlay\/[^/]+\/events$/.test(req.path),
});
});
+ // Request telemetry (openvibe-sdk/service): a no-op until server/index.js calls telemetry.init(); an overlay's event
+ // stream lasts as long as the overlay is open, so it is not a request latency (as for the metrics above).
+ { const { telemetry } = require('openvibe-sdk/service'); app.use((req, res, next) => (/^\/overlay\/[^/]+\/events$/.test(req.path) ? next() : telemetry.middleware(req, res, next))); }
app.use(http.middleware());
app.use(http.middleware());
app.use((req, res, next) => {
app.use((req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Content-Type-Options', 'nosniff');
@@ -21,7 +21,8 @@ const { openDb, migrate } = require('./db');
@@ -21,7 +21,8 @@ const { openDb, migrate } = require('./db');
const { createApp } = require('./app');
const { createApp } = require('./app');
const { createValkey } = require('openvibe-sdk/valkey');
const { createValkey } = require('openvibe-sdk/valkey');
const { createRegistry } = require('openvibe-shared/metrics');
const { createRegistry } = require('openvibe-shared/metrics');
-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');
const { startSubscriptions } = require('openvibe-sdk/account-data');
/**
/**
@@ -41,7 +42,7 @@ function createLifecycle({ server, app, timers = [], exit, signals, extra = [] }
@@ -41,7 +42,7 @@ function createLifecycle({ server, app, timers = [], exit, signals, extra = [] }
() => outbox.stop(),
() => outbox.stop(),
...extra,
...extra,
],
],
- close: [() => db.close(), () => { if (valkey) return valkey.close(); }],
+ close: [async () => { if (app.locals.telemetryRetention) await app.locals.telemetryRetention.stop(); await telemetry.stop(); }, () => db.close(), () => { if (valkey) return valkey.close(); }],
});
});
}
}
@@ -73,6 +74,10 @@ async function start() {
@@ -73,6 +74,10 @@ async function start() {
console.log(`[Tips] billing ${config.billing.url}; chat adapter ${config.chat.adapter}; events relay ${outbox.enabled ? `→ ${config.events.url}` : 'off (outbox accumulates)'}; billing events ${config.events.webhookSecrets.length ? 'accepted' : 'not accepted (TIPS_EVENTS_SECRET unset)'}`);
console.log(`[Tips] billing ${config.billing.url}; chat adapter ${config.chat.adapter}; events relay ${outbox.enabled ? `→ ${config.events.url}` : 'off (outbox accumulates)'}; billing events ${config.events.webhookSecrets.length ? 'accepted' : 'not accepted (TIPS_EVENTS_SECRET unset)'}`);
});
});
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 telemetry_samples; rows older than 14 days go daily.
+ telemetry.init({ service: 'tips', sink: createPgTelemetrySink({ db: db, log: console }), skipPrefixes: ['/shared'], intervalMs: 60_000 });
+ app.locals.telemetryRetention = startTelemetryRetention({ db: db, log: console, olderThanDays: 14 });
// The two account subscriptions at OpenVibe.Events (ADR-033), created when missing; off without EVENTS_URL,
// The two account subscriptions at OpenVibe.Events (ADR-033), created when missing; off without EVENTS_URL,
// TIPS_EVENTS_SECRET or the client secret. The billing.* ones stay scripts/subscribe.js's.
// TIPS_EVENTS_SECRET or the client secret. The billing.* ones stay scripts/subscribe.js's.
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 'tips' 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: 'tips', 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: 'tips', 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, 'tips');
+ 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), 'tips', '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); });