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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import os
|
| 3 |
+
import secrets
|
| 4 |
+
import threading
|
| 5 |
+
import time
|
| 6 |
+
from contextlib import asynccontextmanager, suppress
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from datetime import datetime, timezone
|
| 9 |
+
from typing import Callable, Dict, List, Literal, Optional
|
| 10 |
+
|
| 11 |
+
from fastapi import APIRouter, Body, Depends, HTTPException, Query
|
| 12 |
+
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
| 13 |
+
from pydantic import BaseModel, Field
|
| 14 |
+
|
| 15 |
+
# ---------------------------------------------------------------------------
|
| 16 |
+
# Utilities
|
| 17 |
+
# ---------------------------------------------------------------------------
|
| 18 |
+
|
| 19 |
+
def _now() -> float:
|
| 20 |
+
return time.time()
|
| 21 |
+
|
| 22 |
+
def iso_from_ts(ts: float) -> str:
|
| 23 |
+
return (
|
| 24 |
+
datetime.fromtimestamp(ts, tz=timezone.utc)
|
| 25 |
+
.isoformat(timespec="seconds")
|
| 26 |
+
.replace("+00:00", "Z")
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
def generate_job_id() -> str:
|
| 30 |
+
return "job_" + secrets.token_hex(6)
|
| 31 |
+
|
| 32 |
+
# ---------------------------------------------------------------------------
|
| 33 |
+
# Settings
|
| 34 |
+
# ---------------------------------------------------------------------------
|
| 35 |
+
|
| 36 |
+
@dataclass
|
| 37 |
+
class Settings:
|
| 38 |
+
github_shared_secret: str = os.getenv("GITHUB_SHARED_SECRET", "")
|
| 39 |
+
desktop_api_key: str = os.getenv("DESKTOP_API_KEY", "")
|
| 40 |
+
claim_timeout_buffer: float = float(os.getenv("CLAIM_TIMEOUT_BUFFER_SECONDS", "60"))
|
| 41 |
+
liveness_window: float = float(os.getenv("LIVENESS_WINDOW_SECONDS", "60"))
|
| 42 |
+
max_retries: int = int(os.getenv("MAX_RETRIES", "3"))
|
| 43 |
+
retention_seconds: float = float(os.getenv("RESULT_RETENTION_SECONDS", "3600"))
|
| 44 |
+
|
| 45 |
+
# ---------------------------------------------------------------------------
|
| 46 |
+
# Pydantic Models
|
| 47 |
+
# ---------------------------------------------------------------------------
|
| 48 |
+
|
| 49 |
+
class Environment(BaseModel):
|
| 50 |
+
platform: str
|
| 51 |
+
os_version: str
|
| 52 |
+
python_versions: List[str]
|
| 53 |
+
notes: Optional[str] = None
|
| 54 |
+
|
| 55 |
+
class WorkerRegisterRequest(BaseModel):
|
| 56 |
+
worker_id: int
|
| 57 |
+
url: str
|
| 58 |
+
environment: Environment
|
| 59 |
+
|
| 60 |
+
class PollRequest(BaseModel):
|
| 61 |
+
worker_id: int
|
| 62 |
+
|
| 63 |
+
class DoneRequest(BaseModel):
|
| 64 |
+
worker_id: int
|
| 65 |
+
url: str
|
| 66 |
+
|
| 67 |
+
class JobSubmission(BaseModel):
|
| 68 |
+
job_id: Optional[str] = None
|
| 69 |
+
python_version: str
|
| 70 |
+
platform: str = "windows"
|
| 71 |
+
entry_point: str
|
| 72 |
+
files: Dict[str, str]
|
| 73 |
+
dependencies: List[str] = Field(default_factory=list)
|
| 74 |
+
network_required: bool = False
|
| 75 |
+
stdin: Optional[str] = None
|
| 76 |
+
timeout: float
|
| 77 |
+
|
| 78 |
+
Category = Literal[
|
| 79 |
+
"success",
|
| 80 |
+
"timeout",
|
| 81 |
+
"dependency_install_failed",
|
| 82 |
+
"infra_failure",
|
| 83 |
+
"checker_error",
|
| 84 |
+
"not_applicable",
|
| 85 |
+
]
|
| 86 |
+
|
| 87 |
+
class ResultObject(BaseModel):
|
| 88 |
+
job_id: str
|
| 89 |
+
stdout: str
|
| 90 |
+
stderr: str
|
| 91 |
+
exit_code: int
|
| 92 |
+
timed_out: bool
|
| 93 |
+
category: Category
|
| 94 |
+
failure_reason: Optional[str] = None
|
| 95 |
+
network_activity_detected: Optional[bool] = None
|
| 96 |
+
|
| 97 |
+
# ---------------------------------------------------------------------------
|
| 98 |
+
# In‑Memory Store
|
| 99 |
+
# ---------------------------------------------------------------------------
|
| 100 |
+
|
| 101 |
+
class MemoryStore:
|
| 102 |
+
def __init__(self, settings: Settings, clock: Callable[[], float] = _now):
|
| 103 |
+
self.settings = settings
|
| 104 |
+
self.clock = clock
|
| 105 |
+
self.lock = threading.RLock()
|
| 106 |
+
self.workers: Dict[int, dict] = {}
|
| 107 |
+
self.jobs: Dict[str, dict] = {}
|
| 108 |
+
self.start_time = self.clock()
|
| 109 |
+
self.total_submitted = 0
|
| 110 |
+
self.total_completed = 0
|
| 111 |
+
|
| 112 |
+
# --- Registration ------------------------------------------------------
|
| 113 |
+
def register_worker(self, worker_id: int, url: str, environment: dict) -> dict:
|
| 114 |
+
with self.lock:
|
| 115 |
+
now = self.clock()
|
| 116 |
+
worker = self.workers.get(worker_id)
|
| 117 |
+
|
| 118 |
+
if worker is None:
|
| 119 |
+
worker = {
|
| 120 |
+
"worker_id": worker_id,
|
| 121 |
+
"url": url,
|
| 122 |
+
"environment": environment,
|
| 123 |
+
"registered_at": now,
|
| 124 |
+
"last_seen_at": now,
|
| 125 |
+
"reported_done": False,
|
| 126 |
+
}
|
| 127 |
+
self.workers[worker_id] = worker
|
| 128 |
+
else:
|
| 129 |
+
worker["url"] = url
|
| 130 |
+
worker["environment"] = environment
|
| 131 |
+
worker["last_seen_at"] = now
|
| 132 |
+
worker["registered_at"] = now
|
| 133 |
+
worker["reported_done"] = False
|
| 134 |
+
|
| 135 |
+
return self._worker_public_locked(worker_id, now)
|
| 136 |
+
|
| 137 |
+
# --- Polling -----------------------------------------------------------
|
| 138 |
+
def poll_job(self, worker_id: int):
|
| 139 |
+
with self.lock:
|
| 140 |
+
worker = self.workers.get(worker_id)
|
| 141 |
+
if worker is None:
|
| 142 |
+
raise KeyError("worker not registered")
|
| 143 |
+
|
| 144 |
+
now = self.clock()
|
| 145 |
+
# Update last_seen regardless
|
| 146 |
+
worker["last_seen_at"] = now
|
| 147 |
+
|
| 148 |
+
# Check liveness
|
| 149 |
+
if worker.get("reported_done") or (now - worker["last_seen_at"]) > self.settings.liveness_window:
|
| 150 |
+
return None
|
| 151 |
+
|
| 152 |
+
# Check if this worker instance (by URL) is already busy
|
| 153 |
+
for job in self.jobs.values():
|
| 154 |
+
if job["status"] == "claimed" and job.get("claimed_by") == worker_id and job.get("claimed_worker_url") == worker["url"]:
|
| 155 |
+
return None
|
| 156 |
+
|
| 157 |
+
eligible = []
|
| 158 |
+
for job in self.jobs.values():
|
| 159 |
+
if job["status"] != "queued":
|
| 160 |
+
continue
|
| 161 |
+
if job["platform"] != worker["environment"].get("platform"):
|
| 162 |
+
continue
|
| 163 |
+
if job["python_version"] in worker["environment"].get("python_versions", []):
|
| 164 |
+
eligible.append(job)
|
| 165 |
+
|
| 166 |
+
if not eligible:
|
| 167 |
+
return None
|
| 168 |
+
|
| 169 |
+
eligible.sort(key=lambda j: j["submitted_at"])
|
| 170 |
+
job = eligible[0]
|
| 171 |
+
|
| 172 |
+
job["status"] = "claimed"
|
| 173 |
+
job["claimed_by"] = worker_id
|
| 174 |
+
job["claimed_worker_url"] = worker["url"]
|
| 175 |
+
job["claimed_at"] = now
|
| 176 |
+
job["claim_deadline"] = (
|
| 177 |
+
now + job["timeout"] + self.settings.claim_timeout_buffer
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
return self._public_job(job)
|
| 181 |
+
|
| 182 |
+
# --- Result Reporting ---------------------------------------------------
|
| 183 |
+
def report_result(self, worker_id: int, url: str, result: ResultObject) -> None:
|
| 184 |
+
with self.lock:
|
| 185 |
+
job = self.jobs.get(result.job_id)
|
| 186 |
+
if job is None:
|
| 187 |
+
raise KeyError("job not found")
|
| 188 |
+
if job.get("claimed_by") != worker_id or job.get("claimed_worker_url") != url:
|
| 189 |
+
raise PermissionError("job is not claimed by this worker instance")
|
| 190 |
+
|
| 191 |
+
now = self.clock()
|
| 192 |
+
job["status"] = "complete"
|
| 193 |
+
job["result"] = result.model_dump()
|
| 194 |
+
job["completed_at"] = now
|
| 195 |
+
job["claimed_by"] = None
|
| 196 |
+
job["claimed_worker_url"] = None
|
| 197 |
+
job["claimed_at"] = None
|
| 198 |
+
job["claim_deadline"] = None
|
| 199 |
+
|
| 200 |
+
self.total_completed += 1
|
| 201 |
+
|
| 202 |
+
worker = self.workers.get(worker_id)
|
| 203 |
+
if worker is not None:
|
| 204 |
+
worker["last_seen_at"] = now
|
| 205 |
+
|
| 206 |
+
# --- Graceful Shutdown --------------------------------------------------
|
| 207 |
+
def report_done(self, worker_id: int, url: str) -> List[str]:
|
| 208 |
+
with self.lock:
|
| 209 |
+
worker = self.workers.get(worker_id)
|
| 210 |
+
if worker is None:
|
| 211 |
+
return []
|
| 212 |
+
|
| 213 |
+
# Ignore if the URL doesn't match current registration
|
| 214 |
+
if worker["url"] != url:
|
| 215 |
+
return []
|
| 216 |
+
|
| 217 |
+
now = self.clock()
|
| 218 |
+
worker["reported_done"] = True
|
| 219 |
+
worker["last_seen_at"] = now
|
| 220 |
+
|
| 221 |
+
released = []
|
| 222 |
+
for job in list(self.jobs.values()):
|
| 223 |
+
if job["status"] == "claimed" and job["claimed_by"] == worker_id and job.get("claimed_worker_url") == url:
|
| 224 |
+
self._abandon_claim_locked(job, "worker reported done", now)
|
| 225 |
+
released.append(job["job_id"])
|
| 226 |
+
|
| 227 |
+
return released
|
| 228 |
+
|
| 229 |
+
# --- Job Submission -----------------------------------------------------
|
| 230 |
+
def submit_job(self, job_data: JobSubmission) -> str:
|
| 231 |
+
with self.lock:
|
| 232 |
+
job_id = job_data.job_id or generate_job_id()
|
| 233 |
+
if job_id in self.jobs:
|
| 234 |
+
raise ValueError("job_id already exists")
|
| 235 |
+
|
| 236 |
+
now = self.clock()
|
| 237 |
+
self.jobs[job_id] = {
|
| 238 |
+
"job_id": job_id,
|
| 239 |
+
"python_version": job_data.python_version,
|
| 240 |
+
"platform": job_data.platform,
|
| 241 |
+
"entry_point": job_data.entry_point,
|
| 242 |
+
"files": job_data.files,
|
| 243 |
+
"dependencies": job_data.dependencies,
|
| 244 |
+
"network_required": job_data.network_required,
|
| 245 |
+
"stdin": job_data.stdin,
|
| 246 |
+
"timeout": job_data.timeout,
|
| 247 |
+
"status": "queued",
|
| 248 |
+
"submitted_at": now,
|
| 249 |
+
"retry_count": 0,
|
| 250 |
+
"claimed_by": None,
|
| 251 |
+
"claimed_worker_url": None,
|
| 252 |
+
"claimed_at": None,
|
| 253 |
+
"claim_deadline": None,
|
| 254 |
+
"result": None,
|
| 255 |
+
"completed_at": None,
|
| 256 |
+
"last_abandon_reason": None,
|
| 257 |
+
}
|
| 258 |
+
self.total_submitted += 1
|
| 259 |
+
return job_id
|
| 260 |
+
|
| 261 |
+
# --- Query Methods -------------------------------------------------------
|
| 262 |
+
def get_job(self, job_id: str):
|
| 263 |
+
with self.lock:
|
| 264 |
+
job = self.jobs.get(job_id)
|
| 265 |
+
if job is None:
|
| 266 |
+
return None, None
|
| 267 |
+
|
| 268 |
+
if job["status"] == "complete":
|
| 269 |
+
return "complete", job["result"]
|
| 270 |
+
|
| 271 |
+
matching = self._matching_worker_ids_locked(job)
|
| 272 |
+
return "pending", {
|
| 273 |
+
"retry_count": job["retry_count"],
|
| 274 |
+
"matching_worker_ids": matching,
|
| 275 |
+
"last_abandon_reason": job.get("last_abandon_reason"),
|
| 276 |
+
"submitted_at": iso_from_ts(job["submitted_at"]),
|
| 277 |
+
}
|
| 278 |
+
|
| 279 |
+
def list_workers(self) -> List[dict]:
|
| 280 |
+
with self.lock:
|
| 281 |
+
now = self.clock()
|
| 282 |
+
return [self._worker_public_locked(worker["worker_id"], now) for worker in self.workers.values()]
|
| 283 |
+
|
| 284 |
+
def list_jobs(self) -> List[dict]:
|
| 285 |
+
with self.lock:
|
| 286 |
+
result = []
|
| 287 |
+
for job in self.jobs.values():
|
| 288 |
+
item = {
|
| 289 |
+
"job_id": job["job_id"],
|
| 290 |
+
"status": job["status"],
|
| 291 |
+
"submitted_at": iso_from_ts(job["submitted_at"]),
|
| 292 |
+
"python_version": job["python_version"],
|
| 293 |
+
"platform": job["platform"],
|
| 294 |
+
"retry_count": job["retry_count"],
|
| 295 |
+
"claimed_by": job.get("claimed_by"),
|
| 296 |
+
"claimed_worker_url": job.get("claimed_worker_url"),
|
| 297 |
+
"claim_deadline": iso_from_ts(job["claim_deadline"]) if job.get("claim_deadline") else None,
|
| 298 |
+
"matching_worker_ids": self._matching_worker_ids_locked(job),
|
| 299 |
+
"last_abandon_reason": job.get("last_abandon_reason"),
|
| 300 |
+
}
|
| 301 |
+
if job["status"] == "complete" and job.get("result"):
|
| 302 |
+
item["result"] = job["result"]
|
| 303 |
+
result.append(item)
|
| 304 |
+
return result
|
| 305 |
+
|
| 306 |
+
def get_status(self) -> dict:
|
| 307 |
+
with self.lock:
|
| 308 |
+
now = self.clock()
|
| 309 |
+
queued = sum(1 for j in self.jobs.values() if j["status"] == "queued")
|
| 310 |
+
claimed = sum(1 for j in self.jobs.values() if j["status"] == "claimed")
|
| 311 |
+
complete = sum(1 for j in self.jobs.values() if j["status"] == "complete")
|
| 312 |
+
|
| 313 |
+
claimed_by_worker = {}
|
| 314 |
+
for j in self.jobs.values():
|
| 315 |
+
if j["status"] == "claimed":
|
| 316 |
+
wid = j.get("claimed_by")
|
| 317 |
+
if wid is not None:
|
| 318 |
+
claimed_by_worker[wid] = claimed_by_worker.get(wid, 0) + 1
|
| 319 |
+
|
| 320 |
+
workers = []
|
| 321 |
+
for wid, w in self.workers.items():
|
| 322 |
+
workers.append({
|
| 323 |
+
"worker_id": wid,
|
| 324 |
+
"url": w["url"],
|
| 325 |
+
"platform": w["environment"].get("platform"),
|
| 326 |
+
"status": self._status_locked(wid, now),
|
| 327 |
+
"claimed_jobs": claimed_by_worker.get(wid, 0),
|
| 328 |
+
"last_seen_at": iso_from_ts(w["last_seen_at"]),
|
| 329 |
+
"registered_at": iso_from_ts(w["registered_at"]),
|
| 330 |
+
})
|
| 331 |
+
|
| 332 |
+
return {
|
| 333 |
+
"uptime_seconds": now - self.start_time,
|
| 334 |
+
"total_submitted": self.total_submitted,
|
| 335 |
+
"total_completed": self.total_completed,
|
| 336 |
+
"jobs_by_status": {
|
| 337 |
+
"queued": queued,
|
| 338 |
+
"claimed": claimed,
|
| 339 |
+
"complete": complete,
|
| 340 |
+
},
|
| 341 |
+
"workers": workers,
|
| 342 |
+
"claimed_by_worker": claimed_by_worker,
|
| 343 |
+
}
|
| 344 |
+
|
| 345 |
+
# --- Background Cleanup --------------------------------------------------
|
| 346 |
+
def process_expired_claims(self) -> None:
|
| 347 |
+
with self.lock:
|
| 348 |
+
now = self.clock()
|
| 349 |
+
for job in list(self.jobs.values()):
|
| 350 |
+
if (job["status"] == "claimed" and job.get("claim_deadline") and now >= job["claim_deadline"]):
|
| 351 |
+
self._abandon_claim_locked(job, "claim timeout", now)
|
| 352 |
+
|
| 353 |
+
def cleanup_completed(self) -> None:
|
| 354 |
+
with self.lock:
|
| 355 |
+
now = self.clock()
|
| 356 |
+
for job_id in list(self.jobs):
|
| 357 |
+
job = self.jobs[job_id]
|
| 358 |
+
if (job["status"] == "complete" and job.get("completed_at") and (now - job["completed_at"]) > self.settings.retention_seconds):
|
| 359 |
+
del self.jobs[job_id]
|
| 360 |
+
|
| 361 |
+
# --- Internal Helpers ----------------------------------------------------
|
| 362 |
+
def _abandon_claim_locked(self, job: dict, reason: str, now: float) -> None:
|
| 363 |
+
if job.get("retry_count", 0) >= self.settings.max_retries:
|
| 364 |
+
job["status"] = "complete"
|
| 365 |
+
job["result"] = {
|
| 366 |
+
"job_id": job["job_id"],
|
| 367 |
+
"stdout": "",
|
| 368 |
+
"stderr": "",
|
| 369 |
+
"exit_code": 1,
|
| 370 |
+
"timed_out": False,
|
| 371 |
+
"category": "infra_failure",
|
| 372 |
+
"failure_reason": f"job abandoned more than {self.settings.max_retries} times ({reason})",
|
| 373 |
+
"network_activity_detected": None,
|
| 374 |
+
}
|
| 375 |
+
job["completed_at"] = now
|
| 376 |
+
job["claimed_by"] = None
|
| 377 |
+
job["claimed_worker_url"] = None
|
| 378 |
+
job["claimed_at"] = None
|
| 379 |
+
job["claim_deadline"] = None
|
| 380 |
+
self.total_completed += 1
|
| 381 |
+
else:
|
| 382 |
+
job["retry_count"] = job.get("retry_count", 0) + 1
|
| 383 |
+
job["status"] = "queued"
|
| 384 |
+
job["claimed_by"] = None
|
| 385 |
+
job["claimed_worker_url"] = None
|
| 386 |
+
job["claimed_at"] = None
|
| 387 |
+
job["claim_deadline"] = None
|
| 388 |
+
job["last_abandon_reason"] = reason
|
| 389 |
+
|
| 390 |
+
def _matching_worker_ids_locked(self, job: dict) -> List[int]:
|
| 391 |
+
matching = []
|
| 392 |
+
for worker_id, worker in self.workers.items():
|
| 393 |
+
if job.get("platform") != worker["environment"].get("platform"):
|
| 394 |
+
continue
|
| 395 |
+
if job.get("python_version") in worker["environment"].get("python_versions", []):
|
| 396 |
+
matching.append(worker_id)
|
| 397 |
+
return matching
|
| 398 |
+
|
| 399 |
+
def _status_locked(self, worker_id: int, now: float) -> str:
|
| 400 |
+
worker = self.workers.get(worker_id)
|
| 401 |
+
if worker is None:
|
| 402 |
+
return "unresponsive"
|
| 403 |
+
if worker.get("reported_done") or (now - worker["last_seen_at"]) > self.settings.liveness_window:
|
| 404 |
+
return "unresponsive"
|
| 405 |
+
for job in self.jobs.values():
|
| 406 |
+
if job["status"] == "claimed" and job.get("claimed_by") == worker_id and job.get("claimed_worker_url") == worker["url"]:
|
| 407 |
+
return "busy"
|
| 408 |
+
return "idle"
|
| 409 |
+
|
| 410 |
+
def _worker_public_locked(self, worker_id: int, now: float) -> dict:
|
| 411 |
+
worker = self.workers[worker_id]
|
| 412 |
+
return {
|
| 413 |
+
"worker_id": worker["worker_id"],
|
| 414 |
+
"url": worker["url"],
|
| 415 |
+
"environment": worker["environment"],
|
| 416 |
+
"registered_at": iso_from_ts(worker["registered_at"]),
|
| 417 |
+
"last_seen_at": iso_from_ts(worker["last_seen_at"]),
|
| 418 |
+
"status": self._status_locked(worker_id, now),
|
| 419 |
+
}
|
| 420 |
+
|
| 421 |
+
@staticmethod
|
| 422 |
+
def _public_job(job: dict) -> dict:
|
| 423 |
+
return {
|
| 424 |
+
"job_id": job["job_id"],
|
| 425 |
+
"python_version": job["python_version"],
|
| 426 |
+
"platform": job["platform"],
|
| 427 |
+
"entry_point": job["entry_point"],
|
| 428 |
+
"files": job["files"],
|
| 429 |
+
"dependencies": job["dependencies"],
|
| 430 |
+
"network_required": job["network_required"],
|
| 431 |
+
"stdin": job["stdin"],
|
| 432 |
+
"timeout": job["timeout"],
|
| 433 |
+
}
|
| 434 |
+
|
| 435 |
+
# ---------------------------------------------------------------------------
|
| 436 |
+
# Global Store and Background Task
|
| 437 |
+
# ---------------------------------------------------------------------------
|
| 438 |
+
|
| 439 |
+
settings = Settings()
|
| 440 |
+
store = MemoryStore(settings)
|
| 441 |
+
|
| 442 |
+
def _background_loop():
|
| 443 |
+
while True:
|
| 444 |
+
time.sleep(1)
|
| 445 |
+
store.process_expired_claims()
|
| 446 |
+
store.cleanup_completed()
|
| 447 |
+
|
| 448 |
+
threading.Thread(target=_background_loop, daemon=True).start()
|
| 449 |
+
|
| 450 |
+
# ---------------------------------------------------------------------------
|
| 451 |
+
# APIRouter Definition
|
| 452 |
+
# ---------------------------------------------------------------------------
|
| 453 |
+
|
| 454 |
+
router = APIRouter()
|
| 455 |
+
security = HTTPBearer(auto_error=False)
|
| 456 |
+
|
| 457 |
+
def worker_auth(credentials: HTTPAuthorizationCredentials = Depends(security)):
|
| 458 |
+
expected = settings.github_shared_secret
|
| 459 |
+
if (not expected or not credentials or credentials.scheme.lower() != "bearer"
|
| 460 |
+
or not secrets.compare_digest(credentials.credentials.encode(), expected.encode())):
|
| 461 |
+
raise HTTPException(status_code=401, detail="Unauthorized")
|
| 462 |
+
|
| 463 |
+
def desktop_auth(credentials: HTTPAuthorizationCredentials = Depends(security)):
|
| 464 |
+
expected = settings.desktop_api_key
|
| 465 |
+
if (not expected or not credentials or credentials.scheme.lower() != "bearer"
|
| 466 |
+
or not secrets.compare_digest(credentials.credentials.encode(), expected.encode())):
|
| 467 |
+
raise HTTPException(status_code=401, detail="Unauthorized")
|
| 468 |
+
|
| 469 |
+
# Worker endpoints
|
| 470 |
+
@router.post("/worker/register", dependencies=[Depends(worker_auth)])
|
| 471 |
+
def worker_register(body: WorkerRegisterRequest):
|
| 472 |
+
return store.register_worker(body.worker_id, body.url, body.environment.model_dump())
|
| 473 |
+
|
| 474 |
+
@router.post("/worker/poll", dependencies=[Depends(worker_auth)])
|
| 475 |
+
def worker_poll(body: PollRequest):
|
| 476 |
+
try:
|
| 477 |
+
job = store.poll_job(body.worker_id)
|
| 478 |
+
return {"job": job}
|
| 479 |
+
except KeyError:
|
| 480 |
+
raise HTTPException(status_code=404, detail="Worker not registered")
|
| 481 |
+
|
| 482 |
+
@router.post("/worker/result", dependencies=[Depends(worker_auth)])
|
| 483 |
+
def worker_result(
|
| 484 |
+
worker_id: int = Query(...),
|
| 485 |
+
url: str = Query(...),
|
| 486 |
+
result: ResultObject = Body(...),
|
| 487 |
+
):
|
| 488 |
+
try:
|
| 489 |
+
store.report_result(worker_id, url, result)
|
| 490 |
+
return {"status": "complete", "job_id": result.job_id}
|
| 491 |
+
except KeyError:
|
| 492 |
+
raise HTTPException(status_code=404, detail="Job not found")
|
| 493 |
+
except PermissionError:
|
| 494 |
+
raise HTTPException(status_code=409, detail="Job not claimed by this worker")
|
| 495 |
+
|
| 496 |
+
@router.post("/worker/done", dependencies=[Depends(worker_auth)])
|
| 497 |
+
def worker_done(body: DoneRequest):
|
| 498 |
+
released = store.report_done(body.worker_id, body.url)
|
| 499 |
+
return {"released_job_ids": released}
|
| 500 |
+
|
| 501 |
+
# Desktop endpoints
|
| 502 |
+
@router.post("/desktop/job", dependencies=[Depends(desktop_auth)])
|
| 503 |
+
def desktop_submit_job(body: JobSubmission):
|
| 504 |
+
try:
|
| 505 |
+
job_id = store.submit_job(body)
|
| 506 |
+
return {"job_id": job_id, "status": "queued"}
|
| 507 |
+
except ValueError:
|
| 508 |
+
raise HTTPException(status_code=409, detail="job_id already exists")
|
| 509 |
+
|
| 510 |
+
@router.get("/desktop/job/{job_id}", dependencies=[Depends(desktop_auth)])
|
| 511 |
+
def desktop_get_result(job_id: str):
|
| 512 |
+
status, data = store.get_job(job_id)
|
| 513 |
+
if status is None:
|
| 514 |
+
raise HTTPException(status_code=404, detail="Job not found")
|
| 515 |
+
if status == "complete":
|
| 516 |
+
return {"status": "complete", "result": data}
|
| 517 |
+
return {"status": "pending", **data}
|
| 518 |
+
|
| 519 |
+
@router.get("/desktop/workers", dependencies=[Depends(desktop_auth)])
|
| 520 |
+
def desktop_list_workers():
|
| 521 |
+
return store.list_workers()
|
| 522 |
+
|
| 523 |
+
@router.get("/desktop/jobs", dependencies=[Depends(desktop_auth)])
|
| 524 |
+
def desktop_list_jobs():
|
| 525 |
+
return store.list_jobs()
|
| 526 |
+
|
| 527 |
+
@router.get("/desktop/status", dependencies=[Depends(desktop_auth)])
|
| 528 |
+
def desktop_status():
|
| 529 |
+
return store.get_status()
|