openvibers/openvibe.space Commits
Space: request telemetry in its own table, 30-day retention (#55)
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);@@@ -72,6 +72,7 @@ async function createApp(opts = {}) {const proc = sharedMetrics.processMetrics(registry);sharedMetrics.releaseInfo(registry, { service: 'space', release: release.release });app.use(httpMetrics.middleware);++ app.use(require('openvibe-sdk/service').telemetryMiddleware); // request telemetry: a no-op until server/index.js calls telemetry.init()require('openvibe-shared/express-async').routeAsyncErrors(app);const metrics = { registry, http: httpMetrics, stop: proc.stop };app.locals.metrics = metrics.registry;@@@ -6,6 +6,8 @@*/const config = require('./config');const { createApp } = require('./app');++const { telemetry } = require('openvibe-sdk/service');++const { createPgTelemetrySink, startTelemetryRetention } = require('openvibe-sdk/telemetry');(async () => {// PostgreSQL first (migrations run as the owner); readiness reports the serving database.@@@ -16,6 +18,10 @@ const { createApp } = require('./app');console.log(`[Space] static hosting for staff; dynamic pages and spaces planned; the forum is on ${config.communityUrl}; identity via ${config.networkUrl}`);});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: 'space', sink: createPgTelemetrySink({ db: require('./db').getDb(), log: console }), skipPrefixes: ['/shared'], intervalMs: 60_000 });++ const telemetryRetention = startTelemetryRetention({ db: require('./db').getDb(), log: console, olderThanDays: 14 });app.locals.hosting.worker.start();app.locals.hosting.outbox.start();app.locals.hosting.billing.start(); // off unless SPACE_BILLING_INTERVAL_MS > 0@@@ -30,6 +36,7 @@ const { createApp } = require('./app');drainMs: 4000, deadlineMs: 5000, deadlineExitCode: 1,stop: [async () => { app.locals.hosting.worker.stop(); await app.locals.hosting.outbox.stop(); await app.locals.hosting.billing.stop(); }],close: [++ async () => { if (telemetryRetention) await telemetryRetention.stop(); await telemetry.stop(); },async () => {console.log('[Space] stopped');return await require('./db').closeDb();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 'space' 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: 'space', 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: 'space', 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.get('/')).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, 'space');++ assert.strictEqual(hit[0].extra.count, 5);++++ samples.length = 0;++ await await t.get('/metrics');++ await await t.get('/shared/navbar.js');++ 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), 'space', '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);
@@ -72,6 +72,7 @@ async function createApp(opts = {}) {
@@ -72,6 +72,7 @@ async function createApp(opts = {}) {
const proc = sharedMetrics.processMetrics(registry);
const proc = sharedMetrics.processMetrics(registry);
sharedMetrics.releaseInfo(registry, { service: 'space', release: release.release });
sharedMetrics.releaseInfo(registry, { service: 'space', release: release.release });
app.use(httpMetrics.middleware);
app.use(httpMetrics.middleware);
+ app.use(require('openvibe-sdk/service').telemetryMiddleware); // request telemetry: a no-op until server/index.js calls telemetry.init()
require('openvibe-shared/express-async').routeAsyncErrors(app);
require('openvibe-shared/express-async').routeAsyncErrors(app);
const metrics = { registry, http: httpMetrics, stop: proc.stop };
const metrics = { registry, http: httpMetrics, stop: proc.stop };
app.locals.metrics = metrics.registry;
app.locals.metrics = metrics.registry;
@@ -6,6 +6,8 @@
@@ -6,6 +6,8 @@
*/
*/
const config = require('./config');
const config = require('./config');
const { createApp } = require('./app');
const { createApp } = require('./app');
+const { telemetry } = require('openvibe-sdk/service');
+const { createPgTelemetrySink, startTelemetryRetention } = require('openvibe-sdk/telemetry');
(async () => {
(async () => {
// PostgreSQL first (migrations run as the owner); readiness reports the serving database.
// PostgreSQL first (migrations run as the owner); readiness reports the serving database.
@@ -16,6 +18,10 @@ const { createApp } = require('./app');
@@ -16,6 +18,10 @@ const { createApp } = require('./app');
console.log(`[Space] static hosting for staff; dynamic pages and spaces planned; the forum is on ${config.communityUrl}; identity via ${config.networkUrl}`);
console.log(`[Space] static hosting for staff; dynamic pages and spaces planned; the forum is on ${config.communityUrl}; identity via ${config.networkUrl}`);
});
});
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: 'space', sink: createPgTelemetrySink({ db: require('./db').getDb(), log: console }), skipPrefixes: ['/shared'], intervalMs: 60_000 });
+ const telemetryRetention = startTelemetryRetention({ db: require('./db').getDb(), log: console, olderThanDays: 14 });
app.locals.hosting.worker.start();
app.locals.hosting.worker.start();
app.locals.hosting.outbox.start();
app.locals.hosting.outbox.start();
app.locals.hosting.billing.start(); // off unless SPACE_BILLING_INTERVAL_MS > 0
app.locals.hosting.billing.start(); // off unless SPACE_BILLING_INTERVAL_MS > 0
@@ -30,6 +36,7 @@ const { createApp } = require('./app');
@@ -30,6 +36,7 @@ const { createApp } = require('./app');
drainMs: 4000, deadlineMs: 5000, deadlineExitCode: 1,
drainMs: 4000, deadlineMs: 5000, deadlineExitCode: 1,
stop: [async () => { app.locals.hosting.worker.stop(); await app.locals.hosting.outbox.stop(); await app.locals.hosting.billing.stop(); }],
stop: [async () => { app.locals.hosting.worker.stop(); await app.locals.hosting.outbox.stop(); await app.locals.hosting.billing.stop(); }],
close: [
close: [
+ async () => { if (telemetryRetention) await telemetryRetention.stop(); await telemetry.stop(); },
async () => {
async () => {
console.log('[Space] stopped');
console.log('[Space] stopped');
return await require('./db').closeDb();
return await require('./db').closeDb();
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 'space' 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: 'space', 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: 'space', 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.get('/')).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, 'space');
+ assert.strictEqual(hit[0].extra.count, 5);
+
+ samples.length = 0;
+ await await t.get('/metrics');
+ await await t.get('/shared/navbar.js');
+ 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), 'space', '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); });