53 lines
1.6 KiB
Python
53 lines
1.6 KiB
Python
|
|
from datetime import datetime
|
||
|
|
from app.models.session import TaskHistory, Task
|
||
|
|
from app.services.storage import storage
|
||
|
|
from app.core.logging import logger
|
||
|
|
|
||
|
|
HISTORY_KEY = "task_history"
|
||
|
|
|
||
|
|
|
||
|
|
class HistoryService:
|
||
|
|
def __init__(self):
|
||
|
|
self._history: list[dict] = []
|
||
|
|
|
||
|
|
def load(self):
|
||
|
|
data = storage.load(HISTORY_KEY, [])
|
||
|
|
self._history = data if isinstance(data, list) else []
|
||
|
|
logger.info(f"Loaded {len(self._history)} history records")
|
||
|
|
|
||
|
|
def save(self):
|
||
|
|
storage.save(HISTORY_KEY, self._history)
|
||
|
|
|
||
|
|
def add_task_history(self, task: Task):
|
||
|
|
history = TaskHistory(
|
||
|
|
id=task.id,
|
||
|
|
type=task.type,
|
||
|
|
prompt=task.prompt,
|
||
|
|
status=task.status,
|
||
|
|
session_id=task.session_id,
|
||
|
|
schedule=task.schedule,
|
||
|
|
created_at=task.created_at.isoformat()
|
||
|
|
if task.created_at
|
||
|
|
else datetime.now().isoformat(),
|
||
|
|
started_at=task.started_at.isoformat() if task.started_at else None,
|
||
|
|
finished_at=task.finished_at.isoformat() if task.finished_at else None,
|
||
|
|
error=task.error,
|
||
|
|
)
|
||
|
|
self._history.append(history.model_dump())
|
||
|
|
self.save()
|
||
|
|
logger.info(f"Added task {task.id} to history")
|
||
|
|
|
||
|
|
def get_history(self, limit: int | None = None) -> list[TaskHistory]:
|
||
|
|
history = [TaskHistory(**h) for h in self._history]
|
||
|
|
if limit:
|
||
|
|
return history[-limit:]
|
||
|
|
return history
|
||
|
|
|
||
|
|
def clear_history(self):
|
||
|
|
self._history = []
|
||
|
|
self.save()
|
||
|
|
logger.info("Cleared task history")
|
||
|
|
|
||
|
|
|
||
|
|
history_service = HistoryService()
|