from hyrex import HyrexKV
import json
from datetime import datetime
@hy.task
def task_with_metrics(data: dict):
start_time = datetime.now()
try:
# Process data
result = process(data)
# Track success metrics
metrics = {
"status": "success",
"duration": (datetime.now() - start_time).total_seconds(),
"timestamp": datetime.now().isoformat(),
"items_processed": len(result)
}
except Exception as e:
# Track failure metrics
metrics = {
"status": "error",
"error": str(e),
"duration": (datetime.now() - start_time).total_seconds(),
"timestamp": datetime.now().isoformat()
}
raise
finally:
# Store metrics
task_name = get_hyrex_context().task_name if get_hyrex_context() else "unknown"
HyrexKV.set(f"metrics:{task_name}:{datetime.now().timestamp()}", json.dumps(metrics))
return result