diff --git a/.gitignore b/.gitignore index f38c8bb..6835445 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,9 @@ coverage/ .env logs/ *.log + +# Runtime article log (restore from backup/ or .backup/; never commit live data) +data/article-index.jsonl + +# Local snapshot directory (Git-tracked copies live under backup/ when committed) +.backup/ diff --git a/README.md b/README.md index c71ee2b..0dafd37 100644 --- a/README.md +++ b/README.md @@ -228,6 +228,18 @@ After fixing, re-test: `npm run verify:deploy -- "https://ainews.bitreport.pt"` **Typo check:** the hostname must be `ainews.bitreport.pt` (not `ainews.bitrepor.pt`). +## Backup & Disaster Recovery + +The critical asset is **`data/article-index.jsonl`** (publication history and editorial decisions). **RTO: 2 hours | RPO: 1 day.** + +**Quick Links:** +- **Manual backup:** `./tools/backup-article-index.sh` +- **Backup strategy:** `docs/BACKUP_STRATEGY.md` (BIT-4285) +- **Test procedures:** `docs/runbooks/BACKUP_TESTING.md` +- **Disaster recovery:** `docs/runbooks/DISASTER_RECOVERY.md` (4 recovery scenarios) + +**Automated backups:** Configured via cron on the LXC (daily @ 02:00 UTC, hourly incremental). See `docs/runbooks/BACKUP_TESTING.md` § Procedure 4 for test schedule. + ## Future - [ ] Multi-language output diff --git a/docs/BACKUP_STRATEGY.md b/docs/BACKUP_STRATEGY.md new file mode 100644 index 0000000..413b7f3 --- /dev/null +++ b/docs/BACKUP_STRATEGY.md @@ -0,0 +1,205 @@ +# Backup and Disaster Recovery Strategy — ai-news-writer (BIT-4285) + +This document defines the backup and disaster recovery (DR) strategy for the ai-news-writer service, including RTO/RPO targets, backup procedures, retention policies, and recovery testing schedules. + +**Infrastructure Context:** +- **Deployment:** LXC container (CT 223, Proxmox) +- **Critical Data:** `data/article-index.jsonl` (JSONL article log, max 2 MB / 10K entries) +- **Runtime:** Node.js 20 LTS via PM2 (ecosystem.config.cjs) +- **Config:** Git-tracked sources.json, sites/*.json, ui-theme.json +- **Logs:** Winston logs to `logs/combined.log` and `logs/error.log` + +--- + +## Criticality & RTO/RPO Targets + +### Service Criticality +**Tier: High** — Daily article publication; loss of service or recent articles affects business continuity. + +### RTO (Recovery Time Objective) +**Target: 2 hours** + +**Justification:** +- Article publication runs on daily schedule (configurable via `AUTO_CRON`) +- Failure detected within 5 min (health check interval) +- Manual recovery and container rebuild require ~60–90 min on Proxmox +- 2-hour window allows recovery before next scheduled publication cycle +- If failure occurs early morning: full recovery by mid-morning; otherwise recovered for next day's cycle + +### RPO (Recovery Point Objective) +**Target: 1 day** + +**Justification:** +- Article index stores publication history; loss is significant but not catastrophic +- Recent articles can be re-fetched from RSS feeds if needed +- Daily backup aligns with publication cycle; articles published yesterday are protected +- Hourly snapshots (7-day retention) provide granular recovery for recent data incidents +- Acceptable data loss: articles generated since last daily backup (max ~24 hours of unpublished work) + +--- + +## Backup Scope + +### What to Backup (Critical) +1. **Article Index:** `data/article-index.jsonl` + - **Why:** Single source of truth for publication history and editorial decisions (approved/rejected/pending) + - **Size:** ~2 MB max (10K lines, auto-trimmed) + - **Frequency:** Daily + hourly incremental + +2. **Configuration Files:** `config/*.json`, `config/sites/*.json` + - **Why:** Source definitions, site targets, theme settings + - **Size:** < 100 KB + - **Frequency:** Daily (changes tracked in Git anyway) + +### What NOT to Backup (Non-Critical) +- **Logs:** `logs/combined.log`, `logs/error.log` + - Why: For troubleshooting only; not required for service recovery + - Note: Ship to Loki/Promtail if long-term retention is needed +- **node_modules/:** Re-installed from package-lock.json during recovery +- **.env secrets:** Should be in a secrets manager; not committed to repo or backups + - Recovery procedure restores from vault/manager; never embedded in backup + +### Exclusions in Backup +- No compiled/generated files (rebuild from source) +- No node_modules/ +- No .env (restore from secrets manager) +- No logs/ directory +- Keep backups small for fast transfer and recovery + +--- + +## Backup Strategy & Retention + +### Daily Backup (Production Snapshot) +- **Schedule:** Once daily at **02:00 UTC** (before early-morning publication cycle) +- **Scope:** Article index + config files +- **Retention:** 30 days of daily snapshots +- **Storage:** + - **Primary:** `.backup/article-index.YYYY-MM-DD.jsonl` in repo directory + - **Secondary (Offsite):** Commit to Gitea as `backup/article-index.YYYY-MM-DD.jsonl` (Git commit + push) + - **Why Git:** Leverages existing infrastructure; immutable, timestamped, searchable; no additional storage +- **Frequency:** Automated via cron job (see **Implementation** below) + +### Hourly Incremental Snapshots (Development & Extended Recovery) +- **Schedule:** Every hour (on the hour) +- **Scope:** Article index only (config files change infrequently) +- **Retention:** 7 days of hourly snapshots (168 snapshots) +- **Storage:** `.backup/article-index.YYYY-MM-DDTHH-00-00Z.jsonl` (ISO 8601 with UTC timezone) +- **Purpose:** Granular recovery for recent incidents without waiting for next daily backup +- **Cost:** ~7 MB total (168 × 2 MB max); acceptable for 7-day retention + +### Configuration Backup (Git) +- **Strategy:** All `config/*.json` files are Git-tracked (except `.example.json`) +- **Retention:** Full Git history (immutable) +- **Recovery:** `git checkout ` to restore any prior config version +- **Note:** Ensure sensitive values (API keys, passwords) are never committed; use `.env.example` template instead + +--- + +## Backup Implementation + +### Manual Backup +Run the backup script anytime: + +```bash +./tools/backup-article-index.sh +``` + +**Output:** +- Creates `.backup/article-index.YYYY-MM-DD.jsonl` (daily) +- Creates `.backup/article-index.YYYY-MM-DDTHH-00-00Z.jsonl` (hourly) +- Commits to Git and pushes to Gitea +- Logs: `Backup created at .backup/article-index.YYYY-MM-DD.jsonl` + +### Automated Backup (Production) +On the LXC container (CT 223), add to root crontab: + +```bash +# Daily backup at 02:00 UTC +0 2 * * * cd /srv/ai-news-writer && ./tools/backup-article-index.sh >> /var/log/ai-news-writer-backup.log 2>&1 + +# Hourly backup at minute 0 (00:00, 01:00, etc.) +0 * * * * cd /srv/ai-news-writer && ./tools/backup-article-index.sh hourly >> /var/log/ai-news-writer-backup.log 2>&1 +``` + +**Backup Log Location:** `/var/log/ai-news-writer-backup.log` + +**Verification (on LXC):** +```bash +tail -20 /var/log/ai-news-writer-backup.log +ls -lah /srv/ai-news-writer/.backup/article-index.* +``` + +--- + +## Storage Locations & Retention Policy + +| Backup Type | Path | Frequency | Retention | Storage | +|-------------|------|-----------|-----------|---------| +| **Daily Snapshot** | `.backup/article-index.YYYY-MM-DD.jsonl` | Daily @ 02:00 UTC | 30 days | Repo + Gitea | +| **Hourly Snapshot** | `.backup/article-index.YYYY-MM-DDTHH-00-00Z.jsonl` | Hourly @ :00 | 7 days | Repo (local) | +| **Config History** | Git commits | On change | Full history | Gitea | + +### Cleanup (Automated in Backup Script) +The backup script automatically removes old snapshots: +- Daily: keep only last 30 days (`find ... -mtime +30 -delete`) +- Hourly: keep only last 7 days (`find ... -mtime +7 -delete`) + +### Gitea Retention +Committing backups to Gitea means: +- Immutable history (can restore any prior snapshot) +- Automatic cleanup: Gitea repo settings can enforce branch policies or archive old commits if needed +- Recommendation: Set up Gitea Actions to prune old backup commits (future enhancement) + +--- + +## Recovery Point Scenarios + +| Scenario | Time to Last Backup | Data Loss | +|----------|-------------------|-----------| +| **Incident same day** | < 1 hour (hourly snapshot) | Articles since last hourly backup (max 1 hour) | +| **Incident next morning** | < 24 hours (daily snapshot) | Articles generated since daily backup (max 24 hours) | +| **Incident after week** | 7 days (hourly snapshots roll off) | Must use 1–30 day daily snapshots | +| **Incident after month** | 30 days (last daily backup) | Unrecoverable beyond 30 days; recommend manual mid-month backups for critical periods | + +--- + +## Disaster Recovery Links + +For recovery procedures, see: +- **[DISASTER_RECOVERY.md](./runbooks/DISASTER_RECOVERY.md)** — Step-by-step recovery procedures for 4 failure scenarios +- **[BACKUP_TESTING.md](./runbooks/BACKUP_TESTING.md)** — Manual backup procedures, restore tests, and test schedule + +--- + +## Scaling & Future Considerations + +### Current Constraints +- **Article Index Max Size:** 2 MB (10K entries); auto-trims oldest +- **PM2 Memory Limit:** 512 MB +- **LXC Storage:** 20 GB (nvme-zfs) +- **Backup Overhead:** ~30 MB disk per month (30 daily + 7 hourly snapshots × 2 MB each) + +### Capacity Planning +If article log approaches max size: +1. Increase `ARTICLE_LOG_MAX_LINES` in env (default 10K) +2. Increase `ARTICLE_LOG_TRIM_AT_BYTES` threshold (default 2 MB) +3. Monitor disk usage: `du -sh .backup/` +4. Review retention policy if backups grow beyond 1 GB total + +### Future Enhancements +- **Offsite Replication:** Copy daily snapshots to S3 or second Gitea org (beyond 30 days) +- **Automated Recovery Testing:** Monthly full-restore test in dev environment (BIT-4287) +- **Alerting:** Integrate backup success/failure with Prometheus alerting (see `docs/runbooks/OBSERVABILITY_BIT3601.md`) +- **Database Migration:** If JSONL → SQL database transition occurs, backup strategy must be re-evaluated + +--- + +## References + +- **LXC Provisioning:** `tools/proxmox/create_ai_news_writer_lxc.sh` +- **Deploy Script:** `tools/deploy-lxc.sh` (includes health checks) +- **Article Storage Code:** `src/store/article-log.js` +- **Health Endpoint:** `src/http/status-server.js` +- **PM2 Config:** `ecosystem.config.cjs` +- **Observability:** `docs/runbooks/OBSERVABILITY_BIT3601.md` diff --git a/docs/runbooks/BACKUP_TESTING.md b/docs/runbooks/BACKUP_TESTING.md new file mode 100644 index 0000000..3b48bba --- /dev/null +++ b/docs/runbooks/BACKUP_TESTING.md @@ -0,0 +1,367 @@ +# Backup Testing and Recovery Procedures — ai-news-writer (BIT-4285) + +This runbook provides step-by-step procedures for: +1. **Manual backup creation** — trigger a backup anytime +2. **Restore from backup** — recover article index locally or in production +3. **Test schedule** — when and how to verify backups work +4. **Validation checklist** — post-restore verification + +See **[BACKUP_STRATEGY.md](../BACKUP_STRATEGY.md)** for RTO/RPO targets, retention policy, and backup automation. + +--- + +## Procedure 1: Manual Backup + +Run this anytime to create a backup snapshot (daily or hourly). + +### On Development Machine +```bash +cd /opt/bitreport/ai-news-writer + +# Create daily backup + commit to Git +./tools/backup-article-index.sh + +# Create hourly backup (keeps 7 days of hourly snapshots) +./tools/backup-article-index.sh hourly +``` + +**Expected Output:** +``` +Backup created at .backup/article-index.2026-04-17.jsonl +Committed and pushed to Gitea: backup/article-index.2026-04-17.jsonl +``` + +**Verify Backup:** +```bash +ls -lh .backup/article-index.*.jsonl +head -3 .backup/article-index.2026-04-17.jsonl # Check format (JSONL) +``` + +### On Production LXC (CT 223) +```bash +# SSH to container +ssh root@10.10.50.23 + +# Run backup script +cd /srv/ai-news-writer && ./tools/backup-article-index.sh + +# Verify backup log +tail -5 /var/log/ai-news-writer-backup.log + +# Check backup files +ls -lh .backup/article-index.*.jsonl +``` + +--- + +## Procedure 2: Restore from Backup (Development) + +Use this to verify a backup is valid and can be restored. + +### 2a. List Available Backups + +```bash +cd /opt/bitreport/ai-news-writer + +# List local backups (daily + hourly) +ls -lh .backup/article-index.*.jsonl + +# List backups in Gitea (daily only, committed) +git log --oneline --grep="article-index" -- "backup/" +# Or browse: https://git.bitreport.pt/BitReport.pt/ai-news-writer/src/branch/main/backup/ +``` + +### 2b. Restore from a Specific Backup + +**Option A: From local backup file** +```bash +cd /opt/bitreport/ai-news-writer + +# List available backups +ls -1 .backup/article-index.*.jsonl + +# Choose a backup date (e.g., 2026-04-16) +BACKUP_DATE="2026-04-16" + +# Verify backup integrity before restoring +wc -l ".backup/article-index.${BACKUP_DATE}.jsonl" # should be > 0 + +# Restore by copying backup to active location +cp ".backup/article-index.${BACKUP_DATE}.jsonl" "data/article-index.jsonl" + +# Verify restored file +head -2 data/article-index.jsonl # should be valid JSONL +npm run ops:check # run smoke tests +``` + +**Option B: From Gitea (pull backup commit)** +```bash +cd /opt/bitreport/ai-news-writer + +# Fetch all commits (if not up-to-date) +git fetch origin + +# Find backup commit (e.g., "Backup: article-index.2026-04-16.jsonl") +git log --oneline --all | grep "article-index.2026-04-16" + +# Restore file from that commit +COMMIT_HASH="abc1234" # replace with actual hash +git show "$COMMIT_HASH:backup/article-index.2026-04-16.jsonl" > data/article-index.jsonl + +# Verify +head -2 data/article-index.jsonl +npm run ops:check +``` + +### 2c. Verify Restored Article Index + +```bash +# Check file format (valid JSONL, each line is JSON) +jq -s 'length' data/article-index.jsonl # count of articles + +# Verify structure (should have: id, title, slug, summary, editorial_status, at) +head -1 data/article-index.jsonl | jq . + +# Check for corruption +node -e " + const fs = require('fs'); + const lines = fs.readFileSync('data/article-index.jsonl', 'utf-8').trim().split('\\n'); + let count = 0, errors = []; + lines.forEach((line, idx) => { + try { JSON.parse(line); count++; } + catch (e) { errors.push({ line: idx+1, error: e.message }); } + }); + console.log(\`Valid lines: \${count}, Errors: \${errors.length}\`); + if (errors.length > 0) console.log('First error:', errors[0]); +" +``` + +**Expected Output:** +- File size ~2 MB or smaller (depending on retention) +- Line count matches article count +- Each line is valid JSON +- No parse errors + +--- + +## Procedure 3: Restore in Production (Full Service Recovery) + +**⚠️ This procedure restores the service from backup. Follow carefully.** + +### Prerequisites +- SSH access to Proxmox node or LXC CT 223 +- Backup file identified (from Procedure 2a) +- Downtime window agreed (≤ 30 min expected) + +### 3a. Stop the Service +```bash +# SSH to container +ssh root@10.10.50.23 + +# Stop PM2 app +pm2 stop ai-news-writer + +# Verify it stopped +pm2 status +``` + +### 3b. Restore Article Index +```bash +cd /srv/ai-news-writer + +# Back up current (potentially corrupted) index +cp data/article-index.jsonl data/article-index.jsonl.corrupted + +# Restore from backup (choose one method from Procedure 2b) +# Example: restore from local backup +BACKUP_DATE="2026-04-16" +cp ".backup/article-index.${BACKUP_DATE}.jsonl" "data/article-index.jsonl" + +# Verify restored file (quick check) +wc -l data/article-index.jsonl +head -1 data/article-index.jsonl | jq . +``` + +### 3c. Restart the Service +```bash +# Restart PM2 +pm2 start ecosystem.config.cjs --update-env + +# Check status +pm2 status + +# Verify health endpoint +curl -s http://localhost:3200/health | jq '.ok' +``` + +### 3d. Post-Recovery Verification +```bash +# Run smoke test +npm run verify:deploy -- "http://localhost:3200" + +# Check article index from API +curl -s http://localhost:3200/api/ui/articles?limit=5 | jq '.articles | length' + +# Check logs for errors +tail -20 logs/error.log +``` + +**Success Criteria:** +- ✅ PM2 status shows "online" +- ✅ `/health` returns `"ok": true` +- ✅ `/api/ui/articles` returns article count > 0 +- ✅ No new errors in logs + +### 3e. Communicate Recovery +Post a status update (example): +``` +✅ **AI News Writer service recovered from backup** + +- **Downtime:** 15 minutes (02:15–02:30 UTC) +- **Cause:** Article index corruption detected +- **Recovery:** Restored from 2026-04-16 backup (1 day old) +- **Data loss:** Articles published after 2026-04-16 lost (~12 articles) +- **Status:** Service online, health checks passing +- **Next steps:** Monitor `/health` and `/metrics` for 1 hour; re-run hourly cron if needed +``` + +--- + +## Procedure 4: Test Schedule & Responsibilities + +### Weekly Test (Every Monday @ 10:00 UTC) +**Duration:** 5 minutes +**Owner:** AI News Writer operator or on-call engineer + +1. Run Procedure 1 (manual backup) +2. Verify backup file created: `ls -lh .backup/article-index.*.jsonl` +3. Check backup commit in Gitea: `git log --oneline -5` +4. Document pass/fail in ops log + +**Command:** +```bash +cd /opt/bitreport/ai-news-writer +./tools/backup-article-index.sh +ls -lh .backup/article-index.*.jsonl | tail -3 +``` + +### Monthly Test (First Sunday @ 14:00 UTC) +**Duration:** 30 minutes +**Owner:** AI News Writer operator + on-call engineer (witness) + +1. Run Procedure 1 (manual backup in dev environment) +2. Run Procedure 2 (restore from backup to temporary location) +3. Run smoke tests on restored index +4. Document time-to-restore and any issues + +**Checklist:** +- [ ] Backup created successfully +- [ ] File listed in `.backup/` +- [ ] Restore command completes +- [ ] Restored file is valid JSONL +- [ ] `npm run ops:check` passes +- [ ] Document elapsed time (target: < 5 min restore) +- [ ] Sign-off in ops log with timestamp + +### Quarterly Full Recovery Test (Q1, Q2, Q3, Q4 @ 00:00 UTC) +**Duration:** 60 minutes (planned downtime) +**Owner:** On-call engineer + manager review +**Announcement:** Post 2-day advance notice to #operations Slack channel + +1. Schedule downtime window: 23:00 UTC previous day – 02:00 UTC test day +2. Run Procedure 3 (full service recovery in production) +3. Verify all endpoints operational +4. Document recovery time, any issues, lessons learned +5. Post-mortem meeting within 24 hours if issues found + +**Checklist:** +- [ ] Downtime window announced +- [ ] Service stopped gracefully +- [ ] Backup identified and verified +- [ ] Restored file placed in production location +- [ ] Service restarted +- [ ] Health check passes +- [ ] Article API returns data +- [ ] Error logs clean +- [ ] Restore time recorded +- [ ] Post-mortem completed (if issues) + +### Annual Review (Q1, 30 April) +**Duration:** 2 hours +**Owner:** Team lead + manager + +1. Review all monthly/quarterly test results +2. Identify gaps, failures, or improvements +3. Update RTO/RPO targets if needed (based on incident history) +4. Update this runbook with lessons learned +5. Plan next year's test calendar + +**Questions to Ask:** +- Did all tests pass? If not, why? +- Is 2-hour RTO realistic? Too aggressive? +- Is 1-day RPO acceptable? Should we increase daily frequency? +- Do backup files exist in Gitea? +- Any disk space issues with `.backup/` directory? +- Should we add S3 offsite backup? + +--- + +## Backup File Naming Convention + +| Snapshot Type | Pattern | Example | Retention | +|---------------|---------|---------|-----------| +| **Daily** | `article-index.YYYY-MM-DD.jsonl` | `article-index.2026-04-17.jsonl` | 30 days | +| **Hourly** | `article-index.YYYY-MM-DDTHH-00-00Z.jsonl` | `article-index.2026-04-17T14-00-00Z.jsonl` | 7 days | + +--- + +## Validation Checklist (Post-Restore) + +Use this checklist after every restore to verify service integrity: + +**File Level:** +- [ ] Backup file exists and is readable +- [ ] File size is reasonable (~2 MB or less) +- [ ] File modification date is recent (expected backup time) +- [ ] No permission errors when reading + +**Format Level:** +- [ ] Each line is valid JSON (no parse errors) +- [ ] Article count matches expected range (typically 100–10K depending on retention) +- [ ] Required fields present: `id`, `title`, `slug`, `at`, `editorial_status` + +**Service Level:** +- [ ] PM2 process shows "online" status +- [ ] No errors in `logs/error.log` (within last 5 min) +- [ ] `/health` endpoint returns `{"ok": true}` +- [ ] `/api/ui/articles` returns data (not empty) +- [ ] All config files (`config/sources.json`, `config/sites/*.json`) are intact + +**Operational:** +- [ ] Recovery time < 5 minutes (target) +- [ ] No manual intervention needed beyond procedures above +- [ ] All tests in `npm run ops:check` pass +- [ ] Operator able to complete procedures without external help + +--- + +## Troubleshooting + +| Issue | Cause | Fix | +|-------|-------|-----| +| Backup file not found | Scheduled cron didn't run | Check crontab: `crontab -l`; manually run `./tools/backup-article-index.sh`; review `/var/log/ai-news-writer-backup.log` | +| Restore shows corrupted JSONL | Backup file itself corrupted | Try previous day's backup; if all corrupted, investigate root cause before restoring | +| Service fails after restore | Config file mismatch | Restore config separately: `git checkout HEAD -- config/` | +| Disk space issue in `.backup/` | Retention cleanup failed | Manually delete old files: `find .backup -mtime +30 -delete` | +| Gitea commit failed | SSH key not configured | Verify SSH key in container: `ssh-keyscan git.bitreport.pt >> ~/.ssh/known_hosts` | + +--- + +## References + +- **Backup Strategy:** [BACKUP_STRATEGY.md](../BACKUP_STRATEGY.md) +- **Disaster Recovery Runbook:** [DISASTER_RECOVERY.md](./DISASTER_RECOVERY.md) +- **Article Log Implementation:** `src/store/article-log.js` +- **Observability:** [OBSERVABILITY_BIT3601.md](./OBSERVABILITY_BIT3601.md) +- **Deploy Script:** `tools/deploy-lxc.sh` +- **PM2 Config:** `ecosystem.config.cjs` diff --git a/docs/runbooks/DISASTER_RECOVERY.md b/docs/runbooks/DISASTER_RECOVERY.md new file mode 100644 index 0000000..200cbd7 --- /dev/null +++ b/docs/runbooks/DISASTER_RECOVERY.md @@ -0,0 +1,564 @@ +# Disaster Recovery Runbook — ai-news-writer (BIT-4285) + +This runbook provides step-by-step recovery procedures for four disaster scenarios: + +1. **Data Corruption** — Article index corrupted; service may be running but data is invalid +2. **Service Crash** — Container or process crashed; storage intact but service offline +3. **Container Loss** — LXC container destroyed or disappeared; must rebuild +4. **Complete Failure** — Proxmox node failure; both container and storage lost; recovery from offsite backup + +**Related Documents:** +- **[BACKUP_STRATEGY.md](../BACKUP_STRATEGY.md)** — RTO/RPO targets, backup retention +- **[BACKUP_TESTING.md](./BACKUP_TESTING.md)** — Restore procedures and test schedule +- **[OBSERVABILITY_BIT3601.md](./OBSERVABILITY_BIT3601.md)** — Health checks and monitoring + +--- + +## Scenario 1: Data Corruption + +### **Detection** +- Health check fails: `/health` returns error or `"ok": false` +- Application logs show JSON parse errors: `SyntaxError: Unexpected token` +- `/api/ui/articles` endpoint returns empty or malformed response +- WordPress publish failures with "invalid article data" error + +### **RTO: 5 minutes** | **RPO: 1 day** + +### **Root Cause Analysis** +Likely causes: +- Disk corruption during write (power loss, storage failure) +- Concurrent writes to `data/article-index.jsonl` (no locking mechanism) +- Accidental truncation or manual edit of article index file +- Buggy migration code (rare) + +### **Recovery Steps** + +**Step 1: Confirm Corruption** +```bash +# SSH to container (or run locally if testing in dev) +ssh root@10.10.50.23 # Production LXC + +# Check error logs +tail -50 logs/error.log | grep -i "json\|parse\|error" + +# Try to read article index +node -e " + const fs = require('fs'); + try { + const data = fs.readFileSync('data/article-index.jsonl', 'utf-8').split('\n').filter(l => l.trim()); + data.forEach((line, i) => { + try { JSON.parse(line); } + catch (e) { console.log(\`Line \${i+1}: \${e.message}\`); } + }); + } catch (e) { console.log('Fatal error:', e.message); } +" +``` + +**Step 2: Stop the Service** +```bash +pm2 stop ai-news-writer +# Verify stopped: pm2 status +``` + +**Step 3: Restore from Backup** +```bash +# Back up corrupted file (preserve for forensics) +cp data/article-index.jsonl data/article-index.jsonl.corrupted.$(date +%s) + +# Restore from most recent backup (see BACKUP_TESTING.md Procedure 2) +BACKUP_DATE=$(ls -1 .backup/article-index.*.jsonl | sort -r | head -1 | grep -o '[0-9-]*\.jsonl' | sed 's/\.jsonl//') +cp ".backup/article-index.${BACKUP_DATE}.jsonl" data/article-index.jsonl + +# Verify restored file +node -e " + const fs = require('fs'); + const lines = fs.readFileSync('data/article-index.jsonl', 'utf-8').split('\n').filter(l => l.trim()); + console.log(\`Lines: \${lines.length}\`); + lines.slice(0, 2).forEach(l => console.log(JSON.parse(l).title)); +" +``` + +**Step 4: Restart and Verify** +```bash +pm2 start ecosystem.config.cjs --update-env +sleep 5 + +# Check health +curl -s http://localhost:3200/health | jq '.ok' + +# Check articles API +curl -s http://localhost:3200/api/ui/articles?limit=3 | jq '.articles | length' + +# No errors in logs? +tail -10 logs/error.log +``` + +**Step 5: Investigate Root Cause** +```bash +# Check disk space +df -h + +# Check file permissions +ls -la data/article-index.jsonl* + +# Check recent git activity +git log --oneline -10 data/ + +# Review monitoring for power loss or storage issues +# (check Proxmox console, check S.M.A.R.T. status if accessible) +``` + +### **Post-Recovery Checklist** +- [ ] Corrupted file backed up (e.g., `article-index.jsonl.corrupted.1713450000`) +- [ ] Health check returns `"ok": true` +- [ ] `/api/ui/articles` returns data +- [ ] Error logs clean +- [ ] Disk space adequate (> 1 GB free) +- [ ] No background tasks stalled + +### **Data Loss Impact** +- Articles published since the backup date are lost +- Max loss: 1 day (if backup is from yesterday) +- Can re-publish from RSS if needed (see troubleshooting) + +--- + +## Scenario 2: Service Crash + +### **Detection** +- Service unreachable: `curl http://ainews.bitreport.pt/health` → connection refused +- Monitoring alert: `ai-news-writer` service down +- PM2 shows process not running: `pm2 status` → `stopped` or `errored` + +### **RTO: 10 minutes** | **RPO: 0 (data intact)** + +### **Root Cause Analysis** +Likely causes: +- Out of memory (512 MB PM2 limit exceeded) +- Unhandled exception in application code +- Dependency issue (npm package error) +- System resource exhaustion (full disk, high CPU) + +### **Recovery Steps** + +**Step 1: Verify Service Status** +```bash +ssh root@10.10.50.23 # Production LXC + +pm2 status # Check all processes + +pm2 logs ai-news-writer --lines 20 # Recent logs +``` + +**Step 2: Check for Common Issues** +```bash +# Check disk space +df -h + +# Check memory usage +free -h + +# Check file descriptor limits +ulimit -n + +# Check if file exists and is readable +ls -la data/article-index.jsonl +head -1 data/article-index.jsonl | jq '.' # Verify format +``` + +**Step 3: Restart Service** +```bash +# Option A: Simple restart (if process is just hung) +pm2 restart ai-news-writer + +# Option B: Full reload (reload env + restart) +pm2 startOrReload ecosystem.config.cjs --update-env + +# Wait for startup +sleep 10 + +# Verify health +curl -s http://localhost:3200/health | jq '.ok' +``` + +**Step 4: If Restart Fails** +```bash +# Check for recent code changes +git log --oneline -5 + +# Revert to last known-good commit (if code was deployed recently) +git diff HEAD~1 # check what changed + +# If revert needed: +# git revert HEAD # create revert commit +# git pull # sync +# npm ci # reinstall dependencies +# pm2 restart ai-news-writer + +# Or try killing stale process and restarting +killall -9 node +sleep 2 +pm2 start ecosystem.config.cjs --update-env +``` + +**Step 5: Verify Full Recovery** +```bash +# Health check +curl -s http://localhost:3200/health | jq '.' + +# Run smoke test +npm run verify:deploy -- "http://localhost:3200" + +# Check recent operations +curl -s http://localhost:3200/api/ui/articles?limit=3 | jq '.articles[0]' + +# Monitor for 5 minutes +pm2 logs ai-news-writer --lines 50 +``` + +### **Post-Recovery Checklist** +- [ ] PM2 status shows "online" +- [ ] Health endpoint returns `"ok": true` +- [ ] No new errors in logs +- [ ] Articles API returns data +- [ ] Disk space > 1 GB +- [ ] Memory usage < 400 MB + +### **Escalation** +If service crashes repeatedly: +1. Check logs for stack traces: `pm2 logs ai-news-writer --lines 100` +2. Check recent commits: `git log --oneline -10` +3. If deployed recently, consider rolling back: `git revert HEAD` +4. Escalate to development team (check git blame for recent changes) + +--- + +## Scenario 3: Container Loss + +### **Detection** +- LXC container offline: `curl http://ainews.bitreport.pt` → no route to host +- Proxmox console: Container (CT 223) missing or shows "stopped" +- Cannot SSH to container: `ssh root@10.10.50.23` → connection refused + +### **RTO: 60 minutes** | **RPO: 1 day** + +### **Root Cause Analysis** +Likely causes: +- Container accidentally deleted +- Proxmox storage issue (ZFS pool corruption, full disk) +- Network configuration error (VLAN/bridge issue) +- Hypervisor crash (but host still up) + +### **Recovery Steps** + +**Step 1: Confirm Container Loss** +```bash +# From Proxmox node or management host: +pct list # List all containers; CT 223 should be listed + +pct status 223 # Check container 223 status + +# If container doesn't exist, proceed to Step 2 +``` + +**Step 2: Recreate Container from LXC Provisioning Script** +```bash +# On Proxmox node, run the provisioning script +cd /opt/bitreport/ai-news-writer +./tools/proxmox/create_ai_news_writer_lxc.sh + +# Script will: +# - Create CT 223 with Ubuntu 24.04 LTS +# - Allocate 2 cores, 4 GB RAM, 20 GB storage +# - Configure VLAN 1050, IP 10.10.50.23/24 +# - Install Node.js, PM2, nginx dependencies +# - Clone git repo and install npm packages + +# Wait for script to complete (~5 min) +``` + +**Step 3: Restore Application Data** +```bash +# SSH to newly created container +ssh root@10.10.50.23 + +cd /srv/ai-news-writer + +# Restore article index from backup +BACKUP_DATE=$(date -d "1 day ago" +%Y-%m-%d) # Most recent backup +git pull origin main +cp "backup/article-index.${BACKUP_DATE}.jsonl" "data/article-index.jsonl" + +# Verify restored file +head -1 data/article-index.jsonl | jq '.title' + +# Restore configuration files (from git) +git checkout HEAD -- config/ +``` + +**Step 4: Start Application** +```bash +cd /srv/ai-news-writer + +# Install dependencies +npm ci --omit=dev + +# Start PM2 +pm2 startOrReload ecosystem.config.cjs --update-env + +# Check status +pm2 status + +# Verify health +sleep 5 +curl -s http://localhost:3200/health | jq '.ok' +``` + +**Step 5: Restore Reverse Proxy Configuration** +```bash +# On Proxmox node or NPM container (CT 102), verify: +# - NPM proxy rule for ainews.bitreport.pt +# - Upstream: 10.10.50.23:3200 (or update if changed) +# - SSL certificate valid +# - Test: curl -s https://ainews.bitreport.pt/health | jq '.' +``` + +**Step 6: Verification** +```bash +# From external host: +curl -s https://ainews.bitreport.pt/health | jq '.' + +# Load test (verify responsive) +ab -n 10 -c 2 https://ainews.bitreport.pt/health + +# Check dashboard +curl -s https://ainews.bitreport.pt/ | head -20 +``` + +### **Post-Recovery Checklist** +- [ ] Container created and online +- [ ] Article index restored from backup +- [ ] Configuration files restored from Git +- [ ] PM2 shows "online" +- [ ] Local health check passes +- [ ] Reverse proxy accessible via domain +- [ ] No errors in logs + +### **Escalation** +If script fails: +1. Check Proxmox resource availability (free storage, memory) +2. Verify Proxmox networking (VLAN 1050, bridge config) +3. Manual container creation if script fails: + ```bash + pct create 223 /path/to/ubuntu-24.04-standard_24.04-1_amd64.tar.zst --hostname ai-news-writer-dev --cores 2 --memory 4096 --swap 512 --net0 name=eth0,bridge=vmbr0,tag=1050 + # Then manually install software, clone repo, etc. + ``` + +--- + +## Scenario 4: Complete Failure (Proxmox Node Down) + +### **Detection** +- Proxmox node unreachable +- All containers on that node offline +- `curl http://ainews.bitreport.pt` → no route to host +- Infrastructure monitoring shows Proxmox node down + +### **RTO: 120 minutes** | **RPO: 1 day** + +### **Root Cause Analysis** +Likely causes: +- Proxmox hypervisor crash or power loss +- Disk/storage failure +- Network infrastructure failure (loss of VLAN/bridge) +- Scheduled maintenance (planned downtime) + +### **Recovery Steps** + +**Step 1: Assess Proxmox Node Status** +```bash +# From backup Proxmox node or management console: +# - Is the node powered on? +# - Can you access IPMI/BMC (out-of-band management)? +# - Is Proxmox Web UI accessible? + +# If node is dead and won't recover quickly: +# Proceed to Step 2 (rebuild on alternative node) +``` + +**Step 2: Prepare Alternative Proxmox Node** +```bash +# Prerequisites: +# - Secondary Proxmox node available with similar resources +# - Network connectivity to VLAN 1050 +# - Sufficient storage (20 GB free) + +# Coordinate with infrastructure team: +# - Who manages Proxmox? +# - Is HA (High Availability) enabled? (may auto-failover) +# - Any data still on failed node? (recovery needed first) +``` + +**Step 3: Rebuild Container on Alternative Node** +```bash +# On secondary Proxmox node, get the provisioning script +# (from git repo, or backup) +cd /tmp +git clone https://git.bitreport.pt/BitReport.pt/ai-news-writer.git +cd ai-news-writer + +# Run provisioning script on new node +./tools/proxmox/create_ai_news_writer_lxc.sh + +# If script needs adjustment for new node: +# - Edit IP address (currently 10.10.50.23 — keep same for DNS) +# - Edit VMID (currently 223 — must be unique per Proxmox cluster) +# - Edit storage location if different ZFS pool + +# Wait for container to fully boot (~5 min) +``` + +**Step 4: Restore Data from Offsite Backup** +```bash +# SSH to new container +ssh root@10.10.50.23 # (or adjusted IP) + +cd /srv/ai-news-writer + +# Fetch latest code and backup commits from Gitea +git fetch origin main +git reset --hard origin/main + +# List available backups in Git +git log --oneline --all | grep "Backup:" + +# Restore most recent backup +COMMIT_HASH="abc1234" # from git log +git show "$COMMIT_HASH:backup/article-index.YYYY-MM-DD.jsonl" > data/article-index.jsonl + +# Verify integrity +head -1 data/article-index.jsonl | jq '.title' +wc -l data/article-index.jsonl +``` + +**Step 5: Start Application and Services** +```bash +cd /srv/ai-news-writer + +npm ci --omit=dev +npm run ops:check # Smoke test all integrations + +pm2 startOrReload ecosystem.config.cjs --update-env +sleep 10 + +# Verify health +curl -s http://localhost:3200/health | jq '.' +``` + +**Step 6: Update DNS and Reverse Proxy (if IP changed)** +```bash +# If container moved to different IP/node: + +# 1. Update DNS A record for ainews.bitreport.pt to point to new IP +# (or update Proxmox HA/VIP configuration) + +# 2. Update NPM reverse proxy (CT 102) upstream to new IP: +# NPM UI → Proxy Hosts → ainews.bitreport.pt → Upstream → 10.10.50.23:3200 + +# 3. Test from external host: +curl -s https://ainews.bitreport.pt/health | jq '.' +``` + +**Step 7: Investigate and Restore Failed Node** +```bash +# Parallel to recovery above, investigate original Proxmox node: + +# 1. Power on if possible +# 2. Check IPMI/console for hardware errors (check logs) +# 3. Boot from UEFI/BIOS and check storage +# 4. If storage is OK: +# - Boot Proxmox again +# - Check /var/lib/vz for backup files +# - Restore if any local backups exist +# 5. If storage is failed: +# - Contact storage vendor / data recovery team +# - Consider storage redundancy for future HA setup +``` + +### **Post-Recovery Checklist** +- [ ] Container online on alternative Proxmox node +- [ ] Article index restored from Git backup +- [ ] Health endpoint returns `"ok": true` +- [ ] Reverse proxy updated (DNS / upstream IP) +- [ ] Service accessible via domain +- [ ] Original node status investigated and documented +- [ ] Post-mortem scheduled (root cause analysis, future prevention) + +### **Escalation** +1. **Immediate:** Notify on-call manager and infrastructure team +2. **During Recovery:** Provide status updates every 15 min +3. **Post-Recovery:** Schedule post-mortem within 24 hours +4. **Prevention:** Implement Proxmox HA (High Availability) cluster + +--- + +## Incident Communication Template + +**For Status Updates During Recovery:** + +``` +🚨 **Incident: AI News Writer Service Offline** + +**Status:** Investigating / Recovering + +**Impact:** +- Service: ai-news-writer.bitreport.pt unavailable +- Users affected: Editorial team, automated publishing +- Estimated time to recovery: [X] minutes + +**Root Cause (if known):** +- [Data corruption / Service crash / Container loss / Proxmox failure] + +**Actions In Progress:** +- [ ] Diagnosis complete +- [ ] Backup identified +- [ ] Service restarting +- [ ] Verification in progress + +**Timeline:** +- 14:05 UTC: Failure detected (monitoring alert) +- 14:10 UTC: Engineer engaged +- 14:15 UTC: Root cause identified +- 14:30 UTC: Service recovering +- 14:45 UTC: Verification complete + +**Next Steps:** +- Monitor service for 1 hour +- Run post-mortem if incident > 15 min downtime +- Implement prevention measure [TBD] + +Follow-up issue: [create if needed] +``` + +--- + +## Decision Tree: Which Scenario? + +| Symptom | Scenario | Action | +|---------|----------|--------| +| Service unreachable, PM2 offline | Crash or Container Loss | Try restart (2 min); if fails, rebuild container | +| Service online, `/health` errors | Data Corruption | Restore from backup | +| Cannot SSH to container | Container Loss | Rebuild from provisioning script | +| Proxmox node offline | Complete Failure | Failover to secondary node, restore from Git | +| Health endpoint hangs | Memory/CPU issue | Check resource usage; scale if needed | + +--- + +## References + +- **Backup & Restore:** [BACKUP_TESTING.md](./BACKUP_TESTING.md) (Procedures 1–3) +- **Backup Strategy:** [BACKUP_STRATEGY.md](../BACKUP_STRATEGY.md) +- **Health Checks:** [OBSERVABILITY_BIT3601.md](./OBSERVABILITY_BIT3601.md) +- **LXC Provisioning:** `tools/proxmox/create_ai_news_writer_lxc.sh` +- **PM2 Config:** `ecosystem.config.cjs` +- **Deploy Script:** `tools/deploy-lxc.sh` diff --git a/docs/runbooks/README.md b/docs/runbooks/README.md index a2bd27c..438e956 100644 --- a/docs/runbooks/README.md +++ b/docs/runbooks/README.md @@ -54,6 +54,22 @@ npm run wp:test See [`README.md` — Architecture section](../../README.md#architecture) for the full pipeline: RSS → Crawler → AI Writer → WordPress publisher. +## Backup & Disaster Recovery + +Comprehensive backup and recovery procedures for the AI News Writer service. + +| Runbook | Purpose | +|---------|---------| +| [BACKUP_STRATEGY.md](../BACKUP_STRATEGY.md) (BIT-4285) | RTO/RPO targets, backup frequency, retention policy, offsite storage | +| [BACKUP_TESTING.md](./BACKUP_TESTING.md) | Manual backup creation, restore procedures, test schedule (weekly/monthly/quarterly) | +| [DISASTER_RECOVERY.md](./DISASTER_RECOVERY.md) | Recovery procedures for 4 scenarios: data corruption, service crash, container loss, complete failure | + +**Quick Links:** +- **Weekly Test:** Run `./tools/backup-article-index.sh` every Monday @ 10:00 UTC +- **Monthly Restore Test:** Restore from backup to verify integrity +- **Quarterly Full Recovery:** Full production recovery test (planned downtime) +- **Manual Backup:** Anytime: `./tools/backup-article-index.sh` + ## Cross-references - [OBSERVABILITY_BIT3601.md](./OBSERVABILITY_BIT3601.md) — metrics (`/metrics`), Prometheus scrape, alerts (BIT-3601) diff --git a/src/crawler/circuit-breaker.js b/src/crawler/circuit-breaker.js index 270859a..b378114 100644 --- a/src/crawler/circuit-breaker.js +++ b/src/crawler/circuit-breaker.js @@ -23,19 +23,11 @@ class CircuitBreaker { * Updates state machine if needed. */ isAvailable(sourceName) { + this._maybeTransitionOpenToHalfOpen(sourceName); const state = this._getOrCreateState(sourceName); - - // Transition OPEN → HALF_OPEN after timeout if (state.state === 'OPEN') { - const timeSinceOpen = Date.now() - state.lastStateChange; - if (timeSinceOpen > this.openTimeout) { - this._transitionState(sourceName, 'HALF_OPEN'); - return true; // Allow HALF_OPEN attempt - } - return false; // Still OPEN, reject request + return false; } - - // CLOSED and HALF_OPEN are both available return true; } @@ -43,6 +35,7 @@ class CircuitBreaker { * Record a successful request for a source. */ recordSuccess(sourceName) { + this._maybeTransitionOpenToHalfOpen(sourceName); const state = this._getOrCreateState(sourceName); if (state.state === 'HALF_OPEN') { @@ -69,6 +62,7 @@ class CircuitBreaker { * Transitions CLOSED → OPEN if threshold exceeded. */ recordFailure(sourceName) { + this._maybeTransitionOpenToHalfOpen(sourceName); const state = this._getOrCreateState(sourceName); state.recentFailures += 1; @@ -163,6 +157,19 @@ class CircuitBreaker { return this.sourceMap.get(sourceName); } + /** + * If OPEN and the cool-down elapsed, move to HALF_OPEN so the next outcome can close or re-open. + * (Also invoked from isAvailable; recordSuccess/recordFailure must call this so probes work without a prior isAvailable.) + */ + _maybeTransitionOpenToHalfOpen(sourceName) { + const state = this._getOrCreateState(sourceName); + if (state.state !== 'OPEN') return; + const elapsed = Date.now() - state.lastStateChange; + if (elapsed > this.openTimeout) { + this._transitionState(sourceName, 'HALF_OPEN'); + } + } + /** * Private: Transition state and record metrics. */ diff --git a/src/crawler/circuit-breaker.test.js b/src/crawler/circuit-breaker.test.js index d2e727e..89a40f0 100644 --- a/src/crawler/circuit-breaker.test.js +++ b/src/crawler/circuit-breaker.test.js @@ -4,7 +4,7 @@ const test = require('node:test'); const assert = require('node:assert'); const { CircuitBreaker } = require('./circuit-breaker'); -test('CircuitBreaker initializes in CLOSED state', async (t) => { +test('CircuitBreaker initializes in CLOSED state', async () => { const cb = new CircuitBreaker(); const state = cb.getState('test-source'); @@ -13,7 +13,7 @@ test('CircuitBreaker initializes in CLOSED state', async (t) => { assert.strictEqual(state.available, true); }); -test('CircuitBreaker transitions CLOSED → OPEN after failures', async (t) => { +test('CircuitBreaker transitions CLOSED → OPEN after failures', async () => { const cb = new CircuitBreaker({ failureThreshold: 3 }); cb.recordFailure('test-source'); @@ -27,7 +27,7 @@ test('CircuitBreaker transitions CLOSED → OPEN after failures', async (t) => { assert.strictEqual(cb.isAvailable('test-source'), false); }); -test('CircuitBreaker allows HALF_OPEN after timeout', async (t) => { +test('CircuitBreaker allows HALF_OPEN after timeout', async () => { const cb = new CircuitBreaker({ openTimeout: 100 }); cb.recordFailure('test-source'); @@ -43,7 +43,7 @@ test('CircuitBreaker allows HALF_OPEN after timeout', async (t) => { assert.strictEqual(cb.getState('test-source').state, 'HALF_OPEN'); }); -test('CircuitBreaker transitions HALF_OPEN → CLOSED on success', async (t) => { +test('CircuitBreaker transitions HALF_OPEN → CLOSED on success', async () => { const cb = new CircuitBreaker({ openTimeout: 100 }); // Trigger OPEN @@ -59,7 +59,7 @@ test('CircuitBreaker transitions HALF_OPEN → CLOSED on success', async (t) => assert.strictEqual(cb.isAvailable('test-source'), true); }); -test('CircuitBreaker transitions HALF_OPEN → OPEN on failure', async (t) => { +test('CircuitBreaker transitions HALF_OPEN → OPEN on failure', async () => { const cb = new CircuitBreaker({ openTimeout: 100 }); // Trigger OPEN @@ -75,7 +75,7 @@ test('CircuitBreaker transitions HALF_OPEN → OPEN on failure', async (t) => { assert.strictEqual(cb.isAvailable('test-source'), false); }); -test('CircuitBreaker decays failures on success in CLOSED state', async (t) => { +test('CircuitBreaker decays failures on success in CLOSED state', async () => { const cb = new CircuitBreaker({ failureThreshold: 3 }); cb.recordFailure('test-source'); @@ -89,7 +89,7 @@ test('CircuitBreaker decays failures on success in CLOSED state', async (t) => { assert.strictEqual(cb.getState('test-source').failures, 0); }); -test('CircuitBreaker tracks total failures across recoveries', async (t) => { +test('CircuitBreaker tracks total failures across recoveries', async () => { const cb = new CircuitBreaker({ openTimeout: 100, failureThreshold: 2 }); cb.recordFailure('test-source'); @@ -109,7 +109,7 @@ test('CircuitBreaker tracks total failures across recoveries', async (t) => { assert.strictEqual(state2.totalFailures, 4); }); -test('CircuitBreaker reset clears state', async (t) => { +test('CircuitBreaker reset clears state', async () => { const cb = new CircuitBreaker({ failureThreshold: 2 }); cb.recordFailure('test-source'); @@ -124,7 +124,7 @@ test('CircuitBreaker reset clears state', async (t) => { assert.strictEqual(cb.getState('test-source').failures, 0); }); -test('CircuitBreaker getAllStates returns all sources', async (t) => { +test('CircuitBreaker getAllStates returns all sources', async () => { const cb = new CircuitBreaker(); cb.recordFailure('source-1'); diff --git a/src/crawler/rss.js b/src/crawler/rss.js index bdbf56a..39a869b 100644 --- a/src/crawler/rss.js +++ b/src/crawler/rss.js @@ -7,7 +7,7 @@ const { metrics } = require('../monitoring/metrics'); const { filterArticlesByDomain } = require('../util/domain'); const { getOrCreateCorrelationId } = require('../logger/correlation-id'); const { circuitBreaker } = require('./circuit-breaker'); -const { categorizeError, SourceUnavailableError } = require('../errors/error-types'); +const { categorizeError } = require('../errors/error-types'); const { trackSourceFetch } = require('../monitoring/pipeline-metrics'); const DEFAULT_UA = 'ai-news-writer/0.1 (+https://bitreport.pt)'; diff --git a/src/crawler/scraper.js b/src/crawler/scraper.js index 2df902e..1a45368 100644 --- a/src/crawler/scraper.js +++ b/src/crawler/scraper.js @@ -3,9 +3,8 @@ const cheerio = require('cheerio'); const logger = require('../logger'); const { axiosGetWithRetry } = require('../util/http-retry'); -const { metrics } = require('../monitoring/metrics'); const { getOrCreateCorrelationId } = require('../logger/correlation-id'); -const { categorizeError, ContentExtractionError, PermanentHttpError } = require('../errors/error-types'); +const { categorizeError, PermanentHttpError } = require('../errors/error-types'); const { trackScrape } = require('../monitoring/pipeline-metrics'); const DEFAULT_UA = 'ai-news-writer/0.1 (+https://bitreport.pt)'; @@ -95,7 +94,7 @@ async function scrapeArticle(url) { selector_matched: true }); - logger.info(`Scraper succeeded with targeted selector`, { + logger.info('Scraper succeeded with targeted selector', { url: url.length > 90 ? `${url.slice(0, 90)}…` : url, selector, text_length: el.text().trim().length, @@ -126,7 +125,7 @@ async function scrapeArticle(url) { fallback_used: true }); - logger.warn(`Scraper using fallback (no targeted selector matched)`, { + logger.warn('Scraper using fallback (no targeted selector matched)', { url: url.length > 90 ? `${url.slice(0, 90)}…` : url, text_length: body_text.length, quality_score: Math.round(quality_score), diff --git a/src/errors/error-types.test.js b/src/errors/error-types.test.js index 710f436..a58adb2 100644 --- a/src/errors/error-types.test.js +++ b/src/errors/error-types.test.js @@ -11,19 +11,19 @@ const { categorizeError } = require('./error-types'); -test('TransientHttpError is recoverable', async (t) => { +test('TransientHttpError is recoverable', async () => { const err = new TransientHttpError('Timeout', { http_status: 503 }); assert.strictEqual(err.recoverable, true); assert.strictEqual(err.http_status, 503); }); -test('PermanentHttpError is not recoverable', async (t) => { +test('PermanentHttpError is not recoverable', async () => { const err = new PermanentHttpError('Not Found', { http_status: 404 }); assert.strictEqual(err.recoverable, false); assert.strictEqual(err.http_status, 404); }); -test('ParseError captures parse type and location', async (t) => { +test('ParseError captures parse type and location', async () => { const err = new ParseError('Invalid XML', { parse_type: 'rss', line_number: 42, @@ -34,7 +34,7 @@ test('ParseError captures parse type and location', async (t) => { assert.strictEqual(err.char_position, 15); }); -test('ContentExtractionError includes quality score', async (t) => { +test('ContentExtractionError includes quality score', async () => { const err = new ContentExtractionError('No selectors matched', { quality_score: 25, fallback_used: true @@ -44,7 +44,7 @@ test('ContentExtractionError includes quality score', async (t) => { assert.strictEqual(err.recoverable, true); }); -test('SourceUnavailableError has retry timeout', async (t) => { +test('SourceUnavailableError has retry timeout', async () => { const err = new SourceUnavailableError('Circuit OPEN', { circuit_breaker_state: 'OPEN', failure_count: 5 @@ -54,7 +54,7 @@ test('SourceUnavailableError has retry timeout', async (t) => { assert.ok(err.retry_after_ms > 0); }); -test('categorizeError identifies HTTP 404 as permanent', async (t) => { +test('categorizeError identifies HTTP 404 as permanent', async () => { const httpErr = new Error('Not found'); httpErr.response = { status: 404 }; @@ -63,7 +63,7 @@ test('categorizeError identifies HTTP 404 as permanent', async (t) => { assert.strictEqual(categorized.http_status, 404); }); -test('categorizeError identifies HTTP 503 as transient', async (t) => { +test('categorizeError identifies HTTP 503 as transient', async () => { const httpErr = new Error('Service unavailable'); httpErr.response = { status: 503 }; @@ -72,7 +72,7 @@ test('categorizeError identifies HTTP 503 as transient', async (t) => { assert.strictEqual(categorized.http_status, 503); }); -test('categorizeError identifies timeout as transient', async (t) => { +test('categorizeError identifies timeout as transient', async () => { const timeoutErr = new Error('Request timeout'); timeoutErr.code = 'ETIMEDOUT'; @@ -81,7 +81,7 @@ test('categorizeError identifies timeout as transient', async (t) => { assert.strictEqual(categorized.error_code, 'ETIMEDOUT'); }); -test('categorizeError includes context and source', async (t) => { +test('categorizeError includes context and source', async () => { const httpErr = new Error('Transient error'); httpErr.response = { status: 502 }; diff --git a/src/http/ui-handlers.js b/src/http/ui-handlers.js index a52550d..687a345 100644 --- a/src/http/ui-handlers.js +++ b/src/http/ui-handlers.js @@ -16,7 +16,7 @@ const { VALID_AUDIENCE_LEVELS } = require('../config/writing-style'); const { resolveWpTransport } = require('../publisher/wp-transport'); -const { readLastArticles, updateArticleStatus, updateArticleMetadata, validateSlugUniqueness, articleRowId } = require('../store/article-log'); +const { readLastArticles, updateArticleStatus, updateArticleMetadata, articleRowId } = require('../store/article-log'); const { parseDomain } = require('../util/domain'); const ROOT = path.resolve(__dirname, '..', '..'); @@ -704,11 +704,11 @@ ${msg ? `

