""" Background worker thread for webmention processing Per background-worker.md: - Daemon thread that processes webmention queues - Handles both incoming validation and outgoing sending - Graceful shutdown on app termination - Orphan detection and cleanup on startup References: - Background Worker Design: /docs/design/v1.6.0/background-worker.md - ADR-063: Webmention Implementation """ import logging import threading import time import sqlite3 import httpx from datetime import datetime, timedelta from pathlib import Path from typing import Dict, Any, Optional, TypedDict from urllib.parse import urlparse from lxml import html as lxml_html from starpunk.webmention_processor import process_webmention, ValidationError from starpunk.webmention_ssrf import validate_url_for_fetch, SSRFBlockedError from flask import has_app_context logger = logging.getLogger(__name__) # Discovery cache entry type class DiscoveryCacheEntry(TypedDict): """Cache entry for endpoint discovery results""" endpoint: Optional[str] # None = negative cache (no endpoint found) expires_at: datetime class WebmentionWorker(threading.Thread): """ Background thread for webmention queue processing Follows MemoryMonitor pattern: daemon thread with stop event """ def __init__( self, db_path: Path, site_url: str, poll_interval: int = 10, error_backoff: int = 60, batch_size: int = 5, auto_approve: bool = True ): """ Initialize webmention worker thread Args: db_path: Path to SQLite database site_url: Site URL for User-Agent header poll_interval: Seconds between queue checks (default: 10) error_backoff: Seconds to wait after error (default: 60) batch_size: Items to process per iteration (default: 5) auto_approve: Auto-approve valid webmentions (default: True) """ super().__init__(daemon=True, name="webmention-worker") self.db_path = db_path self.site_url = site_url self.poll_interval = poll_interval self.error_backoff = error_backoff self.batch_size = batch_size self.auto_approve = auto_approve self._stop_event = threading.Event() self._last_processed = None # Phase 3: Discovery cache (worker instance variable) # Per architect's answer to Q4 self._discovery_cache: Dict[str, DiscoveryCacheEntry] = {} def run(self): """ Main processing loop Per background-worker.md: 1. Clean up orphaned items on startup 2. Process pending validations (incoming) 3. Process pending sends (outgoing) - Phase 3 4. Sleep if nothing to process """ try: logger.info("Webmention worker started") # Cleanup orphaned items from previous crashes self._cleanup_orphaned_items() # Main processing loop while not self._stop_event.is_set(): try: processed = 0 # Process incoming webmentions processed += self._process_pending_validations() # Phase 3: Process outgoing webmentions processed += self._process_pending_sends() # Update last processed time if processed > 0: self._last_processed = datetime.utcnow() # Sleep if nothing processed if processed == 0: self._stop_event.wait(self.poll_interval) except Exception as e: logger.error(f"Worker error: {e}", exc_info=True) self._stop_event.wait(self.error_backoff) except Exception as e: logger.error(f"Webmention worker thread failed: {e}", exc_info=True) finally: logger.info("Webmention worker stopped") def _cleanup_orphaned_items(self): """ Clean up orphaned 'sending' status items on startup Per background-worker.md: Reset items stuck in 'sending' status from previous crashes """ try: conn = sqlite3.connect(self.db_path) cursor = conn.cursor() # Reset orphaned outgoing webmentions cursor.execute(""" UPDATE webmention_queue SET status = 'pending', started_at = NULL WHERE status = 'sending' AND started_at < datetime('now', '-5 minutes') """) orphaned = cursor.rowcount conn.commit() conn.close() if orphaned > 0: logger.info(f"Reset {orphaned} orphaned webmention queue items") except Exception as e: logger.error(f"Failed to cleanup orphaned items: {e}") def _process_pending_validations(self) -> int: """ Process pending incoming webmentions Returns: Number of webmentions processed """ processed = 0 try: conn = sqlite3.connect(self.db_path) conn.row_factory = sqlite3.Row cursor = conn.cursor() # Get pending webmentions cursor.execute(""" SELECT id, source_url, target_url, target_note_id FROM webmentions WHERE validation_status = 'pending' ORDER BY received_at ASC LIMIT ? """, (self.batch_size,)) pending = cursor.fetchall() conn.close() # Process each webmention for row in pending: try: self._validate_webmention( row['id'], row['source_url'], row['target_url'], row['target_note_id'] ) processed += 1 except Exception as e: logger.error( f"Failed to validate webmention {row['id']}: {e}", exc_info=True ) except Exception as e: logger.error(f"Error fetching pending validations: {e}") return processed def _validate_webmention( self, webmention_id: int, source_url: str, target_url: str, target_note_id: Optional[int] ): """ Validate a single webmention Args: webmention_id: Database ID of webmention source_url: Source URL target_url: Target URL target_note_id: Target note ID (if applicable) """ try: # Process webmention (fetch, validate, extract) result = process_webmention(source_url, target_url, self.site_url) # Update database with successful validation conn = sqlite3.connect(self.db_path) cursor = conn.cursor() moderation_status = 'approved' if self.auto_approve else 'pending' cursor.execute(""" UPDATE webmentions SET validation_status = 'valid', validated_at = CURRENT_TIMESTAMP, mention_type = ?, author_name = ?, author_url = ?, author_photo = ?, content_snippet = ?, moderation_status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? """, ( result['mention_type'], result['author_name'], result['author_url'], result['author_photo'], result['content_snippet'], moderation_status, webmention_id )) conn.commit() conn.close() logger.info( f"Validated webmention: {source_url} -> {target_url} " f"(type={result['mention_type']}, status={moderation_status})" ) except ValidationError as e: # Validation failed - update with error self._mark_validation_failed(webmention_id, source_url, target_url, str(e)) except Exception as e: # Unexpected error - mark as error self._mark_validation_failed( webmention_id, source_url, target_url, f"Unexpected error: {e}" ) raise def _mark_validation_failed( self, webmention_id: int, source_url: str, target_url: str, error: str ): """ Mark webmention validation as failed/invalid Args: webmention_id: Database ID source_url: Source URL target_url: Target URL error: Error message """ # Determine if error or invalid # Per background-worker.md: HTTP 4xx and "no link" are invalid # All other errors are 'error' status if any(x in error.lower() for x in ['does not link', 'returned 4']): status = 'invalid' else: status = 'error' try: conn = sqlite3.connect(self.db_path) cursor = conn.cursor() cursor.execute(""" UPDATE webmentions SET validation_status = ?, validation_error = ?, validated_at = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP WHERE id = ? """, (status, error, webmention_id)) conn.commit() conn.close() logger.warning( f"Invalid webmention: {source_url} -> {target_url}: {error}" ) except Exception as e: logger.error(f"Failed to mark webmention as failed: {e}") def _process_pending_sends(self) -> int: """ Process pending outgoing webmentions (Phase 3) Returns: Number of webmentions processed """ processed = 0 try: conn = sqlite3.connect(self.db_path) conn.row_factory = sqlite3.Row cursor = conn.cursor() # Get pending webmentions ready to send cursor.execute(""" SELECT id, source_url, target_url, endpoint_url, retry_count FROM webmention_queue WHERE status = 'pending' AND (next_retry_at IS NULL OR next_retry_at <= datetime('now')) ORDER BY created_at ASC LIMIT ? """, (self.batch_size,)) pending = cursor.fetchall() conn.close() # Process each webmention for row in pending: try: self._send_webmention( row['id'], row['source_url'], row['target_url'], row['endpoint_url'], row['retry_count'] ) processed += 1 except Exception as e: logger.error( f"Failed to send webmention {row['id']}: {e}", exc_info=True ) except Exception as e: logger.error(f"Error fetching pending sends: {e}") return processed def _send_webmention( self, queue_id: int, source_url: str, target_url: str, cached_endpoint: Optional[str], retry_count: int ): """ Send a single outgoing webmention Args: queue_id: Database ID of queue item source_url: Source URL (our note) target_url: Target URL to notify cached_endpoint: Previously discovered endpoint (if any) retry_count: Current retry count """ # Mark as sending conn = sqlite3.connect(self.db_path) cursor = conn.cursor() cursor.execute(""" UPDATE webmention_queue SET status = 'sending', started_at = CURRENT_TIMESTAMP WHERE id = ? """, (queue_id,)) conn.commit() conn.close() try: # Discover endpoint if not cached endpoint = cached_endpoint if not endpoint: endpoint = self._discover_endpoint(target_url) if not endpoint: # No endpoint found - permanent failure self._mark_send_no_endpoint(queue_id, source_url, target_url) return # Cache the discovered endpoint in database conn = sqlite3.connect(self.db_path) cursor = conn.cursor() cursor.execute(""" UPDATE webmention_queue SET endpoint_url = ? WHERE id = ? """, (endpoint, queue_id)) conn.commit() conn.close() # Send webmention POST try: # SSRF protection for endpoint URL validate_url_for_fetch(endpoint) response = httpx.post( endpoint, data={ 'source': source_url, 'target': target_url }, timeout=10, headers={'User-Agent': f'StarPunk/1.6.0 (+{self.site_url})'}, follow_redirects=True ) # Check response if 200 <= response.status_code < 300: # Success self._mark_send_success(queue_id, source_url, target_url) elif 400 <= response.status_code < 500: # Permanent failure (4xx) error = f"HTTP {response.status_code}: {response.text[:200]}" self._mark_send_failed(queue_id, source_url, target_url, error) else: # Temporary failure (5xx) - retry error = f"HTTP {response.status_code}: {response.text[:200]}" self._mark_send_retry(queue_id, source_url, target_url, retry_count, error) except (httpx.TimeoutException, httpx.HTTPError) as e: # Connection error - retry self._mark_send_retry(queue_id, source_url, target_url, retry_count, str(e)) except (SSRFBlockedError, ValueError) as e: # SSRF blocked - permanent failure logger.warning(f"SSRF blocked endpoint {endpoint}: {e}") self._mark_send_failed(queue_id, source_url, target_url, f"Blocked: {e}") except Exception as e: # Discovery failed - retry self._mark_send_retry(queue_id, source_url, target_url, retry_count, str(e)) def _discover_endpoint(self, target_url: str) -> Optional[str]: """ Discover webmention endpoint for target URL with caching Per architect's answers to Q3, Q4, Q10: - GET only (no HEAD) - Check Link header → → - First match wins - Cache results: 1h for found, 24h for not found - SSRF protection on target URL Args: target_url: Target URL to discover endpoint for Returns: Endpoint URL if found, None otherwise """ # Check cache first cached = self._discovery_cache.get(target_url) if cached and cached['expires_at'] > datetime.utcnow(): logger.debug(f"Using cached endpoint for {target_url}: {cached['endpoint']}") return cached['endpoint'] # SSRF protection try: validate_url_for_fetch(target_url) except (SSRFBlockedError, ValueError) as e: logger.warning(f"SSRF protection blocked target {target_url}: {e}") # Cache negative result self._cache_endpoint(target_url, None, hours=24) return None # Fetch target URL try: response = httpx.get( target_url, timeout=10, headers={'User-Agent': f'StarPunk/1.6.0 (+{self.site_url})'}, follow_redirects=True ) response.raise_for_status() # 1. Check Link header link_header = response.headers.get('Link', '') if link_header: endpoint = self._parse_link_header(link_header, response.url) if endpoint: self._cache_endpoint(target_url, endpoint, hours=1) return endpoint # 2. Parse HTML for and elements content_type = response.headers.get('Content-Type', '') if 'html' in content_type.lower(): endpoint = self._parse_html_for_endpoint(response.text, response.url) if endpoint: self._cache_endpoint(target_url, endpoint, hours=1) return endpoint # No endpoint found - cache negative result logger.info(f"No webmention endpoint found for {target_url}") self._cache_endpoint(target_url, None, hours=24) return None except Exception as e: logger.warning(f"Failed to discover endpoint for {target_url}: {e}") # Don't cache on error - allow retry return None def _parse_link_header(self, link_header: str, base_url: str) -> Optional[str]: """ Parse Link header for webmention endpoint Args: link_header: Raw Link header value base_url: Base URL for resolving relative URLs Returns: Absolute endpoint URL if found, None otherwise """ # Simple parsing - look for rel="webmention" # Format: ; rel="webmention" import re pattern = r'<([^>]+)>\s*;\s*rel\s*=\s*["\']?webmention["\']?' match = re.search(pattern, link_header, re.IGNORECASE) if match: endpoint = match.group(1) # Make absolute if relative from urllib.parse import urljoin return urljoin(base_url, endpoint) return None def _parse_html_for_endpoint(self, html_content: str, base_url: str) -> Optional[str]: """ Parse HTML for webmention endpoint in or elements Args: html_content: HTML content base_url: Base URL for resolving relative URLs Returns: Absolute endpoint URL if found, None otherwise """ try: doc = lxml_html.fromstring(html_content) # Check first links = doc.xpath('//link[@rel="webmention"]/@href') if links: from urllib.parse import urljoin return urljoin(base_url, links[0]) # Check anchors = doc.xpath('//a[@rel="webmention"]/@href') if anchors: from urllib.parse import urljoin return urljoin(base_url, anchors[0]) except Exception as e: logger.debug(f"HTML parsing failed: {e}") return None def _cache_endpoint(self, target_url: str, endpoint: Optional[str], hours: int): """ Cache endpoint discovery result Args: target_url: Target URL endpoint: Discovered endpoint (None = negative cache) hours: TTL in hours """ self._discovery_cache[target_url] = { 'endpoint': endpoint, 'expires_at': datetime.utcnow() + timedelta(hours=hours) } # Optional: Evict old entries (keep cache bounded) if len(self._discovery_cache) > 1000: # Remove expired entries now = datetime.utcnow() self._discovery_cache = { k: v for k, v in self._discovery_cache.items() if v['expires_at'] > now } def _mark_send_success(self, queue_id: int, source_url: str, target_url: str): """Mark webmention send as successful""" try: conn = sqlite3.connect(self.db_path) cursor = conn.cursor() cursor.execute(""" UPDATE webmention_queue SET status = 'sent', sent_at = CURRENT_TIMESTAMP WHERE id = ? """, (queue_id,)) conn.commit() conn.close() logger.info(f"Sent webmention: {source_url} -> {target_url}") except Exception as e: logger.error(f"Failed to mark send success: {e}") def _mark_send_failed(self, queue_id: int, source_url: str, target_url: str, error: str): """Mark webmention send as permanently failed""" try: conn = sqlite3.connect(self.db_path) cursor = conn.cursor() cursor.execute(""" UPDATE webmention_queue SET status = 'failed', last_error = ? WHERE id = ? """, (error, queue_id)) conn.commit() conn.close() logger.warning(f"Webmention send failed permanently: {source_url} -> {target_url}: {error}") except Exception as e: logger.error(f"Failed to mark send failed: {e}") def _mark_send_no_endpoint(self, queue_id: int, source_url: str, target_url: str): """Mark webmention as no endpoint found""" try: conn = sqlite3.connect(self.db_path) cursor = conn.cursor() cursor.execute(""" UPDATE webmention_queue SET status = 'no_endpoint' WHERE id = ? """, (queue_id,)) conn.commit() conn.close() logger.info(f"No webmention endpoint for {target_url}") except Exception as e: logger.error(f"Failed to mark no endpoint: {e}") def _mark_send_retry( self, queue_id: int, source_url: str, target_url: str, current_retry_count: int, error: str ): """ Mark webmention for retry with exponential backoff Per architect's answer to Q5 and background-worker.md: - Increment retry_count AFTER failed attempt - Check retry_count >= 4 AFTER incrementing - Retry schedule: 1h, 6h, 24h """ new_retry_count = current_retry_count + 1 # Calculate next retry time next_retry_at = None if new_retry_count < 4: delays = { 1: timedelta(hours=1), 2: timedelta(hours=6), 3: timedelta(hours=24), } delay = delays.get(new_retry_count) if delay: next_retry_at = datetime.utcnow() + delay try: conn = sqlite3.connect(self.db_path) cursor = conn.cursor() if new_retry_count >= 4: # Max retries reached - mark as failed cursor.execute(""" UPDATE webmention_queue SET status = 'failed', retry_count = ?, last_error = ? WHERE id = ? """, (new_retry_count, error, queue_id)) logger.warning( f"Webmention send failed permanently after {new_retry_count} attempts: " f"{source_url} -> {target_url}: {error}" ) else: # Schedule retry cursor.execute(""" UPDATE webmention_queue SET status = 'pending', retry_count = ?, next_retry_at = ?, last_error = ? WHERE id = ? """, (new_retry_count, next_retry_at, error, queue_id)) logger.warning( f"Webmention send failed, retry {new_retry_count}: " f"{source_url} -> {target_url}: {error}" ) conn.commit() conn.close() except Exception as e: logger.error(f"Failed to mark send retry: {e}") def stop(self): """ Stop the worker thread gracefully Sets the stop event to signal the thread to exit """ logger.info("Stopping webmention worker") self._stop_event.set() def get_stats(self) -> Dict[str, Any]: """ Get current worker statistics Returns: Dict with worker stats for health check """ try: conn = sqlite3.connect(self.db_path) cursor = conn.cursor() # Count pending validations cursor.execute(""" SELECT COUNT(*) FROM webmentions WHERE validation_status = 'pending' """) pending_validations = cursor.fetchone()[0] # Count pending sends (Phase 3) cursor.execute(""" SELECT COUNT(*) FROM webmention_queue WHERE status = 'pending' """) pending_sends = cursor.fetchone()[0] conn.close() return { 'running': self.is_alive(), 'last_processed': self._last_processed.isoformat() if self._last_processed else None, 'pending_validations': pending_validations, 'pending_sends': pending_sends } except Exception as e: logger.error(f"Failed to get worker stats: {e}") return { 'running': self.is_alive(), 'error': str(e) }