diff --git a/docs/runbooks/DEPLOY_AND_ROLLBACK.md b/docs/runbooks/DEPLOY_AND_ROLLBACK.md new file mode 100644 index 0000000..7a743a3 --- /dev/null +++ b/docs/runbooks/DEPLOY_AND_ROLLBACK.md @@ -0,0 +1,269 @@ +# Deployment & Rollback Procedures + +This runbook documents the complete deployment process and rollback strategies for the ai-news-writer service. + +**Service:** ai-news-writer (Node.js / PM2 / LXC) +**Container:** CTID 223 | **Domain:** `ainews.bitreport.pt` +**Repo:** `https://git.bitreport.pt/BitReport.pt/ai-news-writer` + +--- + +## Deployment Process + +### Prerequisites + +- SSH access to Proxmox node / LXC container CTID 223 +- Git access to `https://git.bitreport.pt/BitReport.pt/ai-news-writer` +- PM2 installed globally on container: `npm install -g pm2` +- `.env` file configured with required secrets (OpenAI key, WordPress credentials) + +### Step 1: Pre-Deployment Checks + +Before deploying, verify the system is healthy: + +```bash +# SSH into container +ssh @ + +# Check current status +pm2 list +pm2 logs ai-news-writer --lines 20 + +# Verify service is responding +curl https://ainews.bitreport.pt/health + +# Check disk space +df -h /opt/bitreport/ai-news-writer + +# Verify RSS feeds are accessible +npm run rss:test + +# Test WordPress connectivity +npm run wp:test +``` + +### Step 2: Code Deployment + +```bash +# Pull latest changes from main branch +git pull --ff-only origin main + +# If ff-only fails, abort and investigate divergence +# Do NOT use --force or --rebase without understanding the conflict + +# Install dependencies (prod mode) +npm ci --omit=dev + +# Verify no build/lint errors in dependencies +npm run lint --quiet +``` + +### Step 3: Post-Deployment Validation + +```bash +# Reload/restart PM2 app (maintains uptime if possible) +pm2 startOrReload ecosystem.config.cjs --update-env + +# Monitor for errors (wait 30 seconds) +pm2 logs ai-news-writer --lines 50 --err + +# Run comprehensive ops check +npm run ops:check + +# If using deployment flag with smoke test: +npm run deploy:lxc -- --with-ops-check +``` + +### Step 4: Health Check + +```bash +# Endpoint check (health endpoint) +curl -I https://ainews.bitreport.pt/health +# Expected: 200 OK + +# Operations dashboard +curl https://ainews.bitreport.pt/ + +# UI availability +curl -I https://ainews.bitreport.pt/ui +# Expected: 200 OK (if behind reverse proxy with auth) + +# Feed probe (verify RSS connectivity) +npm run rss:test +``` + +--- + +## Rollback Procedures + +Rollback is needed when: +- Deployment introduces a service error or crash +- Health checks fail post-deployment +- Critical functionality is broken +- WordPress connectivity fails +- Performance degradation detected + +### Immediate Rollback (Last Known Good) + +If deployment is actively breaking the service: + +```bash +# Option 1: Rollback to previous git commit +git log --oneline -5 # View last 5 commits +git revert HEAD # Create a revert commit +git push origin main # Push revert to repo + +# Then re-run deployment with reverted code +npm ci --omit=dev +pm2 startOrReload ecosystem.config.cjs --update-env + +# Option 2: Rollback via git reset (use only if repo not yet pushed) +git reset --hard # Go back to known good state +npm ci --omit=dev +pm2 startOrReload ecosystem.config.cjs --update-env +``` + +### Post-Deployment Rollback (30 Minute Window) + +If issues are detected within 30 minutes of deployment: + +```bash +# 1. Check git log for previous stable commit +git log --oneline -10 +git diff HEAD # Review what changed + +# 2. Revert using git revert (keeps history) +git revert HEAD +git push origin main + +# 3. Redeploy with reverted code +git pull --ff-only origin main +npm ci --omit=dev +pm2 startOrReload ecosystem.config.cjs --update-env + +# 4. Verify rollback +npm run ops:check +curl https://ainews.bitreport.pt/health +``` + +### Extended Rollback (Checkpoint Restore) + +For critical scenarios where a quick fix isn't possible: + +```bash +# 1. Save current state +npm run ops:check > /tmp/pre-rollback-ops.txt +pm2 save # Save process state + +# 2. Restore to last known good commit (from git history) +# Check when deployment happened and pick a commit from before that time +git log --pretty=format:"%h %ai %s" | head -20 + +# 3. Full rollback with dependency refresh +git reset --hard +rm -rf node_modules package-lock.json +npm ci --omit=dev +npm run lint # Ensure no lint errors before restart + +# 4. Restart service +pm2 startOrReload ecosystem.config.cjs --update-env + +# 5. Comprehensive validation +npm run ops:check +pm2 logs ai-news-writer --lines 50 + +# 6. Document rollback reason +# Create an issue or alert in Paperclip with: +# - What broke +# - When detected +# - Which commit caused it +# - Rollback steps taken +``` + +--- + +## Recovery Checklist + +After any rollback or emergency restart: + +- [ ] Service is responding: `curl https://ainews.bitreport.pt/health` +- [ ] Health endpoint returns 200: expected status +- [ ] UI is accessible: `curl -I https://ainews.bitreport.pt/ui` +- [ ] RSS feeds are reachable: `npm run rss:test` +- [ ] WordPress connectivity confirmed: `npm run wp:test` +- [ ] PM2 process running: `pm2 list | grep ai-news-writer` +- [ ] No errors in recent logs: `pm2 logs ai-news-writer --lines 30` +- [ ] Disk space OK: `df -h /opt/bitreport/ai-news-writer` +- [ ] Paperclip issue created documenting incident (if rollback occurred) + +--- + +## Common Deployment Issues + +### Issue: `git pull --ff-only` fails with merge conflict + +**Cause:** Branch has diverged from origin/main +**Resolution:** +```bash +# DO NOT force merge. Investigate the conflict. +git status +git diff origin/main + +# If safe, rebase: +git rebase origin/main + +# If conflict, abort and contact team +git rebase --abort +``` + +### Issue: `npm ci` fails with dependency errors + +**Cause:** Corrupted node_modules or lock file +**Resolution:** +```bash +rm -rf node_modules package-lock.json +npm ci --omit=dev +``` + +### Issue: PM2 restart fails with port already in use + +**Cause:** Previous process didn't fully terminate +**Resolution:** +```bash +# Kill any lingering node processes +pkill -f "node.*ai-news-writer" +sleep 2 + +# Restart PM2 +pm2 startOrReload ecosystem.config.cjs --update-env + +# Verify port is free +lsof -i :3000 # adjust port based on ecosystem.config.cjs +``` + +### Issue: WordPress connectivity fails after deployment + +**Cause:** Environment variables not updated or WP site down +**Resolution:** +```bash +# Verify .env variables +cat .env | grep WP_ + +# Test WP connectivity +npm run wp:test + +# If WP is down, escalate to WordPress team +# If variables are wrong, update .env and restart: +pm2 startOrReload ecosystem.config.cjs --update-env +``` + +--- + +## Escalation + +- **Deployment assistance:** DevOps team (@devops) +- **WordPress issues:** WordPress platform team (@wp-platform) +- **Service down >15min:** On-call engineering (@engineering-oncall) +- **Git/Repo issues:** Gitea admin team (@gitea-admin) + +See [ESCALATION.md](./ESCALATION.md) for contact details and escalation procedures. diff --git a/docs/runbooks/ESCALATION.md b/docs/runbooks/ESCALATION.md new file mode 100644 index 0000000..bff6389 --- /dev/null +++ b/docs/runbooks/ESCALATION.md @@ -0,0 +1,363 @@ +# Escalation Procedures & Contacts + +Guidelines for when and how to escalate ai-news-writer operational issues. + +**Service:** ai-news-writer (Node.js / PM2 / LXC) +**Container:** CTID 223 | **Domain:** `ainews.bitreport.pt` +**Escalation System:** Paperclip (@username for notifications) + +--- + +## Escalation Matrix + +| Severity | Impact | SLA | First Contact | Escalation | Example | +|----------|--------|-----|-------|-----------|---------| +| **Critical** | Service completely down >5min | 15min | On-call engineer | @peter-spark (CTO) | 502 after restart fails x2 | +| **High** | Partial service degradation >15min | 30min | Team lead | @devops or @wp-platform | Memory leak causing slowdown | +| **Medium** | Non-blocking issue, workaround exists | 2h | Assigned team | Team lead | Single RSS feed failing | +| **Low** | Future enhancement or cleanup | None | Backlog | Next sprint planning | Documentation update | + +--- + +## Team Contacts + +### DevOps & Infrastructure +- **Slack:** #infrastructure (@devops team) +- **Primary:** Tiago Neves (@tiago-neves) — infrastructure lead +- **Backup:** Rosa Oliveira (@rosa-oliveira) — operations manager +- **Issues:** Container health, memory upgrades, network connectivity, Proxmox access + +### WordPress Platform +- **Slack:** #wordpress (@wp-platform team) +- **Primary:** WordPress team lead (see Paperclip org chart) +- **Issues:** WordPress down, API errors, plugin issues, authentication + +### Gitea / Repository +- **Slack:** #gitea (@gitea-admin) +- **Primary:** Gitea admin team +- **Issues:** Repository access, branch protection, action failures, SSH key setup + +### On-Call Engineering +- **Slack:** #engineering-oncall +- **Rotation:** Check Paperclip on-call board or `/who_oncall` Slack command +- **Issues:** Critical outages, undiagnosed crashes, data loss + +### OpenAI / External APIs +- **Contact:** OpenAI support portal (separate from slack) +- **Internal liaison:** Engineering team (@engineering) +- **Issues:** Rate limits, API errors, quota exceeded + +--- + +## When to Escalate + +### Critical (Escalate Immediately) + +- Service has been down >5 minutes after restart attempts +- Data loss or corruption suspected +- Security incident (unauthorized access, credential leak) +- Cascading failure (affecting other services) + +**Action:** +``` +1. Post to #engineering-oncall with: + - Service name: ai-news-writer + - Issue: [1-2 line description] + - Timestamp: [when started] + - Steps taken: [what you've already tried] + - Error logs: [relevant log excerpts] + +2. Create Paperclip issue with label: CRITICAL + - Tag: @ + - Title: "[CRITICAL] ai-news-writer — " + - Description: full context + logs + +3. Page on-call (if available) +``` + +### High (Escalate Within 30 Minutes) + +- Service is degraded (slow responses, errors, >10% failure rate) +- External dependency unavailable (WordPress, RSS hosts, OpenAI) +- Memory/disk/CPU critical (>85% usage) + +**Action:** +``` +1. Post to #engineering-oncall (no page) + +2. Create Paperclip issue with label: HIGH + - Title: "[HIGH] ai-news-writer — " + - Assign to: team lead (@devops or @wp-platform) + +3. Continue troubleshooting while escalated +``` + +### Medium (Escalate Within 2 Hours) + +- Single component failing (one RSS feed, one WordPress site) +- Workaround exists (e.g., disable problematic feed) +- Issue is localized (not affecting service availability) + +**Action:** +``` +1. Create Paperclip issue with label: MEDIUM + - Title: "[MEDIUM] ai-news-writer — " + - Assign to: relevant team + +2. Document workaround (if any) + +3. Normal SLA applies (respond within 2h) +``` + +### Low (No Escalation Required) + +- Minor issues, code improvements, documentation updates +- Can be deferred to next sprint +- No impact on running service + +**Action:** +``` +1. Create Paperclip issue with label: LOW + - Add to backlog for next sprint +``` + +--- + +## Escalation Template (Paperclip) + +When creating an escalation issue, use this template: + +```markdown +## Issue Description + +[1-2 line summary of the problem] + +## Impact + +- Service: ai-news-writer +- Status: [down/degraded/limited] +- Users affected: [ops team / end users / internal] +- Estimated customers impact: [yes/no, how many] + +## Timeline + +- **Detected:** [timestamp] +- **Diagnosis started:** [timestamp] +- **Escalated:** [timestamp] + +## Steps Taken + +- [ ] Checked service status: `pm2 list` +- [ ] Reviewed logs: [link or excerpt] +- [ ] Tested connectivity: `npm run ` +- [ ] Attempted restart: [result] +- [ ] Other: [...] + +## Error Details + +```bash +[Relevant error messages, logs, or output] +``` + +## Current State + +- Status: [down/degraded/investigating] +- Workaround available: [yes/no] +- Workaround: [if yes, describe] + +## Requested Action + +- [ ] Investigate WordPress connectivity +- [ ] Increase container memory +- [ ] Review RSS feed configuration +- [ ] Other: [specify] + +## Escalation + +- **Severity:** [CRITICAL / HIGH / MEDIUM] +- **SLA:** [15min / 30min / 2h] +- **Assigned to:** [@team-name] +``` + +--- + +## Monitoring & Alerting Setup + +### Current Monitoring (2026-04-16) + +As of the date of this runbook, monitoring is being set up as part of [BIT-2838](https://bitreport.pt/issues/BIT-2838) (Observability Foundation). + +**Planned components:** +- Prometheus metrics (CPU, memory, response time) +- Grafana dashboards (real-time health) +- AlertManager rules (auto-escalate on thresholds) +- Loki logs aggregation (centralized logging) + +### Until Automated Monitoring is Online + +**Manual checks (do regularly):** + +```bash +# Every 6 hours (or when alerted) +ssh +pm2 list # Verify running +pm2 logs --lines 20 # Check for errors +curl https://ainews.bitreport.pt/health # Health check +npm run rss:test # Feed connectivity +npm run wp:test # WordPress connectivity +free -h # Memory available +df -h /opt/bitreport/ # Disk space +``` + +**Monitoring dashboard (manual):** + +Once [BIT-2838](https://bitreport.pt/issues/BIT-2838) is complete: +- Grafana: https://monitoring.bitreport.pt/d/ai-news-writer +- Alert rules: Check AlertManager UI +- Logs: Loki log search (query: `job="ai-news-writer"`) + +--- + +## On-Call Handoff + +When transferring on-call duties: + +1. **Current on-call:** Review Paperclip board for open CRITICAL/HIGH issues +2. **Incoming on-call:** Review [escalation status board](https://bitreport.pt/issues?assignee=@on-call&status=in_progress,blocked) +3. **Handoff meeting:** 15 min sync covering: + - Active incidents (if any) + - Known issues / workarounds + - Monitoring status + - Upcoming deployments +4. **Update status:** Post in #engineering-oncall when transition complete + +--- + +## Incident Post-Mortem + +After any CRITICAL or HIGH severity incident: + +1. **Within 24 hours:** Create post-mortem issue + ```markdown + ## Incident Summary + - What happened: [1-2 sentences] + - Duration: [start time to resolution time] + - Root cause: [why did it happen] + + ## Timeline + - T+0min: [detection] + - T+15min: [escalation] + - T+45min: [resolution] + + ## Action Items + - [ ] Fix root cause (e.g., code change, config update) + - [ ] Improve monitoring (e.g., alert rule, health check) + - [ ] Document new runbook section (if new failure type) + - [ ] Team training (if knowledge gap) + + ## Follow-up + - Issue for permanent fix: [BIT-XXXX](link) + - Monitoring improvement: [BIT-XXXX](link) + ``` + +2. **Review & schedule:** Engineering team reviews post-mortem +3. **Track fixes:** Link to permanent fix issues in Paperclip + +--- + +## External Escalation (Vendors) + +### OpenAI API Issues + +**When to contact:** +- API errors (5xx) persisting >15min +- Rate limit exceeded unexpectedly +- Quota issues +- Billing alerts + +**How to contact:** +1. Check OpenAI status page: https://status.openai.com +2. If status is normal, log issue in OpenAI support portal +3. Provide: error message, timestamp, account ID, request details +4. Internal liaison: engineering team (@engineering) + +**Expected SLA:** 1-4 hours (depends on issue severity) + +### RSS Feed / Content Source Issues + +**When to contact:** +- Feed URL changed (404 persistently) +- Feed returns invalid XML +- Excessive timeouts from specific domain + +**How to contact:** +1. Contact feed owner via email or support form +2. Reference your IP/user-agent in case they're blocking +3. Ask for: current feed URL, support contact, expected uptime SLA +4. If critical source, notify content team (@content-team) + +### WordPress Instance Issues + +**When to contact:** +- WordPress team first (see WordPress Platform team above) +- If they determine vendor issue: + - Contact WordPress hosting provider + - Provide: error details, timestamps, affected sites + +--- + +## Communication Channels + +### Slack + +- **#engineering-oncall** — Active incident coordination +- **#infrastructure** — Infrastructure team discussions +- **#wordpress** — WordPress platform team +- **#gitea** — Repository & actions +- **#ai-news-writer-dev** — Project-specific discussions (if exists) + +### Paperclip + +- Create issues for all escalations +- Use @mentions to notify teams +- Use labels: CRITICAL, HIGH, MEDIUM, LOW +- Use priority field for ranking + +### Email + +- Use only for external vendors (OpenAI, hosting providers) +- CC: relevant internal team + +--- + +## Quick Reference Card + +``` +🚨 SERVICE DOWN? + +1. Check status: pm2 list +2. View logs: pm2 logs ai-news-writer --err --lines 50 +3. Restart: pm2 restart ai-news-writer +4. Verify health: curl https://ainews.bitreport.pt/health +5. Still down? Post to #engineering-oncall + create Paperclip issue + +📋 DIAGNOSIS FLOWCHART + +Service down → Check pm2 status + ├─ online? → Check /health endpoint → Test external deps → Check logs + ├─ stopped? → Check logs → npm run ops:check → Restart + └─ error? → Review error logs → Fix issue → Restart + +Still broken? + ├─ 5min → Check with team lead + ├─ 15min → Escalate as HIGH (create Paperclip issue) + └─ 30min → Escalate as CRITICAL (notify #engineering-oncall) + +📞 CONTACTS + +On-call: /who_oncall (Slack) +DevOps: @tiago-neves +WordPress: #wordpress team +Infrastructure: @rosa-oliveira +CTO (critical): @peter-spark +``` diff --git a/docs/runbooks/INCIDENT_RESPONSE.md b/docs/runbooks/INCIDENT_RESPONSE.md new file mode 100644 index 0000000..24fd7d8 --- /dev/null +++ b/docs/runbooks/INCIDENT_RESPONSE.md @@ -0,0 +1,454 @@ +# Incident Response Playbooks + +Structured playbooks for diagnosing and resolving common ai-news-writer failures. + +**Service:** ai-news-writer (Node.js / PM2 / LXC) +**Container:** CTID 223 | **Domain:** `ainews.bitreport.pt` +**On-call:** See [ESCALATION.md](./ESCALATION.md) + +--- + +## 502 Bad Gateway / Service Down + +**Detection:** Users report connection refused or 502 errors; load balancer health check fails. + +### Diagnosis + +```bash +# 1. Verify service status +pm2 list | grep ai-news-writer +# Expected: online | Exited code 1 | stopped | errored + +# 2. Check if process is running at all +ps aux | grep node +# Look for "ai-news-writer" in process name + +# 3. Review recent logs for crash signature +pm2 logs ai-news-writer --lines 50 --err +# Look for: EADDRINUSE, uncaught exception, OOM killer, segfault + +# 4. Verify listening port is free +lsof -i :3000 # adjust port from ecosystem.config.cjs +# No output = port is free + +# 5. Check container connectivity +ping ainews.bitreport.pt +curl -v https://ainews.bitreport.pt/health 2>&1 | head -20 +``` + +### Resolution + +**If process is stopped:** +```bash +# Restart via PM2 +pm2 restart ai-news-writer + +# Wait 5 seconds for startup +sleep 5 + +# Verify it's running +pm2 list | grep ai-news-writer +pm2 logs ai-news-writer --lines 5 +``` + +**If process is errored/crashed:** +```bash +# Review error logs +pm2 logs ai-news-writer --err --lines 100 + +# Common causes: +# - Configuration error: check .env and config/ files +# - Dependency issue: try npm ci --omit=dev && pm2 restart +# - Port conflict: lsof -i :3000 && kill +# - Memory: check free memory with free -h + +# If unable to determine cause: +npm run ops:check +# This runs full diagnostics + +# Restart with clean state +pm2 delete ai-news-writer +pm2 startOrReload ecosystem.config.cjs --update-env +``` + +**If port is in use:** +```bash +# Find and kill the conflicting process +lsof -i :3000 # identify PID +kill -9 + +# Restart service +pm2 restart ai-news-writer +``` + +### Escalation + +- **Not resolved in 5 minutes:** Escalate to DevOps (@devops) +- **Requires configuration change:** Contact infrastructure team +- **After 2 restart failures:** Follow [Extended Rollback](./DEPLOY_AND_ROLLBACK.md#extended-rollback-checkpoint-restore) + +--- + +## High Memory Usage / Out of Memory (OOM) + +**Detection:** +- Health check reports `memory > 500MB` +- PM2 logs show "JavaScript heap out of memory" +- Load average spikes without corresponding traffic increase + +### Diagnosis + +```bash +# 1. Check memory usage +free -h +# Check if RSS listener has been running for days + +# 2. Examine PM2 memory metrics +pm2 monit # real-time view of CPU/memory +# Press 'q' to exit + +# 3. Dump recent logs for memory errors +pm2 logs ai-news-writer --err --lines 100 +# Look for: "FATAL ERROR" or "heap out of memory" + +# 4. Check for memory leaks in data files +du -sh ./data/ # size of persisted data +du -sh ./node_modules/ + +# 5. Test with RSS listener +npm run rss:test +# High memory during this = possible memory leak in crawler +``` + +### Resolution + +**Immediate (buy time):** +```bash +# Restart service (clears memory) +pm2 restart ai-news-writer + +# Monitor memory for 5 minutes +watch -n 1 'pm2 monit' +``` + +**If memory stabilizes:** +- Likely a temporary spike (e.g., large RSS feed processing) +- No action needed +- Document pattern in issue if recurring + +**If memory climbs again:** +```bash +# Check if particular feed is causing issue +npm run rss:test 2>&1 | grep -E "error|fail" + +# If specific feed fails, remove from config/sources.json +# Edit config, restart: +vim config/sources.json +pm2 restart ai-news-writer +``` + +**If problem persists:** +```bash +# Check for zombie processes or hung listeners +ps aux | grep node | grep -v grep + +# Full restart with ops check +npm run deploy:lxc -- --with-ops-check + +# If OOM persists after restart: +# - Check container memory limit: lxc-ls -f CTID +# - Contact infrastructure team for memory upgrade +# - Escalate as CRITICAL +``` + +### Prevention + +- Monitor memory daily (automated alerts via [BIT-2838](./ESCALATION.md#monitoring-setup)) +- Restart service weekly: add cron job or PM2 cron hook +- Limit RSS feed count in config/sources.json +- Enable Node heap snapshots: `NODE_OPTIONS="--max-old-space-size=512"` in .env + +### Escalation + +- **Memory not reducing after restart:** Contact DevOps (@devops) +- **Recurring hourly:** Create issue in Paperclip (possible memory leak) +- **OOM killer active:** Container memory upgrade required (escalate to infrastructure) + +--- + +## Stuck / Hanging Article Generation + +**Detection:** +- RSS listener queued but no progress for >30 minutes +- UI shows articles with status "processing" for hours +- Article generation started but doesn't finish + +### Diagnosis + +```bash +# 1. Check process is still running +pm2 list | grep ai-news-writer +# Should show: online + +# 2. Review logs for hanging indication +pm2 logs ai-news-writer --lines 100 +# Look for: last log is stale (>30 min old) + +# 3. Check if specific article is stuck +ls -lth data/article-index.jsonl | head -5 +# Note the timestamp of last write + +# 4. Identify which operation is hanging +# Check logs around the last article timestamp +pm2 logs ai-news-writer --lines 200 | tail -50 + +# 5. Test individual components +npm run rss:test # Can it fetch RSS? +npm run wp:test # Can it reach WordPress? +npm run x:test # Can it query X/Twitter? +``` + +### Resolution + +**If RSS is slow/hanging:** +```bash +# Increase timeout or reduce feed count +# Edit ecosystem.config.cjs or .env: +# RSS_HTTP_MAX_ATTEMPTS=5 +# RSS_RETRY_BASE_MS=500 + +# Restart +pm2 restart ai-news-writer +``` + +**If WordPress is slow/hanging:** +```bash +# Verify WordPress is responsive +npm run wp:test + +# If WP doesn't respond, escalate to WordPress team +# If WP responds but slowly: +# - Check WP health: curl https:///wp-json/ +# - Increase connection timeout in config/sites/.json +# - Contact WordPress team (@wp-platform) +``` + +**If AI generation is hanging:** +```bash +# Likely hitting OpenAI rate limit or API timeout +# Check recent logs for OpenAI errors: +pm2 logs ai-news-writer --grep "openai\|429\|timeout" --lines 50 + +# If 429 (rate limited): +# - Increase delay between requests in src/writer/ai.js +# - Contact OpenAI for higher rate limit + +# If timeout: +# - Increase timeout in .env: OPENAI_TIMEOUT_MS +# - Reduce prompt complexity +``` + +**Force restart (last resort):** +```bash +# Kill hanging process and restart +pm2 delete ai-news-writer +pm2 startOrReload ecosystem.config.cjs --update-env + +# Monitor +pm2 logs ai-news-writer +``` + +### Escalation + +- **Hanging >1 hour after restart:** Escalate to engineering (@engineering-oncall) +- **OpenAI API timeout:** Contact OpenAI support + update our config +- **WordPress timeout:** Escalate to WordPress team (@wp-platform) + +--- + +## WordPress Connectivity Failures + +**Detection:** +- `npm run wp:test` reports connection errors +- Article publication fails with 403/404/500 from WordPress +- UI shows "WordPress unavailable" banner + +### Diagnosis + +```bash +# 1. Test basic WordPress connectivity +npm run wp:test +# If fails, note the error message + +# 2. Verify .env credentials are set +cat .env | grep -E "WP_URL|WP_USER|WP_PASSWORD" + +# 3. Test XML-RPC if configured +npm run wp:probe-xmlrpc +# If configured but not enabled, escalate to WordPress team + +# 4. Verify network connectivity to WordPress +curl -I https:///wp-json/wp/v2/users/me \ + -H "Authorization: Basic $(echo -n 'user:pass' | base64)" + +# 5. Check for WordPress errors +curl https:///wp-json/ | jq '.code' +# If code != null, WordPress has an issue +``` + +### Resolution + +**If credentials are wrong:** +```bash +# Update .env with correct values +# Verify with: npm run wp:test +vim .env +pm2 restart ai-news-writer +``` + +**If WordPress is down:** +```bash +# Contact WordPress team +# Provide: error message, timestamp, affected articles +# They will check WordPress health and restore if needed +``` + +**If network is blocking:** +```bash +# Test from container to WordPress server +curl -v https:/// 2>&1 | head -30 +# Look for: Connection refused, timeout, SSL error + +# If SSL error: +curl -k https:/// # -k skips SSL verify (insecure, debug only) + +# Contact network team if connection is blocked +``` + +**If rate limited by WordPress:** +```bash +# Increase delay between article publishes +# Edit ecosystem.config.cjs or .env: +# WP_PUBLISH_DELAY_MS=5000 + +pm2 restart ai-news-writer +``` + +### Escalation + +- **WordPress returns 500:** WordPress team investigates (@wp-platform) +- **Network timeout:** Network/infrastructure team (@infrastructure) +- **Ongoing >15 min:** Escalate as HIGH priority; pause auto publishing temporarily + +--- + +## RSS Feed Failures + +**Detection:** +- `npm run rss:test` reports feed errors +- RSS listener stops processing articles +- Specific feeds return 404/500/timeout + +### Diagnosis + +```bash +# 1. Run comprehensive RSS test +npm run rss:test +# Output shows which feeds pass/fail with error details + +# 2. Test individual feed (curl) +FEED_URL="https://example.com/feed.xml" +curl -I "$FEED_URL" --max-time 5 +# Look for: 200 OK (success) vs 404/403/500 (error) + +# 3. Check if URL has changed +# Review config/sources.json +# Compare URLs against feed publisher websites + +# 4. Check for domain changes +# Some publishers update feed URLs without notice +# Google: " rss feed new url" +``` + +### Resolution + +**If feed returns 404/403 (URL dead or wrong):** +```bash +# Find current feed URL from publisher +# Update config/sources.json +vim config/sources.json + +# Test updated feed +npm run rss:test + +# Restart +pm2 restart ai-news-writer +``` + +**If feed times out (network issue):** +```bash +# Increase RSS timeout in .env: +# RSS_HTTP_MAX_ATTEMPTS=5 +# RSS_RETRY_BASE_MS=1000 + +pm2 restart ai-news-writer +``` + +**If feed returns bad XML:** +```bash +# Document the issue and disable that feed +# Edit config/sources.json and comment out +# Notify feed owner of bad XML format +``` + +**If multiple feeds fail simultaneously:** +```bash +# Likely network/DNS issue, not feed issue +# Run: npm run rss:test +# If ALL feeds fail: +ping 8.8.8.8 # test external connectivity +nslookup example.com # test DNS + +# If network is down, escalate to infrastructure +``` + +### Escalation + +- **One feed recurring failures:** Remove from config; note for backlog +- **Multiple feeds failing:** Network team (@infrastructure) +- **Feed returns 500 with valid XML:** Contact feed owner for investigation + +--- + +## Common Diagnosis Commands Cheat Sheet + +```bash +# Service status +pm2 list +pm2 logs ai-news-writer --lines 50 --err + +# System resources +free -h # memory +df -h /opt/bitreport/ai-news-writer # disk +top -bn1 | head -15 # CPU usage + +# Connectivity tests +npm run rss:test # RSS feeds +npm run wp:test # WordPress +npm run verify:deploy -- https://ainews.bitreport.pt # health check + +# Operations validation +npm run ops:check # full diagnostic +npm run lint # code quality + +# Configuration +cat .env | grep -v "^#" # secrets (careful with display) +cat config/sources.json | jq . # RSS feeds +cat config/sites/*.json | jq . # WordPress targets +``` + +--- + +## Escalation Contacts + +See [ESCALATION.md](./ESCALATION.md) for contact details, escalation levels, and on-call procedures. diff --git a/docs/runbooks/TROUBLESHOOTING.md b/docs/runbooks/TROUBLESHOOTING.md new file mode 100644 index 0000000..396eb06 --- /dev/null +++ b/docs/runbooks/TROUBLESHOOTING.md @@ -0,0 +1,516 @@ +# Advanced Troubleshooting Guide + +Detailed diagnostic procedures and deep dives for complex issues. + +**Service:** ai-news-writer (Node.js / PM2 / LXC) +**Intended for:** DevOps engineers, infrastructure team, senior developers + +--- + +## Log Analysis & Debugging + +### Accessing Logs + +```bash +# Last N lines of logs (includes both stdout and stderr) +pm2 logs ai-news-writer --lines 100 + +# Follow logs in real-time +pm2 logs ai-news-writer --follow + +# Error-only logs +pm2 logs ai-news-writer --err --lines 50 + +# Search for specific pattern +pm2 logs ai-news-writer --grep "error\|ERROR" --lines 200 +pm2 logs ai-news-writer --grep "openai" --lines 100 + +# Logs between timestamps (manual search) +pm2 logs ai-news-writer --lines 500 | grep "2026-04-16 10:3" + +# Save logs to file for analysis +pm2 logs ai-news-writer --lines 500 > /tmp/ai-news-logs.txt + +# Analyze log file +grep "FATAL\|ERROR" /tmp/ai-news-logs.txt | sort | uniq -c +``` + +### Log Format Understanding + +Default Node.js / PM2 logs include: +``` +[timestamp] [process-id] [log-level] [message] + +Example: +2026-04-16 10:30:42 [12345] [ERROR] RSS fetch failed: ECONNREFUSED +``` + +**Common log levels:** +- `INFO` — Normal operation events +- `WARN` — Warning, non-critical issue +- `ERROR` — Error occurred but service continues +- `FATAL` / uncaught exception → service crashed + +--- + +## Performance Diagnostics + +### CPU Usage Spike + +**Detection:** +```bash +# Real-time CPU monitoring +top -bn1 | head -15 +# Look for ai-news-writer process + +# Historical CPU (via PM2) +pm2 monit +# Watch CPU column; press 'q' to exit +``` + +**Diagnosis:** +```bash +# Identify CPU-heavy operation +pm2 logs ai-news-writer --lines 200 +# Look for: AI generation in progress, large feed parsing + +# Check system load +uptime +# Format: load average: 1.5, 1.2, 0.9 (1/5/15 min average) + +# Find kernel process eating CPU +ps aux --sort=-%cpu | head -10 +``` + +**Resolution:** +- **AI generation heavy:** Reduce concurrent article generation (edit ecosystem.config.cjs) +- **RSS parsing heavy:** Reduce feed count or optimize crawler +- **High load:** Wait for CPU to normalize or restart service with decreased load +- **Sustained high CPU:** Escalate to DevOps (@devops) + +### Memory Leak Investigation + +**Detection:** +```bash +# Check RSS (Resident Set Size - actual memory) +ps aux | grep node | grep -v grep +# Look for increasing VSZ / RSS columns + +# Monitor over time +for i in {1..20}; do + echo "$(date): $(ps aux | grep 'ai-news-writer' | grep -v grep | awk '{print $6}')" + sleep 60 +done +``` + +**Diagnosis:** +```bash +# Heap snapshot (if service supports it) +node --inspect=0.0.0.0:9229 src/index.js +# Then use Chrome DevTools: chrome://inspect + +# Check for circular references or event listeners +# Review logs for "MaxListenersExceededWarning" +pm2 logs ai-news-writer --grep "MaxListeners\|leak" + +# Identify slow memory growth pattern +pm2 logs ai-news-writer --lines 1000 | grep "memory\|heap" + +# Check git history for recent memory-impacting changes +git log --oneline -10 +git diff --stat +``` + +**Resolution:** +- **Identified leak:** Fix in code (PR / commit) +- **Unknown cause:** Add memory limit: `NODE_OPTIONS="--max-old-space-size=256"` in .env +- **Escalate if:** Persists after restart or memory limit increases don't help + +### Slow Response Times + +**Detection:** +```bash +# Check health endpoint response time +time curl https://ainews.bitreport.pt/health + +# Monitor via logs +pm2 logs ai-news-writer --lines 100 | grep "response\|duration" + +# Watch service metrics +pm2 monit +# Press 'q' to exit +``` + +**Diagnosis:** +```bash +# Check if specific endpoint is slow +# Test endpoints individually: +curl -w "\nTotal time: %{time_total}s\n" https://ainews.bitreport.pt/health +curl -w "\nTotal time: %{time_total}s\n" https://ainews.bitreport.pt/ +curl -w "\nTotal time: %{time_total}s\n" https://ainews.bitreport.pt/ui + +# Check if upstream is slow (WordPress, RSS feeds) +npm run wp:test +# Note the response time + +npm run rss:test +# Check which feeds are slow + +# Check container CPU/memory during slow response +watch -n 1 'free -h && top -bn1 | head -5' +``` + +**Resolution:** +- **External slowness:** Escalate to relevant team (WordPress, feed provider) +- **High CPU:** See CPU Usage Spike section +- **High memory:** See Memory Leak Investigation section +- **Network slow:** Check network connectivity: `ping 8.8.8.8`, `iperf3` + +--- + +## Configuration & Environment Issues + +### .env Not Being Applied + +**Symptoms:** +- Configuration changes in .env don't take effect after restart +- `npm run deploy:lxc` ignores new env values + +**Diagnosis:** +```bash +# Check what env variables are actually set +pm2 env ai-news-writer +# Compare with your .env file + +# Verify .env file is readable +ls -la .env +# Should be: -rw-r--r-- (readable by all) + +# Check if PM2 has the file cached +pm2 log ai-news-writer | grep "env" +``` + +**Resolution:** +```bash +# Force .env reload +pm2 delete ai-news-writer +pm2 startOrReload ecosystem.config.cjs --update-env + +# Or use deploy command +npm run deploy:lxc -- --update-env +``` + +### Configuration File Syntax Errors + +**Symptoms:** +- Service fails to start +- Logs show JSON or YAML parse errors + +**Diagnosis:** +```bash +# Validate JSON config files +node -e "console.log(JSON.parse(require('fs').readFileSync('config/sources.json')))" +# If no error, syntax is valid + +# Check for UTF-8 BOM or encoding issues +file config/sources.json # Should be "ASCII text" +od -c config/sources.json | head # Check first bytes +``` + +**Resolution:** +```bash +# Fix JSON (common issues: trailing comma, unquoted keys) +vim config/sources.json + +# Validate again +node -e "console.log(JSON.parse(require('fs').readFileSync('config/sources.json')))" + +# Restart +pm2 restart ai-news-writer +``` + +--- + +## Database & Persistence Issues + +### Corrupted Data Files + +**Symptoms:** +- Service crashes on startup with JSON parse error +- Articles appear incomplete or duplicated + +**Diagnosis:** +```bash +# Check data directory size and integrity +ls -lh data/ +file data/article-index.jsonl + +# Check JSONL format (one JSON object per line) +head -5 data/article-index.jsonl | jq . + +# Look for incomplete/corrupted lines +tail -10 data/article-index.jsonl | jq . +# Any lines that don't parse = corruption + +# Count lines and objects +wc -l data/article-index.jsonl +grep -c "^{" data/article-index.jsonl +# These should match +``` + +**Resolution:** +```bash +# Backup corrupted file +cp data/article-index.jsonl data/article-index.jsonl.bak.$(date +%s) + +# If corruption is at end (common): +# Remove last incomplete line +head -n -1 data/article-index.jsonl > data/article-index.jsonl.tmp +mv data/article-index.jsonl.tmp data/article-index.jsonl + +# Validate again +tail -5 data/article-index.jsonl | jq . + +# Restart service +pm2 restart ai-news-writer +``` + +### Data Directory Permissions + +**Symptoms:** +- Service can't write to data/ +- Permission denied errors in logs + +**Diagnosis:** +```bash +# Check directory ownership and permissions +ls -ld data/ +# Should be: drwxr-xr-x [user] [group] + +# Check file ownership +ls -l data/article-index.jsonl +# Should be owned by node process user +``` + +**Resolution:** +```bash +# Fix permissions +chmod 755 data/ +chmod 644 data/article-index.jsonl + +# Or fix ownership (if running as different user) +chown -R node:node data/ +``` + +--- + +## Network & Connectivity Issues + +### DNS Resolution Failures + +**Symptoms:** +- RSS feeds fail with ENOTFOUND errors +- WordPress connection fails with hostname lookup error + +**Diagnosis:** +```bash +# Test DNS for feed domains +nslookup example.com +dig example.com +short + +# Test from container context +curl -v https://example.com/feed.xml 2>&1 | grep -E "Resolving\|Trying\|Connected" + +# Check container DNS config +cat /etc/resolv.conf +# Should have at least one nameserver +``` + +**Resolution:** +```bash +# Add/fix nameserver (if missing) +echo "nameserver 8.8.8.8" | sudo tee -a /etc/resolv.conf +echo "nameserver 8.8.4.4" | sudo tee -a /etc/resolv.conf + +# Restart service +pm2 restart ai-news-writer + +# Test again +npm run rss:test +``` + +### Port Already in Use + +**Symptoms:** +- Service fails to start +- Logs show EADDRINUSE on port 3000 (or configured port) + +**Diagnosis:** +```bash +# Check what's using the port +lsof -i :3000 +# or +netstat -tulpn | grep 3000 +``` + +**Resolution:** +```bash +# Kill the conflicting process +kill -9 + +# Or change port in ecosystem.config.cjs if intended +vim ecosystem.config.cjs +# Change: port: 3001 + +pm2 restart ai-news-writer +``` + +### SSL/TLS Certificate Issues + +**Symptoms:** +- WordPress REST API connection fails with SSL error +- Self-signed cert warning (in production, this is a problem) + +**Diagnosis:** +```bash +# Check certificate validity +echo | openssl s_client -servername example.com -connect example.com:443 2>/dev/null | openssl x509 -noout -dates + +# Test from service +curl -I https://example.com/ +# If: "certificate problem: self signed certificate" +# This is a real issue, not just a curl warning +``` + +**Resolution:** +```bash +# If self-signed in production: escalate to WordPress team +# For testing only, allow insecure: +# Set in src/publisher/wordpress.js: +# axios.defaults.httpsAgent = new https.Agent({ rejectUnauthorized: false }) + +# If cert expired: contact WordPress hosting to renew +``` + +--- + +## Development & Debugging + +### Node Process Won't Start + +**Symptoms:** +- Service crashes immediately after restart +- No clear error in logs + +**Diagnosis:** +```bash +# Run directly (not via PM2) to see immediate output +npm start 2>&1 | head -50 + +# Or with verbose Node flags +NODE_DEBUG=http node src/index.js 2>&1 | head -100 + +# Check for syntax errors +node --check src/index.js +node --check src/listener/rss-listener.js +# etc. + +# Validate package.json +node -e "console.log(require('./package.json').name)" +``` + +**Resolution:** +```bash +# If syntax error: fix code and commit +# If module not found: npm ci --omit=dev +# If permission issue: sudo -u node npm start + +# Once fixed +pm2 restart ai-news-writer +``` + +### Testing Individual Components + +**RSS Crawler:** +```bash +node -e " +const crawler = require('./src/crawler/rss.js'); +crawler.fetchRssArticles(['https://example.com/feed.xml']).then(r => console.log(r)).catch(e => console.error(e)); +" +``` + +**AI Writer:** +```bash +node -e " +const writer = require('./src/writer/ai.js'); +writer.generateArticle({title: 'Test'}).then(r => console.log(r)).catch(e => console.error(e)); +" +``` + +**WordPress Publisher:** +```bash +npm run wp:test +npm run wp:probe-xmlrpc +``` + +--- + +## Monitoring Commands (Until Automated Alerts Ready) + +```bash +# Create a monitoring script (run every 15 min) +cat > /opt/bitreport/ai-news-writer/monitor.sh <<'EOF' +#!/bin/bash + +# Health check +curl -f https://ainews.bitreport.pt/health > /dev/null 2>&1 || echo "ALERT: Health check failed" + +# Memory check +MEM=$(free -h | awk '/^Mem:/ {print $3}') +echo "Memory used: $MEM" + +# Disk check +DISK=$(df -h /opt/bitreport/ai-news-writer | awk 'NR==2 {print $5}') +echo "Disk used: $DISK" + +# Service status +pm2 list | grep ai-news-writer + +# Recent errors +pm2 logs ai-news-writer --err --lines 5 +EOF + +chmod +x /opt/bitreport/ai-news-writer/monitor.sh + +# Add to crontab (every 15 minutes) +# */15 * * * * /opt/bitreport/ai-news-writer/monitor.sh +``` + +--- + +## Escalation Checklist + +Before escalating, ensure you've checked: + +- [ ] Service status: `pm2 list` +- [ ] Recent logs: `pm2 logs --lines 50 --err` +- [ ] Health endpoint: `curl https://ainews.bitreport.pt/health` +- [ ] System resources: `free -h`, `df -h`, `top -bn1` +- [ ] External dependencies: `npm run rss:test`, `npm run wp:test` +- [ ] Configuration files: `.env`, `config/*.json` are valid +- [ ] Recent git changes: `git log --oneline -5` +- [ ] Attempted basic restart: `pm2 restart ai-news-writer` +- [ ] Attempted hard restart: `pm2 delete && pm2 startOrReload` + +If issue persists after all checks, create Paperclip issue and escalate. See [ESCALATION.md](./ESCALATION.md). + +--- + +## References + +- **AI News Writer README:** [`README.md`](../../README.md) +- **Runbooks Index:** [`docs/runbooks/README.md`](./README.md) +- **Incident Response Playbooks:** [`INCIDENT_RESPONSE.md`](./INCIDENT_RESPONSE.md) +- **Escalation Procedures:** [`ESCALATION.md`](./ESCALATION.md) +- **PM2 Documentation:** https://pm2.keymetrics.io/docs/usage/quick-start +- **Node.js Debugging:** https://nodejs.org/en/docs/guides/debugging-getting-started/ diff --git a/src/cli/index.js b/src/cli/index.js index 8f7c04e..558e483 100644 --- a/src/cli/index.js +++ b/src/cli/index.js @@ -1,5 +1,7 @@ 'use strict'; +const logger = require('../logger'); +const { validateConfigsAtStartup } = require('../config/loader'); const { runManualWrite } = require('./write'); const { runAutoMode } = require('./listen'); const { runWpTest, runWpProbeXmlRpc } = require('./test-wp'); @@ -7,6 +9,12 @@ const { runRssTest } = require('./test-rss'); const { runXTest } = require('./test-x'); async function main() { + // Validate configurations at startup + const configValid = validateConfigsAtStartup(); + if (!configValid) { + logger.warn('Config validation completed with errors — please review configuration files'); + } + const command = process.argv[2] || 'write'; const argument = process.argv[3] || ''; diff --git a/src/config/loader.js b/src/config/loader.js index 45978f8..e7b54e9 100644 --- a/src/config/loader.js +++ b/src/config/loader.js @@ -3,6 +3,7 @@ const fs = require('fs'); const path = require('path'); const logger = require('../logger'); +const { validateSources, validateSiteConfig, validateSocialConfig } = require('./validator'); const ROOT = path.resolve(__dirname, '..', '..'); @@ -125,11 +126,96 @@ function formatPublishHoursLabel(publishHours) { return `${publishHours.start}-${publishHours.end}`; } +/** + * Validate all startup configurations and log any issues. + * Returns true if all configs are valid, false if there are errors. + */ +function validateConfigsAtStartup() { + let hasErrors = false; + + // Validate sources.json + const sources_path = path.join(ROOT, 'config', 'sources.json'); + if (fs.existsSync(sources_path)) { + try { + const sources = JSON.parse(fs.readFileSync(sources_path, 'utf8')); + const validation = validateSources(sources); + + validation.errors.forEach((err) => { + logger.error(`Config validation: ${err}`); + hasErrors = true; + }); + validation.warnings.forEach((warn) => { + logger.warn(`Config validation: ${warn}`); + }); + } catch (err) { + logger.error(`Config validation: config/sources.json parse error: ${err.message}`); + hasErrors = true; + } + } else { + logger.warn('Config validation: config/sources.json not found — using empty sources'); + } + + // Validate site configs + const sites_dir = path.join(ROOT, 'config', 'sites'); + if (fs.existsSync(sites_dir)) { + const site_files = fs + .readdirSync(sites_dir) + .filter((f) => f.endsWith('.json') && f !== 'example.json'); + + if (site_files.length === 0) { + logger.warn('Config validation: no site configs found in config/sites/ — using default from environment variables'); + } + + for (const file of site_files) { + try { + const siteConfig = JSON.parse(fs.readFileSync(path.join(sites_dir, file), 'utf8')); + const validation = validateSiteConfig(siteConfig, `config/sites/${file}`); + + validation.errors.forEach((err) => { + logger.error(`Config validation: ${err}`); + hasErrors = true; + }); + validation.warnings.forEach((warn) => { + logger.warn(`Config validation: ${warn}`); + }); + } catch (err) { + logger.error(`Config validation: config/sites/${file} parse error: ${err.message}`); + hasErrors = true; + } + } + } + + // Validate social.json + const social_path = path.join(ROOT, 'config', 'social.json'); + if (fs.existsSync(social_path)) { + try { + const socialConfig = JSON.parse(fs.readFileSync(social_path, 'utf8')); + const validation = validateSocialConfig(socialConfig); + + validation.errors.forEach((err) => { + logger.error(`Config validation: ${err}`); + hasErrors = true; + }); + validation.warnings.forEach((warn) => { + logger.warn(`Config validation: ${warn}`); + }); + } catch (err) { + logger.error(`Config validation: config/social.json parse error: ${err.message}`); + hasErrors = true; + } + } else { + logger.warn('Config validation: config/social.json not found — X API integration disabled'); + } + + return !hasErrors; +} + module.exports = { loadSources, loadSiteConfigs, loadDefaultSiteConfig, loadSocialConfig, loadPublishHours, - formatPublishHoursLabel + formatPublishHoursLabel, + validateConfigsAtStartup }; diff --git a/src/config/validator.test.js b/src/config/validator.test.js new file mode 100644 index 0000000..3ec5c8a --- /dev/null +++ b/src/config/validator.test.js @@ -0,0 +1,311 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const test = require('node:test'); +const { validateSources, validateSiteConfig, validateSocialConfig } = require('./validator'); + +test('validateSources — valid config', () => { + const config = { + rss: [ + { + name: 'BBC Sport', + url: 'https://feeds.bbci.co.uk/sport/rss.xml', + category: 'sports', + lang: 'en' + } + ], + keywords: ['football', 'basketball'], + trusted_domains: ['bbc.co.uk'] + }; + + const result = validateSources(config); + assert.equal(result.valid, true); + assert.equal(result.errors.length, 0); +}); + +test('validateSources — missing rss field', () => { + const config = { + keywords: ['football'], + trusted_domains: ['bbc.co.uk'] + }; + + const result = validateSources(config); + assert.equal(result.valid, true); + assert(result.warnings.some((w) => w.includes('sources.rss'))); +}); + +test('validateSources — empty rss array', () => { + const config = { + rss: [], + keywords: ['football'], + trusted_domains: ['bbc.co.uk'] + }; + + const result = validateSources(config); + assert.equal(result.valid, true); + assert(result.warnings.some((w) => w.includes('no RSS sources'))); +}); + +test('validateSources — rss not array', () => { + const config = { + rss: 'not-an-array', + keywords: ['football'] + }; + + const result = validateSources(config); + assert.equal(result.valid, false); + assert(result.errors.some((e) => e.includes('sources.rss: must be an array'))); +}); + +test('validateSources — rss source missing name', () => { + const config = { + rss: [ + { + url: 'https://feeds.bbci.co.uk/sport/rss.xml', + category: 'sports', + lang: 'en' + } + ] + }; + + const result = validateSources(config); + assert.equal(result.valid, false); + assert(result.errors.some((e) => e.includes('name'))); +}); + +test('validateSources — rss source with invalid url', () => { + const config = { + rss: [ + { + name: 'BBC Sport', + url: 'not-a-valid-url', + category: 'sports', + lang: 'en' + } + ] + }; + + const result = validateSources(config); + assert.equal(result.valid, false); + assert(result.errors.some((e) => e.includes('invalid URL'))); +}); + +test('validateSources — rss source missing category', () => { + const config = { + rss: [ + { + name: 'BBC Sport', + url: 'https://feeds.bbci.co.uk/sport/rss.xml', + lang: 'en' + } + ] + }; + + const result = validateSources(config); + assert.equal(result.valid, false); + assert(result.errors.some((e) => e.includes('category'))); +}); + +test('validateSources — rss source missing lang', () => { + const config = { + rss: [ + { + name: 'BBC Sport', + url: 'https://feeds.bbci.co.uk/sport/rss.xml', + category: 'sports' + } + ] + }; + + const result = validateSources(config); + assert.equal(result.valid, false); + assert(result.errors.some((e) => e.includes('lang'))); +}); + +test('validateSources — empty keywords and trusted_domains', () => { + const config = { + rss: [ + { + name: 'BBC Sport', + url: 'https://feeds.bbci.co.uk/sport/rss.xml', + category: 'sports', + lang: 'en' + } + ], + keywords: [], + trusted_domains: [] + }; + + const result = validateSources(config); + assert.equal(result.valid, true); + assert(result.warnings.some((w) => w.includes('keywords'))); + assert(result.warnings.some((w) => w.includes('trusted_domains'))); +}); + +test('validateSiteConfig — valid config', () => { + const config = { + name: 'sports news', + wp_transport: 'rest', + wp_url: 'https://wp.newsproject.bitreport.pt', + user: 'wp-api-user', + password: 'app-password-from-vault', + category_default: 5, + status_default: 'draft', + tags_auto: true, + lang: 'pt' + }; + + const result = validateSiteConfig(config, 'test-site.json'); + assert.equal(result.valid, true); + assert.equal(result.errors.length, 0); +}); + +test('validateSiteConfig — missing name', () => { + const config = { + wp_url: 'https://wp.example.com', + user: 'user', + password: 'pass', + category_default: 5, + status_default: 'draft', + lang: 'en' + }; + + const result = validateSiteConfig(config, 'test-site.json'); + assert.equal(result.valid, false); + assert(result.errors.some((e) => e.includes('name'))); +}); + +test('validateSiteConfig — invalid wp_url', () => { + const config = { + name: 'test', + wp_url: 'not-a-url', + user: 'user', + password: 'pass', + category_default: 5, + status_default: 'draft', + lang: 'en' + }; + + const result = validateSiteConfig(config, 'test-site.json'); + assert.equal(result.valid, false); + assert(result.errors.some((e) => e.includes('invalid URL'))); +}); + +test('validateSiteConfig — invalid category_default', () => { + const config = { + name: 'test', + wp_url: 'https://wp.example.com', + user: 'user', + password: 'pass', + category_default: 'not-an-int', + status_default: 'draft', + lang: 'en' + }; + + const result = validateSiteConfig(config, 'test-site.json'); + assert.equal(result.valid, false); + assert(result.errors.some((e) => e.includes('category_default'))); +}); + +test('validateSiteConfig — unusual status_default', () => { + const config = { + name: 'test', + wp_url: 'https://wp.example.com', + user: 'user', + password: 'pass', + category_default: 5, + status_default: 'scheduled', + lang: 'en' + }; + + const result = validateSiteConfig(config, 'test-site.json'); + assert.equal(result.valid, true); + assert(result.warnings.some((w) => w.includes('status_default'))); +}); + +test('validateSiteConfig — unusual wp_transport', () => { + const config = { + name: 'test', + wp_url: 'https://wp.example.com', + user: 'user', + password: 'pass', + category_default: 5, + status_default: 'draft', + wp_transport: 'invalid', + lang: 'en' + }; + + const result = validateSiteConfig(config, 'test-site.json'); + assert.equal(result.valid, true); + assert(result.warnings.some((w) => w.includes('wp_transport'))); +}); + +test('validateSocialConfig — valid config', () => { + const config = { + x: { + queries: ['(FC Porto OR Benfica) football -is:retweet'], + max_results_per_query: 10 + } + }; + + const result = validateSocialConfig(config); + assert.equal(result.valid, true); + assert.equal(result.errors.length, 0); +}); + +test('validateSocialConfig — missing x field', () => { + const config = {}; + + const result = validateSocialConfig(config); + assert.equal(result.valid, true); + assert(result.warnings.some((w) => w.includes('social.x'))); +}); + +test('validateSocialConfig — x not object', () => { + const config = { + x: 'not-an-object' + }; + + const result = validateSocialConfig(config); + assert.equal(result.valid, false); + assert(result.errors.some((e) => e.includes('social.x: must be an object'))); +}); + +test('validateSocialConfig — x.queries not array', () => { + const config = { + x: { + queries: 'not-an-array', + max_results_per_query: 10 + } + }; + + const result = validateSocialConfig(config); + assert.equal(result.valid, false); + assert(result.errors.some((e) => e.includes('social.x.queries: must be an array'))); +}); + +test('validateSocialConfig — empty queries', () => { + const config = { + x: { + queries: [], + max_results_per_query: 10 + } + }; + + const result = validateSocialConfig(config); + assert.equal(result.valid, true); + assert(result.warnings.some((w) => w.includes('no queries'))); +}); + +test('validateSocialConfig — invalid max_results_per_query', () => { + const config = { + x: { + queries: ['query'], + max_results_per_query: 0 + } + }; + + const result = validateSocialConfig(config); + assert.equal(result.valid, false); + assert(result.errors.some((e) => e.includes('max_results_per_query'))); +}); diff --git a/src/crawler/rss.js b/src/crawler/rss.js index a6b8764..2151b76 100644 --- a/src/crawler/rss.js +++ b/src/crawler/rss.js @@ -240,4 +240,12 @@ function filterByDomain(articles, whitelist, mode = 'strict') { return result.filtered; } -module.exports = { fetchFeed, fetchFeedWithResult, fetchAllFeeds, filterByKeywords, filterByDomain }; +module.exports = { + fetchFeed, + fetchFeedWithResult, + fetchAllFeeds, + filterByKeywords, + filterByDomain, + readBoundedInt, + mapFeedItems +}; diff --git a/src/crawler/rss.test.js b/src/crawler/rss.test.js new file mode 100644 index 0000000..30d58ae --- /dev/null +++ b/src/crawler/rss.test.js @@ -0,0 +1,318 @@ +'use strict'; + +const { describe, it, beforeEach, afterEach } = require('node:test'); +const assert = require('node:assert/strict'); +const { filterByKeywords, readBoundedInt, mapFeedItems } = require('./rss'); + +describe('rss', () => { + it('filters articles by keywords (case-insensitive)', () => { + const articles = [ + { title: 'AI breakthrough', summary: 'New AI model announced' }, + { title: 'Sports news', summary: 'Game results today' }, + { title: 'AI regulation', summary: 'New AI laws passed' } + ]; + + const filtered = filterByKeywords(articles, ['AI']); + + assert.equal(filtered.length, 2); + assert.ok(filtered.every((a) => a.title.includes('AI') || a.summary.includes('AI'))); + }); + + it('filters articles with multiple keywords (OR logic)', () => { + const articles = [ + { title: 'Python news', summary: 'New Python version' }, + { title: 'JavaScript update', summary: 'JS release' }, + { title: 'Sports event', summary: 'Football match' } + ]; + + const filtered = filterByKeywords(articles, ['Python', 'JavaScript']); + + assert.equal(filtered.length, 2); + }); + + it('returns all articles when keywords list is empty', () => { + const articles = [ + { title: 'Article 1', summary: 'Summary 1' }, + { title: 'Article 2', summary: 'Summary 2' } + ]; + + const filtered = filterByKeywords(articles, []); + + assert.equal(filtered.length, 2); + }); + + it('returns empty array when no articles match keywords', () => { + const articles = [ + { title: 'Sports', summary: 'Game news' }, + { title: 'Weather', summary: 'Forecast' } + ]; + + const filtered = filterByKeywords(articles, ['AI', 'tech']); + + assert.equal(filtered.length, 0); + }); + + it('handles case-insensitive keyword matching', () => { + const articles = [ + { title: 'PYTHON NEWS', summary: 'programming' }, + { title: 'Java tutorial', summary: 'LANGUAGE' } + ]; + + const filtered = filterByKeywords(articles, ['python']); + + assert.equal(filtered.length, 1); + assert.equal(filtered[0].title, 'PYTHON NEWS'); + }); + + it('filters when keyword matches in summary only', () => { + const articles = [ + { title: 'News', summary: 'Contains AI technology discussion' }, + { title: 'Article', summary: 'Other content' } + ]; + + const filtered = filterByKeywords(articles, ['AI']); + + assert.equal(filtered.length, 1); + assert.equal(filtered[0].summary.includes('AI'), true); + }); + + it('returns original articles when keywords is not an array', () => { + const articles = [ + { title: 'Article', summary: 'Content' } + ]; + + const filtered = filterByKeywords(articles, 'keyword'); + + assert.equal(filtered.length, 1); + }); + + it('returns original articles when keywords is null', () => { + const articles = [ + { title: 'Article', summary: 'Content' } + ]; + + const filtered = filterByKeywords(articles, null); + + assert.equal(filtered.length, 1); + }); +}); + +describe('rss helper functions', () => { + beforeEach(() => { + // Clear env vars before each test + delete process.env.RSS_TIMEOUT_MS; + delete process.env.RSS_HTTP_MAX_ATTEMPTS; + delete process.env.RSS_RETRY_BASE_MS; + delete process.env.RSS_FETCH_CONCURRENCY; + }); + + describe('readBoundedInt', () => { + it('returns default value when env var unset', () => { + assert.equal(readBoundedInt('RSS_TEST_VAR', 100, 10, 1000), 100); + }); + + it('returns default value when env var is empty string', () => { + process.env.RSS_TEST_VAR = ''; + assert.equal(readBoundedInt('RSS_TEST_VAR', 100, 10, 1000), 100); + }); + + it('returns default value when env var is not a number', () => { + process.env.RSS_TEST_VAR = 'invalid'; + assert.equal(readBoundedInt('RSS_TEST_VAR', 100, 10, 1000), 100); + }); + + it('returns parsed value within bounds', () => { + process.env.RSS_TEST_VAR = '500'; + assert.equal(readBoundedInt('RSS_TEST_VAR', 100, 10, 1000), 500); + }); + + it('enforces minimum boundary', () => { + process.env.RSS_TEST_VAR = '5'; + assert.equal(readBoundedInt('RSS_TEST_VAR', 100, 10, 1000), 10); + }); + + it('enforces maximum boundary', () => { + process.env.RSS_TEST_VAR = '5000'; + assert.equal(readBoundedInt('RSS_TEST_VAR', 100, 10, 1000), 1000); + }); + + it('rounds down float values', () => { + process.env.RSS_TEST_VAR = '500.7'; + assert.equal(readBoundedInt('RSS_TEST_VAR', 100, 10, 1000), 500); + }); + + it('handles negative numbers by enforcing minimum', () => { + process.env.RSS_TEST_VAR = '-50'; + assert.equal(readBoundedInt('RSS_TEST_VAR', 100, 10, 1000), 10); + }); + + afterEach(() => { + delete process.env.RSS_TEST_VAR; + }); + }); + + describe('mapFeedItems', () => { + it('maps basic feed items to article format', () => { + const feed = { + items: [ + { + title: 'Test Article', + link: 'http://example.com/1', + contentSnippet: 'Test summary', + pubDate: '2024-01-15T10:00:00Z', + guid: 'guid-1' + } + ] + }; + + const articles = mapFeedItems(feed, 'Test Feed', 'http://example.com/feed', 'technology', 'en'); + + assert.equal(articles.length, 1); + assert.equal(articles[0].title, 'Test Article'); + assert.equal(articles[0].source, 'Test Feed'); + assert.equal(articles[0].category, 'technology'); + assert.equal(articles[0].lang, 'en'); + assert.equal(articles[0].link, 'http://example.com/1'); + }); + + it('handles missing optional fields with defaults', () => { + const feed = { + items: [ + { + title: 'Article' + // missing link, contentSnippet, pubDate, guid + } + ] + }; + + const articles = mapFeedItems(feed, 'Feed', 'http://example.com/feed', 'general', 'pt'); + + assert.equal(articles.length, 1); + assert.equal(articles[0].title, 'Article'); + assert.equal(articles[0].link, ''); + assert.equal(articles[0].summary, ''); + assert.ok(articles[0].published_at); // Should have current timestamp + assert.equal(articles[0].guid, ''); + }); + + it('prefers content over content:encoded field', () => { + const feed = { + items: [ + { + title: 'Article', + 'content:encoded': '

