Spaces:
Runtime error
Runtime error
File size: 6,898 Bytes
04c4194 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 | """
DocuLens — Webhook management and delivery.
Allows users to register webhook URLs that receive POST notifications
when extraction or validation completes.
"""
import os
import json
import hmac
import hashlib
import logging
import time
from typing import Optional
from uuid import uuid4
import requests
from fastapi import APIRouter, HTTPException, Depends
from pydantic import BaseModel, HttpUrl
from middleware import check_rate_limit
logger = logging.getLogger(__name__)
webhooks_router = APIRouter()
# ---------------------------------------------------------------------------
# In-memory webhook store (Supabase-backed when available)
# ---------------------------------------------------------------------------
_webhooks: dict[str, dict] = {} # keyed by webhook_id
def _get_webhooks_from_db() -> list[dict]:
"""Load webhooks from Supabase if available."""
try:
from db.supabase import get_client
client = get_client()
if not client:
return []
resp = client.table("webhooks").select("*").eq("is_active", True).execute()
return resp.data or []
except Exception as e:
logger.debug(f"Could not load webhooks from DB: {e}")
return []
def _save_webhook_to_db(webhook: dict) -> bool:
"""Persist webhook to Supabase."""
try:
from db.supabase import get_client
client = get_client()
if not client:
return False
client.table("webhooks").insert(webhook).execute()
return True
except Exception as e:
logger.warning(f"Failed to save webhook to DB: {e}")
return False
def _delete_webhook_from_db(webhook_id: str) -> bool:
"""Remove webhook from Supabase."""
try:
from db.supabase import get_client
client = get_client()
if not client:
return False
client.table("webhooks").delete().eq("id", webhook_id).execute()
return True
except Exception as e:
logger.warning(f"Failed to delete webhook from DB: {e}")
return False
# ---------------------------------------------------------------------------
# Models
# ---------------------------------------------------------------------------
class WebhookCreate(BaseModel):
url: HttpUrl
events: list[str] = ["extraction.completed", "validation.completed"]
secret: Optional[str] = None # optional signing secret
class WebhookResponse(BaseModel):
id: str
url: str
events: list[str]
is_active: bool
created_at: str
# ---------------------------------------------------------------------------
# Endpoints
# ---------------------------------------------------------------------------
@webhooks_router.post("/api/v1/webhooks")
async def register_webhook(
body: WebhookCreate,
api_key: str = Depends(check_rate_limit),
):
"""Register a webhook URL to receive extraction/validation result notifications."""
valid_events = {"extraction.completed", "validation.completed", "batch.completed"}
for event in body.events:
if event not in valid_events:
raise HTTPException(
status_code=400,
detail=f"Invalid event '{event}'. Valid events: {sorted(valid_events)}",
)
webhook_id = str(uuid4())
webhook = {
"id": webhook_id,
"url": str(body.url),
"events": body.events,
"secret": body.secret or "",
"is_active": True,
"created_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
}
_save_webhook_to_db(webhook)
_webhooks[webhook_id] = webhook
return {
"id": webhook_id,
"url": webhook["url"],
"events": webhook["events"],
"is_active": True,
"created_at": webhook["created_at"],
}
@webhooks_router.get("/api/v1/webhooks")
async def list_webhooks(api_key: str = Depends(check_rate_limit)):
"""List all registered webhooks."""
# Merge in-memory and DB webhooks
db_hooks = _get_webhooks_from_db()
all_hooks = {h["id"]: h for h in db_hooks}
all_hooks.update(_webhooks)
return {
"webhooks": [
{
"id": h["id"],
"url": h["url"],
"events": h.get("events", []),
"is_active": h.get("is_active", True),
"created_at": h.get("created_at", ""),
}
for h in all_hooks.values()
if h.get("is_active", True)
]
}
@webhooks_router.delete("/api/v1/webhooks/{webhook_id}")
async def delete_webhook(webhook_id: str, api_key: str = Depends(check_rate_limit)):
"""Deactivate a webhook."""
if webhook_id in _webhooks:
_webhooks[webhook_id]["is_active"] = False
_delete_webhook_from_db(webhook_id)
return {"deleted": True}
# ---------------------------------------------------------------------------
# Delivery — called internally after extraction/validation completes
# ---------------------------------------------------------------------------
WEBHOOK_TIMEOUT = int(os.environ.get("WEBHOOK_TIMEOUT", "10")) # seconds
def _sign_payload(payload_bytes: bytes, secret: str) -> str:
"""Create HMAC-SHA256 signature for webhook payload."""
return hmac.new(secret.encode(), payload_bytes, hashlib.sha256).hexdigest()
def deliver_webhook(event: str, data: dict):
"""
Fire webhooks for a given event. Called internally after
extraction or validation completes. Non-blocking best-effort.
"""
# Gather all active webhooks (in-memory + DB)
all_hooks = list(_webhooks.values())
try:
all_hooks.extend(_get_webhooks_from_db())
except Exception:
pass
# Deduplicate by ID
seen = set()
unique_hooks = []
for h in all_hooks:
if h["id"] not in seen and h.get("is_active", True):
seen.add(h["id"])
unique_hooks.append(h)
for hook in unique_hooks:
if event not in hook.get("events", []):
continue
payload = {
"event": event,
"timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"data": data,
}
payload_bytes = json.dumps(payload, default=str).encode()
headers = {"Content-Type": "application/json"}
if hook.get("secret"):
headers["X-Webhook-Signature"] = _sign_payload(payload_bytes, hook["secret"])
try:
resp = requests.post(
hook["url"],
data=payload_bytes,
headers=headers,
timeout=WEBHOOK_TIMEOUT,
)
logger.info(
"Webhook delivered: event=%s url=%s status=%d",
event, hook["url"], resp.status_code,
)
except Exception as e:
logger.warning("Webhook delivery failed: url=%s error=%s", hook["url"], e)
|