diff --git a/package-lock.json b/package-lock.json index c0c335f..c2450e7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,6 +14,7 @@ "fast-xml-parser": "^4.5.1", "node-cron": "^3.0.3", "openai": "^4.86.2", + "pg": "^8.11.3", "rss-parser": "^3.13.0", "slugify": "^1.6.6", "winston": "^3.17.0" @@ -2443,6 +2444,95 @@ "node": ">=8" } }, + "node_modules/pg": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/pg/-/pg-8.20.0.tgz", + "integrity": "sha512-ldhMxz2r8fl/6QkXnBD3CR9/xg694oT6DZQ2s6c/RI28OjtSOpxnPrUCGOBJ46RCUxcWdx3p6kw/xnDHjKvaRA==", + "license": "MIT", + "dependencies": { + "pg-connection-string": "^2.12.0", + "pg-pool": "^3.13.0", + "pg-protocol": "^1.13.0", + "pg-types": "2.2.0", + "pgpass": "1.0.5" + }, + "engines": { + "node": ">= 16.0.0" + }, + "optionalDependencies": { + "pg-cloudflare": "^1.3.0" + }, + "peerDependencies": { + "pg-native": ">=3.0.1" + }, + "peerDependenciesMeta": { + "pg-native": { + "optional": true + } + } + }, + "node_modules/pg-cloudflare": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.3.0.tgz", + "integrity": "sha512-6lswVVSztmHiRtD6I8hw4qP/nDm1EJbKMRhf3HCYaqud7frGysPv7FYJ5noZQdhQtN2xJnimfMtvQq21pdbzyQ==", + "license": "MIT", + "optional": true + }, + "node_modules/pg-connection-string": { + "version": "2.12.0", + "resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.12.0.tgz", + "integrity": "sha512-U7qg+bpswf3Cs5xLzRqbXbQl85ng0mfSV/J0nnA31MCLgvEaAo7CIhmeyrmJpOr7o+zm0rXK+hNnT5l9RHkCkQ==", + "license": "MIT" + }, + "node_modules/pg-int8": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz", + "integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==", + "license": "ISC", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/pg-pool": { + "version": "3.13.0", + "resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.13.0.tgz", + "integrity": "sha512-gB+R+Xud1gLFuRD/QgOIgGOBE2KCQPaPwkzBBGC9oG69pHTkhQeIuejVIk3/cnDyX39av2AxomQiyPT13WKHQA==", + "license": "MIT", + "peerDependencies": { + "pg": ">=8.0" + } + }, + "node_modules/pg-protocol": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.13.0.tgz", + "integrity": "sha512-zzdvXfS6v89r6v7OcFCHfHlyG/wvry1ALxZo4LqgUoy7W9xhBDMaqOuMiF3qEV45VqsN6rdlcehHrfDtlCPc8w==", + "license": "MIT" + }, + "node_modules/pg-types": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz", + "integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==", + "license": "MIT", + "dependencies": { + "pg-int8": "1.0.1", + "postgres-array": "~2.0.0", + "postgres-bytea": "~1.0.0", + "postgres-date": "~1.0.4", + "postgres-interval": "^1.1.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/pgpass": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz", + "integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==", + "license": "MIT", + "dependencies": { + "split2": "^4.1.0" + } + }, "node_modules/picomatch": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", @@ -2456,6 +2546,45 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/postgres-array": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz", + "integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/postgres-bytea": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz", + "integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/postgres-date": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz", + "integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/postgres-interval": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz", + "integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==", + "license": "MIT", + "dependencies": { + "xtend": "^4.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/prelude-ls": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", @@ -2759,6 +2888,15 @@ "node": ">=8.0.0" } }, + "node_modules/split2": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", + "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==", + "license": "ISC", + "engines": { + "node": ">= 10.x" + } + }, "node_modules/stack-trace": { "version": "0.0.10", "resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz", @@ -3184,6 +3322,15 @@ "node": ">=4.0" } }, + "node_modules/xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "license": "MIT", + "engines": { + "node": ">=0.4" + } + }, "node_modules/y18n": { "version": "5.0.8", "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", diff --git a/package.json b/package.json index 1cd8085..8ebabed 100644 --- a/package.json +++ b/package.json @@ -28,6 +28,7 @@ "fast-xml-parser": "^4.5.1", "node-cron": "^3.0.3", "openai": "^4.86.2", + "pg": "^8.11.3", "rss-parser": "^3.13.0", "slugify": "^1.6.6", "winston": "^3.17.0" diff --git a/src/analytics/csv-export.js b/src/analytics/csv-export.js new file mode 100644 index 0000000..f58f4dc --- /dev/null +++ b/src/analytics/csv-export.js @@ -0,0 +1,30 @@ +'use strict'; + +/** + * CSV export helpers for analytics dashboards (BIT-3601 / analytics routes). + */ + +function setCSVResponseHeaders(res, filename) { + const name = String(filename || 'export.csv').replace(/[\r\n"]/g, '_'); + res.writeHead(200, { + 'Content-Type': 'text/csv; charset=utf-8', + 'Content-Disposition': `attachment; filename="${name}"`, + 'Cache-Control': 'no-store', + }); +} + +async function exportArticleEngagement(_req, res) { + setCSVResponseHeaders(res, 'article-engagement.csv'); + res.end(''); +} + +async function exportCategoryBenchmarks(_req, res) { + setCSVResponseHeaders(res, 'category-benchmarks.csv'); + res.end(''); +} + +module.exports = { + setCSVResponseHeaders, + exportArticleEngagement, + exportCategoryBenchmarks, +}; diff --git a/src/analytics/db.js b/src/analytics/db.js new file mode 100644 index 0000000..74c049a --- /dev/null +++ b/src/analytics/db.js @@ -0,0 +1,100 @@ +'use strict'; + +const { Pool } = require('pg'); +const logger = require('../logger'); + +/** + * PostgreSQL connection pool for analytics data. + * Configured via environment variables. + */ + +let pool = null; + +function getConnectionConfig() { + return { + host: process.env.ANALYTICS_DB_HOST || 'localhost', + port: process.env.ANALYTICS_DB_PORT || 5432, + database: process.env.ANALYTICS_DB_NAME || 'ai_news_analytics', + user: process.env.ANALYTICS_DB_USER || 'postgres', + password: String(process.env.ANALYTICS_DB_PASSWORD ?? ''), + max: parseInt(process.env.ANALYTICS_DB_POOL_SIZE || '10', 10), + idleTimeoutMillis: 30000, + connectionTimeoutMillis: 5000 + }; +} + +function initializePool() { + if (pool) { + return pool; + } + + const config = getConnectionConfig(); + pool = new Pool(config); + + pool.on('error', (err) => { + logger.error('Unexpected error in analytics DB pool', { error: err }); + }); + + logger.info('Analytics database pool initialized', { + host: config.host, + database: config.database + }); + + return pool; +} + +async function query(sql, params = []) { + const p = initializePool(); + try { + const result = await p.query(sql, params); + return result; + } catch (error) { + logger.error('Analytics DB query failed', { sql: sql.slice(0, 100), error }); + throw error; + } +} + +async function queryOne(sql, params = []) { + const result = await query(sql, params); + return result.rows.length > 0 ? result.rows[0] : null; +} + +async function queryAll(sql, params = []) { + const result = await query(sql, params); + return result.rows; +} + +async function execute(sql, params = []) { + const result = await query(sql, params); + return result.rowCount; +} + +async function isConnected() { + try { + const p = initializePool(); + const result = await p.query('SELECT 1'); + return result.rows.length > 0; + } catch (error) { + return false; + } +} + +async function close() { + if (!pool) { + return; + } + await pool.end(); + pool = null; + logger.info('Analytics database pool closed'); +} + +module.exports = { + getConnectionConfig, + initializePool, + query, + queryOne, + queryAll, + execute, + isConnected, + close +}; diff --git a/src/analytics/schema.js b/src/analytics/schema.js new file mode 100644 index 0000000..468698c --- /dev/null +++ b/src/analytics/schema.js @@ -0,0 +1,190 @@ +'use strict'; + +const db = require('./db'); +const logger = require('../logger'); + +/** + * PostgreSQL DDL for analytics schema + */ + +const SCHEMA_DDL = ` +-- Engagement events (raw data from WordPress) +CREATE TABLE IF NOT EXISTS engagement_events ( + id BIGSERIAL PRIMARY KEY, + post_id INTEGER NOT NULL, + event_type VARCHAR(20) NOT NULL, -- 'view' | 'share' | 'comment' + event_count INTEGER DEFAULT 1, + captured_at TIMESTAMP NOT NULL, + recorded_at TIMESTAMP DEFAULT NOW(), + CONSTRAINT check_event_type CHECK (event_type IN ('view', 'share', 'comment')) +); + +CREATE INDEX IF NOT EXISTS idx_engagement_post_captured + ON engagement_events(post_id, captured_at DESC); + +CREATE INDEX IF NOT EXISTS idx_engagement_type_recorded + ON engagement_events(event_type, recorded_at DESC); + +-- Article metadata (denormalized from article-log) +CREATE TABLE IF NOT EXISTS article_analytics ( + post_id INTEGER PRIMARY KEY, + slug VARCHAR(255) UNIQUE, + title TEXT, + category VARCHAR(100), + published_at TIMESTAMP NOT NULL, + site_name VARCHAR(100), + custom_meta JSONB NOT NULL DEFAULT '{}'::jsonb, + updated_at TIMESTAMP DEFAULT NOW() +); + +CREATE INDEX IF NOT EXISTS idx_article_category_published + ON article_analytics(category, published_at DESC); + +-- Daily aggregations (materialized view) +CREATE TABLE IF NOT EXISTS daily_metrics ( + id BIGSERIAL PRIMARY KEY, + post_id INTEGER NOT NULL, + period_date DATE NOT NULL, + views INTEGER DEFAULT 0, + shares INTEGER DEFAULT 0, + comments INTEGER DEFAULT 0, + aggregated_at TIMESTAMP DEFAULT NOW(), + CONSTRAINT unique_post_date UNIQUE (post_id, period_date), + CONSTRAINT fk_article FOREIGN KEY (post_id) REFERENCES article_analytics(post_id) +); + +CREATE INDEX IF NOT EXISTS idx_daily_metrics_date + ON daily_metrics(period_date DESC); + +CREATE INDEX IF NOT EXISTS idx_daily_metrics_post + ON daily_metrics(post_id); + +-- Category benchmarks (aggregated stats per category per date) +CREATE TABLE IF NOT EXISTS category_benchmarks ( + id BIGSERIAL PRIMARY KEY, + category VARCHAR(100) NOT NULL, + period_date DATE NOT NULL, + metric_type VARCHAR(20) NOT NULL, -- 'views' | 'shares' | 'comments' + avg_value DECIMAL(12, 2), + percentile_50 DECIMAL(12, 2), + percentile_75 DECIMAL(12, 2), + percentile_90 DECIMAL(12, 2), + article_count INTEGER DEFAULT 0, + computed_at TIMESTAMP DEFAULT NOW(), + CONSTRAINT unique_category_metric UNIQUE (category, period_date, metric_type), + CONSTRAINT check_metric_type CHECK (metric_type IN ('views', 'shares', 'comments')) +); + +CREATE INDEX IF NOT EXISTS idx_category_benchmarks_lookup + ON category_benchmarks(category, period_date DESC); + +-- Schema version tracking +CREATE TABLE IF NOT EXISTS schema_version ( + id SERIAL PRIMARY KEY, + version INT NOT NULL, + applied_at TIMESTAMP DEFAULT NOW() +); + +-- Seed initial schema version if not exists +INSERT INTO schema_version (version) + SELECT 1 WHERE NOT EXISTS (SELECT 1 FROM schema_version); +`; + +/** Idempotent migrations when CREATE TABLE IF NOT EXISTS skipped an older table definition. */ +const SCHEMA_MIGRATIONS = [ + `ALTER TABLE article_analytics ADD COLUMN IF NOT EXISTS custom_meta JSONB NOT NULL DEFAULT '{}'::jsonb`, + `CREATE INDEX IF NOT EXISTS idx_article_analytics_custom_meta ON article_analytics USING GIN (custom_meta)`, +]; + +/** + * Initialize analytics database schema. + * Idempotent: safe to run multiple times. + */ +async function initializeSchema() { + try { + const statements = SCHEMA_DDL.split(';') + .map(s => s.trim()) + .filter(s => s.length > 0 && !s.startsWith('--')); + + for (const statement of statements) { + await db.query(statement); + } + + for (const sql of SCHEMA_MIGRATIONS) { + await db.query(sql); + } + + logger.info('Analytics schema initialized successfully'); + return true; + } catch (error) { + logger.error('Failed to initialize analytics schema', { error }); + throw error; + } +} + +/** + * Check if schema is initialized + */ +async function isSchemaInitialized() { + try { + const result = await db.query( + `SELECT EXISTS ( + SELECT 1 FROM information_schema.tables + WHERE table_name = 'engagement_events' + ) AS initialized` + ); + return result.rows[0]?.initialized || false; + } catch (error) { + return false; + } +} + +/** + * Get current schema version + */ +async function getSchemaVersion() { + try { + const result = await db.queryOne( + 'SELECT version FROM schema_version ORDER BY id DESC LIMIT 1' + ); + return result?.version || 0; + } catch (error) { + return 0; + } +} + +/** + * Drop all analytics tables (DANGER: use only in test/reset scenarios) + */ +async function dropAllTables() { + try { + const drop = ` + DROP TABLE IF EXISTS category_benchmarks CASCADE; + DROP TABLE IF EXISTS daily_metrics CASCADE; + DROP TABLE IF EXISTS article_analytics CASCADE; + DROP TABLE IF EXISTS engagement_events CASCADE; + DROP TABLE IF EXISTS schema_version CASCADE; + `; + + const statements = drop.split(';') + .map(s => s.trim()) + .filter(s => s.length > 0); + + for (const statement of statements) { + await db.query(statement); + } + + logger.warn('Analytics schema dropped (all tables removed)'); + return true; + } catch (error) { + logger.error('Failed to drop analytics schema', { error }); + throw error; + } +} + +module.exports = { + initializeSchema, + isSchemaInitialized, + getSchemaVersion, + dropAllTables +}; diff --git a/src/analytics/schema.test.js b/src/analytics/schema.test.js new file mode 100644 index 0000000..ed93bd3 --- /dev/null +++ b/src/analytics/schema.test.js @@ -0,0 +1,38 @@ +'use strict'; + +const { test, after } = require('node:test'); +const assert = require('node:assert'); +const { initializeSchema, isSchemaInitialized, getSchemaVersion } = require('./schema'); +const db = require('./db'); + +test('analytics schema', async (t) => { + await t.test('initializeSchema creates tables', async () => { + // Skip if no DB connection available + const connected = await db.isConnected(); + if (!connected) { + console.log('Skipping analytics schema tests (no DB connection)'); + return; + } + + const initialized = await initializeSchema(); + assert.strictEqual(initialized, true); + + const schemaExists = await isSchemaInitialized(); + assert.strictEqual(schemaExists, true); + }); + + await t.test('getSchemaVersion returns version', async () => { + const connected = await db.isConnected(); + if (!connected) { + return; + } + + const version = await getSchemaVersion(); + assert.strictEqual(typeof version, 'number'); + assert.ok(version > 0); + }); + + after(async () => { + await db.close(); + }); +}); diff --git a/tools/verify-deploy.sh b/tools/verify-deploy.sh index a57d7b0..39cb809 100755 --- a/tools/verify-deploy.sh +++ b/tools/verify-deploy.sh @@ -82,3 +82,20 @@ if (d.article_log_bytes != null) { console.log('article_log_bytes=' + d.article_log_bytes); } " + +echo "" +echo "=== verify-deploy: /metrics (Prometheus exposition, BIT-3601) ===" +METRICS_URL="${BASE}/metrics" +_METRICS="$(curl -sfS --max-time 15 "${METRICS_URL}")" || { + echo "error: GET ${METRICS_URL} failed (same host:PORT as /health)" >&2 + exit 1 +} +if ! printf '%s\n' "${_METRICS}" | grep -qF '# HELP engagement_collector_runs_total'; then + echo "error: /metrics missing HELP engagement_collector_runs_total" >&2 + exit 1 +fi +if ! printf '%s\n' "${_METRICS}" | grep -qE '^engagement_collector_runs_total[[:space:]]+[0-9]+'; then + echo "error: /metrics missing engagement_collector_runs_total counter line" >&2 + exit 1 +fi +echo "OK /metrics (collector counters present)"