diff --git a/.gitignore b/.gitignore index 6835445..811fb5c 100644 --- a/.gitignore +++ b/.gitignore @@ -5,8 +5,10 @@ coverage/ logs/ *.log -# Runtime article log (restore from backup/ or .backup/; never commit live data) +# Runtime data files (restore from backup/ or regenerate; never commit live data) data/article-index.jsonl +data/listener-guid-store.json +data/*.json # Local snapshot directory (Git-tracked copies live under backup/ when committed) .backup/ diff --git a/docs/DB_SCHEMA.md b/docs/DB_SCHEMA.md new file mode 100644 index 0000000..382ce84 --- /dev/null +++ b/docs/DB_SCHEMA.md @@ -0,0 +1,236 @@ +# Database & Caching: Schema and Strategy Reference + +_Updated: 2026-04-27 — BIT-14772_ + +--- + +## 1. Article Index (JSONL file store) + +**Path:** `data/article-index.jsonl` (override: `ARTICLE_LOG_PATH`) + +Each line is a JSON object representing one published/generated article. + +| Field | Type | Description | +|---|---|---| +| `at` | ISO timestamp | Record creation time (used as row ID when slug is empty) | +| `title` | string | Article headline | +| `subtitle` | string | Article sub-headline | +| `slug` | string | URL slug — used as primary row ID when non-empty | +| `summary` | string (≤500 chars) | AI-generated summary | +| `wp_link` | string \| null | WordPress published URL | +| `site_name` | string \| null | Target WordPress site | +| `mode` | `write` \| `listen` \| `unknown` | How the article was generated | +| `editorial_status` | `pending` \| `approved` \| `rejected` | Editorial workflow state | +| `tags` | string[] \| null | Up to 20 tags | +| `category` | string \| null | Article category | +| `sources` | `{url, publication}[]` \| null | Up to 10 source references | +| `quality_score` | integer \| null | AI quality assessment score | +| `quality_issues` | string[] \| null | Up to 10 quality flags | +| `quality_status` | string \| null | Overall quality verdict | + +**Row identity:** `slug` when non-empty; `at` (ISO timestamp) otherwise. + +**Retention:** file is trimmed to the last 10,000 lines when it exceeds 2 MB. Configure with: +- `ARTICLE_LOG_MAX_LINES` (default: 10,000) +- `ARTICLE_LOG_TRIM_AT_BYTES` (default: 2,097,152) + +**Concurrency safety:** all write operations (`appendArticleRecord`, `updateArticleMetadata`) acquire an advisory file lock at `.lock` before reading or writing. The slug uniqueness check runs inside the lock to prevent race conditions between concurrent processes. + +--- + +## 2. PostgreSQL Analytics Database + +**Connection env vars:** + +| Var | Default | Notes | +|---|---|---| +| `ANALYTICS_DB_HOST` | `localhost` | | +| `ANALYTICS_DB_PORT` | `5432` | | +| `ANALYTICS_DB_NAME` | `ai_news_analytics` | | +| `ANALYTICS_DB_USER` | `postgres` | | +| `ANALYTICS_DB_PASSWORD` | _(empty)_ | | +| `ANALYTICS_DB_POOL_SIZE` | `10` | Max pool connections | + +### 2.1 `engagement_events` + +Raw engagement events captured from WordPress. + +| Column | Type | Constraints | +|---|---|---| +| `id` | BIGSERIAL | PK | +| `post_id` | INTEGER | NOT NULL | +| `event_type` | VARCHAR(20) | CHECK: `view \| share \| comment` | +| `event_count` | INTEGER | DEFAULT 1 | +| `captured_at` | TIMESTAMP | NOT NULL | +| `recorded_at` | TIMESTAMP | DEFAULT NOW() | + +**Indexes:** +- `idx_engagement_post_captured` — `(post_id, captured_at DESC)` — per-post time range queries +- `idx_engagement_type_recorded` — `(event_type, recorded_at DESC)` — type-filtered queries +- `idx_engagement_captured_date` — `(DATE(captured_at))` — daily aggregation queries + +**Retention:** delete rows older than `ANALYTICS_ENGAGEMENT_RETENTION_DAYS` days (default: 90). + +### 2.2 `article_analytics` + +Denormalized article metadata for analytics joins. + +| Column | Type | Constraints | +|---|---|---| +| `post_id` | INTEGER | PK | +| `slug` | VARCHAR(255) | UNIQUE | +| `title` | TEXT | | +| `category` | VARCHAR(100) | | +| `published_at` | TIMESTAMP | NOT NULL | +| `site_name` | VARCHAR(100) | | +| `custom_meta` | JSONB | NOT NULL DEFAULT `{}` | +| `updated_at` | TIMESTAMP | DEFAULT NOW() | + +**Indexes:** +- `idx_article_category_published` — `(category, published_at DESC)` — category dashboard filters +- `idx_article_analytics_custom_meta` — GIN on `custom_meta` — JSONB field queries +- `idx_article_published_date` — `(DATE(published_at))` — date-based dashboard filters + +### 2.3 `daily_metrics` + +Pre-aggregated daily engagement per article. + +| Column | Type | Constraints | +|---|---|---| +| `id` | BIGSERIAL | PK | +| `post_id` | INTEGER | FK → `article_analytics.post_id` | +| `period_date` | DATE | NOT NULL | +| `views` | INTEGER | DEFAULT 0 | +| `shares` | INTEGER | DEFAULT 0 | +| `comments` | INTEGER | DEFAULT 0 | +| `aggregated_at` | TIMESTAMP | DEFAULT NOW() | + +**Constraints:** UNIQUE `(post_id, period_date)` + +**Indexes:** +- `idx_daily_metrics_date` — `(period_date DESC)` — time-range queries +- `idx_daily_metrics_post` — `(post_id)` — single-article lookup +- `idx_daily_metrics_post_date` — `(post_id, period_date DESC)` — combined post+time filter + +**Retention:** delete rows where `period_date < today - ANALYTICS_DAILY_METRICS_RETENTION_DAYS` (default: 365). + +### 2.4 `category_benchmarks` + +Aggregated percentile stats per category per day. + +| Column | Type | Constraints | +|---|---|---| +| `id` | BIGSERIAL | PK | +| `category` | VARCHAR(100) | NOT NULL | +| `period_date` | DATE | NOT NULL | +| `metric_type` | VARCHAR(20) | CHECK: `views \| shares \| comments` | +| `avg_value` | DECIMAL(12,2) | | +| `percentile_50` | DECIMAL(12,2) | | +| `percentile_75` | DECIMAL(12,2) | | +| `percentile_90` | DECIMAL(12,2) | | +| `article_count` | INTEGER | DEFAULT 0 | +| `computed_at` | TIMESTAMP | DEFAULT NOW() | + +**Constraints:** UNIQUE `(category, period_date, metric_type)` + +**Indexes:** +- `idx_category_benchmarks_lookup` — `(category, period_date DESC)` — benchmark queries + +**Retention:** delete rows where `period_date < today - ANALYTICS_BENCHMARKS_RETENTION_DAYS` (default: 365). + +### 2.5 `schema_version` + +| Column | Type | Notes | +|---|---|---| +| `id` | SERIAL | PK | +| `version` | INT | NOT NULL | +| `applied_at` | TIMESTAMP | DEFAULT NOW() | + +--- + +## 3. In-Memory Caches + +### 3.1 RSS GUID Store + +**Module:** `src/listener/guid-store.js` +**Persistence:** `data/listener-guid-store.json` (override: `GUID_STORE_PATH`) + +Tracks seen article GUIDs across listener ticks to prevent duplicate processing. + +| Property | Value | +|---|---| +| Max size | 2,000 GUIDs | +| Trim-to | 1,500 GUIDs (when cap exceeded) | +| Eviction policy | Oldest GUIDs dropped (FIFO trim) | +| Persistence | Saved to disk after each tick with new articles; loaded on process start | +| TTL | None — GUIDs expire only when trimmed | + +**Restart safety:** the store is written atomically (temp file + rename) before calling `on_new_articles`. A process restart re-reads the file and continues deduplication from the last known state. + +### 3.2 Circuit Breaker State + +**Module:** `src/crawler/circuit-breaker.js` + +Per-source state machine preventing hammering of failing RSS feeds. + +| Property | Value | +|---|---| +| Storage | In-memory Map (process lifetime) | +| Failure threshold | 3 consecutive failures → OPEN | +| Window size | 5 observations | +| Open timeout | 5 minutes → transitions to HALF_OPEN | +| Persistence | None — resets on process restart | + +### 3.3 Queue Backpressure + +**Module:** `src/queue/backpressure.js` + +| Property | Value | +|---|---| +| Max in-flight | 5 articles (configurable) | +| Storage | In-memory counters | +| Persistence | None | + +--- + +## 4. Maintenance Policy + +**Module:** `src/analytics/maintenance.js` + +Run `runMaintenanceCycle()` on a daily schedule (e.g. via node-cron at 03:00). + +| Task | Default retention | Env override | +|---|---|---| +| Purge `engagement_events` | 90 days | `ANALYTICS_ENGAGEMENT_RETENTION_DAYS` | +| Purge `daily_metrics` | 365 days | `ANALYTICS_DAILY_METRICS_RETENTION_DAYS` | +| Purge `category_benchmarks` | 365 days | `ANALYTICS_BENCHMARKS_RETENTION_DAYS` | +| VACUUM ANALYZE all tables | After every purge | — | + +**`getTableStats()`** returns row counts and sizes for all analytics tables — useful for monitoring dashboards. + +### Integrating the maintenance cron + +```js +const cron = require('node-cron'); +const { runMaintenanceCycle } = require('./src/analytics/maintenance'); + +// Daily at 03:00 local time +cron.schedule('0 3 * * *', async () => { + await runMaintenanceCycle(); +}); +``` + +--- + +## 5. Access Pattern Benchmarks + +The following operations have O(n) cost on the article JSONL log (n = number of lines): + +| Operation | Cost | Mitigation | +|---|---|---| +| `readLastArticles(limit)` | O(n) read | Capped at 500 results; log capped at 10K lines | +| `validateSlugUniqueness` | O(n) scan | Runs inside file lock; acceptable at ≤10K lines | +| `trimArticleLogIfNeeded` | O(n) rewrite | Triggered only when file exceeds 2 MB | +| `updateArticleMetadata` | O(n) rewrite | Serialized via file lock | + +All PostgreSQL queries use indexed access patterns. See indexes in Section 2. diff --git a/src/analytics/maintenance.js b/src/analytics/maintenance.js new file mode 100644 index 0000000..af89003 --- /dev/null +++ b/src/analytics/maintenance.js @@ -0,0 +1,154 @@ +'use strict'; + +const db = require('./db'); +const logger = require('../logger'); + +const DEFAULT_ENGAGEMENT_RETENTION_DAYS = 90; +const DEFAULT_DAILY_METRICS_RETENTION_DAYS = 365; +const DEFAULT_BENCHMARKS_RETENTION_DAYS = 365; + +/** + * VACUUM ANALYZE on all analytics tables to reclaim dead rows and update planner stats. + * This is safe to run while the DB is live; it does NOT lock tables. + */ +async function vacuumAnalyze() { + const tables = ['engagement_events', 'daily_metrics', 'article_analytics', 'category_benchmarks']; + const start = Date.now(); + logger.info('analytics/maintenance: starting VACUUM ANALYZE'); + for (const table of tables) { + try { + await db.query(`VACUUM ANALYZE ${table}`); + logger.debug(`analytics/maintenance: VACUUM ANALYZE ${table} ok`); + } catch (err) { + // Non-fatal: log and continue — cannot VACUUM inside a transaction + logger.warn(`analytics/maintenance: VACUUM ANALYZE ${table} failed: ${err.message}`); + } + } + logger.info(`analytics/maintenance: VACUUM ANALYZE complete in ${Date.now() - start}ms`); +} + +/** + * Delete engagement_events older than retentionDays. + * Returns the number of rows deleted. + */ +async function purgeOldEngagementEvents(retentionDays = DEFAULT_ENGAGEMENT_RETENTION_DAYS) { + const start = Date.now(); + const result = await db.execute( + `DELETE FROM engagement_events WHERE captured_at < NOW() - INTERVAL '${Number(retentionDays)} days'` + ); + const deleted = result.rowCount || 0; + if (deleted > 0) { + logger.info(`analytics/maintenance: purged ${deleted} engagement_events older than ${retentionDays} days (${Date.now() - start}ms)`); + } + return deleted; +} + +/** + * Delete daily_metrics rows older than retentionDays. + * Returns the number of rows deleted. + */ +async function purgeOldDailyMetrics(retentionDays = DEFAULT_DAILY_METRICS_RETENTION_DAYS) { + const start = Date.now(); + const result = await db.execute( + `DELETE FROM daily_metrics WHERE period_date < CURRENT_DATE - INTERVAL '${Number(retentionDays)} days'` + ); + const deleted = result.rowCount || 0; + if (deleted > 0) { + logger.info(`analytics/maintenance: purged ${deleted} daily_metrics rows older than ${retentionDays} days (${Date.now() - start}ms)`); + } + return deleted; +} + +/** + * Delete category_benchmarks rows older than retentionDays. + * Returns the number of rows deleted. + */ +async function purgeOldBenchmarks(retentionDays = DEFAULT_BENCHMARKS_RETENTION_DAYS) { + const start = Date.now(); + const result = await db.execute( + `DELETE FROM category_benchmarks WHERE period_date < CURRENT_DATE - INTERVAL '${Number(retentionDays)} days'` + ); + const deleted = result.rowCount || 0; + if (deleted > 0) { + logger.info(`analytics/maintenance: purged ${deleted} category_benchmarks rows older than ${retentionDays} days (${Date.now() - start}ms)`); + } + return deleted; +} + +/** + * Update the schema_version table to record a completed maintenance cycle. + */ +async function recordMaintenanceCycle() { + await db.execute(` + INSERT INTO schema_version (version) VALUES ( + (SELECT COALESCE(MAX(version), 0) FROM schema_version) + ) + `); +} + +/** + * Run the full maintenance cycle: purge old data, then VACUUM ANALYZE. + * Safe to call on a schedule (e.g. daily via node-cron). + * + * Retention periods are configurable via env vars: + * ANALYTICS_ENGAGEMENT_RETENTION_DAYS (default 90) + * ANALYTICS_DAILY_METRICS_RETENTION_DAYS (default 365) + * ANALYTICS_BENCHMARKS_RETENTION_DAYS (default 365) + */ +async function runMaintenanceCycle() { + const engagementDays = Number(process.env.ANALYTICS_ENGAGEMENT_RETENTION_DAYS || DEFAULT_ENGAGEMENT_RETENTION_DAYS); + const dailyDays = Number(process.env.ANALYTICS_DAILY_METRICS_RETENTION_DAYS || DEFAULT_DAILY_METRICS_RETENTION_DAYS); + const benchmarkDays = Number(process.env.ANALYTICS_BENCHMARKS_RETENTION_DAYS || DEFAULT_BENCHMARKS_RETENTION_DAYS); + + logger.info('analytics/maintenance: starting daily maintenance cycle'); + const cycleStart = Date.now(); + + const [engDeleted, dailyDeleted, benchDeleted] = await Promise.all([ + purgeOldEngagementEvents(engagementDays), + purgeOldDailyMetrics(dailyDays), + purgeOldBenchmarks(benchmarkDays), + ]); + + await vacuumAnalyze(); + await recordMaintenanceCycle(); + + const elapsed = Date.now() - cycleStart; + logger.info(`analytics/maintenance: cycle complete in ${elapsed}ms — deleted: engagement=${engDeleted}, daily=${dailyDeleted}, benchmarks=${benchDeleted}`); + + return { engDeleted, dailyDeleted, benchDeleted, elapsedMs: elapsed }; +} + +/** + * Collect table size statistics for monitoring. + * Returns row counts and approximate size for each analytics table. + */ +async function getTableStats() { + const tables = ['engagement_events', 'daily_metrics', 'article_analytics', 'category_benchmarks']; + const stats = {}; + + for (const table of tables) { + try { + const [rowResult, sizeResult] = await Promise.all([ + db.queryOne(`SELECT COUNT(*) AS row_count FROM ${table}`), + db.queryOne(`SELECT pg_size_pretty(pg_total_relation_size($1)) AS total_size`, [table]), + ]); + stats[table] = { + row_count: parseInt(rowResult.row_count, 10), + total_size: sizeResult.total_size, + }; + } catch (err) { + stats[table] = { error: err.message }; + } + } + + return stats; +} + +module.exports = { + vacuumAnalyze, + purgeOldEngagementEvents, + purgeOldDailyMetrics, + purgeOldBenchmarks, + runMaintenanceCycle, + getTableStats, +}; diff --git a/src/analytics/schema.js b/src/analytics/schema.js index 468698c..5d4ac64 100644 --- a/src/analytics/schema.js +++ b/src/analytics/schema.js @@ -94,6 +94,9 @@ INSERT INTO schema_version (version) const SCHEMA_MIGRATIONS = [ `ALTER TABLE article_analytics ADD COLUMN IF NOT EXISTS custom_meta JSONB NOT NULL DEFAULT '{}'::jsonb`, `CREATE INDEX IF NOT EXISTS idx_article_analytics_custom_meta ON article_analytics USING GIN (custom_meta)`, + `CREATE INDEX IF NOT EXISTS idx_engagement_captured_date ON engagement_events(DATE(captured_at))`, + `CREATE INDEX IF NOT EXISTS idx_article_published_date ON article_analytics(DATE(published_at))`, + `CREATE INDEX IF NOT EXISTS idx_daily_metrics_post_date ON daily_metrics(post_id, period_date DESC)`, ]; /** diff --git a/src/listener/guid-store.js b/src/listener/guid-store.js new file mode 100644 index 0000000..76056df --- /dev/null +++ b/src/listener/guid-store.js @@ -0,0 +1,76 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const logger = require('../logger'); + +const ROOT = path.resolve(__dirname, '..', '..'); +const DEFAULT_STORE_PATH = path.join(ROOT, 'data', 'listener-guid-store.json'); +const MAX_GUIDS = 2000; +const TRIM_TO = 1500; + +function getStorePath() { + const custom = (process.env.GUID_STORE_PATH || '').trim(); + if (!custom) return DEFAULT_STORE_PATH; + return path.isAbsolute(custom) ? custom : path.join(ROOT, custom); +} + +/** + * Load the persisted GUID set from disk. + * Returns an empty Set on missing or corrupt file. + */ +function loadGuidStore() { + const storePath = getStorePath(); + try { + if (!fs.existsSync(storePath)) return new Set(); + const raw = fs.readFileSync(storePath, 'utf8'); + const parsed = JSON.parse(raw); + if (!Array.isArray(parsed)) return new Set(); + return new Set(parsed); + } catch (err) { + logger.warn(`guid-store: failed to load from ${storePath}: ${err.message}`); + return new Set(); + } +} + +/** + * Persist the GUID set to disk (best-effort; never throws). + * Trims to MAX_GUIDS before saving; uses atomic rename. + */ +function saveGuidStore(guidSet) { + const storePath = getStorePath(); + try { + const dir = path.dirname(storePath); + if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); + + let entries = [...guidSet]; + if (entries.length > MAX_GUIDS) { + entries = entries.slice(-TRIM_TO); + } + const tmp = `${storePath}.${process.pid}.${Date.now()}.tmp`; + fs.writeFileSync(tmp, JSON.stringify(entries), 'utf8'); + fs.renameSync(tmp, storePath); + } catch (err) { + logger.warn(`guid-store: failed to save to ${storePath}: ${err.message}`); + } +} + +/** + * Add GUIDs to the set and trim if needed. + * Returns the (possibly trimmed) updated set and a boolean indicating + * whether it was trimmed so the caller can decide to persist. + */ +function addGuids(guidSet, newGuids) { + for (const guid of newGuids) { + guidSet.add(guid); + } + let trimmed = false; + if (guidSet.size > MAX_GUIDS) { + const entries = [...guidSet]; + guidSet = new Set(entries.slice(-TRIM_TO)); + trimmed = true; + } + return { guidSet, trimmed }; +} + +module.exports = { loadGuidStore, saveGuidStore, addGuids }; diff --git a/src/listener/guid-store.test.js b/src/listener/guid-store.test.js new file mode 100644 index 0000000..2151186 --- /dev/null +++ b/src/listener/guid-store.test.js @@ -0,0 +1,103 @@ +'use strict'; + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { describe, it, beforeEach, afterEach } = require('node:test'); +const assert = require('node:assert/strict'); + +const { loadGuidStore, saveGuidStore, addGuids } = require('./guid-store'); + +describe('guid-store', () => { + let tmpDir; + let prevPath; + + beforeEach(() => { + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'anw-gs-')); + prevPath = process.env.GUID_STORE_PATH; + process.env.GUID_STORE_PATH = path.join(tmpDir, 'guid-store.json'); + }); + + afterEach(() => { + if (prevPath !== undefined) { + process.env.GUID_STORE_PATH = prevPath; + } else { + delete process.env.GUID_STORE_PATH; + } + fs.rmSync(tmpDir, { recursive: true, force: true }); + }); + + it('loadGuidStore returns empty Set when file does not exist', () => { + const store = loadGuidStore(); + assert.ok(store instanceof Set); + assert.equal(store.size, 0); + }); + + it('saveGuidStore + loadGuidStore roundtrip', () => { + const original = new Set(['guid-1', 'guid-2', 'guid-3']); + saveGuidStore(original); + const loaded = loadGuidStore(); + assert.deepEqual([...loaded].sort(), [...original].sort()); + }); + + it('saveGuidStore writes atomically via tmp+rename', () => { + const storePath = process.env.GUID_STORE_PATH; + saveGuidStore(new Set(['g1'])); + assert.ok(fs.existsSync(storePath)); + const tmpFiles = fs.readdirSync(tmpDir).filter(f => f.includes('.tmp')); + assert.equal(tmpFiles.length, 0, 'no .tmp files should remain after save'); + }); + + it('loadGuidStore returns empty Set for corrupt file', () => { + const storePath = process.env.GUID_STORE_PATH; + fs.writeFileSync(storePath, 'not valid json', 'utf8'); + const store = loadGuidStore(); + assert.equal(store.size, 0); + }); + + it('loadGuidStore returns empty Set when file contains non-array', () => { + const storePath = process.env.GUID_STORE_PATH; + fs.writeFileSync(storePath, JSON.stringify({ not: 'array' }), 'utf8'); + const store = loadGuidStore(); + assert.equal(store.size, 0); + }); + + it('addGuids adds new GUIDs to set', () => { + const set = new Set(['existing']); + const { guidSet } = addGuids(set, ['new-1', 'new-2']); + assert.ok(guidSet.has('existing')); + assert.ok(guidSet.has('new-1')); + assert.ok(guidSet.has('new-2')); + assert.equal(guidSet.size, 3); + }); + + it('addGuids trims to 1500 when exceeding 2000', () => { + const big = new Set(); + for (let i = 0; i < 1999; i++) big.add(`g${i}`); + const { guidSet, trimmed } = addGuids(big, ['overflow-1', 'overflow-2']); + assert.equal(guidSet.size, 1500); + assert.equal(trimmed, true); + }); + + it('addGuids does not trim when under cap', () => { + const small = new Set(['a', 'b']); + const { guidSet, trimmed } = addGuids(small, ['c']); + assert.equal(guidSet.size, 3); + assert.equal(trimmed, false); + }); + + it('saveGuidStore trims to MAX_GUIDS before persisting', () => { + const big = new Set(); + for (let i = 0; i < 2100; i++) big.add(`g${i}`); + saveGuidStore(big); + const loaded = loadGuidStore(); + assert.equal(loaded.size, 1500); + }); + + it('saveGuidStore creates parent directory if missing', () => { + const nested = path.join(tmpDir, 'nested', 'store.json'); + process.env.GUID_STORE_PATH = nested; + saveGuidStore(new Set(['x'])); + assert.ok(fs.existsSync(nested)); + }); +}); diff --git a/src/listener/rss-listener.js b/src/listener/rss-listener.js index f56093b..08efa14 100644 --- a/src/listener/rss-listener.js +++ b/src/listener/rss-listener.js @@ -7,8 +7,9 @@ const { parseIanaTimezone } = require('../util/iana-timezone'); const { recordRssListenerTick, recordRssListenerOverlapSkip } = require('../runtime/listen-state'); const { DEFAULT_AUTO_CRON } = require('../config/listen-defaults'); const { fetchAndFilterSourceArticles } = require('../pipeline/source-articles'); +const { loadGuidStore, saveGuidStore, addGuids } = require('./guid-store'); -let _last_seen_guids = new Set(); +let _last_seen_guids = loadGuidStore(); let _tick_in_flight = false; /** @@ -67,12 +68,9 @@ function startRSSListener(sources, cron_expr, on_new_articles) { if (new_articles.length > 0) { logger.info(`RSS listener: ${new_articles.length} new articles detected`); - new_articles.forEach((a) => _last_seen_guids.add(a.guid)); - // Prevent unbounded growth — keep only last 2000 GUIDs - if (_last_seen_guids.size > 2000) { - const _entries = [..._last_seen_guids]; - _last_seen_guids = new Set(_entries.slice(-1500)); - } + const { guidSet } = addGuids(_last_seen_guids, new_articles.map(a => a.guid)); + _last_seen_guids = guidSet; + saveGuidStore(_last_seen_guids); await on_new_articles(new_articles); } else { logger.debug('RSS listener: no new articles'); diff --git a/src/store/article-log.js b/src/store/article-log.js index d39a67b..cf12b75 100644 --- a/src/store/article-log.js +++ b/src/store/article-log.js @@ -3,6 +3,7 @@ const fs = require('fs'); const path = require('path'); const logger = require('../logger'); +const { acquireLock } = require('./file-lock'); const ROOT = path.resolve(__dirname, '..', '..'); const DATA_DIR = path.join(ROOT, 'data'); @@ -135,58 +136,62 @@ function updateArticleMetadata(id, updates) { throw new Error('invalid editorial status'); } - // Validate slug uniqueness if slug is being updated - if (updates.slug) { - const validation = validateSlugUniqueness(updates.slug, id); - if (!validation.valid) { - throw new Error(validation.error); - } - } - const logPath = getArticleLogPath(); - if (!fs.existsSync(logPath)) { - throw new Error('article not found'); - } - const raw = fs.readFileSync(logPath, 'utf8'); - const lines = raw.split('\n').filter((l) => l.trim().length > 0); - const out = []; - let found = false; + const release = acquireLock(`${logPath}.lock`); + try { + // Slug uniqueness check runs inside the lock to prevent TOCTOU races + if (updates.slug) { + const validation = validateSlugUniqueness(updates.slug, id); + if (!validation.valid) { + throw new Error(validation.error); + } + } - for (const line of lines) { - let rec; - try { - rec = JSON.parse(line); - } catch (_err) { - out.push(line); - continue; + if (!fs.existsSync(logPath)) { + throw new Error('article not found'); } - if (articleRowId(rec) === id) { - // Update only provided fields - if (updates.editorial_status) rec.editorial_status = updates.editorial_status; - if (updates.title !== undefined) rec.title = updates.title || ''; - if (updates.subtitle !== undefined) rec.subtitle = updates.subtitle || ''; - if (updates.slug !== undefined) rec.slug = updates.slug || ''; - if (updates.tags !== undefined) { - if (Array.isArray(updates.tags)) { - const tags = updates.tags.filter(t => String(t || '').trim()).map(t => String(t).trim()).slice(0, 20); - rec.tags = tags.length > 0 ? tags : null; - } else { - rec.tags = null; + const raw = fs.readFileSync(logPath, 'utf8'); + const lines = raw.split('\n').filter((l) => l.trim().length > 0); + const out = []; + let found = false; + + for (const line of lines) { + let rec; + try { + rec = JSON.parse(line); + } catch (_err) { + out.push(line); + continue; + } + if (articleRowId(rec) === id) { + if (updates.editorial_status) rec.editorial_status = updates.editorial_status; + if (updates.title !== undefined) rec.title = updates.title || ''; + if (updates.subtitle !== undefined) rec.subtitle = updates.subtitle || ''; + if (updates.slug !== undefined) rec.slug = updates.slug || ''; + if (updates.tags !== undefined) { + if (Array.isArray(updates.tags)) { + const tags = updates.tags.filter(t => String(t || '').trim()).map(t => String(t).trim()).slice(0, 20); + rec.tags = tags.length > 0 ? tags : null; + } else { + rec.tags = null; + } } + if (updates.category !== undefined) { + rec.category = updates.category ? String(updates.category).trim() : null; + } + found = true; } - if (updates.category !== undefined) { - rec.category = updates.category ? String(updates.category).trim() : null; - } - found = true; + out.push(JSON.stringify(rec)); } - out.push(JSON.stringify(rec)); + if (!found) { + throw new Error('article not found'); + } + const tmp = `${logPath}.${process.pid}.${Date.now()}.tmp`; + fs.writeFileSync(tmp, `${out.join('\n')}\n`, 'utf8'); + fs.renameSync(tmp, logPath); + } finally { + release(); } - if (!found) { - throw new Error('article not found'); - } - const tmp = `${logPath}.${process.pid}.${Date.now()}.tmp`; - fs.writeFileSync(tmp, `${out.join('\n')}\n`, 'utf8'); - fs.renameSync(tmp, logPath); } /** @@ -224,8 +229,13 @@ function appendArticleRecord(rec) { quality_status: rec.quality_status || null }); const logPath = getArticleLogPath(); - fs.appendFileSync(logPath, `${line}\n`, 'utf8'); - trimArticleLogIfNeeded(); + const release = acquireLock(`${logPath}.lock`); + try { + fs.appendFileSync(logPath, `${line}\n`, 'utf8'); + trimArticleLogIfNeeded(); + } finally { + release(); + } } /** diff --git a/src/store/file-lock.js b/src/store/file-lock.js new file mode 100644 index 0000000..2a97fe8 --- /dev/null +++ b/src/store/file-lock.js @@ -0,0 +1,52 @@ +'use strict'; + +const fs = require('fs'); + +const DEFAULT_LOCK_TIMEOUT_MS = 5000; +const DEFAULT_RETRY_INTERVAL_MS = 50; + +/** + * Acquire an exclusive advisory lock on `lockPath`. + * Returns a release function; throws if timeout is exceeded. + * + * Uses O_CREAT|O_EXCL which is atomic on POSIX and NTFS: + * only one process can create the file; others spin-wait. + */ +function acquireLock(lockPath, opts = {}) { + const timeout = opts.timeout || DEFAULT_LOCK_TIMEOUT_MS; + const interval = opts.retryInterval || DEFAULT_RETRY_INTERVAL_MS; + const deadline = Date.now() + timeout; + + while (true) { + try { + const fd = fs.openSync(lockPath, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 0o600); + fs.writeSync(fd, String(process.pid)); + fs.closeSync(fd); + return () => _releaseLock(lockPath); + } catch (err) { + if (err.code !== 'EEXIST') throw err; + if (Date.now() >= deadline) { + // Stale lock guard: if the lock file is older than the timeout, remove it + try { + const st = fs.statSync(lockPath); + if (Date.now() - st.mtimeMs > timeout) { + fs.unlinkSync(lockPath); + continue; + } + } catch (_) { /* already removed by another process */ } + throw new Error(`Failed to acquire lock on ${lockPath} within ${timeout}ms`); + } + // Synchronous busy-wait in small increments + const waitUntil = Date.now() + interval; + while (Date.now() < waitUntil) { /* spin */ } + } + } +} + +function _releaseLock(lockPath) { + try { + fs.unlinkSync(lockPath); + } catch (_) { /* already removed */ } +} + +module.exports = { acquireLock }; diff --git a/src/store/file-lock.test.js b/src/store/file-lock.test.js new file mode 100644 index 0000000..d164f60 --- /dev/null +++ b/src/store/file-lock.test.js @@ -0,0 +1,77 @@ +'use strict'; + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { describe, it, beforeEach, afterEach } = require('node:test'); +const assert = require('node:assert/strict'); + +const { acquireLock } = require('./file-lock'); + +describe('file-lock', () => { + let tmpDir; + let lockPath; + + beforeEach(() => { + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'anw-fl-')); + lockPath = path.join(tmpDir, 'test.lock'); + }); + + afterEach(() => { + fs.rmSync(tmpDir, { recursive: true, force: true }); + }); + + it('acquires lock and returns a release function', () => { + const release = acquireLock(lockPath); + assert.equal(typeof release, 'function'); + assert.ok(fs.existsSync(lockPath)); + release(); + assert.ok(!fs.existsSync(lockPath)); + }); + + it('lock file is removed after release', () => { + const release = acquireLock(lockPath); + release(); + assert.ok(!fs.existsSync(lockPath)); + }); + + it('can re-acquire lock after release', () => { + const r1 = acquireLock(lockPath); + r1(); + const r2 = acquireLock(lockPath); + assert.ok(fs.existsSync(lockPath)); + r2(); + assert.ok(!fs.existsSync(lockPath)); + }); + + it('release is idempotent (second call does not throw)', () => { + const release = acquireLock(lockPath); + release(); + assert.doesNotThrow(() => release()); + }); + + it('lock file contains the process PID', () => { + const release = acquireLock(lockPath); + try { + const content = fs.readFileSync(lockPath, 'utf8'); + assert.equal(content, String(process.pid)); + } finally { + release(); + } + }); + + it('cleans up stale lock file older than timeout and acquires', () => { + // Write a lock file with mtime set 300ms in the past + fs.writeFileSync(lockPath, '99999'); + const pastTime = (Date.now() - 300) / 1000; + fs.utimesSync(lockPath, pastTime, pastTime); + + // With 100ms timeout: stale guard fires at deadline, file is ~400ms old > 100ms + // → stale lock removed → acquires successfully + const release = acquireLock(lockPath, { timeout: 100, retryInterval: 10 }); + assert.ok(fs.existsSync(lockPath)); + const content = fs.readFileSync(lockPath, 'utf8'); + assert.equal(content, String(process.pid)); + release(); + }); +});