tasklert-api / src /services /event_service.py
hashir-qt's picture
initial deploy
507973e
Raw History Blame Contribute Delete
2.66 kB
"""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)