定时任务订阅模式

This commit is contained in:
吉鑫升 committed 2026-05-13 14:59:27 +08:00
1 parent 839386f0b4
commit aa034f8669
14 files changed
+1143 -98

No files matched your search

@@ -197,16 +197,70 @@ class ScheduledTaskService:
return thread
async def list_tasks(self, user_id: str) -> list[dict[str, Any]]:
return await self.store.list_tasks(user_id)
owned = await self.store.list_tasks(user_id)
for task in owned:
task["role"] = "owner"
subscribed = await self.store.list_subscribed_tasks(user_id)
owned_ids = {task["task_id"] for task in owned}
for task in subscribed:
if task["task_id"] in owned_ids:
continue
task["role"] = "subscriber"
owned.append(task)
return owned
async def list_published(self, *, limit: int = 50, offset: int = 0) -> list[dict[str, Any]]:
"""Public discovery list. Strips author prompt details to a short summary."""
tasks = await self.store.list_published_tasks(limit=limit, offset=offset)
result: list[dict[str, Any]] = []
for task in tasks:
prompt = (task.get("prompt") or "").strip()
summary = prompt if len(prompt) <= 200 else prompt[:200].rstrip() + "…"
result.append(
{
"task_id": task["task_id"],
"name": task.get("name"),
"prompt_summary": summary,
"schedule_text": task.get("schedule_text"),
"timezone": task.get("timezone"),
"published_at": task.get("published_at"),
"owner_user_id": task.get("user_id"),
}
)
return result
async def _accessible_task(self, user_id: str, task_id: str) -> dict[str, Any] | None:
task = await self.store.get_task_any(task_id)
if task is None:
return None
if task["user_id"] == user_id:
task["role"] = "owner"
return task
sub = await self.store.get_subscription(task_id, user_id)
if sub is None:
return None
task["role"] = "subscriber"
task["_subscription"] = sub
return task
async def list_runs(self, user_id: str, task_id: str, *, limit: int = 50) -> list[dict[str, Any]]:
task = await self.store.get_task(task_id, user_id)
if task is None:
accessible = await self._accessible_task(user_id, task_id)
if accessible is None:
return []
return await self.store.list_runs(task_id, user_id, limit=limit)
return await self.store.list_runs(task_id, accessible["user_id"], limit=limit)
async def get_run(self, user_id: str, run_id: str) -> dict[str, Any] | None:
return await self.store.get_run(run_id, user_id)
run = await self.store.get_run(run_id, user_id)
if run is not None:
return run
# Subscriber visibility: look up the run unfiltered, then verify the
# caller has a subscription on the parent task.
candidate = await self.store.get_run_any(run_id)
if candidate is None:
return None
if await self.store.get_subscription(candidate["task_id"], user_id) is None:
return None
return candidate
async def delete_run(self, user_id: str, run_id: str) -> bool:
deleted = await self.store.delete_run(run_id, user_id)
@@ -655,15 +709,62 @@ class ScheduledTaskService:
async def _deliver_element_result(self, task: dict[str, Any], result_text: str) -> None:
if self._element_client is None:
return
profile = await self.store.get_delivery_profile(task["user_id"])
body = f"【定时任务】{task['name']}\n\n{result_text}"
# 1) Author
await self._deliver_to_user(task["user_id"], task, body)
# 2) Subscribers who opted into notifications
try:
subscribers = await self.store.list_notify_subscribers(task["task_id"])
except Exception:
logger.exception("Failed to list scheduled task subscribers for %s", task["task_id"])
subscribers = []
for sub in subscribers:
sub_user_id = sub.get("user_id")
if not sub_user_id or sub_user_id == task["user_id"]:
continue
await self._deliver_to_user(sub_user_id, task, body)
async def _deliver_to_user(self, user_id: str, task: dict[str, Any], body: str) -> None:
if self._element_client is None:
return
try:
profile = await self.store.get_delivery_profile(user_id)
except Exception:
logger.exception("Failed to load delivery profile for user %s", user_id)
return
element_user_id = profile.get("element_user_id")
if not isinstance(element_user_id, str) or not element_user_id.strip():
return
existing_room_id: str | None = profile.get("element_room_id") or None
body = f"【定时任务】{task['name']}\n\n{result_text}"
try:
room_id = await self._element_client.send_direct_message(element_user_id.strip(), body, room_id=existing_room_id)
if room_id and room_id != existing_room_id:
await self.store.update_delivery_profile(task["user_id"], {"element_room_id": room_id})
await self.store.update_delivery_profile(user_id, {"element_room_id": room_id})
except Exception:
logger.exception("Failed to deliver scheduled task %s to Element user %s", task["task_id"], element_user_id)
# --- Publish / subscribe ---
async def publish_task(self, user_id: str, task_id: str) -> dict[str, Any] | None:
return await self.store.set_task_published(task_id, user_id, published=True)
async def unpublish_task(self, user_id: str, task_id: str) -> dict[str, Any] | None:
return await self.store.set_task_published(task_id, user_id, published=False)
async def subscribe_task(
self, user_id: str, task_id: str, *, notify_element: bool
) -> dict[str, Any] | None:
task = await self.store.get_task_any(task_id)
if task is None:
return None
if task["user_id"] == user_id:
# Authors don't need to subscribe to their own tasks.
return None
existing = await self.store.get_subscription(task_id, user_id)
if existing is None and not task.get("published"):
# First-time subscription requires the task to currently be published.
return None
return await self.store.upsert_subscription(task_id, user_id, notify_element=notify_element)
async def unsubscribe_task(self, user_id: str, task_id: str) -> bool:
return await self.store.delete_subscription(task_id, user_id)