File size: 2,660 Bytes
507973e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Phase V: Dapr pub/sub event publishing and Jobs API scheduling."""
import json
import logging
from datetime import datetime

import httpx

logger = logging.getLogger(__name__)

DAPR_SIDECAR_URL = "http://localhost:3500"
PUBSUB_NAME = "taskpubsub"


async def publish_task_event(
    event_type: str,
    task_id: int,
    user_id: str,
    payload: dict,
) -> None:
    """Publish a task event to the task-events Kafka topic via Dapr sidecar."""
    event = {
        "event_type": event_type,
        "task_id": task_id,
        "user_id": user_id,
        "timestamp": datetime.utcnow().isoformat(),
        "task_data": payload,
    }
    try:
        async with httpx.AsyncClient() as client:
            resp = await client.post(
                f"{DAPR_SIDECAR_URL}/v1.0/publish/{PUBSUB_NAME}/task-events",
                json=event,
                headers={"Content-Type": "application/json"},
                timeout=5.0,
            )
            resp.raise_for_status()
    except Exception as exc:
        # Event publishing is non-critical — log and continue
        logger.warning("Failed to publish task event: %s", exc)


async def publish_sync_event(user_id: str, event_type: str, task_id: int) -> None:
    """Publish a lightweight event to task-updates topic for WebSocket broadcast."""
    event = {"user_id": user_id, "event_type": event_type, "task_id": task_id}
    try:
        async with httpx.AsyncClient() as client:
            resp = await client.post(
                f"{DAPR_SIDECAR_URL}/v1.0/publish/{PUBSUB_NAME}/task-updates",
                json=event,
                headers={"Content-Type": "application/json"},
                timeout=5.0,
            )
            resp.raise_for_status()
    except Exception as exc:
        logger.warning("Failed to publish sync event: %s", exc)


async def schedule_reminder(task_id: int, user_id: str, title: str, remind_at: datetime) -> None:
    """Schedule an exact-time reminder via Dapr Jobs API."""
    job_name = f"reminder-{task_id}"
    payload = {"task_id": task_id, "user_id": user_id, "title": title}
    try:
        async with httpx.AsyncClient() as client:
            resp = await client.post(
                f"{DAPR_SIDECAR_URL}/v1.0-alpha1/jobs/{job_name}",
                json={
                    "schedule": remind_at.isoformat() + "Z",
                    "data": json.dumps(payload),
                },
                headers={"Content-Type": "application/json"},
                timeout=5.0,
            )
            resp.raise_for_status()
    except Exception as exc:
        logger.warning("Failed to schedule reminder %s: %s", job_name, exc)