openvibers/openvibe.bot Commits
Bot: request telemetry in its own table, 30-day retention (#125)
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);@@@ -111,6 +111,7 @@ function createApp(opts = {}) {const gauges = registerBotGauges(registry, { db, hub, now, log });app.get('/metrics', (req, res, next) => (isLoopbackDirect(req) ? gauges.refresh().then(() => next(), () => next()) : next()));const metrics = require('openvibe-shared/metrics').instrument(app, { service: 'bot', release: release.release, registry });++ app.use(require('openvibe-sdk/service').telemetryMiddleware); // request telemetry: a no-op until server/index.js calls telemetry.init()app.use(http.middleware());app.use((req, res, next) => {@@@ -18,7 +18,8 @@ const { openDb, migrate } = require('./db');const { seedProfiles } = require('./profiles');const { createApp } = require('./app');const { createValkey } = require('openvibe-sdk/valkey');--const { gracefulStop } = require('openvibe-sdk/service');++const { gracefulStop, telemetry } = require('openvibe-sdk/service');++const { createPgTelemetrySink, startTelemetryRetention } = require('openvibe-sdk/telemetry');const { startSubscriptions, TOPICS } = require('openvibe-sdk/account-data');const { createRegistry } = require('openvibe-shared/metrics');@@@ -54,6 +55,10 @@ async function main() {console.log(`[Bot] profiles from server/profiles; events relay ${outbox.enabled ? `→ ${config.events.url}` : 'off (outbox accumulates)'}; usage relay ${usage.enabled ? `→ ${config.billing.url}` : 'off (readings wait)'}; heartbeat ${config.device.heartbeatMs} ms, offline after ${config.device.heartbeatMs * config.device.offlineMisses + config.device.offlineGraceMs} ms`);});server.keepAliveTimeout = 65_000;++ // Request telemetry (openvibe-sdk/service, plan T1): one aggregated sample per route template, method and status++ // class each 15 s, stored in this service's telemetry_samples table; rows older than 30 days go daily.++ telemetry.init({ service: 'bot', sink: createPgTelemetrySink({ db: db, log: console }), skipPrefixes: ['/shared'] });++ const telemetryRetention = startTelemetryRetention({ db: db, log: console });server.on('upgrade', (req, socket, head) => hub.handleUpgrade(req, socket, head));// The robots whose profile's driver is `sim` get their in-process device back (server/sim); the ones whose// driver is `onvif` get their configured camera attached server-side (server/onvif).@@@ -95,6 +100,7 @@ async function main() {() => { if (subscriptions) subscriptions.stop(); },],close: [++ async () => { if (telemetryRetention) await telemetryRetention.stop(); await telemetry.stop(); },() => db.close().catch(() => {}),() => valkey && valkey.close().catch(() => {}),],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 'bot' with a PostgreSQL sink, starts the 30-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 30 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: 'bot', 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: 'bot', 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, 'bot');++ 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.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), 'bot', '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);++ 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);
@@ -111,6 +111,7 @@ function createApp(opts = {}) {
@@ -111,6 +111,7 @@ function createApp(opts = {}) {
const gauges = registerBotGauges(registry, { db, hub, now, log });
const gauges = registerBotGauges(registry, { db, hub, now, log });
app.get('/metrics', (req, res, next) => (isLoopbackDirect(req) ? gauges.refresh().then(() => next(), () => next()) : next()));
app.get('/metrics', (req, res, next) => (isLoopbackDirect(req) ? gauges.refresh().then(() => next(), () => next()) : next()));
const metrics = require('openvibe-shared/metrics').instrument(app, { service: 'bot', release: release.release, registry });
const metrics = require('openvibe-shared/metrics').instrument(app, { service: 'bot', release: release.release, registry });
+ app.use(require('openvibe-sdk/service').telemetryMiddleware); // request telemetry: a no-op until server/index.js calls telemetry.init()
app.use(http.middleware());
app.use(http.middleware());
app.use((req, res, next) => {
app.use((req, res, next) => {
@@ -18,7 +18,8 @@ const { openDb, migrate } = require('./db');
@@ -18,7 +18,8 @@ const { openDb, migrate } = require('./db');
const { seedProfiles } = require('./profiles');
const { seedProfiles } = require('./profiles');
const { createApp } = require('./app');
const { createApp } = require('./app');
const { createValkey } = require('openvibe-sdk/valkey');
const { createValkey } = require('openvibe-sdk/valkey');
-const { gracefulStop } = require('openvibe-sdk/service');
+const { gracefulStop, telemetry } = require('openvibe-sdk/service');
+const { createPgTelemetrySink, startTelemetryRetention } = require('openvibe-sdk/telemetry');
const { startSubscriptions, TOPICS } = require('openvibe-sdk/account-data');
const { startSubscriptions, TOPICS } = require('openvibe-sdk/account-data');
const { createRegistry } = require('openvibe-shared/metrics');
const { createRegistry } = require('openvibe-shared/metrics');
@@ -54,6 +55,10 @@ async function main() {
@@ -54,6 +55,10 @@ async function main() {
console.log(`[Bot] profiles from server/profiles; events relay ${outbox.enabled ? `→ ${config.events.url}` : 'off (outbox accumulates)'}; usage relay ${usage.enabled ? `→ ${config.billing.url}` : 'off (readings wait)'}; heartbeat ${config.device.heartbeatMs} ms, offline after ${config.device.heartbeatMs * config.device.offlineMisses + config.device.offlineGraceMs} ms`);
console.log(`[Bot] profiles from server/profiles; events relay ${outbox.enabled ? `→ ${config.events.url}` : 'off (outbox accumulates)'}; usage relay ${usage.enabled ? `→ ${config.billing.url}` : 'off (readings wait)'}; heartbeat ${config.device.heartbeatMs} ms, offline after ${config.device.heartbeatMs * config.device.offlineMisses + config.device.offlineGraceMs} ms`);
});
});
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 15 s, stored in this service's telemetry_samples table; rows older than 30 days go daily.
+ telemetry.init({ service: 'bot', sink: createPgTelemetrySink({ db: db, log: console }), skipPrefixes: ['/shared'] });
+ const telemetryRetention = startTelemetryRetention({ db: db, log: console });
server.on('upgrade', (req, socket, head) => hub.handleUpgrade(req, socket, head));
server.on('upgrade', (req, socket, head) => hub.handleUpgrade(req, socket, head));
// The robots whose profile's driver is `sim` get their in-process device back (server/sim); the ones whose
// The robots whose profile's driver is `sim` get their in-process device back (server/sim); the ones whose
// driver is `onvif` get their configured camera attached server-side (server/onvif).
// driver is `onvif` get their configured camera attached server-side (server/onvif).
@@ -95,6 +100,7 @@ async function main() {
@@ -95,6 +100,7 @@ async function main() {
() => { if (subscriptions) subscriptions.stop(); },
() => { if (subscriptions) subscriptions.stop(); },
],
],
close: [
close: [
+ async () => { if (telemetryRetention) await telemetryRetention.stop(); await telemetry.stop(); },
() => db.close().catch(() => {}),
() => db.close().catch(() => {}),
() => valkey && valkey.close().catch(() => {}),
() => valkey && valkey.close().catch(() => {}),
],
],
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 'bot' with a PostgreSQL sink, starts the 30-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 30 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: 'bot', 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: 'bot', 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, 'bot');
+ 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.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), 'bot', '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);
+ console.log('telemetry ok');
+ } finally {
+ await telemetry.stop();
+ await t.close();
+ }
+})().catch((err) => { console.error(err); process.exit(1); });