"""Acquire the fixed Gaia query through one bounded public asynchronous job.""" from collections.abc import Callable from pathlib import Path import math import re import time GAIA_SYNC_ENDPOINT = "https://gea.esac.esa.int/tap-server/tap/sync" GAIA_ASYNC_ENDPOINT = "https://gea.esac.esa.int/tap-server/tap/async" PENDING_PHASES = {"PENDING", "QUEUED", "EXECUTING", "UNKNOWN"} def download_gaia_async( request: Callable, source: dict, *, maximum_wait_seconds: float = 600, poll_interval_seconds: float = 15, monotonic: Callable = time.monotonic, sleep: Callable = time.sleep, ) -> Path: """Keep the query, result bytes and integrity checks identical to sync mode. request owns TLS, response-size accounting, receipt files and exact status checks. A returned job URL must stay on the fixed ESA endpoint. Polling never submits a second job, follows a redirect or fetches a different catalogue. """ if not all(math.isfinite(value) and value > 0 for value in [maximum_wait_seconds, poll_interval_seconds]) or maximum_wait_seconds > 600: raise ValueError("Gaia polling requires finite positive limits and at most 600 seconds") if ( source["url"] != GAIA_SYNC_ENDPOINT or source["name"] != "m67-gaia-dr3-cone.csv" ): raise ValueError("Async transport requires the fixed Gaia source recipe") _, headers = request( "gaia-job-submit.xml", GAIA_ASYNC_ENDPOINT, 32768, form={**source["form"], "PHASE": "RUN"}, expected_status=303, ) job_url = headers.get("location", "") if not re.fullmatch(re.escape(GAIA_ASYNC_ENDPOINT) + r"/[A-Za-z0-9-]+", job_url): raise ValueError("Gaia returned a job outside the exact ESA async endpoint") deadline = monotonic() + maximum_wait_seconds phase_index = 0 while True: remaining_seconds = deadline - monotonic() if remaining_seconds <= 0: raise TimeoutError( "Gaia query remains pending; its job URL is in the fetch receipt. " "No duplicate query was submitted." ) phase_file, _ = request( f"gaia-job-phase-{phase_index:03d}.txt", job_url + "/phase", 4096, timeout_seconds=min(30, remaining_seconds), ) phase = phase_file.read_text().strip() if phase == "COMPLETED": result, _ = request( source["name"], job_url + "/results/result", max(source["bytes"] + 200000, 500000), ) return result if phase not in PENDING_PHASES: raise RuntimeError(f"Gaia job ended in {phase!r}; see the fetch receipt") remaining_seconds = deadline - monotonic() if remaining_seconds <= 0: continue sleep(min(poll_interval_seconds, remaining_seconds)) phase_index += 1