Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

Refactor notification system based on djpetti's feedback

tombii44c2aa638ec5
diff --git a/src/local_deep_research/notifications/__init__.py b/src/local_deep_research/notifications/__init__.py
index d9a8c34cf1..12c25fe627 100644
--- a/src/local_deep_research/notifications/__init__.py
+++ b/src/local_deep_research/notifications/__init__.py
@@ -22,6 +22,10 @@ from .url_builder import (
validate_url,
URLValidationError,
)
+from .queue_helpers import (
+ send_queue_notification,
+ send_queue_failed_notification,
+)
__all__ = [
"NotificationError",
@@ -35,4 +39,6 @@ __all__ = [
"build_notification_url",
"validate_url",
"URLValidationError",
+ "send_queue_notification",
+ "send_queue_failed_notification",
]
diff --git a/src/local_deep_research/notifications/queue_helpers.py b/src/local_deep_research/notifications/queue_helpers.py
new file mode 100644
index 0000000000..cec685b216
--- /dev/null
+++ b/src/local_deep_research/notifications/queue_helpers.py
@@ -0,0 +1,111 @@
+"""
+Queue notification helpers for the notification system.
+
+Provides helper functions for sending queue-related notifications
+to keep the queue manager focused on queue logic.
+"""
+
+from typing import Dict, Any, Optional
+from loguru import logger
+
+from .manager import NotificationManager
+from .templates import EventType
+
+
+def send_queue_notification(
+ username: str,
+ research_id: str,
+ query: str,
+ settings_snapshot: Dict[str, Any],
+ position: Optional[int] = None,
+) -> bool:
+ """
+ Send a research queued notification.
+
+ Args:
+ username: User who owns the research
+ research_id: UUID of the research
+ query: Research query string
+ settings_snapshot: Settings snapshot for thread-safe access
+ position: Queue position (optional)
+
+ Returns:
+ True if notification was sent successfully, False otherwise
+ """
+ try:
+ notification_manager = NotificationManager(
+ settings_snapshot=settings_snapshot, user_id=username
+ )
+
+ # Build notification context
+ context = {
+ "query": query,
+ "research_id": research_id,
+ }
+
+ if position is not None:
+ context["position"] = position
+ context["wait_time"] = (
+ "Unknown" # Could estimate based on active researches
+ )
+
+ return notification_manager.send_notification(
+ event_type=EventType.RESEARCH_QUEUED,
+ context=context,
+ )
+
+ except Exception as e:
+ logger.debug(
+ f"Failed to send queued notification for {research_id}: {e}"
+ )
+ return False
+
+
+def send_queue_failed_notification(
+ username: str,
+ research_id: str,
+ query: str,
+ error_message: Optional[str] = None,
+ settings_snapshot: Optional[Dict[str, Any]] = None,
+) -> bool:
+ """
+ Send a research failed notification from queue operations.
+
+ Args:
+ username: User who owns the research
+ research_id: UUID of the research
+ query: Research query string
+ error_message: Optional error message
+ settings_snapshot: Settings snapshot for thread-safe access
+
+ Returns:
+ True if notification was sent successfully, False otherwise
+ """
+ if not settings_snapshot:
+ logger.debug("No settings snapshot provided for failed notification")
+ return False
+
+ try:
+ notification_manager = NotificationManager(
+ settings_snapshot=settings_snapshot, user_id=username
+ )
+
+ # Build notification context
+ context = {
+ "query": query,
+ "research_id": research_id,
+ }
+
+ if error_message:
+ context["error"] = error_message
+
+ return notification_manager.send_notification(
+ event_type=EventType.RESEARCH_FAILED,
+ context=context,
+ )
+
+ except Exception as e:
+ logger.debug(
+ f"Failed to send failed notification for {research_id}: {e}"
+ )
+ return False
diff --git a/src/local_deep_research/notifications/service.py b/src/local_deep_research/notifications/service.py
index b0b56353eb..2bfec1e941 100644
--- a/src/local_deep_research/notifications/service.py
+++ b/src/local_deep_research/notifications/service.py
@@ -17,6 +17,7 @@ from tenacity import (
from .exceptions import ServiceError, SendError
from .templates import EventType, NotificationTemplate
+from ..security.url_builder import mask_sensitive_url
# Backward compatibility constants - now handled by Tenacity internally
MAX_RETRY_ATTEMPTS = 3
@@ -137,7 +138,7 @@ class NotificationService:
if not result:
logger.error(
f"Failed to add service URLs to Apprise: "
- f"{self._mask_url(service_urls)}"
+ f"{mask_sensitive_url(service_urls)}"
)
return False
@@ -160,7 +161,7 @@ class NotificationService:
except Exception as e:
# Tenacity will retry, but if all retries fail, raise SendError
- logger.error(
+ logger.exception(
f"Failed to send notification after retries: '{title[:50]}...'"
)
raise SendError(f"Failed to send notification: {str(e)}")
@@ -282,47 +283,6 @@ class NotificationService:
"service URL (e.g., discord://webhook_id/token)"
)
- @staticmethod
- def _mask_url(url: str) -> str:
- """
- Mask sensitive parts of a URL for logging.
-
- Args:
- url: URL to mask
-
- Returns:
- Masked URL with credentials hidden
- """
- try:
- parsed = urlparse(url)
-
- # Mask password if present
- if parsed.password:
- netloc = parsed.netloc.replace(parsed.password, "***")
- else:
- netloc = parsed.netloc
-
- # Mask path tokens (common in webhooks)
- path = parsed.path
- if path:
- # Replace long alphanumeric tokens with ***
- path = re.sub(
- r"/[a-zA-Z0-9_-]{20,}",
- "/***",
- path,
- )
-
- # Reconstruct URL
- masked = f"{parsed.scheme}://{netloc}{path}"
- if parsed.query:
- masked += "?***"
-
- return masked
-
- except Exception:
- # If parsing fails, just return generic mask
- return f"{url.split(':')[0]}://***"
-
def get_service_type(self, url: str) -> Optional[str]:
"""
Detect service type from URL.
diff --git a/src/local_deep_research/notifications/url_builder.py b/src/local_deep_research/notifications/url_builder.py
index 9531688d11..307db41b08 100644
--- a/src/local_deep_research/notifications/url_builder.py
+++ b/src/local_deep_research/notifications/url_builder.py
@@ -1,11 +1,23 @@
"""
-URL builder utility for notification links.
+URL builder utility for notification callback links.
+
+This module builds HTTP/HTTPS URLs that are included in notifications for users
+to click on (e.g., https://myapp.com/research/123). This is separate from
+Apprise service URLs which use their own protocols (discord://, mailto://, etc.).
+
+Uses the existing security URL validator for consistency with the rest of the application.
"""
from typing import Optional
from urllib.parse import urlparse
from loguru import logger
+from ..security.url_builder import (
+ build_base_url_from_settings,
+ build_full_url,
+)
+from ..security.url_validator import URLValidator
+
class URLValidationError(ValueError):
"""Raised when URL construction fails validation."""
@@ -13,12 +25,32 @@ class URLValidationError(ValueError):
pass
+def _normalize_base_url(base_url: str) -> str:
+ """
+ Normalize a base URL by removing trailing slashes.
+
+ This is a small helper to consistently handle base URLs
+ throughout the notification system.
+
+ Args:
+ base_url: Base URL to normalize
+
+ Returns:
+ Base URL without trailing slash
+ """
+ return base_url.rstrip("/")
+
+
def validate_url(url: str) -> bool:
"""
- Validate that a URL is well-formed and safe.
+ Validate that a notification callback URL is well-formed and safe.
+
+ This validates HTTP/HTTPS URLs that users will click on from notifications,
+ not Apprise service URLs. Apprise URLs use different protocols like
+ discord://, mailto://, etc. and are validated by Apprise itself.
Args:
- url: URL to validate
+ url: HTTP/HTTPS callback URL to validate
Returns:
True if valid
@@ -31,32 +63,41 @@ def validate_url(url: str) -> bool:
try:
parsed = urlparse(url)
- except Exception as e:
- raise URLValidationError(f"Failed to parse URL: {e}")
- # Must have a scheme
- if not parsed.scheme:
- raise URLValidationError("URL must have a scheme (http or https)")
+ # Must have a scheme
+ if not parsed.scheme:
+ raise URLValidationError("URL must have a scheme (http or https)")
- # Must be http or https
- if parsed.scheme not in ("http", "https"):
- raise URLValidationError(
- f"URL scheme must be http or https, got: {parsed.scheme}"
- )
+ # Must be http or https (notification callback URLs)
+ if parsed.scheme not in ("http", "https"):
+ raise URLValidationError(
+ f"URL scheme must be http or https, got: {parsed.scheme}"
+ )
- # Must have a netloc (hostname)
- if not parsed.netloc:
- raise URLValidationError("URL must have a hostname")
+ # Use the existing security URL validator for additional safety
+ if not URLValidator.is_safe_url(url, require_scheme=True):
+ raise URLValidationError(f"URL failed security validation: {url}")
- # Check for obvious issues
- if parsed.netloc.startswith(".") or parsed.netloc.endswith("."):
- raise URLValidationError(f"Invalid hostname: {parsed.netloc}")
+ # Must have a netloc (hostname)
+ if not parsed.netloc:
+ raise URLValidationError("URL must have a hostname")
- # Path should be valid
- if parsed.path and not parsed.path.startswith("/"):
- raise URLValidationError(f"URL path must start with /: {parsed.path}")
+ # Check for obvious issues
+ if parsed.netloc.startswith(".") or parsed.netloc.endswith("."):
+ raise URLValidationError(f"Invalid hostname: {parsed.netloc}")
- return True
+ # Path should be valid
+ if parsed.path and not parsed.path.startswith("/"):
+ raise URLValidationError(
+ f"URL path must start with /: {parsed.path}"
+ )
+
+ return True
+
+ except Exception as e:
+ if isinstance(e, URLValidationError):
+ raise
+ raise URLValidationError(f"Failed to validate URL: {e}")
def build_notification_url(
@@ -67,7 +108,11 @@ def build_notification_url(
validate: bool = True,
) -> str:
"""
- Build a full URL for use in notifications.
+ Build a full HTTP/HTTPS callback URL for use in notifications.
+
+ This builds URLs that users can click on from notifications to return to
+ the application (e.g., https://myapp.com/research/123). This is separate
+ from Apprise service URLs which use their own protocols.
Args:
path: Relative path (e.g., "/research/123")
@@ -77,7 +122,7 @@ def build_notification_url(
validate: Whether to validate the constructed URL (default: True)
Returns:
- Full URL (e.g., "https://myapp.com/research/123")
+ Full HTTP/HTTPS URL (e.g., "https://myapp.com/research/123")
Raises:
URLValidationError: If validate=True and URL is invalid
@@ -86,81 +131,49 @@ def build_notification_url(
You can provide either settings_manager OR settings_snapshot, not both.
settings_snapshot is preferred for thread-safe background tasks.
"""
- # Ensure path starts with /
- if not path.startswith("/"):
- path = f"/{path}"
-
- # Try to get external URL from settings
- base_url = None
-
- # Try settings_snapshot first (preferred for thread-safety)
- if settings_snapshot:
- try:
- base_url = settings_snapshot.get("app.external_url", "")
- # Clean up base_url
- if base_url:
- base_url = base_url.rstrip("/")
- logger.debug(
- f"Using configured external URL from snapshot: {base_url}"
- )
- except Exception as e:
- logger.debug(f"Could not get external_url from snapshot: {e}")
-
- # Fallback to settings_manager if provided
- elif settings_manager:
- try:
- base_url = settings_manager.get_setting(
+ try:
+ # Extract settings from snapshot or manager
+ external_url = None
+ host = None
+ port = None
+
+ if settings_snapshot:
+ external_url = settings_snapshot.get("app.external_url", "")
+ host = settings_snapshot.get("app.host", "localhost")
+ port = settings_snapshot.get("app.port", 5000)
+ elif settings_manager:
+ external_url = settings_manager.get_setting(
"app.external_url", default=""
)
- # Clean up base_url
- if base_url:
- base_url = base_url.rstrip("/")
- logger.debug(f"Using configured external URL: {base_url}")
- except Exception as e:
- logger.debug(f"Could not get external_url setting: {e}")
-
- # Fallback to constructing from app.host and app.port (if settings available)
- if not base_url and (settings_snapshot or settings_manager):
- try:
- if settings_snapshot:
- host = settings_snapshot.get("app.host", "localhost")
- port = settings_snapshot.get("app.port", 5000)
- elif settings_manager:
- host = settings_manager.get_setting(
- "app.host", default="localhost"
- )
- port = settings_manager.get_setting("app.port", default=5000)
- else:
- host = None
- port = None
-
- if host and port:
- # Convert 0.0.0.0 to localhost for URLs
- if host in ("0.0.0.0", "::"):
- host = "localhost"
-
- base_url = f"http://{host}:{port}"
- logger.debug(f"Constructed URL from host/port: {base_url}")
- except Exception as e:
- logger.debug(f"Could not construct URL from settings: {e}")
-
- # Final fallback
- if not base_url:
- base_url = fallback_base
- logger.debug(f"Using fallback URL: {base_url}")
-
- # Construct full URL
- full_url = f"{base_url}{path}"
-
- # Validate if requested
- if validate:
- try:
+ host = settings_manager.get_setting("app.host", default="localhost")
+ port = settings_manager.get_setting("app.port", default=5000)
+
+ # Build base URL using the centralized utility
+ base_url = build_base_url_from_settings(
+ external_url=external_url,
+ host=host,
+ port=port,
+ fallback_base=fallback_base,
+ )
+
+ # Build full URL
+ full_url = build_full_url(
+ base_url=base_url,
+ path=path,
+ validate=False, # We'll validate with our own validator
+ )
+
+ # Validate if requested using our own validator
+ if validate:
validate_url(full_url)
- except URLValidationError as e:
- logger.exception(
- f"Constructed invalid URL '{full_url}' from base '{base_url}' "
- f"and path '{path}': {e}"
- )
+
+ return full_url
+
+ except Exception as e:
+ if isinstance(e, URLValidationError):
raise
- return full_url
+ logger.exception(
+ f"Failed to build notification URL for path '{path}': {e}"
+ )
+ raise URLValidationError(f"Failed to build notification URL: {e}")
diff --git a/src/local_deep_research/security/url_builder.py b/src/local_deep_research/security/url_builder.py
new file mode 100644
index 0000000000..38a65a7cc2
--- /dev/null
+++ b/src/local_deep_research/security/url_builder.py
@@ -0,0 +1,208 @@
+"""
+URL building utilities for security and application use.
+
+Provides centralized URL construction logic that can be reused
+throughout the application for consistent URL handling.
+"""
+
+import re
+from typing import Optional, Union
+from urllib.parse import urlparse
+from loguru import logger
+
+
+class URLBuilderError(Exception):
+ """Raised when URL construction fails."""
+
+ pass
+
+
+def normalize_bind_address(host: str) -> str:
+ """
+ Convert bind addresses to URL-friendly hostnames.
+
+ Args:
+ host: Host address from settings (may include bind addresses)
+
+ Returns:
+ URL-friendly hostname
+ """
+ # Convert bind-all addresses to localhost for URLs
+ if host in ("0.0.0.0", "::"):
+ return "localhost"
+ return host
+
+
+def build_base_url_from_settings(
+ external_url: Optional[str] = None,
+ host: Optional[str] = None,
+ port: Optional[Union[str, int]] = None,
+ fallback_base: str = "http://localhost:5000",
+) -> str:
+ """
+ Build a base URL from application settings with intelligent fallbacks.
+
+ This function handles the common pattern of building application URLs
+ from various configuration sources with proper normalization.
+
+ Args:
+ external_url: Pre-configured external URL (highest priority)
+ host: Hostname/IP address (used if external_url not provided)
+ port: Port number (used with host if external_url not provided)
+ fallback_base: Final fallback URL if nothing else is available
+
+ Returns:
+ Complete base URL (e.g., "https://myapp.com" or "http://localhost:5000")
+
+ Raises:
+ URLBuilderError: If URL construction fails
+ """
+ try:
+ # Try external URL first (highest priority)
+ if external_url and external_url.strip():
+ base_url = external_url.strip().rstrip("/")
+ logger.debug(f"Using configured external URL: {base_url}")
+ return base_url
+
+ # Try to construct from host and port
+ if host and port:
+ normalized_host = normalize_bind_address(host)
+
+ # Use HTTP for host/port combinations (typically internal server addresses)
+ # For external URLs, users should configure external_url setting instead
+ base_url = f"http://{normalized_host}:{int(port)}"
+ logger.debug(f"Constructed URL from host/port: {base_url}")
+ return base_url
+
+ # Final fallback
+ base_url = fallback_base.rstrip("/")
+ logger.debug(f"Using fallback URL: {base_url}")
+ return base_url
+
+ except Exception as e:
+ raise URLBuilderError(f"Failed to build base URL: {e}")
+
+
+def build_full_url(
+ base_url: str,
+ path: str,
+ validate: bool = True,
+ allowed_schemes: Optional[list] = None,
+) -> str:
+ """
+ Build a complete URL from base URL and path.
+
+ Args:
+ base_url: Base URL (e.g., "https://myapp.com")
+ path: Path to append (e.g., "/research/123")
+ validate: Whether to validate the resulting URL
+ allowed_schemes: List of allowed URL schemes (default: ["http", "https"])
+
+ Returns:
+ Complete URL (e.g., "https://myapp.com/research/123")
+
+ Raises:
+ URLBuilderError: If URL construction or validation fails
+ """
+ try:
+ # Ensure path starts with /
+ if not path.startswith("/"):
+ path = f"/{path}"
+
+ # Ensure base URL doesn't end with /
+ base_url = base_url.rstrip("/")
+
+ # Construct full URL
+ full_url = f"{base_url}{path}"
+
+ if validate:
+ validate_constructed_url(full_url, allowed_schemes)
+
+ return full_url
+
+ except Exception as e:
+ raise URLBuilderError(f"Failed to build full URL: {e}")
+
+
+def validate_constructed_url(
+ url: str, allowed_schemes: Optional[list] = None
+) -> bool:
+ """
+ Validate a constructed URL.
+
+ Args:
+ url: URL to validate
+ allowed_schemes: List of allowed schemes (default: ["http", "https"])
+
+ Returns:
+ True if valid
+
+ Raises:
+ URLBuilderError: If URL is invalid
+ """
+ if not url or not isinstance(url, str):
+ raise URLBuilderError("URL must be a non-empty string")
+
+ try:
+ parsed = urlparse(url)
+ except Exception as e:
+ raise URLBuilderError(f"Failed to parse URL: {e}")
+
+ # Check scheme
+ if not parsed.scheme:
+ raise URLBuilderError("URL must have a scheme")
+
+ if allowed_schemes and parsed.scheme not in allowed_schemes:
+ raise URLBuilderError(
+ f"URL scheme '{parsed.scheme}' not in allowed schemes: {allowed_schemes}"
+ )
+
+ # Check hostname
+ if not parsed.netloc:
+ raise URLBuilderError("URL must have a hostname")
+
+ return True
+
+
+def mask_sensitive_url(url: str) -> str:
+ """
+ Mask sensitive parts of a URL for secure logging.
+
+ This function masks passwords, webhook tokens, and other sensitive
+ information in URLs to prevent accidental exposure in logs.
+
+ Args:
+ url: URL to mask
+
+ Returns:
+ URL with sensitive parts replaced with ***
+ """
+ try:
+ parsed = urlparse(url)
+
+ # Mask password if present
+ if parsed.password:
+ netloc = parsed.netloc.replace(parsed.password, "***")
+ else:
+ netloc = parsed.netloc
+
+ # Mask path tokens (common in webhooks)
+ path = parsed.path
+ if path:
+ # Replace long alphanumeric tokens with ***
+ path = re.sub(
+ r"/[a-zA-Z0-9_-]{20,}",
+ "/***",
+ path,
+ )
+
+ # Reconstruct URL
+ masked = f"{parsed.scheme}://{netloc}{path}"
+ if parsed.query:
+ masked += "?***"
+
+ return masked
+
+ except Exception:
+ # If parsing fails, just return generic mask
+ return f"{url.split(':')[0]}://***"
diff --git a/src/local_deep_research/web/queue/manager.py b/src/local_deep_research/web/queue/manager.py
index cb09a3c267..531dcd3add 100644
--- a/src/local_deep_research/web/queue/manager.py
+++ b/src/local_deep_research/web/queue/manager.py
@@ -61,26 +61,17 @@ class QueueManager:
# Send RESEARCH_QUEUED notification if enabled
try:
from ...settings import SettingsManager
- from ...notifications.manager import NotificationManager
- from ...notifications import EventType
+ from ...notifications import send_queue_notification
settings_manager = SettingsManager(session)
settings_snapshot = settings_manager.get_settings_snapshot()
- notification_manager = NotificationManager(
- settings_snapshot=settings_snapshot, user_id=username
- )
-
- # Build notification context
- context = {
- "query": query,
- "position": max_position + 1,
- "wait_time": "Unknown", # Could estimate based on active researches
- }
-
- notification_manager.send_notification(
- event_type=EventType.RESEARCH_QUEUED,
- context=context,
+ send_queue_notification(
+ username=username,
+ research_id=research_id,
+ query=query,
+ settings_snapshot=settings_snapshot,
+ position=max_position + 1,
)
except Exception as e:
logger.debug(f"Failed to send queued notification: {e}")