import os import json import datetime import fasteners # Para evitar colisiones de archivos HISTORY_FILE = "task_history.json" lock = fasteners.InterProcessLock("history.lock") def load_history(): if os.path.exists(HISTORY_FILE): try: with open(HISTORY_FILE, "r") as f: return json.load(f) except: return {} return {} def save_task_history(task_id, data): """Guarda o actualiza metadatos de la tarea con bloqueo de archivo""" with lock: history = load_history() history[task_id] = { **history.get(task_id, {}), **data, "updated_at": datetime.datetime.now().isoformat() } # Limitar historial a los Ășltimos 500 registros if len(history) > 500: sorted_keys = sorted(history.keys(), key=lambda x: history[x].get("updated_at", ""), reverse=True) history = {k: history[k] for k in sorted_keys[:500]} with open(HISTORY_FILE, "w") as f: json.dump(history, f, indent=2)