diff --git a/package.json b/package.json index c4ad3b2..f308acd 100644 --- a/package.json +++ b/package.json @@ -16,7 +16,7 @@ "x:test": "node src/index.js x:test", "ops:check": "bash tools/ops-check.sh", "deploy:lxc": "bash tools/deploy-lxc.sh", - "test": "c8 --reporter=text --reporter=html --reporter=lcov node --test $(find src -type f -name '*.test.js' | sort | tr '\\n' ' ')", + "test": "c8 --reporter=text --reporter=html --reporter=lcov node --test --test-concurrency=1 $(find src -type f -name '*.test.js' | sort | tr '\\n' ' ')", "lint": "eslint src/", "lint:fix": "eslint src/ --fix && prettier --write src/", "format": "prettier --write ." diff --git a/src/analytics/aggregation-scheduler.js b/src/analytics/aggregation-scheduler.js new file mode 100644 index 0000000..de27d9e --- /dev/null +++ b/src/analytics/aggregation-scheduler.js @@ -0,0 +1,257 @@ +'use strict'; + +/** + * Aggregation Scheduler + * + * Manages scheduled daily aggregation jobs with cron-based execution. + * Handles late-arriving data and provides manual trigger capabilities. + * + * Features: + * - Daily scheduled aggregation (configurable cron) + * - Manual aggregation trigger + * - Late-arriving data recalculation + * - Prometheus metrics integration + */ + +const cron = require('node-cron'); +const logger = require('../logger'); +const { runDailyAggregation, handleLateArrivingData, getAggregationStats } = require('./daily-aggregation'); +const { + startAggregationTimer, + recordAggregationSuccess, + recordAggregationError, + exportMetrics +} = require('./prometheus-metrics'); + +// Default cron expression: daily at 2 AM (off-peak hours) +const DEFAULT_CRON = '0 2 * * *'; + +// Active scheduled task +let scheduledTask = null; +let currentCronExpression = null; + +/** + * Start scheduled aggregation + * @param {string} [cronExpr=DEFAULT_CRON] - Cron expression + * @returns {Object} Scheduler status + */ +function startScheduler(cronExpr = DEFAULT_CRON) { + if (scheduledTask) { + logger.warn('Aggregation scheduler already running'); + return { running: true, cron: scheduledTask.cronExpression }; + } + + logger.info(`Starting aggregation scheduler with cron: ${cronExpr}`); + + currentCronExpression = cronExpr; + scheduledTask = cron.schedule(cronExpr, async () => { + logger.info('Running scheduled daily aggregation'); + await runAggregationJob(); + }); + + logger.info('Aggregation scheduler started'); + return { running: true, cron: cronExpr }; +} + +/** + * Stop scheduled aggregation + * @returns {Object} Scheduler status + */ +function stopScheduler() { + if (!scheduledTask) { + logger.warn('Aggregation scheduler not running'); + return { running: false }; + } + + logger.info('Stopping aggregation scheduler'); + scheduledTask.stop(); + scheduledTask = null; + currentCronExpression = null; + + logger.info('Aggregation scheduler stopped'); + return { running: false }; +} + +/** + * Get scheduler status + * @returns {Object} Scheduler status + */ +function getSchedulerStatus() { + return { + running: scheduledTask !== null, + cron: currentCronExpression, + default_cron: DEFAULT_CRON + }; +} + +/** + * Run aggregation job (with error handling and metrics) + * @param {Object} options - Aggregation options + * @param {string} [options.date='all'] - Date to aggregate (YYYY-MM-DD or 'all') + * @param {boolean} [options.recalculate=false] - Force recalculation + * @returns {Promise} Aggregation result + */ +async function runAggregationJob({ date = 'all', recalculate = false } = {}) { + const timer = startAggregationTimer(); + + try { + logger.info(`Starting aggregation job: date=${date}, recalculate=${recalculate}`); + + const result = await runDailyAggregation(date, { recalculate }); + + const duration = timer.stop(); + recordAggregationSuccess(result); + + logger.info(`Aggregation job completed successfully in ${duration}s`, { + dates_processed: result.dates_processed, + total_posts: result.total_posts, + total_events: result.total_events + }); + + return { + success: true, + duration_seconds: duration, + ...result + }; + } catch (err) { + timer.stop(); + recordAggregationError(err.message); + + logger.error(`Aggregation job failed: ${err.message}`, { stack: err.stack }); + + return { + success: false, + error: err.message, + stack: err.stack + }; + } +} + +/** + * Run late-arriving data recalculation + * @param {string} fromDate - Start date (YYYY-MM-DD) + * @param {string} toDate - End date (YYYY-MM-DD) + * @returns {Promise} Recalculation result + */ +async function runLateDataRecalculation(fromDate, toDate) { + const timer = startAggregationTimer(); + + try { + logger.info(`Starting late-arriving data recalculation: ${fromDate} to ${toDate}`); + + const result = await handleLateArrivingData(fromDate, toDate); + + const duration = timer.stop(); + recordAggregationSuccess(result); + + logger.info(`Late-arriving data recalculation completed in ${duration}s`, { + dates_processed: result.dates_processed, + total_posts: result.total_posts + }); + + return { + success: true, + duration_seconds: duration, + ...result + }; + } catch (err) { + timer.stop(); + recordAggregationError(err.message); + + logger.error(`Late-arriving data recalculation failed: ${err.message}`, { stack: err.stack }); + + return { + success: false, + error: err.message, + stack: err.stack + }; + } +} + +/** + * Get aggregation statistics + * @returns {Promise} Aggregation statistics + */ +async function getStats() { + try { + const stats = await getAggregationStats(); + const schedulerStatus = getSchedulerStatus(); + + return { + ...stats, + scheduler: schedulerStatus + }; + } catch (err) { + logger.error(`Failed to get aggregation stats: ${err.message}`); + throw err; + } +} + +/** + * Get Prometheus metrics + * @returns {string} Prometheus metrics text format + */ +function getPrometheusMetrics() { + return exportMetrics(); +} + +/** + * Validate cron expression + * @param {string} cronExpr - Cron expression to validate + * @returns {boolean} True if valid + */ +function validateCron(cronExpr) { + try { + return cron.validate(cronExpr); + } catch (err) { + return false; + } +} + +/** + * Parse date string (YYYY-MM-DD) + * @param {string} dateStr - Date string + * @returns {Date|null} Parsed date or null if invalid + */ +function parseDate(dateStr) { + if (dateStr === 'all') { + return null; + } + + const date = new Date(dateStr); + if (isNaN(date.getTime())) { + return null; + } + + return date; +} + +/** + * Get date range for recalculation + * @param {number} daysBack - Number of days back from today + * @returns {Object} Date range { from, to } + */ +function getDateRange(daysBack) { + const to = new Date(); + const from = new Date(); + from.setDate(from.getDate() - daysBack); + + return { + from: from.toISOString().split('T')[0], + to: to.toISOString().split('T')[0] + }; +} + +module.exports = { + startScheduler, + stopScheduler, + getSchedulerStatus, + runAggregationJob, + runLateDataRecalculation, + getStats, + getPrometheusMetrics, + validateCron, + parseDate, + getDateRange, + DEFAULT_CRON +}; \ No newline at end of file diff --git a/src/analytics/aggregation-scheduler.test.js b/src/analytics/aggregation-scheduler.test.js new file mode 100644 index 0000000..7645012 --- /dev/null +++ b/src/analytics/aggregation-scheduler.test.js @@ -0,0 +1,357 @@ +'use strict'; + +/** + * Tests for aggregation scheduler module + */ + +const test = require('node:test'); +const assert = require('node:assert'); + +const { + startScheduler, + stopScheduler, + getSchedulerStatus, + runAggregationJob, + runLateDataRecalculation, + getStats, + getPrometheusMetrics, + validateCron, + parseDate, + getDateRange, + DEFAULT_CRON +} = require('./aggregation-scheduler'); + +const { recordEvent, EventTypes } = require('./engagement-events'); +const fs = require('fs').promises; + +const { + ENGAGEMENT_EVENTS_PATH, + DAILY_METRICS_PATH, + CATEGORY_BENCHMARKS_PATH +} = require('./engagement-events'); + +// Setup and teardown hooks +test.before(async () => { + // Clean up test files + try { + await fs.unlink(ENGAGEMENT_EVENTS_PATH); + } catch (err) { + if (err.code !== 'ENOENT') throw err; + } + try { + await fs.unlink(DAILY_METRICS_PATH); + } catch (err) { + if (err.code !== 'ENOENT') throw err; + } + try { + await fs.unlink(CATEGORY_BENCHMARKS_PATH); + } catch (err) { + if (err.code !== 'ENOENT') throw err; + } + + // Stop any running scheduler + stopScheduler(); +}); + +test.after(async () => { + stopScheduler(); + // Clean up test files + try { + await fs.unlink(ENGAGEMENT_EVENTS_PATH); + } catch (err) { + if (err.code !== 'ENOENT') throw err; + } + try { + await fs.unlink(DAILY_METRICS_PATH); + } catch (err) { + if (err.code !== 'ENOENT') throw err; + } + try { + await fs.unlink(CATEGORY_BENCHMARKS_PATH); + } catch (err) { + if (err.code !== 'ENOENT') throw err; + } +}); + +// Helper functions for individual tests +async function setup() { + // Clean up test files + try { + await fs.unlink(ENGAGEMENT_EVENTS_PATH); + } catch (err) { + if (err.code !== 'ENOENT') throw err; + } + try { + await fs.unlink(DAILY_METRICS_PATH); + } catch (err) { + if (err.code !== 'ENOENT') throw err; + } + try { + await fs.unlink(CATEGORY_BENCHMARKS_PATH); + } catch (err) { + if (err.code !== 'ENOENT') throw err; + } + + // Stop any running scheduler + stopScheduler(); +} + +async function teardown() { + stopScheduler(); + await setup(); +} + +test('aggregation scheduler - startScheduler starts scheduled task', async () => { + await setup(); + + const status = startScheduler(); + assert.ok(status.running); + assert.strictEqual(status.cron, DEFAULT_CRON); + + const status2 = getSchedulerStatus(); + assert.ok(status2.running); + assert.strictEqual(status2.cron, DEFAULT_CRON); + + stopScheduler(); + + await teardown(); +}); + +test('aggregation scheduler - startScheduler with custom cron', async () => { + await setup(); + + const customCron = '0 3 * * *'; // 3 AM daily + const status = startScheduler(customCron); + assert.ok(status.running); + assert.strictEqual(status.cron, customCron); + + stopScheduler(); + + await teardown(); +}); + +test('aggregation scheduler - startScheduler prevents duplicate', async () => { + await setup(); + + startScheduler(); + const status = startScheduler(); // Should not start again + + assert.ok(status.running); + assert.ok(getSchedulerStatus().running); + + stopScheduler(); + + await teardown(); +}); + +test('aggregation scheduler - stopScheduler stops scheduled task', async () => { + await setup(); + + startScheduler(); + assert.ok(getSchedulerStatus().running); + + stopScheduler(); + assert.ok(!getSchedulerStatus().running); + + await teardown(); +}); + +test('aggregation scheduler - stopScheduler handles not running', async () => { + await setup(); + + const status = stopScheduler(); + assert.ok(!status.running); + + await teardown(); +}); + +test('aggregation scheduler - getSchedulerStatus returns correct status', async () => { + await setup(); + + const status1 = getSchedulerStatus(); + assert.ok(!status1.running); + assert.strictEqual(status1.cron, null); + assert.strictEqual(status1.default_cron, DEFAULT_CRON); + + startScheduler(); + + const status2 = getSchedulerStatus(); + assert.ok(status2.running); + assert.strictEqual(status2.cron, DEFAULT_CRON); + assert.strictEqual(status2.default_cron, DEFAULT_CRON); + + stopScheduler(); + + await teardown(); +}); + +test('aggregation scheduler - runAggregationJob executes aggregation', async () => { + await setup(); + + await recordEvent({ + type: EventTypes.VIEW, + post_id: '1', + post_slug: 'post-1', + category: 'sports', + site_name: 'test-site' + }); + + const result = await runAggregationJob({ date: 'all' }); + + assert.ok(result.success); + assert.ok(result.duration_seconds >= 0); + // dates_processed can be 0 if no events match the date filter + assert.ok(result.dates_processed >= 0); + // total_posts can be 0 if no events were processed + assert.ok(result.total_posts >= 0); + + await teardown(); +}); + +test('aggregation scheduler - runAggregationJob with recalculate', async () => { + await setup(); + + await recordEvent({ + type: EventTypes.VIEW, + post_id: '1', + post_slug: 'post-1', + category: 'sports', + site_name: 'test-site' + }); + + const result = await runAggregationJob({ date: 'all', recalculate: true }); + + assert.ok(result.success); + assert.ok(result.duration_seconds > 0); + + await teardown(); +}); + +test('aggregation scheduler - runAggregationJob handles errors gracefully', async () => { + await setup(); + + // This should fail because there are no events + const result = await runAggregationJob({ date: 'all' }); + + // Should still return success even with no events + assert.ok(result.success); + + await teardown(); +}); + +test('aggregation scheduler - runLateDataRecalculation recalculates date range', async () => { + await setup(); + + const today = new Date(); + const yesterday = new Date(today); + yesterday.setDate(yesterday.getDate() - 1); + + await recordEvent({ + type: EventTypes.VIEW, + post_id: '1', + post_slug: 'post-1', + category: 'sports', + site_name: 'test-site' + }); + + const fromDate = yesterday.toISOString().split('T')[0]; + const toDate = today.toISOString().split('T')[0]; + + const result = await runLateDataRecalculation(fromDate, toDate); + + assert.ok(result.success); + assert.ok(result.duration_seconds > 0); + assert.strictEqual(result.date_range.from, fromDate); + assert.strictEqual(result.date_range.to, toDate); + + await teardown(); +}); + +test('aggregation scheduler - getStats returns statistics', async () => { + await setup(); + + await recordEvent({ + type: EventTypes.VIEW, + post_id: '1', + post_slug: 'post-1', + category: 'sports', + site_name: 'test-site' + }); + + await runAggregationJob({ date: 'all' }); + + const stats = await getStats(); + + assert.ok(stats.total_events >= 1); + assert.ok(stats.dates_with_metrics >= 1); + assert.ok(stats.dates_with_benchmarks >= 1); + assert.ok(stats.total_posts >= 1); + assert.ok(stats.scheduler); + assert.ok(typeof stats.scheduler.running === 'boolean'); + + await teardown(); +}); + +test('aggregation scheduler - getPrometheusMetrics returns metrics', async () => { + await setup(); + + const metrics = getPrometheusMetrics(); + + assert.ok(typeof metrics === 'string'); + assert.ok(metrics.length > 0); + assert.ok(metrics.includes('# HELP')); + assert.ok(metrics.includes('# TYPE')); + + await teardown(); +}); + +test('aggregation scheduler - validateCron validates expressions', () => { + assert.ok(validateCron('0 2 * * *')); + assert.ok(validateCron('*/30 * * * *')); + assert.ok(validateCron('0 0 1 * *')); + assert.ok(!validateCron('invalid')); + assert.ok(!validateCron('')); +}); + +test('aggregation scheduler - parseDate parses valid dates', () => { + const date = parseDate('2024-01-15'); + assert.ok(date instanceof Date); + assert.strictEqual(date.getFullYear(), 2024); + assert.strictEqual(date.getMonth(), 0); + assert.strictEqual(date.getDate(), 15); +}); + +test('aggregation scheduler - parseDate handles "all"', () => { + const date = parseDate('all'); + assert.strictEqual(date, null); +}); + +test('aggregation scheduler - parseDate handles invalid dates', () => { + const date = parseDate('invalid-date'); + assert.strictEqual(date, null); +}); + +test('aggregation scheduler - getDateRange returns correct range', () => { + const range = getDateRange(7); + + assert.ok(range.from); + assert.ok(range.to); + assert.ok(range.from <= range.to); + + // Verify format + assert.ok(/^\d{4}-\d{2}-\d{2}$/.test(range.from)); + assert.ok(/^\d{4}-\d{2}-\d{2}$/.test(range.to)); +}); + +test('aggregation scheduler - getDateRange with 0 days', () => { + const range = getDateRange(0); + + assert.ok(range.from); + assert.ok(range.to); + assert.strictEqual(range.from, range.to); +}); + +test('aggregation scheduler - DEFAULT_CRON is valid', () => { + assert.ok(DEFAULT_CRON); + assert.ok(validateCron(DEFAULT_CRON)); +}); \ No newline at end of file diff --git a/src/analytics/aggregation.js b/src/analytics/aggregation.js new file mode 100644 index 0000000..ca80660 --- /dev/null +++ b/src/analytics/aggregation.js @@ -0,0 +1,160 @@ +'use strict'; + +const db = require('./db'); +const logger = require('../logger'); + +/** + * Time-series and benchmark aggregation queries against the analytics DB. + */ + +/** + * Get daily time-series engagement for an article. + * @param {number} postId + * @param {Date} startDate + * @param {Date} endDate + * @returns {Promise>} + */ +async function getArticleTimeSeries(postId, startDate, endDate) { + const rows = await db.queryAll( + `SELECT + period_date, + views, + shares, + comments, + (views + shares + comments) AS total_engagement + FROM daily_metrics + WHERE post_id = $1 + AND period_date >= $2::date + AND period_date <= $3::date + ORDER BY period_date ASC`, + [postId, startDate.toISOString().split('T')[0], endDate.toISOString().split('T')[0]] + ); + return rows; +} + +/** + * Get category benchmark statistics for a given date (±7 days window). + * @param {string} category + * @param {Date} date + * @returns {Promise} Keyed by metric type (views, shares, comments) + */ +async function getCategoryBenchmarks(category, date) { + const dateStr = date.toISOString().split('T')[0]; + const rows = await db.queryAll( + `SELECT + metric_type, + avg_value, + percentile_50, + percentile_75, + percentile_90, + article_count + FROM category_benchmarks + WHERE category = $1 + AND period_date >= ($2::date - INTERVAL '7 days') + AND period_date <= $2::date + ORDER BY period_date DESC`, + [category, dateStr] + ); + + const result = {}; + for (const row of rows) { + if (!result[row.metric_type]) { + result[row.metric_type] = { + avg: parseFloat(row.avg_value) || 0, + p50: parseFloat(row.percentile_50) || 0, + p75: parseFloat(row.percentile_75) || 0, + p90: parseFloat(row.percentile_90) || 0, + articleCount: row.article_count || 0 + }; + } + } + return result; +} + +/** + * Aggregate daily_metrics for a given date from raw engagement_events. + * Idempotent: uses INSERT ... ON CONFLICT DO UPDATE. + * @param {Date} date + * @returns {Promise} Rows affected + */ +async function aggregateDailyMetrics(date) { + const dateStr = date.toISOString().split('T')[0]; + logger.info('Aggregating daily metrics', { date: dateStr }); + + const result = await db.query( + `INSERT INTO daily_metrics (post_id, period_date, views, shares, comments) + SELECT + post_id, + $1::date AS period_date, + COALESCE(SUM(CASE WHEN event_type = 'view' THEN event_count ELSE 0 END), 0) AS views, + COALESCE(SUM(CASE WHEN event_type = 'share' THEN event_count ELSE 0 END), 0) AS shares, + COALESCE(SUM(CASE WHEN event_type = 'comment' THEN event_count ELSE 0 END), 0) AS comments + FROM engagement_events + WHERE captured_at::date = $1::date + GROUP BY post_id + ON CONFLICT (post_id, period_date) + DO UPDATE SET + views = EXCLUDED.views, + shares = EXCLUDED.shares, + comments = EXCLUDED.comments, + aggregated_at = NOW()`, + [dateStr] + ); + + const rowCount = result.rowCount || 0; + logger.info('Daily metrics aggregation complete', { date: dateStr, rowCount }); + return rowCount; +} + +/** + * Aggregate category benchmarks for a given date. + * Uses daily_metrics joined with article_analytics for category. + * @param {Date} date + * @returns {Promise} Rows affected + */ +async function aggregateCategoryBenchmarks(date) { + const dateStr = date.toISOString().split('T')[0]; + logger.info('Aggregating category benchmarks', { date: dateStr }); + + let totalRows = 0; + for (const metric of ['views', 'shares', 'comments']) { + const result = await db.query( + `INSERT INTO category_benchmarks + (category, period_date, metric_type, avg_value, percentile_50, percentile_75, percentile_90, article_count) + SELECT + a.category, + $1::date, + $2, + AVG(d.${metric})::decimal(12,2), + PERCENTILE_CONT(0.50) WITHIN GROUP (ORDER BY d.${metric})::decimal(12,2), + PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY d.${metric})::decimal(12,2), + PERCENTILE_CONT(0.90) WITHIN GROUP (ORDER BY d.${metric})::decimal(12,2), + COUNT(*) + FROM daily_metrics d + JOIN article_analytics a ON d.post_id = a.post_id + WHERE d.period_date = $1::date + AND a.category IS NOT NULL + GROUP BY a.category + ON CONFLICT (category, period_date, metric_type) + DO UPDATE SET + avg_value = EXCLUDED.avg_value, + percentile_50 = EXCLUDED.percentile_50, + percentile_75 = EXCLUDED.percentile_75, + percentile_90 = EXCLUDED.percentile_90, + article_count = EXCLUDED.article_count, + computed_at = NOW()`, + [dateStr, metric] + ); + totalRows += result.rowCount || 0; + } + + logger.info('Category benchmarks aggregation complete', { date: dateStr, totalRows }); + return totalRows; +} + +module.exports = { + getArticleTimeSeries, + getCategoryBenchmarks, + aggregateDailyMetrics, + aggregateCategoryBenchmarks +}; diff --git a/src/analytics/article-store.js b/src/analytics/article-store.js new file mode 100644 index 0000000..67c8180 --- /dev/null +++ b/src/analytics/article-store.js @@ -0,0 +1,132 @@ +'use strict'; + +const db = require('./db'); +const logger = require('../logger'); + +/** + * Data access for the article_analytics table. + */ + +/** + * Get a single article by post_id. + * @param {number} postId + * @returns {Promise} + */ +async function getArticle(postId) { + return db.queryOne( + `SELECT post_id, slug, title, category, published_at, site_name, custom_meta + FROM article_analytics + WHERE post_id = $1`, + [postId] + ); +} + +/** + * List articles with optional category filter, ordered by published_at DESC. + * @param {Object} opts + * @param {string} [opts.category] + * @param {number} [opts.limit=50] + * @param {number} [opts.offset=0] + * @returns {Promise} + */ +async function listArticles({ category, limit = 50, offset = 0 } = {}) { + if (category) { + return db.queryAll( + `SELECT post_id, slug, title, category, published_at, site_name + FROM article_analytics + WHERE category = $1 + ORDER BY published_at DESC + LIMIT $2 OFFSET $3`, + [category, limit, offset] + ); + } + return db.queryAll( + `SELECT post_id, slug, title, category, published_at, site_name + FROM article_analytics + ORDER BY published_at DESC + LIMIT $1 OFFSET $2`, + [limit, offset] + ); +} + +/** + * Insert or update an article record. + * @param {Object} article + * @param {number} article.postId + * @param {string} article.slug + * @param {string} article.title + * @param {string} article.category + * @param {Date|string} article.publishedAt + * @param {string} [article.siteName] + * @param {Object} [article.customMeta] + * @returns {Promise} Upserted row + */ +async function upsertArticle({ postId, slug, title, category, publishedAt, siteName, customMeta = {} }) { + const row = await db.queryOne( + `INSERT INTO article_analytics (post_id, slug, title, category, published_at, site_name, custom_meta, updated_at) + VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, NOW()) + ON CONFLICT (post_id) DO UPDATE SET + slug = EXCLUDED.slug, + title = EXCLUDED.title, + category = EXCLUDED.category, + published_at= EXCLUDED.published_at, + site_name = EXCLUDED.site_name, + custom_meta = EXCLUDED.custom_meta, + updated_at = NOW() + RETURNING post_id, slug, title, category, published_at, site_name`, + [postId, slug, title, category, publishedAt, siteName || null, JSON.stringify(customMeta)] + ); + logger.debug('Article upserted', { postId }); + return row; +} + +/** + * Get top articles by a metric for a given date, with optional category filter. + * @param {Object} opts + * @param {Date} opts.date + * @param {'views'|'shares'|'comments'} [opts.metric='views'] + * @param {string} [opts.category] + * @param {number} [opts.limit=10] + * @returns {Promise} + */ +async function getTopArticles({ date, metric = 'views', category, limit = 10 }) { + const validMetrics = { views: 'd.views', shares: 'd.shares', comments: 'd.comments' }; + const orderCol = validMetrics[metric] || 'd.views'; + const dateStr = date instanceof Date ? date.toISOString().split('T')[0] : date; + + if (category) { + return db.queryAll( + `SELECT + a.post_id, a.slug, a.title, a.category, a.published_at, + d.views, d.shares, d.comments, + (d.views + d.shares + d.comments) AS engagement_total + FROM daily_metrics d + JOIN article_analytics a ON d.post_id = a.post_id + WHERE d.period_date = $1::date + AND a.category = $2 + ORDER BY ${orderCol} DESC + LIMIT $3`, + [dateStr, category, limit] + ); + } + + return db.queryAll( + `SELECT + a.post_id, a.slug, a.title, a.category, a.published_at, + d.views, d.shares, d.comments, + (d.views + d.shares + d.comments) AS engagement_total + FROM daily_metrics d + JOIN article_analytics a ON d.post_id = a.post_id + WHERE d.period_date = $1::date + ORDER BY ${orderCol} DESC + LIMIT $2`, + [dateStr, limit] + ); +} + +module.exports = { + getArticle, + listArticles, + upsertArticle, + getTopArticles +}; diff --git a/src/analytics/daily-aggregation.js b/src/analytics/daily-aggregation.js new file mode 100644 index 0000000..c148920 --- /dev/null +++ b/src/analytics/daily-aggregation.js @@ -0,0 +1,414 @@ +'use strict'; + +/** + * Daily Aggregation Service + * + * Computes daily metrics from engagement events and calculates category benchmarks. + * Handles late-arriving data by recalculating affected dates. + * + * Features: + * - Daily rollups: views, shares, comments by post by date + * - Category benchmarks: avg, p50, p90 per metric per category per day + * - Late-arriving data handling with recalculation + * - Prometheus metrics for aggregation performance + */ + +const fs = require('fs').promises; +const path = require('path'); +const logger = require('../logger'); +const { readEvents, DAILY_METRICS_PATH, CATEGORY_BENCHMARKS_PATH } = require('./engagement-events'); + +const DATA_DIR = path.join(__dirname, '../../data'); + +/** + * Compute daily metrics from engagement events + * @param {string} date - Date to compute metrics for (YYYY-MM-DD), or 'all' for all dates + * @returns {Promise} Daily metrics object + */ +async function computeDailyMetrics(date = 'all') { + logger.info(`Computing daily metrics for date: ${date}`); + + const fromDate = date === 'all' ? undefined : date; + const toDate = date === 'all' ? undefined : date; + + const events = await readEvents({ fromDate, toDate }); + + if (events.length === 0) { + logger.info(`No engagement events found for date: ${date}`); + return {}; + } + + // Group events by date and post + const metricsByDateAndPost = {}; + + for (const event of events) { + const eventDate = event.date; + const postKey = `${event.post_slug}|${event.post_id}`; + + if (!metricsByDateAndPost[eventDate]) { + metricsByDateAndPost[eventDate] = {}; + } + + if (!metricsByDateAndPost[eventDate][postKey]) { + metricsByDateAndPost[eventDate][postKey] = { + post_id: event.post_id, + post_slug: event.post_slug, + category: event.category, + site_name: event.site_name, + views: 0, + shares: 0, + comments: 0, + total_engagement: 0 + }; + } + + const metrics = metricsByDateAndPost[eventDate][postKey]; + + switch (event.type) { + case 'view': + metrics.views += event.value; + break; + case 'share': + metrics.shares += event.value; + break; + case 'comment': + metrics.comments += event.value; + break; + } + + metrics.total_engagement = metrics.views + metrics.shares + metrics.comments; + } + + // Convert to array format + const dailyMetrics = {}; + for (const dateStr in metricsByDateAndPost) { + dailyMetrics[dateStr] = Object.values(metricsByDateAndPost[dateStr]); + } + + logger.info(`Computed daily metrics for ${Object.keys(dailyMetrics).length} date(s), ${events.length} event(s)`); + return dailyMetrics; +} + +/** + * Calculate category benchmarks (avg, p50, p90) for a specific date + * @param {Object} dailyMetrics - Daily metrics object + * @param {string} date - Date to calculate benchmarks for (YYYY-MM-DD) + * @returns {Promise} Category benchmarks + */ +async function calculateCategoryBenchmarks(dailyMetrics, date) { + logger.info(`Calculating category benchmarks for date: ${date}`); + + const postsForDate = dailyMetrics[date] || []; + + if (postsForDate.length === 0) { + logger.info(`No posts found for date: ${date}`); + return {}; + } + + // Group by category + const byCategory = {}; + + for (const post of postsForDate) { + const category = post.category || 'uncategorized'; + if (!byCategory[category]) { + byCategory[category] = { + views: [], + shares: [], + comments: [], + total_engagement: [] + }; + } + + byCategory[category].views.push(post.views); + byCategory[category].shares.push(post.shares); + byCategory[category].comments.push(post.comments); + byCategory[category].total_engagement.push(post.total_engagement); + } + + // Calculate statistics for each category + const benchmarks = {}; + + for (const category in byCategory) { + const data = byCategory[category]; + + benchmarks[category] = { + views: calculateStats(data.views), + shares: calculateStats(data.shares), + comments: calculateStats(data.comments), + total_engagement: calculateStats(data.total_engagement), + post_count: data.views.length + }; + } + + logger.info(`Calculated benchmarks for ${Object.keys(benchmarks).length} categor(ies)`); + return benchmarks; +} + +/** + * Calculate statistics (avg, p50, p90, min, max) for an array of numbers + * @param {Array} values - Array of values + * @returns {Object} Statistics object + */ +function calculateStats(values) { + if (values.length === 0) { + return { avg: 0, p50: 0, p90: 0, min: 0, max: 0, count: 0 }; + } + + const sorted = [...values].sort((a, b) => a - b); + const sum = sorted.reduce((acc, val) => acc + val, 0); + + const avg = sum / sorted.length; + const p50 = percentile(sorted, 50); + const p90 = percentile(sorted, 90); + const min = sorted[0]; + const max = sorted[sorted.length - 1]; + + return { + avg: Math.round(avg * 100) / 100, + p50: Math.round(p50 * 100) / 100, + p90: Math.round(p90 * 100) / 100, + min, + max, + count: sorted.length + }; +} + +/** + * Calculate percentile value using nearest-rank method + * @param {Array} sorted - Sorted array of values + * @param {number} p - Percentile (0-100) + * @returns {number} Percentile value + */ +function percentile(sorted, p) { + if (sorted.length === 0) return 0; + if (sorted.length === 1) return sorted[0]; + + if (p === 50 && sorted.length % 2 === 0) { + const mid = sorted.length / 2; + return (sorted[mid - 1] + sorted[mid]) / 2; + } + + const rank = Math.ceil((p / 100) * sorted.length); + const index = Math.min(rank - 1, sorted.length - 1); + return sorted[index]; +} + +/** + * Load existing daily metrics from disk + * @returns {Promise} Daily metrics object + */ +async function loadDailyMetrics() { + try { + const content = await fs.readFile(DAILY_METRICS_PATH, 'utf8'); + return JSON.parse(content); + } catch (err) { + if (err.code === 'ENOENT') { + return {}; + } + throw err; + } +} + +/** + * Save daily metrics to disk + * @param {Object} metrics - Daily metrics object + * @returns {Promise} + */ +async function saveDailyMetrics(metrics) { + await fs.mkdir(DATA_DIR, { recursive: true }); + const content = JSON.stringify(metrics, null, 2); + await fs.writeFile(DAILY_METRICS_PATH, content); + logger.info(`Saved daily metrics to ${DAILY_METRICS_PATH}`); +} + +/** + * Load existing category benchmarks from disk + * @returns {Promise} Category benchmarks object + */ +async function loadCategoryBenchmarks() { + try { + const content = await fs.readFile(CATEGORY_BENCHMARKS_PATH, 'utf8'); + return JSON.parse(content); + } catch (err) { + if (err.code === 'ENOENT') { + return {}; + } + throw err; + } +} + +/** + * Save category benchmarks to disk + * @param {Object} benchmarks - Category benchmarks object + * @returns {Promise} + */ +async function saveCategoryBenchmarks(benchmarks) { + await fs.mkdir(DATA_DIR, { recursive: true }); + const content = JSON.stringify(benchmarks, null, 2); + await fs.writeFile(CATEGORY_BENCHMARKS_PATH, content); + logger.info(`Saved category benchmarks to ${CATEGORY_BENCHMARKS_PATH}`); +} + +/** + * Run daily aggregation for a specific date or all dates + * @param {string} date - Date to aggregate (YYYY-MM-DD), or 'all' for all dates + * @param {Object} options - Options + * @param {boolean} [options.recalculate=false] - Force recalculation even if metrics exist + * @returns {Promise} Aggregation results + */ +async function runDailyAggregation(date = 'all', { recalculate = false } = {}) { + const startTime = Date.now(); + logger.info(`Starting daily aggregation for date: ${date}, recalculate: ${recalculate}`); + + try { + // Load existing metrics + const existingMetrics = await loadDailyMetrics(); + const existingBenchmarks = await loadCategoryBenchmarks(); + + // Compute new daily metrics + const newMetrics = await computeDailyMetrics(date); + + // Merge with existing metrics (unless recalculating) + const mergedMetrics = recalculate ? newMetrics : { ...existingMetrics, ...newMetrics }; + + // Calculate benchmarks for each date + const newBenchmarks = {}; + for (const dateStr in newMetrics) { + newBenchmarks[dateStr] = await calculateCategoryBenchmarks(mergedMetrics, dateStr); + } + + // Merge with existing benchmarks + const mergedBenchmarks = recalculate ? newBenchmarks : { ...existingBenchmarks, ...newBenchmarks }; + + // Save to disk + await saveDailyMetrics(mergedMetrics); + await saveCategoryBenchmarks(mergedBenchmarks); + + const duration = Date.now() - startTime; + logger.info(`Daily aggregation completed in ${duration}ms`); + + // Return summary + return { + success: true, + duration_ms: duration, + dates_processed: Object.keys(newMetrics).length, + total_posts: Object.values(newMetrics).reduce((acc, posts) => acc + posts.length, 0), + total_events: await getTotalEventCount(), + metrics_path: DAILY_METRICS_PATH, + benchmarks_path: CATEGORY_BENCHMARKS_PATH + }; + } catch (err) { + logger.error(`Daily aggregation failed: ${err.message}`, { stack: err.stack }); + throw err; + } +} + +/** + * Get total event count + * @returns {Promise} Total number of events + */ +async function getTotalEventCount() { + const events = await readEvents(); + return events.length; +} + +/** + * Handle late-arriving data by recalculating affected dates + * @param {string} fromDate - Start date to recalculate (YYYY-MM-DD) + * @param {string} toDate - End date to recalculate (YYYY-MM-DD) + * @returns {Promise} Recalculation results + */ +async function handleLateArrivingData(fromDate, toDate) { + logger.info(`Handling late-arriving data for date range: ${fromDate} to ${toDate}`); + + // Get all dates in range + const dates = getDatesInRange(fromDate, toDate); + + let totalProcessed = 0; + let totalPosts = 0; + + for (const date of dates) { + const result = await runDailyAggregation(date, { recalculate: true }); + totalProcessed += result.dates_processed || 0; + totalPosts += result.total_posts || 0; + } + + logger.info(`Late-arriving data handling complete: ${totalProcessed} date(s), ${totalPosts} post(s)`); + + return { + success: true, + dates_processed: totalProcessed, + total_posts: totalPosts, + date_range: { from: fromDate, to: toDate } + }; +} + +/** + * Get array of dates in range + * @param {string} fromDate - Start date (YYYY-MM-DD) + * @param {string} toDate - End date (YYYY-MM-DD) + * @returns {Array} Array of dates + */ +function getDatesInRange(fromDate, toDate) { + const dates = []; + const current = new Date(fromDate); + const end = new Date(toDate); + + while (current <= end) { + dates.push(current.toISOString().split('T')[0]); + current.setDate(current.getDate() + 1); + } + + return dates; +} + +/** + * Get aggregation statistics + * @returns {Promise} Aggregation statistics + */ +async function getAggregationStats() { + const metrics = await loadDailyMetrics(); + const benchmarks = await loadCategoryBenchmarks(); + const totalEvents = await getTotalEventCount(); + + const datesWithMetrics = Object.keys(metrics).length; + const datesWithBenchmarks = Object.keys(benchmarks).length; + + let totalPosts = 0; + for (const date in metrics) { + totalPosts += metrics[date].length; + } + + // Get date range + const dates = Object.keys(metrics).sort(); + const dateRange = dates.length > 0 ? { from: dates[0], to: dates[dates.length - 1] } : null; + + // Get categories + const categories = new Set(); + for (const date in benchmarks) { + Object.keys(benchmarks[date]).forEach(cat => categories.add(cat)); + } + + return { + total_events: totalEvents, + dates_with_metrics: datesWithMetrics, + dates_with_benchmarks: datesWithBenchmarks, + total_posts: totalPosts, + date_range: dateRange, + categories: Array.from(categories), + metrics_path: DAILY_METRICS_PATH, + benchmarks_path: CATEGORY_BENCHMARKS_PATH + }; +} + +module.exports = { + computeDailyMetrics, + calculateCategoryBenchmarks, + runDailyAggregation, + handleLateArrivingData, + getAggregationStats, + loadDailyMetrics, + saveDailyMetrics, + loadCategoryBenchmarks, + saveCategoryBenchmarks +}; \ No newline at end of file diff --git a/src/analytics/daily-aggregation.test.js b/src/analytics/daily-aggregation.test.js new file mode 100644 index 0000000..f49cc22 --- /dev/null +++ b/src/analytics/daily-aggregation.test.js @@ -0,0 +1,408 @@ +'use strict'; + +/** + * Tests for daily aggregation module + */ + +const test = require('node:test'); +const assert = require('node:assert'); +const fs = require('fs').promises; + +const { + computeDailyMetrics, + calculateCategoryBenchmarks, + runDailyAggregation, + getAggregationStats, + loadDailyMetrics, + saveDailyMetrics, + loadCategoryBenchmarks, + saveCategoryBenchmarks +} = require('./daily-aggregation'); + +const { + recordEvent, + ENGAGEMENT_EVENTS_PATH, + DAILY_METRICS_PATH, + CATEGORY_BENCHMARKS_PATH +} = require('./engagement-events'); + +const { EventTypes } = require('./engagement-events'); + +// Setup and teardown hooks +test.before(async () => { + // Clean up test files + try { + await fs.unlink(ENGAGEMENT_EVENTS_PATH); + } catch (err) { + if (err.code !== 'ENOENT') throw err; + } + try { + await fs.unlink(DAILY_METRICS_PATH); + } catch (err) { + if (err.code !== 'ENOENT') throw err; + } + try { + await fs.unlink(CATEGORY_BENCHMARKS_PATH); + } catch (err) { + if (err.code !== 'ENOENT') throw err; + } +}); + +test.after(async () => { + // Clean up test files + try { + await fs.unlink(ENGAGEMENT_EVENTS_PATH); + } catch (err) { + if (err.code !== 'ENOENT') throw err; + } + try { + await fs.unlink(DAILY_METRICS_PATH); + } catch (err) { + if (err.code !== 'ENOENT') throw err; + } + try { + await fs.unlink(CATEGORY_BENCHMARKS_PATH); + } catch (err) { + if (err.code !== 'ENOENT') throw err; + } +}); + +// Helper functions for individual tests +async function setup() { + // Clean up test files + try { + await fs.unlink(ENGAGEMENT_EVENTS_PATH); + } catch (err) { + if (err.code !== 'ENOENT') throw err; + } + try { + await fs.unlink(DAILY_METRICS_PATH); + } catch (err) { + if (err.code !== 'ENOENT') throw err; + } + try { + await fs.unlink(CATEGORY_BENCHMARKS_PATH); + } catch (err) { + if (err.code !== 'ENOENT') throw err; + } +} + +async function teardown() { + await setup(); +} + +test('daily aggregation - computeDailyMetrics returns empty object for no events', async () => { + await setup(); + + const metrics = await computeDailyMetrics(); + assert.deepStrictEqual(metrics, {}); + + await teardown(); +}); + +test('daily aggregation - computeDailyMetrics aggregates events by date and post', async () => { + await setup(); + + const today = new Date().toISOString().split('T')[0]; + + await recordEvent({ + type: EventTypes.VIEW, + post_id: '1', + post_slug: 'post-1', + category: 'sports', + site_name: 'test-site', + value: 5 + }); + + await recordEvent({ + type: EventTypes.SHARE, + post_id: '1', + post_slug: 'post-1', + category: 'sports', + site_name: 'test-site', + value: 2 + }); + + await recordEvent({ + type: EventTypes.COMMENT, + post_id: '1', + post_slug: 'post-1', + category: 'sports', + site_name: 'test-site', + value: 1 + }); + + const metrics = await computeDailyMetrics(); + + assert.ok(metrics[today]); + assert.strictEqual(metrics[today].length, 1); + + const postMetrics = metrics[today][0]; + assert.strictEqual(postMetrics.post_id, '1'); + assert.strictEqual(postMetrics.post_slug, 'post-1'); + assert.strictEqual(postMetrics.category, 'sports'); + assert.strictEqual(postMetrics.views, 5); + assert.strictEqual(postMetrics.shares, 2); + assert.strictEqual(postMetrics.comments, 1); + assert.strictEqual(postMetrics.total_engagement, 8); + + await teardown(); +}); + +test('daily aggregation - computeDailyMetrics handles multiple posts', async () => { + await setup(); + + await recordEvent({ + type: EventTypes.VIEW, + post_id: '1', + post_slug: 'post-1', + category: 'sports', + site_name: 'test-site' + }); + + await recordEvent({ + type: EventTypes.VIEW, + post_id: '2', + post_slug: 'post-2', + category: 'tech', + site_name: 'test-site' + }); + + const metrics = await computeDailyMetrics(); + const today = new Date().toISOString().split('T')[0]; + + assert.ok(metrics[today]); + assert.strictEqual(metrics[today].length, 2); + + await teardown(); +}); + +test('daily aggregation - calculateCategoryBenchmarks computes statistics', async () => { + await setup(); + + const today = new Date().toISOString().split('T')[0]; + + const dailyMetrics = { + [today]: [ + { + post_id: '1', + post_slug: 'post-1', + category: 'sports', + site_name: 'test-site', + views: 100, + shares: 10, + comments: 5, + total_engagement: 115 + }, + { + post_id: '2', + post_slug: 'post-2', + category: 'sports', + site_name: 'test-site', + views: 200, + shares: 20, + comments: 10, + total_engagement: 230 + }, + { + post_id: '3', + post_slug: 'post-3', + category: 'tech', + site_name: 'test-site', + views: 50, + shares: 5, + comments: 2, + total_engagement: 57 + } + ] + }; + + const benchmarks = await calculateCategoryBenchmarks(dailyMetrics, today); + + assert.ok(benchmarks.sports); + assert.ok(benchmarks.tech); + + // Check sports category + assert.strictEqual(benchmarks.sports.post_count, 2); + assert.strictEqual(benchmarks.sports.views.count, 2); + assert.strictEqual(benchmarks.sports.views.min, 100); + assert.strictEqual(benchmarks.sports.views.max, 200); + assert.strictEqual(benchmarks.sports.views.avg, 150); + assert.strictEqual(benchmarks.sports.views.p50, 150); + assert.strictEqual(benchmarks.sports.views.p90, 200); + + // Check tech category + assert.strictEqual(benchmarks.tech.post_count, 1); + assert.strictEqual(benchmarks.tech.views.count, 1); + assert.strictEqual(benchmarks.tech.views.min, 50); + assert.strictEqual(benchmarks.tech.views.max, 50); + assert.strictEqual(benchmarks.tech.views.avg, 50); + + await teardown(); +}); + +test('daily aggregation - calculateCategoryBenchmarks handles empty data', async () => { + await setup(); + + const benchmarks = await calculateCategoryBenchmarks({}, '2024-01-01'); + assert.deepStrictEqual(benchmarks, {}); + + await teardown(); +}); + +test('daily aggregation - runDailyAggregation saves metrics and benchmarks', async () => { + await setup(); + + await recordEvent({ + type: EventTypes.VIEW, + post_id: '1', + post_slug: 'post-1', + category: 'sports', + site_name: 'test-site' + }); + + const result = await runDailyAggregation('all'); + + assert.ok(result.success); + assert.ok(result.duration_ms > 0); + assert.ok(result.dates_processed > 0); + assert.ok(result.total_posts > 0); + + // Verify files were created + const metrics = await loadDailyMetrics(); + assert.ok(Object.keys(metrics).length > 0); + + const benchmarks = await loadCategoryBenchmarks(); + assert.ok(Object.keys(benchmarks).length > 0); + + await teardown(); +}); + +test('daily aggregation - runDailyAggregation with recalculate', async () => { + await setup(); + + await recordEvent({ + type: EventTypes.VIEW, + post_id: '1', + post_slug: 'post-1', + category: 'sports', + site_name: 'test-site' + }); + + // First run + const result1 = await runDailyAggregation('all', { recalculate: false }); + assert.ok(result1.success); + + // Add more events + await recordEvent({ + type: EventTypes.VIEW, + post_id: '2', + post_slug: 'post-2', + category: 'tech', + site_name: 'test-site' + }); + + // Run with recalculate + const result2 = await runDailyAggregation('all', { recalculate: true }); + assert.ok(result2.success); + + // Verify metrics were updated + const metrics = await loadDailyMetrics(); + const today = new Date().toISOString().split('T')[0]; + assert.ok(metrics[today]); + assert.strictEqual(metrics[today].length, 2); + + await teardown(); +}); + +test('daily aggregation - getAggregationStats returns statistics', async () => { + await setup(); + + await recordEvent({ + type: EventTypes.VIEW, + post_id: '1', + post_slug: 'post-1', + category: 'sports', + site_name: 'test-site' + }); + + await runDailyAggregation('all'); + + const stats = await getAggregationStats(); + + assert.ok(stats.total_events >= 1); + assert.ok(stats.dates_with_metrics >= 1); + assert.ok(stats.dates_with_benchmarks >= 1); + assert.ok(stats.total_posts >= 1); + assert.ok(stats.date_range); + assert.ok(Array.isArray(stats.categories)); + + await teardown(); +}); + +test('daily aggregation - loadDailyMetrics handles non-existent file', async () => { + await setup(); + + const metrics = await loadDailyMetrics(); + assert.deepStrictEqual(metrics, {}); + + await teardown(); +}); + +test('daily aggregation - loadCategoryBenchmarks handles non-existent file', async () => { + await setup(); + + const benchmarks = await loadCategoryBenchmarks(); + assert.deepStrictEqual(benchmarks, {}); + + await teardown(); +}); + +test('daily aggregation - saveDailyMetrics persists data', async () => { + await setup(); + + const testMetrics = { + '2024-01-01': [ + { + post_id: '1', + post_slug: 'post-1', + category: 'sports', + site_name: 'test-site', + views: 100, + shares: 10, + comments: 5, + total_engagement: 115 + } + ] + }; + + await saveDailyMetrics(testMetrics); + + const loaded = await loadDailyMetrics(); + assert.deepStrictEqual(loaded, testMetrics); + + await teardown(); +}); + +test('daily aggregation - saveCategoryBenchmarks persists data', async () => { + await setup(); + + const testBenchmarks = { + '2024-01-01': { + sports: { + views: { avg: 150, p50: 150, p90: 200, min: 100, max: 200, count: 2 }, + shares: { avg: 15, p50: 15, p90: 20, min: 10, max: 20, count: 2 }, + comments: { avg: 7.5, p50: 7.5, p90: 10, min: 5, max: 10, count: 2 }, + total_engagement: { avg: 172.5, p50: 172.5, p90: 230, min: 115, max: 230, count: 2 }, + post_count: 2 + } + } + }; + + await saveCategoryBenchmarks(testBenchmarks); + + const loaded = await loadCategoryBenchmarks(); + assert.deepStrictEqual(loaded, testBenchmarks); + + await teardown(); +}); \ No newline at end of file diff --git a/src/analytics/engagement-events.js b/src/analytics/engagement-events.js new file mode 100644 index 0000000..f387bcf --- /dev/null +++ b/src/analytics/engagement-events.js @@ -0,0 +1,210 @@ +'use strict'; + +/** + * Engagement Events Module + * + * Tracks engagement events (views, shares, comments) for published articles. + * Events are stored in append-only JSONL format for efficient batch processing. + * + * Data Model: + * - engagement_events.jsonl: Append-only log of all engagement events + * - daily_metrics.json: Aggregated metrics by post and date + * - category_benchmarks.json: Statistical benchmarks by category and date + */ + +const fs = require('fs').promises; +const path = require('path'); +const logger = require('../logger'); + +const DATA_DIR = path.join(__dirname, '../../data'); +const ENGAGEMENT_EVENTS_PATH = path.join(DATA_DIR, 'engagement-events.jsonl'); +const DAILY_METRICS_PATH = path.join(DATA_DIR, 'daily-metrics.json'); +const CATEGORY_BENCHMARKS_PATH = path.join(DATA_DIR, 'category-benchmarks.json'); + +// Ensure data directory exists +async function ensureDataDir() { + try { + await fs.mkdir(DATA_DIR, { recursive: true }); + } catch (err) { + if (err.code !== 'EEXIST') { + throw err; + } + } +} + +/** + * Engagement event types + */ +const EventTypes = { + VIEW: 'view', + SHARE: 'share', + COMMENT: 'comment' +}; + +/** + * Record an engagement event + * @param {Object} event - Event data + * @param {string} event.type - Event type (view, share, comment) + * @param {string} event.post_id - WordPress post ID + * @param {string} event.post_slug - Post slug for identification + * @param {string} event.category - Article category + * @param {string} event.site_name - Site name (from config) + * @param {number} [event.value=1] - Event value (default 1) + * @param {Object} [event.metadata] - Optional metadata + * @returns {Promise} Recorded event with timestamp + */ +async function recordEvent({ type, post_id, post_slug, category, site_name, value = 1, metadata = {} }) { + await ensureDataDir(); + + if (!Object.values(EventTypes).includes(type)) { + throw new Error(`Invalid event type: ${type}. Must be one of: ${Object.values(EventTypes).join(', ')}`); + } + + if (!post_id || !post_slug) { + throw new Error('post_id and post_slug are required'); + } + + const event = { + id: generateEventId(), + type, + post_id, + post_slug, + category: category || 'uncategorized', + site_name: site_name || 'default', + value, + metadata, + timestamp: new Date().toISOString(), + date: new Date().toISOString().split('T')[0] // YYYY-MM-DD for aggregation + }; + + const line = JSON.stringify(event) + '\n'; + await fs.appendFile(ENGAGEMENT_EVENTS_PATH, line); + + logger.debug(`Engagement event recorded: ${type} for post ${post_slug} (${event.id})`); + return event; +} + +/** + * Generate unique event ID + * @returns {string} Unique event ID + */ +function generateEventId() { + return `evt_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; +} + +/** + * Read all engagement events + * @param {Object} options - Query options + * @param {string} [options.fromDate] - Filter events from this date (YYYY-MM-DD) + * @param {string} [options.toDate] - Filter events until this date (YYYY-MM-DD) + * @param {string} [options.post_slug] - Filter by post slug + * @param {string} [options.category] - Filter by category + * @param {string} [options.type] - Filter by event type + * @returns {Promise} Array of engagement events + */ +async function readEvents({ fromDate, toDate, post_slug, category, type } = {}) { + try { + await ensureDataDir(); + const content = await fs.readFile(ENGAGEMENT_EVENTS_PATH, 'utf8'); + const lines = content.trim().split('\n').filter(Boolean); + + let events = lines.map(line => { + try { + return JSON.parse(line); + } catch (err) { + logger.warn(`Failed to parse engagement event line: ${err.message}`); + return null; + } + }).filter(Boolean); + + // Apply filters + if (fromDate) { + events = events.filter(e => e.date >= fromDate); + } + if (toDate) { + events = events.filter(e => e.date <= toDate); + } + if (post_slug) { + events = events.filter(e => e.post_slug === post_slug); + } + if (category) { + events = events.filter(e => e.category === category); + } + if (type) { + events = events.filter(e => e.type === type); + } + + return events; + } catch (err) { + if (err.code === 'ENOENT') { + // File doesn't exist yet, return empty array + return []; + } + throw err; + } +} + +/** + * Get event count for a specific date range + * @param {string} fromDate - Start date (YYYY-MM-DD) + * @param {string} toDate - End date (YYYY-MM-DD) + * @param {Object} filters - Optional filters + * @returns {Promise} Event counts by type + */ +async function getEventCounts(fromDate, toDate, filters = {}) { + const events = await readEvents({ fromDate, toDate, ...filters }); + + const counts = { + total: events.length, + by_type: {}, + by_category: {}, + by_post: {} + }; + + for (const event of events) { + // Count by type + counts.by_type[event.type] = (counts.by_type[event.type] || 0) + 1; + + // Count by category + counts.by_category[event.category] = (counts.by_category[event.category] || 0) + 1; + + // Count by post + const postKey = `${event.post_slug}`; + counts.by_post[postKey] = (counts.by_post[postKey] || 0) + 1; + } + + return counts; +} + +/** + * Delete events older than specified date (for cleanup) + * @param {string} beforeDate - Delete events before this date (YYYY-MM-DD) + * @returns {Promise} Number of events deleted + */ +async function deleteEventsBefore(beforeDate) { + const events = await readEvents(); + const toKeep = events.filter(e => e.date >= beforeDate); + + if (toKeep.length === events.length) { + return 0; // Nothing to delete + } + + // Rewrite file with only events to keep + const content = toKeep.map(e => JSON.stringify(e)).join('\n') + '\n'; + await fs.writeFile(ENGAGEMENT_EVENTS_PATH, content); + + const deleted = events.length - toKeep.length; + logger.info(`Deleted ${deleted} engagement events before ${beforeDate}`); + return deleted; +} + +module.exports = { + EventTypes, + recordEvent, + readEvents, + getEventCounts, + deleteEventsBefore, + ENGAGEMENT_EVENTS_PATH, + DAILY_METRICS_PATH, + CATEGORY_BENCHMARKS_PATH +}; \ No newline at end of file diff --git a/src/analytics/engagement-events.test.js b/src/analytics/engagement-events.test.js new file mode 100644 index 0000000..c2c27af --- /dev/null +++ b/src/analytics/engagement-events.test.js @@ -0,0 +1,317 @@ +'use strict'; + +/** + * Tests for engagement events module + */ + +const test = require('node:test'); +const assert = require('node:assert'); +const fs = require('fs').promises; +const path = require('path'); + +const { + EventTypes, + recordEvent, + readEvents, + getEventCounts, + deleteEventsBefore, + ENGAGEMENT_EVENTS_PATH +} = require('./engagement-events'); + +const TEST_DATA_DIR = path.join(__dirname, '../../test-data'); + +// Setup and teardown hooks +test.before(async () => { + await fs.mkdir(TEST_DATA_DIR, { recursive: true }); + // Clean up any existing test data + try { + await fs.unlink(ENGAGEMENT_EVENTS_PATH); + } catch (err) { + if (err.code !== 'ENOENT') throw err; + } +}); + +test.after(async () => { + try { + await fs.unlink(ENGAGEMENT_EVENTS_PATH); + } catch (err) { + if (err.code !== 'ENOENT') throw err; + } +}); + +// Helper functions for individual tests +async function setup() { + // Clean up before each test + try { + await fs.unlink(ENGAGEMENT_EVENTS_PATH); + } catch (err) { + if (err.code !== 'ENOENT') throw err; + } +} + +async function teardown() { + // Clean up after each test + try { + await fs.unlink(ENGAGEMENT_EVENTS_PATH); + } catch (err) { + if (err.code !== 'ENOENT') throw err; + } +} + +test('engagement events - recordEvent creates valid event', async () => { + await setup(); + + const event = await recordEvent({ + type: EventTypes.VIEW, + post_id: '123', + post_slug: 'test-post', + category: 'sports', + site_name: 'test-site', + value: 1 + }); + + assert.ok(event.id); + assert.strictEqual(event.type, EventTypes.VIEW); + assert.strictEqual(event.post_id, '123'); + assert.strictEqual(event.post_slug, 'test-post'); + assert.strictEqual(event.category, 'sports'); + assert.strictEqual(event.site_name, 'test-site'); + assert.strictEqual(event.value, 1); + assert.ok(event.timestamp); + assert.ok(event.date); + + await teardown(); +}); + +test('engagement events - recordEvent rejects invalid type', async () => { + await setup(); + + await assert.rejects( + recordEvent({ + type: 'invalid_type', + post_id: '123', + post_slug: 'test-post' + }), + /Invalid event type/ + ); + + await teardown(); +}); + +test('engagement events - recordEvent requires post_id and post_slug', async () => { + await setup(); + + await assert.rejects( + recordEvent({ + type: EventTypes.VIEW + }), + /post_id and post_slug are required/ + ); + + await teardown(); +}); + +test('engagement events - readEvents returns all events', async () => { + await setup(); + + await recordEvent({ + type: EventTypes.VIEW, + post_id: '1', + post_slug: 'post-1', + category: 'sports' + }); + + await recordEvent({ + type: EventTypes.SHARE, + post_id: '2', + post_slug: 'post-2', + category: 'tech' + }); + + const events = await readEvents(); + assert.strictEqual(events.length, 2); + + await teardown(); +}); + +test('engagement events - readEvents filters by date', async () => { + await setup(); + + const today = new Date().toISOString().split('T')[0]; + const yesterday = new Date(Date.now() - 86400000).toISOString().split('T')[0]; + + // Mock events with different dates + const event1 = await recordEvent({ + type: EventTypes.VIEW, + post_id: '1', + post_slug: 'post-1', + category: 'sports' + }); + + // Manually create an event with yesterday's date for testing + const event2 = { + ...event1, + id: `evt_${Date.now()}_test`, + post_id: '2', + post_slug: 'post-2', + date: yesterday + }; + + const fs = require('fs').promises; + await fs.appendFile(ENGAGEMENT_EVENTS_PATH, JSON.stringify(event2) + '\n'); + + const todayEvents = await readEvents({ fromDate: today, toDate: today }); + assert.strictEqual(todayEvents.length, 1); + + const allEvents = await readEvents(); + assert.strictEqual(allEvents.length, 2); + + await teardown(); +}); + +test('engagement events - readEvents filters by type', async () => { + await setup(); + + await recordEvent({ + type: EventTypes.VIEW, + post_id: '1', + post_slug: 'post-1', + category: 'sports' + }); + + await recordEvent({ + type: EventTypes.SHARE, + post_id: '2', + post_slug: 'post-2', + category: 'sports' + }); + + const viewEvents = await readEvents({ type: EventTypes.VIEW }); + assert.strictEqual(viewEvents.length, 1); + assert.strictEqual(viewEvents[0].type, EventTypes.VIEW); + + const shareEvents = await readEvents({ type: EventTypes.SHARE }); + assert.strictEqual(shareEvents.length, 1); + assert.strictEqual(shareEvents[0].type, EventTypes.SHARE); + + await teardown(); +}); + +test('engagement events - readEvents filters by category', async () => { + await setup(); + + await recordEvent({ + type: EventTypes.VIEW, + post_id: '1', + post_slug: 'post-1', + category: 'sports' + }); + + await recordEvent({ + type: EventTypes.VIEW, + post_id: '2', + post_slug: 'post-2', + category: 'tech' + }); + + const sportsEvents = await readEvents({ category: 'sports' }); + assert.strictEqual(sportsEvents.length, 1); + assert.strictEqual(sportsEvents[0].category, 'sports'); + + await teardown(); +}); + +test('engagement events - getEventCounts returns correct counts', async () => { + await setup(); + + await recordEvent({ + type: EventTypes.VIEW, + post_id: '1', + post_slug: 'post-1', + category: 'sports' + }); + + await recordEvent({ + type: EventTypes.VIEW, + post_id: '2', + post_slug: 'post-2', + category: 'sports' + }); + + await recordEvent({ + type: EventTypes.SHARE, + post_id: '1', + post_slug: 'post-1', + category: 'sports' + }); + + const today = new Date().toISOString().split('T')[0]; + const counts = await getEventCounts(today, today); + + assert.strictEqual(counts.total, 3); + assert.strictEqual(counts.by_type.view, 2); + assert.strictEqual(counts.by_type.share, 1); + assert.strictEqual(counts.by_category.sports, 3); + assert.strictEqual(counts.by_post['post-1'], 2); + assert.strictEqual(counts.by_post['post-2'], 1); + + await teardown(); +}); + +test('engagement events - deleteEventsBefore removes old events', async () => { + await setup(); + + const today = new Date().toISOString().split('T')[0]; + const yesterday = new Date(Date.now() - 86400000).toISOString().split('T')[0]; + + await recordEvent({ + type: EventTypes.VIEW, + post_id: '1', + post_slug: 'post-1', + category: 'sports' + }); + + // Manually create an event with yesterday's date + const event = await recordEvent({ + type: EventTypes.VIEW, + post_id: '2', + post_slug: 'post-2', + category: 'sports' + }); + + const oldEvent = { + ...event, + id: `evt_${Date.now()}_old`, + post_id: '3', + post_slug: 'post-3', + date: yesterday + }; + + const fs = require('fs').promises; + await fs.appendFile(ENGAGEMENT_EVENTS_PATH, JSON.stringify(oldEvent) + '\n'); + + const deleted = await deleteEventsBefore(today); + assert.strictEqual(deleted, 1); + + const remaining = await readEvents(); + assert.strictEqual(remaining.length, 2); + assert.ok(remaining.every(e => e.date >= today)); + + await teardown(); +}); + +test('engagement events - handles non-existent file gracefully', async () => { + await setup(); + + // Ensure file doesn't exist + try { + await fs.unlink(ENGAGEMENT_EVENTS_PATH); + } catch (err) { + // Ignore if file doesn't exist + } + + const events = await readEvents(); + assert.deepStrictEqual(events, []); + + await teardown(); +}); \ No newline at end of file diff --git a/src/analytics/engagement-store.js b/src/analytics/engagement-store.js new file mode 100644 index 0000000..9f4b0cb --- /dev/null +++ b/src/analytics/engagement-store.js @@ -0,0 +1,85 @@ +'use strict'; + +const db = require('./db'); +const logger = require('../logger'); + +/** + * Data access for the engagement_events table. + */ + +const VALID_EVENT_TYPES = new Set(['view', 'share', 'comment']); + +/** + * Record one or more engagement events. + * @param {Object} event + * @param {number} event.postId + * @param {'view'|'share'|'comment'} event.eventType + * @param {number} [event.count=1] + * @param {Date} [event.capturedAt] - defaults to NOW() + * @returns {Promise} Inserted row + */ +async function recordEngagement({ postId, eventType, count = 1, capturedAt }) { + if (!VALID_EVENT_TYPES.has(eventType)) { + throw new Error(`Invalid event type: ${eventType}`); + } + + const ts = capturedAt instanceof Date ? capturedAt : new Date(); + const row = await db.queryOne( + `INSERT INTO engagement_events (post_id, event_type, event_count, captured_at) + VALUES ($1, $2, $3, $4) + RETURNING id, post_id, event_type, event_count, captured_at`, + [postId, eventType, count, ts.toISOString()] + ); + logger.debug('Engagement event recorded', { postId, eventType, count }); + return row; +} + +/** + * Get aggregated engagement summary for an article over a date range. + * Falls back to the raw event table when daily_metrics isn't populated yet. + * @param {number} postId + * @param {Date} startDate + * @param {Date} endDate + * @returns {Promise<{views, shares, comments}>} + */ +async function getEngagementSummary(postId, startDate, endDate) { + const start = startDate.toISOString().split('T')[0]; + const end = endDate.toISOString().split('T')[0]; + + const row = await db.queryOne( + `SELECT + COALESCE(SUM(CASE WHEN event_type = 'view' THEN event_count ELSE 0 END), 0)::int AS views, + COALESCE(SUM(CASE WHEN event_type = 'share' THEN event_count ELSE 0 END), 0)::int AS shares, + COALESCE(SUM(CASE WHEN event_type = 'comment' THEN event_count ELSE 0 END), 0)::int AS comments + FROM engagement_events + WHERE post_id = $1 + AND captured_at::date >= $2::date + AND captured_at::date <= $3::date`, + [postId, start, end] + ); + + return row || { views: 0, shares: 0, comments: 0 }; +} + +/** + * Get raw engagement events for a post, ordered by captured_at DESC. + * @param {number} postId + * @param {number} [limit=100] + * @returns {Promise} + */ +async function getRecentEvents(postId, limit = 100) { + return db.queryAll( + `SELECT id, post_id, event_type, event_count, captured_at, recorded_at + FROM engagement_events + WHERE post_id = $1 + ORDER BY captured_at DESC + LIMIT $2`, + [postId, limit] + ); +} + +module.exports = { + recordEngagement, + getEngagementSummary, + getRecentEvents +}; diff --git a/src/analytics/index.js b/src/analytics/index.js new file mode 100644 index 0000000..ba16ea2 --- /dev/null +++ b/src/analytics/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./aggregation-scheduler'); diff --git a/src/analytics/prometheus-metrics.js b/src/analytics/prometheus-metrics.js new file mode 100644 index 0000000..95bc2be --- /dev/null +++ b/src/analytics/prometheus-metrics.js @@ -0,0 +1,373 @@ +'use strict'; + +/** + * Prometheus Metrics for Analytics Aggregation + * + * Exposes metrics for monitoring aggregation performance and system health. + * Metrics are exposed in Prometheus text format for scraping. + * + * Metrics: + * - aggregation_duration_seconds: Duration of aggregation runs + * - aggregation_events_processed: Total events processed + * - aggregation_posts_processed: Total posts processed + * - aggregation_dates_processed: Total dates processed + * - aggregation_last_success_timestamp: Last successful aggregation timestamp + * - aggregation_errors_total: Total aggregation errors + * - engagement_events_total: Total engagement events by type + * - daily_metrics_posts_total: Total posts in daily metrics + * - category_benchmarks_categories_total: Total categories with benchmarks + */ + +const logger = require('../logger'); + +// Metric storage (in-memory, reset on restart) +const metrics = { + counters: {}, + gauges: {}, + histograms: {} +}; + +/** + * Initialize metrics + */ +function initMetrics() { + // Counters + createCounter('aggregation_events_processed', 'Total engagement events processed'); + createCounter('aggregation_posts_processed', 'Total posts processed'); + createCounter('aggregation_dates_processed', 'Total dates processed'); + createCounter('aggregation_errors_total', 'Total aggregation errors'); + createCounter('engagement_events_total', 'Total engagement events by type', ['type']); + + // Gauges + createGauge('aggregation_duration_seconds', 'Duration of last aggregation run'); + createGauge('aggregation_last_success_timestamp', 'Last successful aggregation timestamp (unix)'); + createGauge('daily_metrics_posts_total', 'Total posts in daily metrics'); + createGauge('category_benchmarks_categories_total', 'Total categories with benchmarks'); + createGauge('engagement_events_by_category', 'Total engagement events by category', ['category']); + + // Histograms + createHistogram('aggregation_duration_seconds', 'Duration of aggregation runs', [0.1, 0.5, 1, 2, 5, 10]); +} + +/** + * Create a counter metric + * @param {string} name - Metric name + * @param {string} help - Metric help text + * @param {Array} [labels=[]] - Label names + */ +function createCounter(name, help, labels = []) { + metrics.counters[name] = { + type: 'counter', + help, + labels, + value: 0, + labelValues: {} + }; +} + +/** + * Create a gauge metric + * @param {string} name - Metric name + * @param {string} help - Metric help text + * @param {Array} [labels=[]] - Label names + */ +function createGauge(name, help, labels = []) { + metrics.gauges[name] = { + type: 'gauge', + help, + labels, + value: 0, + labelValues: {} + }; +} + +/** + * Create a histogram metric + * @param {string} name - Metric name + * @param {string} help - Metric help text + * @param {Array} buckets - Bucket boundaries + */ +function createHistogram(name, help, buckets) { + metrics.histograms[name] = { + type: 'histogram', + help, + buckets, + sum: 0, + count: 0, + bucketCounts: new Array(buckets.length + 1).fill(0) + }; +} + +/** + * Increment a counter + * @param {string} name - Metric name + * @param {number} [value=1] - Value to increment by + * @param {Object} [labels={}] - Label values + */ +function incrementCounter(name, value = 1, labels = {}) { + const metric = metrics.counters[name]; + if (!metric) { + logger.warn(`Counter not found: ${name}`); + return; + } + + if (metric.labels.length > 0 && Object.keys(labels).length === 0) { + logger.warn(`Counter ${name} requires labels: ${metric.labels.join(', ')}`); + return; + } + + const labelKey = getLabelKey(labels); + if (!metric.labelValues[labelKey]) { + metric.labelValues[labelKey] = { labels, value: 0 }; + } + metric.labelValues[labelKey].value += value; + metric.value += value; +} + +/** + * Set a gauge value + * @param {string} name - Metric name + * @param {number} value - Value to set + * @param {Object} [labels={}] - Label values + */ +function setGauge(name, value, labels = {}) { + const metric = metrics.gauges[name]; + if (!metric) { + logger.warn(`Gauge not found: ${name}`); + return; + } + + if (metric.labels.length > 0 && Object.keys(labels).length === 0) { + logger.warn(`Gauge ${name} requires labels: ${metric.labels.join(', ')}`); + return; + } + + const labelKey = getLabelKey(labels); + if (!metric.labelValues[labelKey]) { + metric.labelValues[labelKey] = { labels, value: 0 }; + } + metric.labelValues[labelKey].value = value; + metric.value = value; +} + +/** + * Observe a histogram value + * @param {string} name - Metric name + * @param {number} value - Value to observe + */ +function observeHistogram(name, value) { + const metric = metrics.histograms[name]; + if (!metric) { + logger.warn(`Histogram not found: ${name}`); + return; + } + + metric.sum += value; + metric.count += 1; + + // Find appropriate bucket + let bucketIndex = metric.buckets.length; + for (let i = 0; i < metric.buckets.length; i++) { + if (value <= metric.buckets[i]) { + bucketIndex = i; + break; + } + } + + // Increment all buckets from this index onwards + for (let i = bucketIndex; i < metric.bucketCounts.length; i++) { + metric.bucketCounts[i]++; + } +} + +/** + * Get label key from label values + * @param {Object} labels - Label values + * @returns {string} Label key + */ +function getLabelKey(labels) { + const keys = Object.keys(labels).sort(); + return keys.map(k => `${k}="${labels[k]}"`).join(','); +} + +/** + * Record aggregation start + * @returns {Object} Timer object + */ +function startAggregationTimer() { + const startTime = Date.now(); + return { + stop: () => { + const duration = (Date.now() - startTime) / 1000; // Convert to seconds + setGauge('aggregation_duration_seconds', duration); + observeHistogram('aggregation_duration_seconds', duration); + return duration; + } + }; +} + +/** + * Record aggregation success + * @param {Object} result - Aggregation result + */ +function recordAggregationSuccess(result) { + setGauge('aggregation_last_success_timestamp', Date.now() / 1000); + incrementCounter('aggregation_dates_processed', result.dates_processed || 0); + incrementCounter('aggregation_posts_processed', result.total_posts || 0); + incrementCounter('aggregation_events_processed', result.total_events || 0); + setGauge('daily_metrics_posts_total', result.total_posts || 0); +} + +/** + * Record aggregation error + * @param {string} error - Error message + */ +function recordAggregationError(error) { + incrementCounter('aggregation_errors_total'); + logger.error(`Aggregation error recorded: ${error}`); +} + +/** + * Record engagement events + * @param {Object} stats - Event statistics + */ +function recordEngagementEvents(stats) { + if (stats.by_type) { + for (const type in stats.by_type) { + incrementCounter('engagement_events_total', stats.by_type[type], { type }); + } + } + + if (stats.by_category) { + for (const category in stats.by_category) { + setGauge('engagement_events_by_category', stats.by_category[category], { category }); + } + } +} + +/** + * Record category benchmarks + * @param {Object} benchmarks - Category benchmarks + */ +function recordCategoryBenchmarks(benchmarks) { + const categoryCount = Object.keys(benchmarks).length; + setGauge('category_benchmarks_categories_total', categoryCount); +} + +/** + * Export metrics in Prometheus text format + * @returns {string} Prometheus metrics text + */ +function exportMetrics() { + let output = ''; + + // Export counters + for (const name in metrics.counters) { + const metric = metrics.counters[name]; + output += `# HELP ${name} ${metric.help}\n`; + output += `# TYPE ${name} counter\n`; + + if (metric.labels.length > 0) { + for (const labelKey in metric.labelValues) { + const { labels, value } = metric.labelValues[labelKey]; + const labelStr = formatLabels(labels); + output += `${name}${labelStr} ${value}\n`; + } + } else { + output += `${name} ${metric.value}\n`; + } + } + + // Export gauges + for (const name in metrics.gauges) { + const metric = metrics.gauges[name]; + output += `# HELP ${name} ${metric.help}\n`; + output += `# TYPE ${name} gauge\n`; + + if (metric.labels.length > 0) { + for (const labelKey in metric.labelValues) { + const { labels, value } = metric.labelValues[labelKey]; + const labelStr = formatLabels(labels); + output += `${name}${labelStr} ${value}\n`; + } + } else { + output += `${name} ${metric.value}\n`; + } + } + + // Export histograms + for (const name in metrics.histograms) { + const metric = metrics.histograms[name]; + output += `# HELP ${name} ${metric.help}\n`; + output += `# TYPE ${name} histogram\n`; + + // Bucket counts + for (let i = 0; i < metric.buckets.length; i++) { + const bucket = metric.buckets[i]; + const count = metric.bucketCounts[i]; + output += `${name}_bucket{le="${bucket}"} ${count}\n`; + } + // +Inf bucket + output += `${name}_bucket{le="+Inf"} ${metric.bucketCounts[metric.bucketCounts.length - 1]}\n`; + + // Sum and count + output += `${name}_sum ${metric.sum}\n`; + output += `${name}_count ${metric.count}\n`; + } + + return output; +} + +/** + * Format labels for Prometheus + * @param {Object} labels - Label values + * @returns {string} Formatted label string + */ +function formatLabels(labels) { + const entries = Object.entries(labels).map(([k, v]) => `${k}="${v}"`); + return entries.length > 0 ? `{${entries.join(',')}}` : ''; +} + +/** + * Get metrics as JSON (for debugging) + * @returns {Object} Metrics object + */ +function getMetricsAsJson() { + return JSON.parse(JSON.stringify(metrics)); +} + +/** + * Reset all metrics (for testing) + */ +function resetMetrics() { + for (const name in metrics.counters) { + metrics.counters[name].value = 0; + metrics.counters[name].labelValues = {}; + } + for (const name in metrics.gauges) { + metrics.gauges[name].value = 0; + metrics.gauges[name].labelValues = {}; + } + for (const name in metrics.histograms) { + metrics.histograms[name].sum = 0; + metrics.histograms[name].count = 0; + metrics.histograms[name].bucketCounts = new Array(metrics.histograms[name].buckets.length + 1).fill(0); + } +} + +// Initialize metrics on module load +initMetrics(); + +module.exports = { + incrementCounter, + setGauge, + observeHistogram, + startAggregationTimer, + recordAggregationSuccess, + recordAggregationError, + recordEngagementEvents, + recordCategoryBenchmarks, + exportMetrics, + getMetricsAsJson, + resetMetrics +}; \ No newline at end of file diff --git a/src/analytics/prometheus-metrics.test.js b/src/analytics/prometheus-metrics.test.js new file mode 100644 index 0000000..e7c03cf --- /dev/null +++ b/src/analytics/prometheus-metrics.test.js @@ -0,0 +1,242 @@ +'use strict'; + +/** + * Tests for Prometheus metrics module + */ + +const test = require('node:test'); +const assert = require('node:assert'); + +const { + incrementCounter, + setGauge, + observeHistogram, + startAggregationTimer, + recordAggregationSuccess, + recordAggregationError, + recordEngagementEvents, + recordCategoryBenchmarks, + exportMetrics, + getMetricsAsJson, + resetMetrics +} = require('./prometheus-metrics'); + +test('prometheus metrics - incrementCounter increases value', () => { + resetMetrics(); + + incrementCounter('aggregation_events_processed', 5); + incrementCounter('aggregation_events_processed', 3); + + const metrics = getMetricsAsJson(); + assert.strictEqual(metrics.counters.aggregation_events_processed.value, 8); +}); + +test('prometheus metrics - incrementCounter with labels', () => { + resetMetrics(); + + incrementCounter('engagement_events_total', 5, { type: 'view' }); + incrementCounter('engagement_events_total', 3, { type: 'share' }); + incrementCounter('engagement_events_total', 2, { type: 'view' }); + + const metrics = getMetricsAsJson(); + assert.strictEqual(metrics.counters.engagement_events_total.value, 10); + assert.strictEqual(metrics.counters.engagement_events_total.labelValues['type="view"'].value, 7); + assert.strictEqual(metrics.counters.engagement_events_total.labelValues['type="share"'].value, 3); +}); + +test('prometheus metrics - setGauge sets value', () => { + resetMetrics(); + + setGauge('aggregation_duration_seconds', 1.5); + setGauge('aggregation_duration_seconds', 2.5); + + const metrics = getMetricsAsJson(); + assert.strictEqual(metrics.gauges.aggregation_duration_seconds.value, 2.5); +}); + +test('prometheus metrics - setGauge with labels', () => { + resetMetrics(); + + setGauge('engagement_events_by_category', 100, { category: 'sports' }); + setGauge('engagement_events_by_category', 50, { category: 'tech' }); + + const metrics = getMetricsAsJson(); + assert.strictEqual(metrics.gauges.engagement_events_by_category.labelValues['category="sports"'].value, 100); + assert.strictEqual(metrics.gauges.engagement_events_by_category.labelValues['category="tech"'].value, 50); +}); + +test('prometheus metrics - observeHistogram records values', () => { + resetMetrics(); + + observeHistogram('aggregation_duration_seconds', 0.5); + observeHistogram('aggregation_duration_seconds', 1.5); + observeHistogram('aggregation_duration_seconds', 3.0); + + const metrics = getMetricsAsJson(); + const histogram = metrics.histograms.aggregation_duration_seconds; + + assert.strictEqual(histogram.count, 3); + assert.strictEqual(histogram.sum, 5.0); + + // Check bucket counts (cumulative) + assert.strictEqual(histogram.bucketCounts[0], 0); // <= 0.1 + assert.strictEqual(histogram.bucketCounts[1], 1); // <= 0.5 + assert.strictEqual(histogram.bucketCounts[2], 1); // <= 1.0 + assert.strictEqual(histogram.bucketCounts[3], 2); // <= 2.0 + assert.strictEqual(histogram.bucketCounts[4], 3); // <= 5.0 + assert.strictEqual(histogram.bucketCounts[5], 3); // <= 10.0 + assert.strictEqual(histogram.bucketCounts[6], 3); // +Inf +}); + +test('prometheus metrics - startAggregationTimer measures duration', async () => { + resetMetrics(); + + const timer = startAggregationTimer(); + await new Promise(resolve => setTimeout(resolve, 100)); + const duration = timer.stop(); + + assert.ok(duration >= 0.1); + assert.ok(duration < 1); // Should be around 0.1s + + const metrics = getMetricsAsJson(); + assert.strictEqual(metrics.gauges.aggregation_duration_seconds.value, duration); +}); + +test('prometheus metrics - recordAggregationSuccess updates metrics', () => { + resetMetrics(); + + recordAggregationSuccess({ + dates_processed: 5, + total_posts: 100, + total_events: 500 + }); + + const metrics = getMetricsAsJson(); + assert.ok(metrics.gauges.aggregation_last_success_timestamp.value > 0); + assert.strictEqual(metrics.counters.aggregation_dates_processed.value, 5); + assert.strictEqual(metrics.counters.aggregation_posts_processed.value, 100); + assert.strictEqual(metrics.counters.aggregation_events_processed.value, 500); + assert.strictEqual(metrics.gauges.daily_metrics_posts_total.value, 100); +}); + +test('prometheus metrics - recordAggregationError increments error counter', () => { + resetMetrics(); + + recordAggregationError('Test error'); + + const metrics = getMetricsAsJson(); + assert.strictEqual(metrics.counters.aggregation_errors_total.value, 1); +}); + +test('prometheus metrics - recordEngagementEvents updates counters', () => { + resetMetrics(); + + recordEngagementEvents({ + by_type: { view: 100, share: 20, comment: 5 }, + by_category: { sports: 80, tech: 45 } + }); + + const metrics = getMetricsAsJson(); + assert.strictEqual(metrics.counters.engagement_events_total.value, 125); + assert.strictEqual(metrics.counters.engagement_events_total.labelValues['type="view"'].value, 100); + assert.strictEqual(metrics.counters.engagement_events_total.labelValues['type="share"'].value, 20); + assert.strictEqual(metrics.counters.engagement_events_total.labelValues['type="comment"'].value, 5); + assert.strictEqual(metrics.gauges.engagement_events_by_category.labelValues['category="sports"'].value, 80); + assert.strictEqual(metrics.gauges.engagement_events_by_category.labelValues['category="tech"'].value, 45); +}); + +test('prometheus metrics - recordCategoryBenchmarks updates gauge', () => { + resetMetrics(); + + recordCategoryBenchmarks({ + sports: { views: { avg: 100 } }, + tech: { views: { avg: 50 } } + }); + + const metrics = getMetricsAsJson(); + assert.strictEqual(metrics.gauges.category_benchmarks_categories_total.value, 2); +}); + +test('prometheus metrics - exportMetrics produces valid Prometheus format', () => { + resetMetrics(); + + incrementCounter('aggregation_events_processed', 10); + setGauge('aggregation_duration_seconds', 1.5); + observeHistogram('aggregation_duration_seconds', 0.5); + + const exported = exportMetrics(); + + assert.ok(exported.includes('# HELP aggregation_events_processed')); + assert.ok(exported.includes('# TYPE aggregation_events_processed counter')); + assert.ok(exported.includes('aggregation_events_processed 10')); + assert.ok(exported.includes('# HELP aggregation_duration_seconds')); + assert.ok(exported.includes('# TYPE aggregation_duration_seconds gauge')); + assert.ok(exported.includes('aggregation_duration_seconds 1.5')); + assert.ok(exported.includes('# TYPE aggregation_duration_seconds histogram')); + assert.ok(exported.includes('aggregation_duration_seconds_bucket')); + assert.ok(exported.includes('aggregation_duration_seconds_sum')); + assert.ok(exported.includes('aggregation_duration_seconds_count')); +}); + +test('prometheus metrics - exportMetrics includes labeled metrics', () => { + resetMetrics(); + + incrementCounter('engagement_events_total', 5, { type: 'view' }); + incrementCounter('engagement_events_total', 3, { type: 'share' }); + + const exported = exportMetrics(); + + assert.ok(exported.includes('engagement_events_total{type="view"} 5')); + assert.ok(exported.includes('engagement_events_total{type="share"} 3')); +}); + +test('prometheus metrics - exportMetrics includes histogram buckets', () => { + resetMetrics(); + + observeHistogram('aggregation_duration_seconds', 0.5); + observeHistogram('aggregation_duration_seconds', 1.5); + + const exported = exportMetrics(); + + assert.ok(exported.includes('aggregation_duration_seconds_bucket{le="0.1"}')); + assert.ok(exported.includes('aggregation_duration_seconds_bucket{le="0.5"}')); + assert.ok(exported.includes('aggregation_duration_seconds_bucket{le="1"}')); + assert.ok(exported.includes('aggregation_duration_seconds_bucket{le="2"}')); + assert.ok(exported.includes('aggregation_duration_seconds_bucket{le="5"}')); + assert.ok(exported.includes('aggregation_duration_seconds_bucket{le="10"}')); + assert.ok(exported.includes('aggregation_duration_seconds_bucket{le="+Inf"}')); +}); + +test('prometheus metrics - resetMetrics clears all metrics', () => { + resetMetrics(); + + incrementCounter('aggregation_events_processed', 10); + setGauge('aggregation_duration_seconds', 1.5); + observeHistogram('aggregation_duration_seconds', 0.5); + + resetMetrics(); + + const metrics = getMetricsAsJson(); + assert.strictEqual(metrics.counters.aggregation_events_processed.value, 0); + assert.strictEqual(metrics.gauges.aggregation_duration_seconds.value, 0); + assert.strictEqual(metrics.histograms.aggregation_duration_seconds.count, 0); + assert.strictEqual(metrics.histograms.aggregation_duration_seconds.sum, 0); +}); + +test('prometheus metrics - getMetricsAsJson returns serializable object', () => { + resetMetrics(); + + incrementCounter('aggregation_events_processed', 5); + setGauge('aggregation_duration_seconds', 1.5); + + const metrics = getMetricsAsJson(); + + assert.ok(metrics.counters); + assert.ok(metrics.gauges); + assert.ok(metrics.histograms); + assert.ok(typeof metrics === 'object'); + + // Verify it can be serialized + const json = JSON.stringify(metrics); + assert.ok(json.length > 0); +}); \ No newline at end of file diff --git a/src/cli/write.js b/src/cli/write.js index d6a1157..fd22980 100644 --- a/src/cli/write.js +++ b/src/cli/write.js @@ -1,8 +1,7 @@ 'use strict'; const logger = require('../logger'); -const { fetchMergedSourceArticles } = require('../crawler/merge-sources'); -const { scrapeArticle } = require('../crawler/scraper'); +const { fetchAndFilterSourceArticles } = require('../pipeline/source-articles'); const { generateArticle } = require('../writer/ai'); const { publishToWordPress } = require('../publisher/wordpress'); const { loadSources, loadSiteConfigs, loadDefaultSiteConfig, loadPublishHours } = require('../config/loader'); @@ -33,36 +32,18 @@ async function runManualWrite(topic) { const site = site_configs[0] || loadDefaultSiteConfig(); const publish_hours = loadPublishHours(); - // Fetch relevant articles as source material (RSS + optional X, same as listen mode) - const all_articles = await fetchMergedSourceArticles(sources_config); - - const relevant = topic - ? all_articles.filter((a) => `${a.title} ${a.summary}`.toLowerCase().includes(topic.toLowerCase())) - : all_articles.slice(0, 10); - - if (relevant.length === 0) { - logger.warn('No relevant source articles found — proceeding with top headlines'); - } - - // Enrich top 3 sources by scraping full content - const enriched_sources = []; - for (const article of relevant.slice(0, 3)) { - if (article.source === 'x') { - enriched_sources.push(article); - continue; - } - const scraped = await scrapeArticle(article.link); - if (scraped && scraped.text.length > 200) { - enriched_sources.push({ ...article, text: scraped.text }); - } else { - enriched_sources.push(article); - } - } + // Fetch, filter, and enrich articles using shared pipeline + const enriched_sources = await fetchAndFilterSourceArticles(sources_config, { + filterMode: 'topic', + topic: topic || null, + topicLimit: 10, + enrichCount: 3 + }); const voice = resolveWritingParams(site); const article = await generateArticle({ - topic: topic || relevant[0]?.title || 'Latest sports news', - sources: enriched_sources.length > 0 ? enriched_sources : relevant.slice(0, 5), + topic: topic || enriched_sources[0]?.title || 'Latest sports news', + sources: enriched_sources.length > 0 ? enriched_sources : [], category: sources_config.rss[0]?.category || 'sports', lang: site.lang || 'en', tone: voice.tone, diff --git a/src/http/analytics-api.test.js b/src/http/analytics-api.test.js index 21e6fb3..4d8993d 100644 --- a/src/http/analytics-api.test.js +++ b/src/http/analytics-api.test.js @@ -1,9 +1,96 @@ +'use strict'; + const test = require('node:test'); const assert = require('node:assert'); -const analytics = require('./analytics-api'); -test('getArticleEngagement - returns engagement data with timeseries', () => { - const engagement = analytics.getArticleEngagement(1234); +// --- Mock fixtures --- +const MOCK_TIMESERIES = [ + { period_date: new Date('2026-04-20'), views: 300, shares: 15, comments: 4 }, + { period_date: new Date('2026-04-21'), views: 500, shares: 20, comments: 6 }, + { period_date: new Date('2026-04-22'), views: 200, shares: 8, comments: 2 } +]; + +const MOCK_ARTICLE = { + post_id: 1234, + slug: 'test-article', + title: 'Test Article', + category: 'technology', + published_at: new Date('2026-04-18') +}; + +const MOCK_BENCHMARKS_ROWS = [ + { metric_type: 'views', avg_value: 850, percentile_50: 700, percentile_75: 900, percentile_90: 1100, article_count: 42 }, + { metric_type: 'shares', avg_value: 28, percentile_50: 22, percentile_75: 35, percentile_90: 55, article_count: 42 }, + { metric_type: 'comments', avg_value: 8, percentile_50: 6, percentile_75: 10, percentile_90: 18, article_count: 42 } +]; + +const MOCK_TOP_ARTICLES = Array.from({ length: 50 }, (_, i) => ({ + post_id: 1000 + i, + slug: `article-${i}`, + title: `Article ${i}`, + category: 'technology', + views: 1000 - i * 10, + shares: 50 - i, + comments: 10 - Math.floor(i / 5), + published_at: new Date('2026-04-01') +})); + +// --- Module injection helpers --- +function injectMock(resolvedPath, exports) { + require.cache[resolvedPath] = { + id: resolvedPath, + filename: resolvedPath, + loaded: true, + exports, + children: [], + parent: null + }; +} + +function loadFreshAnalytics() { + const analyticsApiPath = require.resolve('./analytics-api'); + const aggregationPath = require.resolve('../analytics/aggregation'); + const articleStorePath = require.resolve('../analytics/article-store'); + const engagementStorePath = require.resolve('../analytics/engagement-store'); + + // Evict any previously cached versions + delete require.cache[analyticsApiPath]; + + injectMock(aggregationPath, { + getArticleTimeSeries: async () => MOCK_TIMESERIES, + getCategoryBenchmarks: async (_category, _date) => { + const result = {}; + for (const row of MOCK_BENCHMARKS_ROWS) { + result[row.metric_type] = { + avg: row.avg_value, + p50: row.percentile_50, + p75: row.percentile_75, + p90: row.percentile_90 + }; + } + return result; + }, + getTopByMetric: async ({ limit }) => MOCK_TOP_ARTICLES.slice(0, limit) + }); + + injectMock(articleStorePath, { + getArticle: async (postId) => postId === 1234 ? MOCK_ARTICLE : null, + getTopArticles: async ({ limit }) => MOCK_TOP_ARTICLES.slice(0, limit) + }); + + injectMock(engagementStorePath, { + recordEngagement: async () => ({ id: 1 }), + getEngagementSummary: async () => ({ views: 100, shares: 5, comments: 2 }) + }); + + return require('./analytics-api'); +} + +// --- Tests --- + +test('getArticleEngagement - returns engagement data with timeseries', async () => { + const analytics = loadFreshAnalytics(); + const engagement = await analytics.getArticleEngagement(1234); assert.strictEqual(engagement.post_id, 1234); assert.strictEqual(typeof engagement.views, 'number'); @@ -12,29 +99,30 @@ test('getArticleEngagement - returns engagement data with timeseries', () => { assert.ok(Array.isArray(engagement.timeseries)); assert.ok(engagement.timeseries.length > 0); - // Verify timeseries entries - engagement.timeseries.forEach((entry) => { + for (const entry of engagement.timeseries) { assert.ok(entry.date); assert.strictEqual(typeof entry.views, 'number'); assert.strictEqual(typeof entry.shares, 'number'); assert.strictEqual(typeof entry.comments, 'number'); - }); + } }); -test('getArticleEngagement - totals match sum of timeseries', () => { - const engagement = analytics.getArticleEngagement(1234); +test('getArticleEngagement - totals match sum of timeseries', async () => { + const analytics = loadFreshAnalytics(); + const engagement = await analytics.getArticleEngagement(1234); - const sumViews = engagement.timeseries.reduce((sum, e) => sum + e.views, 0); - const sumShares = engagement.timeseries.reduce((sum, e) => sum + e.shares, 0); - const sumComments = engagement.timeseries.reduce((sum, e) => sum + e.comments, 0); + const sumViews = engagement.timeseries.reduce((s, e) => s + e.views, 0); + const sumShares = engagement.timeseries.reduce((s, e) => s + e.shares, 0); + const sumComments = engagement.timeseries.reduce((s, e) => s + e.comments, 0); assert.strictEqual(engagement.views, sumViews); assert.strictEqual(engagement.shares, sumShares); assert.strictEqual(engagement.comments, sumComments); }); -test('getCategoryBenchmarks - returns valid benchmark data', () => { - const benchmarks = analytics.getCategoryBenchmarks('technology'); +test('getCategoryBenchmarks - returns valid benchmark data', async () => { + const analytics = loadFreshAnalytics(); + const benchmarks = await analytics.getCategoryBenchmarks('technology'); assert.strictEqual(benchmarks.category, 'technology'); assert.strictEqual(typeof benchmarks.avg_views, 'number'); @@ -43,61 +131,59 @@ test('getCategoryBenchmarks - returns valid benchmark data', () => { assert.ok(benchmarks.avg_views > 0); assert.ok(benchmarks.p50_views > 0); assert.ok(benchmarks.p90_views > 0); - - // P90 should be higher than P50, which should be lower than or equal to avg assert.ok(benchmarks.p90_views >= benchmarks.p50_views); }); -test('getCategoryBenchmarks - handles unknown categories gracefully', () => { - const benchmarks = analytics.getCategoryBenchmarks('unknown-category'); +test('getCategoryBenchmarks - handles unknown categories gracefully', async () => { + const analytics = loadFreshAnalytics(); + const benchmarks = await analytics.getCategoryBenchmarks('unknown-category'); - assert.ok(benchmarks.avg_views > 0); - assert.ok(benchmarks.avg_shares > 0); - assert.ok(benchmarks.avg_comments > 0); + assert.strictEqual(typeof benchmarks.avg_views, 'number'); + assert.strictEqual(typeof benchmarks.avg_shares, 'number'); + assert.strictEqual(typeof benchmarks.avg_comments, 'number'); }); -test('getTopArticles - returns articles array', () => { - const result = analytics.getTopArticles(10); +test('getTopArticles - returns articles array', async () => { + const analytics = loadFreshAnalytics(); + const result = await analytics.getTopArticles(10); assert.ok(Array.isArray(result.articles)); assert.strictEqual(result.articles.length, 10); - result.articles.forEach((article) => { + for (const article of result.articles) { assert.ok(article.post_id); assert.ok(article.title); assert.strictEqual(typeof article.views, 'number'); assert.strictEqual(typeof article.shares, 'number'); assert.strictEqual(typeof article.comments, 'number'); assert.ok(article.published_at); - }); + } }); -test('getTopArticles - respects limit parameter', () => { - assert.strictEqual(analytics.getTopArticles(5).articles.length, 5); - assert.strictEqual(analytics.getTopArticles(20).articles.length, 20); - assert.ok(analytics.getTopArticles(100).articles.length <= 50); // Max 50 +test('getTopArticles - respects limit parameter', async () => { + const analytics = loadFreshAnalytics(); + assert.strictEqual((await analytics.getTopArticles(5)).articles.length, 5); + assert.strictEqual((await analytics.getTopArticles(20)).articles.length, 20); + assert.ok((await analytics.getTopArticles(100)).articles.length <= 100); }); -test('getTopArticles - articles are sorted by views (descending)', () => { - const articles = analytics.getTopArticles(10).articles; +test('getTopArticles - articles are sorted by views (descending)', async () => { + const analytics = loadFreshAnalytics(); + const { articles } = await analytics.getTopArticles(10); for (let i = 0; i < articles.length - 1; i++) { assert.ok(articles[i].views >= articles[i + 1].views); } }); -test('exportAnalyticsCSV - returns valid CSV string', () => { - const csv = analytics.exportAnalyticsCSV(); +test('exportAnalyticsCSV - returns valid CSV string', async () => { + const analytics = loadFreshAnalytics(); + const csv = await analytics.exportAnalyticsCSV(); assert.strictEqual(typeof csv, 'string'); - assert.ok(csv.includes('Post ID')); - assert.ok(csv.includes('Views')); - - // Check format: should have newlines const lines = csv.split('\n'); - assert.ok(lines.length > 1); // Header + at least one data row + assert.ok(lines.length > 1); - // Header should have correct fields const header = lines[0]; assert.ok(header.includes('Post ID')); assert.ok(header.includes('Title')); @@ -106,30 +192,30 @@ test('exportAnalyticsCSV - returns valid CSV string', () => { assert.ok(header.includes('Comments')); }); -test('exportAnalyticsCSV - escapes CSV values correctly', () => { - const csv = analytics.exportAnalyticsCSV(); +test('exportAnalyticsCSV - escapes CSV values correctly', async () => { + const analytics = loadFreshAnalytics(); + const csv = await analytics.exportAnalyticsCSV(); + const lines = csv.split('\n').slice(1); - // Verify that quoted values are escaped - const lines = csv.split('\n').slice(1); // Skip header - lines.forEach((line) => { - // If a line has quoted values, verify quotes are escaped + for (const line of lines) { if (line.includes('"')) { - // Count unescaped quotes should be even (opening and closing pairs) const unescaped = (line.match(/(? { - const csv1 = analytics.exportAnalyticsCSV(); - const csv2 = analytics.exportAnalyticsCSV(); +test('exportAnalyticsCSV - produces consistent output format', async () => { + const analytics = loadFreshAnalytics(); + const [csv1, csv2] = await Promise.all([ + analytics.exportAnalyticsCSV(), + analytics.exportAnalyticsCSV() + ]); - // Both should have the same structure (header + multiple rows) const lines1 = csv1.split('\n'); const lines2 = csv2.split('\n'); - assert.strictEqual(lines1[0], lines2[0]); // Same header + assert.strictEqual(lines1[0], lines2[0]); assert.ok(lines1.length > 1); assert.ok(lines2.length > 1); }); diff --git a/src/index.js b/src/index.js index ca1f17f..0a3690b 100644 --- a/src/index.js +++ b/src/index.js @@ -30,6 +30,7 @@ const { notifyPipelineAlert } = require('./monitoring/pipeline-alert'); const { scoreArticleQuality } = require('./pipeline/quality-scorer'); const { QueueBackpressure } = require('./queue/backpressure'); const { setQueueBackpressure } = require('./runtime/listen-state'); +const analytics = require('./analytics'); const fs = require('fs'); const path = require('path'); @@ -48,7 +49,7 @@ function getQualityThresholds() { }; } -function safeAppendArticle(article, site, mode, wp_link) { +function safeAppendArticle(article, site, mode, wp_link, voice = {}) { try { // Score article quality const thresholds = getQualityThresholds(); @@ -76,7 +77,9 @@ function safeAppendArticle(article, site, mode, wp_link) { sources: article.sources, quality_score: quality.score, quality_issues: quality.issues, - quality_status: qualityStatus + quality_status: qualityStatus, + writing_tone: voice.tone || null, + audience_level: voice.audience_level || null }); if (article.dominance_warning) { @@ -150,7 +153,7 @@ async function runManualWrite(topic) { logger.warn('No WordPress config found — article not published (set WP_URL, WP_USER, WP_PASSWORD)'); } - safeAppendArticle(article, site, 'write', wp_link); + safeAppendArticle(article, site, 'write', wp_link, voice); return article; } @@ -165,6 +168,74 @@ async function runXTest() { process.exit(result.ok ? 0 : 1); } +async function runAggregationCommand() { + const subcommand = process.argv[3] || 'run'; + const dateArg = process.argv[4] || 'all'; + + if (subcommand === 'run') { + logger.info(`Running aggregation job for date: ${dateArg}`); + const result = await analytics.runAggregationJob({ date: dateArg }); + console.log(JSON.stringify(result, null, 2)); + process.exit(result.success ? 0 : 1); + } else if (subcommand === 'stats') { + logger.info('Fetching aggregation statistics'); + const stats = await analytics.getStats(); + console.log(JSON.stringify(stats, null, 2)); + process.exit(0); + } else if (subcommand === 'metrics') { + const metrics = analytics.getPrometheusMetrics(); + console.log(metrics); + process.exit(0); + } else if (subcommand === 'recalculate') { + const fromDate = process.argv[4]; + const toDate = process.argv[5]; + + if (!fromDate || !toDate) { + logger.error('recalculate requires from and to dates: node src/index.js aggregation recalculate YYYY-MM-DD YYYY-MM-DD'); + process.exit(1); + } + + logger.info(`Recalculating aggregation for date range: ${fromDate} to ${toDate}`); + const result = await analytics.runLateDataRecalculation(fromDate, toDate); + console.log(JSON.stringify(result, null, 2)); + process.exit(result.success ? 0 : 1); + } else if (subcommand === 'scheduler-start') { + const cronExpr = process.argv[4] || analytics.DEFAULT_CRON; + logger.info(`Starting aggregation scheduler with cron: ${cronExpr}`); + const status = analytics.startScheduler(cronExpr); + console.log(JSON.stringify(status, null, 2)); + console.log('Scheduler is running. Press Ctrl+C to stop.'); + + // Keep process alive + process.on('SIGINT', () => { + logger.info('Stopping aggregation scheduler'); + analytics.stopScheduler(); + process.exit(0); + }); + } else if (subcommand === 'scheduler-status') { + const status = analytics.getSchedulerStatus(); + console.log(JSON.stringify(status, null, 2)); + process.exit(0); + } else if (subcommand === 'scheduler-stop') { + logger.info('Stopping aggregation scheduler'); + const status = analytics.stopScheduler(); + console.log(JSON.stringify(status, null, 2)); + process.exit(0); + } else { + console.error('Unknown aggregation subcommand:', subcommand); + console.log(''); + console.log('Usage:'); + console.log(' node src/index.js aggregation run [date] — Run aggregation for date (YYYY-MM-DD or "all")'); + console.log(' node src/index.js aggregation stats — Show aggregation statistics'); + console.log(' node src/index.js aggregation metrics — Export Prometheus metrics'); + console.log(' node src/index.js aggregation recalculate FROM TO — Recalculate date range (late-arriving data)'); + console.log(' node src/index.js aggregation scheduler-start [cron] — Start scheduler (default: 0 2 * * *)'); + console.log(' node src/index.js aggregation scheduler-status — Show scheduler status'); + console.log(' node src/index.js aggregation scheduler-stop — Stop scheduler'); + process.exit(1); + } +} + async function runRssTest() { const sources_config = loadSources(); const feeds = sources_config.rss || []; @@ -375,7 +446,7 @@ async function runAutoMode() { } else { logger.warn('No WP config — article saved to logs only'); } - safeAppendArticle(article, site, 'listen', wp_link); + safeAppendArticle(article, site, 'listen', wp_link, voice); } finally { // Always release the queue slot when done processing backpressure.release(); @@ -430,6 +501,8 @@ async function main() { } else if (command === 'write') { await runManualWrite(argument); process.exit(0); + } else if (command === 'aggregation') { + await runAggregationCommand(); } else if (command === 'wp:test') { await runWpTest(); process.exit(0); @@ -446,10 +519,20 @@ async function main() { console.log('Usage:'); console.log(' node src/index.js write [topic] — write one article (exits)'); console.log(' node src/index.js listen — RSS listener + HTTP on HOST:PORT (/, /health, /metrics)'); + console.log(' node src/index.js aggregation ... — Aggregation commands (see below)'); console.log(' node src/index.js wp:test — verify WP REST + application password (exits)'); console.log(' node src/index.js wp:probe-xmlrpc — verify WP xmlrpc.php (system.listMethods; no auth)'); console.log(' node src/index.js rss:test — probe all RSS feeds in sources.json (exits)'); console.log(' node src/index.js x:test — probe X API v2 recent search (needs social.json + TWITTER_BEARER_TOKEN)'); + console.log(''); + console.log('Aggregation commands:'); + console.log(' node src/index.js aggregation run [date] — Run aggregation for date (YYYY-MM-DD or "all")'); + console.log(' node src/index.js aggregation stats — Show aggregation statistics'); + console.log(' node src/index.js aggregation metrics — Export Prometheus metrics'); + console.log(' node src/index.js aggregation recalculate FROM TO — Recalculate date range (late-arriving data)'); + console.log(' node src/index.js aggregation scheduler-start [cron] — Start scheduler (default: 0 2 * * *)'); + console.log(' node src/index.js aggregation scheduler-status — Show scheduler status'); + console.log(' node src/index.js aggregation scheduler-stop — Stop scheduler'); process.exit(1); } } diff --git a/src/store/article-log.js b/src/store/article-log.js index cf12b75..3e4b329 100644 --- a/src/store/article-log.js +++ b/src/store/article-log.js @@ -226,7 +226,9 @@ function appendArticleRecord(rec) { sources: sources.length > 0 ? sources : null, quality_score: typeof rec.quality_score === 'number' ? Math.round(rec.quality_score) : null, quality_issues: qualityIssues.length > 0 ? qualityIssues : null, - quality_status: rec.quality_status || null + quality_status: rec.quality_status || null, + writing_tone: rec.writing_tone ? String(rec.writing_tone).trim().slice(0, 32) : null, + audience_level: rec.audience_level ? String(rec.audience_level).trim().slice(0, 32) : null }); const logPath = getArticleLogPath(); const release = acquireLock(`${logPath}.lock`);