Encoded content

', + content: 'Regular content' + } + ] + }; + + const articles = mapFeedItems(feed, 'Feed', 'http://example.com/feed', 'news', 'en'); + + assert.equal(articles[0].content, 'Regular content'); + }); + + it('uses content:encoded when content field is absent', () => { + const feed = { + items: [ + { + title: 'Article', + 'content:encoded': '

Encoded content

' + } + ] + }; + + const articles = mapFeedItems(feed, 'Feed', 'http://example.com/feed', 'news', 'en'); + + assert.equal(articles[0].content, '

Encoded content

'); + }); + + it('prefers contentSnippet over summary', () => { + const feed = { + items: [ + { + title: 'Article', + contentSnippet: 'Snippet text', + summary: 'Full summary text' + } + ] + }; + + const articles = mapFeedItems(feed, 'Feed', 'http://example.com/feed', 'news', 'en'); + + assert.equal(articles[0].summary, 'Snippet text'); + }); + + it('uses guid as default when no link provided', () => { + const feed = { + items: [ + { + title: 'Article', + link: '', + guid: 'guid-123' + } + ] + }; + + const articles = mapFeedItems(feed, 'Feed', 'http://example.com/feed', 'news', 'en'); + + assert.equal(articles[0].guid, 'guid-123'); + }); + + it('maps multiple items', () => { + const feed = { + items: [ + { title: 'Article 1', guid: '1' }, + { title: 'Article 2', guid: '2' }, + { title: 'Article 3', guid: '3' } + ] + }; + + const articles = mapFeedItems(feed, 'Feed', 'http://example.com/feed', 'news', 'en'); + + assert.equal(articles.length, 3); + assert.equal(articles[0].title, 'Article 1'); + assert.equal(articles[1].title, 'Article 2'); + assert.equal(articles[2].title, 'Article 3'); + }); + + it('parses valid ISO date', () => { + const feed = { + items: [ + { + title: 'Article', + pubDate: 'Mon, 15 Jan 2024 10:00:00 GMT', + guid: '1' + } + ] + }; + + const articles = mapFeedItems(feed, 'Feed', 'http://example.com/feed', 'news', 'en'); + + assert.ok(articles[0].published_at); // Should parse and convert to ISO + }); + + it('maps empty feed items array', () => { + const feed = { items: [] }; + + const articles = mapFeedItems(feed, 'Feed', 'http://example.com/feed', 'news', 'en'); + + assert.equal(articles.length, 0); + assert.ok(Array.isArray(articles)); + }); + + it('preserves source_url in mapped articles', () => { + const feed = { + items: [ + { + title: 'Article', + guid: '1' + } + ] + }; + + const articles = mapFeedItems(feed, 'Feed', 'http://example.com/feed.xml', 'news', 'en'); + + assert.equal(articles[0].source_url, 'http://example.com/feed.xml'); + }); + }); +}); diff --git a/src/http/status-server.js b/src/http/status-server.js index 5d0279d..82ff92d 100644 --- a/src/http/status-server.js +++ b/src/http/status-server.js @@ -414,4 +414,12 @@ function startStatusServer() { }); } -module.exports = { startStatusServer, DEFAULT_HOST, DEFAULT_PORT }; +module.exports = { + startStatusServer, + DEFAULT_HOST, + DEFAULT_PORT, + // Exported for testing + escapeHtml, + getListenFeatureFlags, + applyHttpServerTimeouts +}; diff --git a/src/http/status-server.test.js b/src/http/status-server.test.js new file mode 100644 index 0000000..11e62aa --- /dev/null +++ b/src/http/status-server.test.js @@ -0,0 +1,190 @@ +'use strict'; + +const { describe, it, beforeEach } = require('node:test'); +const assert = require('node:assert/strict'); +const { escapeHtml, getListenFeatureFlags, DEFAULT_HOST, DEFAULT_PORT } = require('./status-server'); + +describe('status-server', () => { + describe('escapeHtml', () => { + it('escapes ampersand', () => { + assert.equal(escapeHtml('A & B'), 'A & B'); + }); + + it('escapes less-than', () => { + assert.equal(escapeHtml('a < b'), 'a < b'); + }); + + it('escapes greater-than', () => { + assert.equal(escapeHtml('a > b'), 'a > b'); + }); + + it('escapes double quotes', () => { + assert.equal(escapeHtml('say "hello"'), 'say "hello"'); + }); + + it('escapes multiple special characters', () => { + assert.equal(escapeHtml(''), '<script>alert("XSS")</script>'); + }); + + it('does not modify safe text', () => { + assert.equal(escapeHtml('Hello World'), 'Hello World'); + }); + + it('handles empty string', () => { + assert.equal(escapeHtml(''), ''); + }); + + it('converts non-string to string and escapes', () => { + assert.equal(escapeHtml(123), '123'); + assert.equal(escapeHtml(null), 'null'); + assert.equal(escapeHtml(undefined), 'undefined'); + }); + + it('escapes ampersand first to prevent double-escaping', () => { + // & should become &, not &amp; + assert.equal(escapeHtml('&'), '&'); + }); + + it('handles mixed content', () => { + const input = 'Visit link & info'; + const expected = 'Visit <a href="site.com">link & info</a>'; + assert.equal(escapeHtml(input), expected); + }); + }); + + describe('DEFAULT_HOST and DEFAULT_PORT', () => { + it('exports DEFAULT_HOST as 0.0.0.0', () => { + assert.equal(DEFAULT_HOST, '0.0.0.0'); + }); + + it('exports DEFAULT_PORT as 3200', () => { + assert.equal(DEFAULT_PORT, 3200); + }); + }); + + describe('getListenFeatureFlags', () => { + beforeEach(() => { + // Clear config-related env vars + delete process.env.TWITTER_BEARER_TOKEN; + delete process.env.OPENAI_API_KEY; + delete process.env.AI_MODEL; + delete process.env.CRON_TIMEZONE; + delete process.env.BODY_READ_TIMEOUT_MS; + }); + + it('returns object with feature flags', () => { + const flags = getListenFeatureFlags(); + assert.ok(typeof flags === 'object'); + assert.ok('rss_feed_count' in flags); + assert.ok('x_queries_configured' in flags); + assert.ok('wp_credentials_configured' in flags); + assert.ok('rss_listener_active' in flags); + assert.ok('openai_api_key_configured' in flags); + assert.ok('ai_model' in flags); + }); + + it('returns non-negative numbers for counts', () => { + const flags = getListenFeatureFlags(); + assert.ok(typeof flags.rss_feed_count === 'number'); + assert.ok(flags.rss_feed_count >= 0); + assert.ok(typeof flags.x_queries_configured === 'number'); + assert.ok(flags.x_queries_configured >= 0); + }); + + it('returns boolean for api key configuration', () => { + const flags = getListenFeatureFlags(); + assert.equal(typeof flags.openai_api_key_configured, 'boolean'); + }); + + it('detects missing openai api key', () => { + delete process.env.OPENAI_API_KEY; + const flags = getListenFeatureFlags(); + assert.equal(flags.openai_api_key_configured, false); + }); + + it('detects configured openai api key', () => { + process.env.OPENAI_API_KEY = 'sk-test-key'; + const flags = getListenFeatureFlags(); + assert.equal(flags.openai_api_key_configured, true); + }); + + it('detects missing twitter bearer token', () => { + delete process.env.TWITTER_BEARER_TOKEN; + const flags = getListenFeatureFlags(); + assert.equal(flags.x_listening, false); + }); + + it('requires both bearer token and queries for x_listening', () => { + process.env.TWITTER_BEARER_TOKEN = 'test-token'; + // Without queries configured, x_listening should still be false + const flags = getListenFeatureFlags(); + assert.equal(typeof flags.x_listening, 'boolean'); + }); + + it('returns default ai model when unset', () => { + delete process.env.AI_MODEL; + const flags = getListenFeatureFlags(); + assert.equal(flags.ai_model, 'gpt-4o'); + }); + + it('uses configured ai model', () => { + process.env.AI_MODEL = 'gpt-3.5-turbo'; + const flags = getListenFeatureFlags(); + assert.equal(flags.ai_model, 'gpt-3.5-turbo'); + }); + + it('returns http timeout value or null', () => { + const flags = getListenFeatureFlags(); + // http_body_read_timeout_ms should be a number, null, or undefined + assert.ok( + flags.http_body_read_timeout_ms === null || + flags.http_body_read_timeout_ms === undefined || + typeof flags.http_body_read_timeout_ms === 'number' + ); + }); + + it('returns publish hours information', () => { + const flags = getListenFeatureFlags(); + // publish_hours can be undefined, string, null, or object + assert.ok( + flags.publish_hours === undefined || + typeof flags.publish_hours === 'string' || + typeof flags.publish_hours === 'object' + ); + }); + + it('includes article log health fields', () => { + const flags = getListenFeatureFlags(); + // Should have some health fields (exact ones depend on article log state) + assert.ok(typeof flags === 'object'); + }); + + it('returns wp_publish_by_transport object', () => { + const flags = getListenFeatureFlags(); + assert.ok(typeof flags.wp_publish_by_transport === 'object'); + assert.ok('rest' in flags.wp_publish_by_transport); + assert.ok('xmlrpc' in flags.wp_publish_by_transport); + }); + + it('handles gracefully when sources config fails to load', () => { + // Should not throw, should return sensible defaults + const flags = getListenFeatureFlags(); + assert.ok(typeof flags === 'object'); + assert.ok(typeof flags.rss_feed_count === 'number'); + }); + + it('handles gracefully when social config fails to load', () => { + // Should not throw, should return sensible defaults + const flags = getListenFeatureFlags(); + assert.ok(typeof flags === 'object'); + assert.ok(typeof flags.x_queries_configured === 'number'); + }); + + it('handles gracefully when site configs fail to load', () => { + // Should not throw, should return sensible defaults + const flags = getListenFeatureFlags(); + assert.ok(typeof flags === 'object'); + assert.ok(typeof flags.wp_credentials_configured === 'boolean'); + }); + }); +});