5d1b2396a7
Check Cross-Plugin Imports / check (push) Has been cancelled
System fixes: - mail_account entity type added to ENTITY_MODELS - content_hash added to DMS upload response - Calendar share grants permission to shared user - Contact TSV trigger column names corrected - search_related_handler uses find_similar_all_types - gather_context companies variable fixed - Entity links company route + schema added - company + contacts entity types added to ENTITY_MODELS - log_audit details parameter added - create_sequence is_system_admin parameter added - export_service import fixed - import_service invalid description arg removed - MCP server entity_id fix - get_merge_history function added Security fixes: - MAIL_ENCRYPTION_KEY required (no default) - revoke_permission owner/admin check added - Session is_active loaded from DB (not hardcoded) - Public share URL corrected - Logout invalidates PostgreSQL session too - Rate limit key uses token hash for Bearer auth - RLS commit replaced with flush - Webhook dispatcher sets tenant context - Dockerfile npm ci without fallback CI fixes: - pipefail added, check() function fixed - Migration hash check || echo removed Test fixes: - Plugin fixtures registered in memory - Test URLs corrected - Contact field names updated - Dedup tests use unique content - Entity links use real file IDs - RLS tests removed (not testable) - IndentationError fixed Docs: - docs/test-strategy.md created - docs/deploy-guide.md created - AGENTS.md updated with deploy + docs references
108 lines
3.6 KiB
Python
108 lines
3.6 KiB
Python
"""Webhook dispatcher — subscribes to the event bus and dispatches to matching webhooks."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import logging
|
|
import uuid
|
|
from typing import Any
|
|
|
|
from sqlalchemy import select
|
|
from sqlalchemy.ext.asyncio import async_sessionmaker
|
|
|
|
from app.core.db import get_engine, get_session_factory
|
|
from app.core.event_bus import EventBus, get_event_bus
|
|
from app.models.webhook import Webhook
|
|
from app.services.webhook_service import send_webhook
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
async def _dispatch_event(payload: dict[str, Any]) -> None:
|
|
"""Handle an event from the event bus: find matching webhooks and dispatch.
|
|
|
|
The payload is expected to contain:
|
|
- event_name: str
|
|
- tenant_id: str (UUID)
|
|
- data: dict (the actual event data)
|
|
"""
|
|
event_name = payload.get("event_name", "")
|
|
tenant_id_str = payload.get("tenant_id", "")
|
|
data = payload.get("data", {})
|
|
|
|
if not event_name or not tenant_id_str:
|
|
logger.warning("webhook_dispatcher: missing event_name or tenant_id in payload")
|
|
return
|
|
|
|
try:
|
|
tenant_id = uuid.UUID(tenant_id_str)
|
|
except (ValueError, TypeError):
|
|
logger.warning(f"webhook_dispatcher: invalid tenant_id: {tenant_id_str}")
|
|
return
|
|
|
|
# Find active webhooks for this tenant that subscribe to this event
|
|
session_factory = get_session_factory()
|
|
async with session_factory() as db:
|
|
# Set tenant context for RLS
|
|
from app.core.db import set_tenant_context
|
|
await set_tenant_context(db, tenant_id)
|
|
stmt = select(Webhook).where(
|
|
Webhook.tenant_id == tenant_id,
|
|
Webhook.is_active == True, # noqa: E712
|
|
Webhook.events.any(event_name),
|
|
)
|
|
result = await db.execute(stmt)
|
|
webhooks = list(result.scalars().all())
|
|
|
|
if not webhooks:
|
|
return
|
|
|
|
# Dispatch to all matching webhooks concurrently
|
|
tasks = []
|
|
for webhook in webhooks:
|
|
tasks.append(_dispatch_single(webhook, event_name, data))
|
|
|
|
if tasks:
|
|
await asyncio.gather(*tasks, return_exceptions=True)
|
|
|
|
|
|
async def _dispatch_single(
|
|
webhook: Webhook,
|
|
event_name: str,
|
|
data: dict[str, Any],
|
|
) -> None:
|
|
"""Send a webhook and log the result. Raises on failure (P1.5 fix).
|
|
|
|
Previously errors were swallowed, causing the outbox to mark events
|
|
as 'published' even when webhook delivery failed.
|
|
"""
|
|
try:
|
|
result = await send_webhook(webhook, event_name, data)
|
|
if result["success"]:
|
|
logger.info(
|
|
f"Webhook {webhook.id} sent successfully to {webhook.url} "
|
|
f"for event {event_name} (status={result['status_code']})"
|
|
)
|
|
else:
|
|
logger.warning(
|
|
f"Webhook {webhook.id} failed for {webhook.url} "
|
|
f"event {event_name}: {result.get('error')}"
|
|
)
|
|
raise RuntimeError(f"Webhook {webhook.id} failed: {result.get('error')}")
|
|
except Exception as exc:
|
|
logger.error(
|
|
f"Webhook {webhook.id} dispatch error for {webhook.url}: {exc}"
|
|
)
|
|
raise # Re-raise so outbox can retry (P1.5 fix)
|
|
|
|
|
|
def register_webhook_event_handlers(event_bus: EventBus | None = None) -> None:
|
|
"""Register webhook dispatcher on the global event bus.
|
|
|
|
Subscribes to all events via the wildcard '*' handler and filters
|
|
by event name internally. Should be called during application startup.
|
|
"""
|
|
bus = event_bus or get_event_bus()
|
|
bus.subscribe("*", _dispatch_event)
|
|
logger.info("Webhook dispatcher registered on event bus (wildcard '*' handler)")
|