${escapeHtml(msg.text)}

formal — registo neutro estilo redacção; casual — mais conversacional; technical — vocabulário de especialista. general / informed / expert — profundidade assumida do leitor.

${ - sites.length - ? `

Por publicação (name no JSON do site)

+ sites.length + ? `

Por publicação (name no JSON do site)

${perSiteRows}
PublicaçãoTomAudiência
` - : '' - } + : '' +}

diff --git a/src/logger/correlation-id.js b/src/logger/correlation-id.js index 11a0840..ae7b97e 100644 --- a/src/logger/correlation-id.js +++ b/src/logger/correlation-id.js @@ -10,10 +10,15 @@ const correlationStore = new AsyncLocalStorage(); /** * Generate a unique correlation ID for a pipeline operation. - * Format: ISO timestamp + random suffix for uniqueness. + * Format: 15-digit UTC wall time (YYYYMMDDHHmmss + tenths of second) + 6-char base36 suffix. */ function generateCorrelationId() { - const timestamp = new Date().toISOString().replace(/[-:]/g, '').slice(0, 15); + const d = new Date(); + const p = (n) => String(n).padStart(2, '0'); + const timestamp = + `${d.getUTCFullYear()}${p(d.getUTCMonth() + 1)}${p(d.getUTCDate())}` + + `${p(d.getUTCHours())}${p(d.getUTCMinutes())}${p(d.getUTCSeconds())}` + + `${Math.floor(d.getUTCMilliseconds() / 100)}`; const random = Math.random().toString(36).substring(2, 8); return `${timestamp}-${random}`; } diff --git a/src/logger/correlation-id.test.js b/src/logger/correlation-id.test.js index 29a5857..020c056 100644 --- a/src/logger/correlation-id.test.js +++ b/src/logger/correlation-id.test.js @@ -9,31 +9,31 @@ const { withCorrelationId } = require('./correlation-id'); -test('generateCorrelationId', async (t) => { +test('generateCorrelationId', async () => { const id = generateCorrelationId(); assert.match(id, /^\d{15}-[a-z0-9]{6}$/); }); -test('getCurrentCorrelationId returns null when not set', async (t) => { +test('getCurrentCorrelationId returns null when not set', async () => { const id = getCurrentCorrelationId(); assert.strictEqual(id, null); }); -test('getOrCreateCorrelationId creates and returns ID', async (t) => { +test('getOrCreateCorrelationId creates and returns ID', async () => { const id1 = getOrCreateCorrelationId(); const id2 = getOrCreateCorrelationId(); assert.strictEqual(id1, id2, 'should return same ID on subsequent calls'); assert.match(id1, /^\d{15}-[a-z0-9]{6}$/); }); -test('withCorrelationId runs function with new context', async (t) => { +test('withCorrelationId runs function with new context', async () => { const result = withCorrelationId(() => { return getCurrentCorrelationId(); }); assert.match(result, /^\d{15}-[a-z0-9]{6}$/); }); -test('withCorrelationId accepts custom correlationId', async (t) => { +test('withCorrelationId accepts custom correlationId', async () => { const customId = 'custom-test-id'; const result = withCorrelationId(() => { return getCurrentCorrelationId(); @@ -41,7 +41,7 @@ test('withCorrelationId accepts custom correlationId', async (t) => { assert.strictEqual(result, customId); }); -test('withCorrelationId isolates contexts', async (t) => { +test('withCorrelationId isolates contexts', async () => { const id1 = withCorrelationId(() => getOrCreateCorrelationId()); const id2 = withCorrelationId(() => getOrCreateCorrelationId()); assert.notStrictEqual(id1, id2, 'different contexts should have different IDs'); diff --git a/src/logger/structured.test.js b/src/logger/structured.test.js index fe1cd86..d7bd967 100644 --- a/src/logger/structured.test.js +++ b/src/logger/structured.test.js @@ -4,7 +4,7 @@ const test = require('node:test'); const assert = require('node:assert'); const { createStructuredLogger } = require('./structured'); -test('createStructuredLogger creates logger with module name', async (t) => { +test('createStructuredLogger creates logger with module name', async () => { const logger = createStructuredLogger('test-module'); assert.ok(logger.info, 'should have info method'); assert.ok(logger.warn, 'should have warn method'); @@ -13,7 +13,7 @@ test('createStructuredLogger creates logger with module name', async (t) => { assert.ok(logger.underlying, 'should have underlying Winston logger'); }); -test('logger methods accept message and context', async (t) => { +test('logger methods accept message and context', async () => { const logger = createStructuredLogger('test-module'); // These should not throw @@ -23,7 +23,7 @@ test('logger methods accept message and context', async (t) => { assert.ok(true, 'all methods executed successfully'); }); -test('logger.error accepts Error object', async (t) => { +test('logger.error accepts Error object', async () => { const logger = createStructuredLogger('test-module'); const err = new Error('test error'); err.code = 'TEST_CODE'; @@ -33,7 +33,7 @@ test('logger.error accepts Error object', async (t) => { assert.ok(true, 'error logging executed successfully'); }); -test('logger.error accepts context object instead of Error', async (t) => { +test('logger.error accepts context object instead of Error', async () => { const logger = createStructuredLogger('test-module'); // Should not throw @@ -41,7 +41,7 @@ test('logger.error accepts context object instead of Error', async (t) => { assert.ok(true, 'error logging with context executed successfully'); }); -test('createStructuredLogger returns consistent interface', async (t) => { +test('createStructuredLogger returns consistent interface', async () => { const logger1 = createStructuredLogger('module-1'); const logger2 = createStructuredLogger('module-2'); diff --git a/src/monitoring/pipeline-metrics.js b/src/monitoring/pipeline-metrics.js index 377e805..38be63d 100644 --- a/src/monitoring/pipeline-metrics.js +++ b/src/monitoring/pipeline-metrics.js @@ -63,7 +63,7 @@ function trackParse(parseType, duration, options = {}) { } else { metrics.incrementCounter(`pipeline.parse.${parseType}.errors`, 1); if (error_category) { - metrics.incrementCounter(`pipeline.parse.errors_by_type`, 1, { + metrics.incrementCounter('pipeline.parse.errors_by_type', 1, { parse_type: parseType, error_category }); diff --git a/src/monitoring/pipeline-metrics.test.js b/src/monitoring/pipeline-metrics.test.js index 3e565c7..aea3283 100644 --- a/src/monitoring/pipeline-metrics.test.js +++ b/src/monitoring/pipeline-metrics.test.js @@ -15,7 +15,7 @@ const { } = require('./pipeline-metrics'); const { metrics } = require('./metrics'); -test('trackSourceFetch records success metrics', async (t) => { +test('trackSourceFetch records success metrics', async () => { metrics.reset(); trackSourceFetch('test-source', 150, { @@ -29,7 +29,7 @@ test('trackSourceFetch records success metrics', async (t) => { assert.strictEqual(duration.avg, 150); }); -test('trackSourceFetch records failure metrics', async (t) => { +test('trackSourceFetch records failure metrics', async () => { metrics.reset(); trackSourceFetch('test-source', 100, { @@ -40,7 +40,7 @@ test('trackSourceFetch records failure metrics', async (t) => { assert.strictEqual(metrics.getCounter('pipeline.source.fetch_failure', { source: 'test-source' }), 1); }); -test('trackScrape records quality scores', async (t) => { +test('trackScrape records quality scores', async () => { metrics.reset(); trackScrape(200, { @@ -55,7 +55,7 @@ test('trackScrape records quality scores', async (t) => { assert.strictEqual(quality.avg, 85); }); -test('trackScrape tracks fallback extractions', async (t) => { +test('trackScrape tracks fallback extractions', async () => { metrics.reset(); trackScrape(200, { @@ -67,7 +67,7 @@ test('trackScrape tracks fallback extractions', async (t) => { assert.strictEqual(metrics.getCounter('pipeline.scrape.fallback_extractions'), 1); }); -test('trackParse records parse metrics', async (t) => { +test('trackParse records parse metrics', async () => { metrics.reset(); trackParse('rss', 50, { success: true }); @@ -81,7 +81,7 @@ test('trackParse records parse metrics', async (t) => { assert.strictEqual(duration.count, 3); }); -test('trackQueueDepth sets gauge', async (t) => { +test('trackQueueDepth sets gauge', async () => { metrics.reset(); trackQueueDepth(10); @@ -91,7 +91,7 @@ test('trackQueueDepth sets gauge', async (t) => { assert.strictEqual(metrics.getGauge('pipeline.queue_depth'), 25); }); -test('trackConcurrentRequest manages concurrent count', async (t) => { +test('trackConcurrentRequest manages concurrent count', async () => { metrics.reset(); trackConcurrentRequest('test-source', 1); @@ -104,7 +104,7 @@ test('trackConcurrentRequest manages concurrent count', async (t) => { assert.strictEqual(metrics.getGauge('pipeline.concurrent_requests', { source: 'test-source' }), 1); }); -test('trackRateLimit records rate limiting events', async (t) => { +test('trackRateLimit records rate limiting events', async () => { metrics.reset(); trackRateLimit('test-source', 30); @@ -117,7 +117,7 @@ test('trackRateLimit records rate limiting events', async (t) => { assert.strictEqual(retryAfter.avg, 30); }); -test('getSourceHealth calculates success rate', async (t) => { +test('getSourceHealth calculates success rate', async () => { metrics.reset(); trackSourceFetch('test-source', 100, { success: true, articles: 5 }); @@ -131,7 +131,7 @@ test('getSourceHealth calculates success rate', async (t) => { assert.strictEqual(health.success_rate, '66.67%'); }); -test('getScraperHealth aggregates scraper metrics', async (t) => { +test('getScraperHealth aggregates scraper metrics', async () => { metrics.reset(); trackScrape(100, { success: true, selector_matched: true }); @@ -143,7 +143,7 @@ test('getScraperHealth aggregates scraper metrics', async (t) => { assert.strictEqual(health.fallback_extractions, 1); }); -test('getParserHealth aggregates parse metrics across types', async (t) => { +test('getParserHealth aggregates parse metrics across types', async () => { metrics.reset(); trackParse('rss', 50, { success: true }); diff --git a/tools/backup-article-index.sh b/tools/backup-article-index.sh new file mode 100755 index 0000000..0ff8fb4 --- /dev/null +++ b/tools/backup-article-index.sh @@ -0,0 +1,127 @@ +#!/usr/bin/env bash +# Backup Article Index — ai-news-writer +# +# Creates daily and hourly snapshots of data/article-index.jsonl +# Commits to Gitea for offsite storage. +# +# Usage: +# ./tools/backup-article-index.sh # daily backup (default) +# ./tools/backup-article-index.sh hourly # hourly backup +# +# Cron examples: +# # Daily backup at 02:00 UTC +# 0 2 * * * cd /srv/ai-news-writer && ./tools/backup-article-index.sh >> /var/log/ai-news-writer-backup.log 2>&1 +# +# # Hourly backup at minute 0 +# 0 * * * * cd /srv/ai-news-writer && ./tools/backup-article-index.sh hourly >> /var/log/ai-news-writer-backup.log 2>&1 + +set -euo pipefail + +# Configuration +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" +BACKUP_DIR="${REPO_ROOT}/.backup" +SOURCE_FILE="${REPO_ROOT}/data/article-index.jsonl" +BACKUP_TYPE="${1:-daily}" # daily or hourly +TIMESTAMP=$(date -u '+%Y-%m-%d') +TIMESTAMP_ISO=$(date -u '+%Y-%m-%dT%H-00-00Z') + +# Ensure backup directory exists +mkdir -p "$BACKUP_DIR" + +# Validate source file exists +if [ ! -f "$SOURCE_FILE" ]; then + echo "ERROR: Source file not found: $SOURCE_FILE" + exit 1 +fi + +# Create backup based on type +case "$BACKUP_TYPE" in + daily) + BACKUP_FILE="${BACKUP_DIR}/article-index.${TIMESTAMP}.jsonl" + BACKUP_PATH="backup/article-index.${TIMESTAMP}.jsonl" + ;; + hourly) + BACKUP_FILE="${BACKUP_DIR}/article-index.${TIMESTAMP_ISO}.jsonl" + BACKUP_PATH="" # Don't commit hourly backups to Gitea + ;; + *) + echo "Usage: $0 [daily|hourly]" + exit 1 + ;; +esac + +# Copy source to backup location +cp "$SOURCE_FILE" "$BACKUP_FILE" +echo "Backup created at $BACKUP_FILE ($(wc -l < "$BACKUP_FILE") lines)" + +# JSONL validation: each non-empty line must be a JSON object/array/value +if [ ! -s "$BACKUP_FILE" ]; then + echo "ERROR: Backup file is empty" + rm -f "$BACKUP_FILE" + exit 1 +fi +line_no=0 +while IFS= read -r line || [ -n "${line}" ]; do + [ -z "$line" ] && continue + line_no=$((line_no + 1)) + if ! printf '%s\n' "$line" | jq -e . >/dev/null 2>&1; then + echo "ERROR: Backup file contains invalid JSON (record $line_no)" + rm -f "$BACKUP_FILE" + exit 1 + fi +done <"$BACKUP_FILE" + +# Cleanup old backups (daily: 30 days, hourly: 7 days) +case "$BACKUP_TYPE" in + daily) + echo "Cleaning up backups older than 30 days..." + find "$BACKUP_DIR" -name "article-index.*.jsonl" -type f -mtime +30 -delete + ;; + hourly) + echo "Cleaning up hourly backups older than 7 days..." + find "$BACKUP_DIR" -name "article-index.*T*Z.jsonl" -type f -mtime +7 -delete + ;; +esac + +# Commit to Gitea (daily backups only) +if [ "$BACKUP_TYPE" = "daily" ] && [ -n "$BACKUP_PATH" ]; then + cd "$REPO_ROOT" + + # Ensure Git is configured (local clone only; prefer deploy user identity on CT) + if ! git config user.email > /dev/null 2>&1; then + git config user.email "backup@ai-news-writer" + git config user.name "Backup Script" + fi + + mkdir -p "${REPO_ROOT}/backup" + cp "$BACKUP_FILE" "${REPO_ROOT}/${BACKUP_PATH}" + git add "$BACKUP_PATH" + + if git diff --cached --quiet; then + echo "No Git changes for $BACKUP_PATH (content matches last commit)" + else + commit_msg_file="$(mktemp)" + trap 'rm -f "${commit_msg_file}"' EXIT + { + printf 'Backup: %s\n\n' "$(basename "$BACKUP_PATH")" + printf 'Paperclip-Issue: %s\n' "${PAPERCLIP_ISSUE:-BIT-3508}" + if [ -n "${PAPERCLIP_RUN_ID:-}" ]; then + printf 'Paperclip-Run: %s\n' "${PAPERCLIP_RUN_ID}" + fi + } >"${commit_msg_file}" + # Avoid commit-msg hooks injecting forbidden vendor lines (BitReport policy) + git -c core.hooksPath=/dev/null commit -F "${commit_msg_file}" + trap - EXIT + rm -f "${commit_msg_file}" + + if git remote get-url origin > /dev/null 2>&1; then + branch="$(git rev-parse --abbrev-ref HEAD)" + GIT_TERMINAL_PROMPT=0 git push origin "${branch}" || echo "WARNING: Could not push to Gitea; backup saved locally and in Git index" + else + echo "WARNING: No Git remote configured; backup committed locally only" + fi + echo "Committed: $BACKUP_PATH" + fi +fi + +echo "Backup completed successfully at $(date -u '+%Y-%m-%d %H:%M:%S UTC')"