from __future__ import annotations import json import subprocess import time from datetime import UTC, datetime from pathlib import Path from typing import Any def init_queue(path: Path) -> None: path.parent.mkdir(parents=True, exist_ok=True) if not path.exists(): path.write_text("", encoding="utf-8") def add_job(path: Path, name: str, command: str, cwd: str = ".", metadata: dict[str, Any] | None = None) -> dict[str, Any]: init_queue(path) job = { "id": f"{int(time.time() * 1000)}-{name}", "name": name, "command": command, "cwd": cwd, "status": "pending", "created_at": datetime.now(UTC).isoformat(), "metadata": metadata or {}, } with path.open("a", encoding="utf-8") as handle: handle.write(json.dumps(job, sort_keys=True) + "\n") return job def read_jobs(path: Path) -> list[dict[str, Any]]: if not path.exists(): return [] jobs = [] with path.open("r", encoding="utf-8") as handle: for line in handle: if line.strip(): jobs.append(json.loads(line)) return jobs def run_next(path: Path, log_dir: Path) -> dict[str, Any] | None: jobs = read_jobs(path) for job in jobs: if job.get("status") == "pending": return _run_job(path, log_dir, jobs, job) return None def _run_job(path: Path, log_dir: Path, jobs: list[dict[str, Any]], job: dict[str, Any]) -> dict[str, Any]: log_dir.mkdir(parents=True, exist_ok=True) job["status"] = "running" job["started_at"] = datetime.now(UTC).isoformat() _rewrite(path, jobs) log_path = log_dir / f"{job['id']}.log" with log_path.open("w", encoding="utf-8") as log: proc = subprocess.run(job["command"], cwd=job.get("cwd", "."), shell=True, text=True, stdout=log, stderr=subprocess.STDOUT) job["status"] = "complete" if proc.returncode == 0 else "failed" job["returncode"] = proc.returncode job["completed_at"] = datetime.now(UTC).isoformat() job["log_path"] = str(log_path) _rewrite(path, jobs) return job def _rewrite(path: Path, jobs: list[dict[str, Any]]) -> None: with path.open("w", encoding="utf-8") as handle: for job in jobs: handle.write(json.dumps(job, sort_keys=True) + "\n")