forked from 0xWheatyz/SPARC
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2e6b8c7445 |
@@ -40,3 +40,9 @@ JWT_SECRET=your-secure-jwt-secret-change-in-production
|
|||||||
# When USE_CACHE=true: check database for cached responses before making API calls
|
# When USE_CACHE=true: check database for cached responses before making API calls
|
||||||
# When USE_CACHE=false: always make fresh API calls (still stores results in database)
|
# When USE_CACHE=false: always make fresh API calls (still stores results in database)
|
||||||
USE_CACHE=true
|
USE_CACHE=true
|
||||||
|
|
||||||
|
# ---- Webhooks ----
|
||||||
|
|
||||||
|
# Comma-separated list of webhook URLs for job completion and alert notifications
|
||||||
|
# Supports generic HTTP POST and Slack/Discord incoming webhooks
|
||||||
|
# WEBHOOK_URLS=https://hooks.slack.com/services/XXX,https://example.com/webhook
|
||||||
|
|||||||
@@ -519,8 +519,25 @@ def _run_batch_job(job_id: str, companies: list[str], max_workers: int):
|
|||||||
progress=100,
|
progress=100,
|
||||||
result_json=_json.dumps(batch_response.model_dump(), default=str),
|
result_json=_json.dumps(batch_response.model_dump(), default=str),
|
||||||
)
|
)
|
||||||
|
# Fire webhook notification
|
||||||
|
from SPARC.webhooks import notify_job_completed
|
||||||
|
notify_job_completed(
|
||||||
|
job_id=job_id,
|
||||||
|
status="completed",
|
||||||
|
total_companies=result.total_companies,
|
||||||
|
successful=result.successful,
|
||||||
|
failed=result.failed,
|
||||||
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
db.update_job(job_id, status="failed", error=str(e))
|
db.update_job(job_id, status="failed", error=str(e))
|
||||||
|
from SPARC.webhooks import notify_job_completed
|
||||||
|
notify_job_completed(
|
||||||
|
job_id=job_id,
|
||||||
|
status="failed",
|
||||||
|
total_companies=len(companies),
|
||||||
|
successful=0,
|
||||||
|
failed=len(companies),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@app.post("/analyze/batch/async", response_model=JobStatus, tags=["Analysis"])
|
@app.post("/analyze/batch/async", response_model=JobStatus, tags=["Analysis"])
|
||||||
|
|||||||
@@ -0,0 +1,139 @@
|
|||||||
|
"""Webhook notifications for job completion and alert events.
|
||||||
|
|
||||||
|
Sends JSON payloads to configured webhook URLs with retry logic.
|
||||||
|
Supports generic HTTP POST and Slack-compatible text payloads.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import requests
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# Comma-separated list of webhook URLs (env var based config)
|
||||||
|
_WEBHOOK_URLS_RAW = os.getenv("WEBHOOK_URLS", "")
|
||||||
|
WEBHOOK_URLS: list[str] = [
|
||||||
|
url.strip() for url in _WEBHOOK_URLS_RAW.split(",") if url.strip()
|
||||||
|
]
|
||||||
|
|
||||||
|
MAX_RETRIES = 3
|
||||||
|
BACKOFF_BASE = 2 # seconds
|
||||||
|
|
||||||
|
|
||||||
|
def _is_slack_url(url: str) -> bool:
|
||||||
|
"""Check if a URL looks like a Slack incoming webhook."""
|
||||||
|
return "hooks.slack.com" in url or "discord.com/api/webhooks" in url
|
||||||
|
|
||||||
|
|
||||||
|
def _build_payload(event_type: str, data: dict[str, Any], slack: bool = False) -> dict:
|
||||||
|
"""Build the webhook payload.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
event_type: Type of event (e.g., "job_completed", "alert")
|
||||||
|
data: Event-specific data
|
||||||
|
slack: If True, wrap in Slack-compatible ``text`` format
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
JSON-serializable payload dict
|
||||||
|
"""
|
||||||
|
payload = {
|
||||||
|
"event": event_type,
|
||||||
|
"timestamp": datetime.utcnow().isoformat() + "Z",
|
||||||
|
**data,
|
||||||
|
}
|
||||||
|
|
||||||
|
if slack:
|
||||||
|
# Build a human-readable summary for Slack/Discord
|
||||||
|
lines = [f"*[SPARC] {event_type}*"]
|
||||||
|
for key, value in data.items():
|
||||||
|
lines.append(f" {key}: {value}")
|
||||||
|
return {"text": "\n".join(lines)}
|
||||||
|
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
def _send_with_retry(url: str, payload: dict) -> bool:
|
||||||
|
"""Send a POST request with exponential backoff retry.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
url: Webhook URL
|
||||||
|
payload: JSON payload to send
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True if delivered successfully, False after all retries exhausted
|
||||||
|
"""
|
||||||
|
for attempt in range(1, MAX_RETRIES + 1):
|
||||||
|
try:
|
||||||
|
response = requests.post(url, json=payload, timeout=10)
|
||||||
|
if response.status_code < 300:
|
||||||
|
logger.debug("Webhook delivered to %s (attempt %d)", url, attempt)
|
||||||
|
return True
|
||||||
|
logger.warning(
|
||||||
|
"Webhook %s returned %d (attempt %d/%d)",
|
||||||
|
url, response.status_code, attempt, MAX_RETRIES,
|
||||||
|
)
|
||||||
|
except requests.RequestException as e:
|
||||||
|
logger.warning(
|
||||||
|
"Webhook delivery failed for %s (attempt %d/%d): %s",
|
||||||
|
url, attempt, MAX_RETRIES, e,
|
||||||
|
)
|
||||||
|
|
||||||
|
if attempt < MAX_RETRIES:
|
||||||
|
wait = BACKOFF_BASE ** attempt
|
||||||
|
time.sleep(wait)
|
||||||
|
|
||||||
|
logger.error("Webhook permanently failed for %s after %d attempts", url, MAX_RETRIES)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def notify(event_type: str, data: dict[str, Any]) -> None:
|
||||||
|
"""Fire all configured webhooks for an event.
|
||||||
|
|
||||||
|
Safe to call even when no webhooks are configured (returns immediately).
|
||||||
|
|
||||||
|
Args:
|
||||||
|
event_type: Event identifier (e.g., "job_completed", "patent_alert")
|
||||||
|
data: Event data to include in the payload
|
||||||
|
"""
|
||||||
|
if not WEBHOOK_URLS:
|
||||||
|
return
|
||||||
|
|
||||||
|
for url in WEBHOOK_URLS:
|
||||||
|
slack = _is_slack_url(url)
|
||||||
|
payload = _build_payload(event_type, data, slack=slack)
|
||||||
|
_send_with_retry(url, payload)
|
||||||
|
|
||||||
|
|
||||||
|
def notify_job_completed(
|
||||||
|
job_id: str,
|
||||||
|
status: str,
|
||||||
|
total_companies: int,
|
||||||
|
successful: int,
|
||||||
|
failed: int,
|
||||||
|
) -> None:
|
||||||
|
"""Send notification when a batch job completes."""
|
||||||
|
notify("job_completed", {
|
||||||
|
"job_id": job_id,
|
||||||
|
"status": status,
|
||||||
|
"total_companies": total_companies,
|
||||||
|
"successful": successful,
|
||||||
|
"failed": failed,
|
||||||
|
"summary": f"Batch job {job_id}: {successful}/{total_companies} succeeded",
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
def notify_alert(
|
||||||
|
company_name: str,
|
||||||
|
alert_type: str,
|
||||||
|
message: str,
|
||||||
|
) -> None:
|
||||||
|
"""Send notification for a tracked company alert."""
|
||||||
|
notify("patent_alert", {
|
||||||
|
"company_name": company_name,
|
||||||
|
"alert_type": alert_type,
|
||||||
|
"message": message,
|
||||||
|
})
|
||||||
@@ -9,38 +9,15 @@ const COLORS = ['#6366f1', '#0ea5e9', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6'
|
|||||||
export function AnalyticsPage() {
|
export function AnalyticsPage() {
|
||||||
const [days, setDays] = useState(30);
|
const [days, setDays] = useState(30);
|
||||||
|
|
||||||
const { data, isLoading, isError, refetch } = useQuery({
|
const { data, isLoading, isError } = useQuery({
|
||||||
queryKey: ['analytics', days],
|
queryKey: ['analytics', days],
|
||||||
queryFn: () => analyticsApi.getAnalytics(days),
|
queryFn: () => analyticsApi.getAnalytics(days),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (isLoading) {
|
if (isLoading) {
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="flex items-center justify-center min-h-[400px]">
|
||||||
<div>
|
<div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"></div>
|
||||||
<h2 className="text-xl font-semibold text-text-primary border-b-2 border-primary/30 pb-2 mb-2">
|
|
||||||
Analytics Dashboard
|
|
||||||
</h2>
|
|
||||||
<p className="text-text-secondary">Loading analytics data...</p>
|
|
||||||
</div>
|
|
||||||
{/* Skeleton cards */}
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
|
||||||
{[1, 2, 3].map((i) => (
|
|
||||||
<div key={i} className="bg-gradient-to-br from-primary/10 to-secondary/10 border border-primary/20 rounded-xl p-5 text-center animate-pulse">
|
|
||||||
<div className="h-9 w-16 bg-primary/20 rounded mx-auto mb-2" />
|
|
||||||
<div className="h-4 w-24 bg-primary/10 rounded mx-auto" />
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
{/* Skeleton charts */}
|
|
||||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
|
||||||
{[1, 2].map((i) => (
|
|
||||||
<div key={i} className="bg-bg-card/60 border border-primary/15 rounded-2xl p-6 animate-pulse">
|
|
||||||
<div className="h-5 w-40 bg-primary/20 rounded mb-4" />
|
|
||||||
<div className="h-[300px] bg-primary/5 rounded" />
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -56,18 +33,15 @@ export function AnalyticsPage() {
|
|||||||
<div className="bg-gradient-to-br from-primary/10 to-secondary/5 border border-primary/20 rounded-xl p-6">
|
<div className="bg-gradient-to-br from-primary/10 to-secondary/5 border border-primary/20 rounded-xl p-6">
|
||||||
<div className="flex items-center gap-3 text-warning mb-2">
|
<div className="flex items-center gap-3 text-warning mb-2">
|
||||||
<Database size={24} />
|
<Database size={24} />
|
||||||
<span className="font-semibold">Unable to Load Analytics</span>
|
<span className="font-semibold">Database Not Connected</span>
|
||||||
</div>
|
</div>
|
||||||
<p className="text-text-secondary">
|
<p className="text-text-secondary">
|
||||||
Could not connect to the analytics database. Ensure PostgreSQL is running and
|
Set <code className="bg-bg-card px-2 py-1 rounded">USE_DATABASE=true</code> in your .env file to enable analytics tracking.
|
||||||
<code className="bg-bg-card px-2 py-1 rounded mx-1">DATABASE_URL</code> is configured correctly.
|
|
||||||
</p>
|
</p>
|
||||||
<button
|
</div>
|
||||||
onClick={() => refetch()}
|
<div className="flex items-center gap-2 bg-secondary/10 border border-secondary/20 text-secondary rounded-xl px-4 py-3">
|
||||||
className="mt-3 text-sm bg-primary/20 hover:bg-primary/30 text-primary font-medium px-4 py-2 rounded-lg transition-colors"
|
<AlertCircle size={18} />
|
||||||
>
|
<span>Analytics features require storing analysis results in PostgreSQL for historical tracking.</span>
|
||||||
Retry
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -114,21 +114,9 @@ export function Batch() {
|
|||||||
|
|
||||||
{/* Error */}
|
{/* Error */}
|
||||||
{mutation.isError && (
|
{mutation.isError && (
|
||||||
<div className="bg-error/10 border border-error/20 rounded-xl px-4 py-3">
|
<div className="flex items-center gap-2 bg-error/10 border border-error/20 text-error rounded-xl px-4 py-3">
|
||||||
<div className="flex items-center gap-2 text-error">
|
<AlertCircle size={18} />
|
||||||
<AlertCircle size={18} />
|
<span>Batch analysis failed. Please try again.</span>
|
||||||
<span className="font-semibold">Batch analysis failed</span>
|
|
||||||
</div>
|
|
||||||
<p className="text-text-secondary text-sm mt-1 ml-7">
|
|
||||||
{mutation.error instanceof Error ? mutation.error.message : 'An unexpected error occurred.'}
|
|
||||||
{' '}Check your connection and try again.
|
|
||||||
</p>
|
|
||||||
<button
|
|
||||||
onClick={() => mutation.reset()}
|
|
||||||
className="ml-7 mt-2 text-sm text-primary hover:text-primary-dark underline"
|
|
||||||
>
|
|
||||||
Dismiss
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user