Phase 4: Webhooks, Backup/Restore UI, Onboarding/Tutorial
- Webhooks Backend: model, schema, service (HMAC-SHA256, httpx), routes, event bus dispatcher, migration 0042 - Webhooks Frontend: SettingsWebhooksPage (CRUD, test button, event multi-select), API client - Backup/Restore Backend: model, schema, service (pg_dump/pg_restore), routes (admin-only), migration 0043 - Backup/Restore Frontend: SettingsBackupPage (create, list, restore dialog with RESTORE confirmation, auto-refresh) - Onboarding: OnboardingTour (8 steps, custom CSS overlay), WelcomeDialog, onboardingStore (zustand + localStorage) - Onboarding integrated into AppShell - Routes: /settings/webhooks, /settings/backup registered - Settings nav: Webhooks, Backup & Restore entries added - Migration conflict fixed: 0042_webhooks → 0043_backups chain
This commit is contained in:
@@ -0,0 +1,98 @@
|
||||
"""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:
|
||||
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."""
|
||||
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')}"
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.error(
|
||||
f"Webhook {webhook.id} dispatch error for {webhook.url}: {exc}"
|
||||
)
|
||||
|
||||
|
||||
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)")
|
||||
Reference in New Issue
Block a user