File size: 2,158 Bytes
4854e2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Celery tasks for recognition and webhooks."""
import base64
from typing import Optional
from uuid import UUID

from app.core.database import SessionLocal
from app.services.recognition_service import RecognitionService
from app.workers.celery_app import celery_app


@celery_app.task(name="recognize_face")
def recognize_face_task(
    image_b64: str,
    tenant_id: str,
    user_id: str,
    threshold: float,
    return_bboxes: bool,
):
    image_bytes = base64.b64decode(image_b64)
    db = SessionLocal()
    try:
        return RecognitionService.recognize_from_bytes(
            db=db,
            image_bytes=image_bytes,
            tenant_id=UUID(tenant_id),
            user_id=UUID(user_id),
            threshold=threshold,
            return_bboxes=return_bboxes,
            source="async_queue",
        )
    finally:
        db.close()


@celery_app.task(name="deliver_webhook")
def deliver_webhook_task(event_id: str):
    from app.services.webhook_service import WebhookService
    from app.models import WebhookEvent, WebhookEndpoint
    import httpx
    from app.core.config import settings

    db = SessionLocal()
    try:
        event = db.query(WebhookEvent).filter(WebhookEvent.id == UUID(event_id)).first()
        if not event:
            return
        endpoint = db.query(WebhookEndpoint).filter(WebhookEndpoint.id == event.endpoint_id).first()
        if not endpoint or not endpoint.is_active:
            return

        payload = event.payload
        headers = {"Content-Type": "application/json"}
        if endpoint.secret:
            headers["X-Webhook-Secret"] = endpoint.secret

        try:
            with httpx.Client(timeout=settings.WEBHOOK_TIMEOUT_SECONDS) as client:
                response = client.post(endpoint.url, content=payload, headers=headers)
            if 200 <= response.status_code < 300:
                WebhookService.mark_delivered(db, event, response.status_code)
            else:
                WebhookService.increment_attempt(db, event, response.status_code)
        except Exception:
            WebhookService.increment_attempt(db, event, None)
    finally:
        db.close()