Skip to content

Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)

Keep slow uploads from blocking job cancellation

Cinna Davis9d6fc00ae12c
diff --git a/src/dopplergeist/jobs.py b/src/dopplergeist/jobs.py
index 18ce61f..5214806 100644
--- a/src/dopplergeist/jobs.py
+++ b/src/dopplergeist/jobs.py
@@ -57,6 +57,8 @@ class JobManager:
self._lockfile.close()
raise ValueError("Another job manager is using this directory") from None
self._mutex = threading.RLock()
+ self._uploads_changed = threading.Condition(self._mutex)
+ self._uploads = 0
self._serial = threading.Semaphore(1)
self._threads = {}
self._processes = {}
@@ -89,11 +91,13 @@ class JobManager:
with self._mutex:
if self._closed:
raise ValueError("Service is shutting down")
- if sum(thread.is_alive() for thread in self._threads.values()) >= self.max_pending:
+ if self._uploads + sum(thread.is_alive() for thread in self._threads.values()) >= self.max_pending:
raise OverflowError("Job queue is full; try again after a job finishes")
job_id = uuid.uuid4().hex
directory = self.root / job_id
directory.mkdir(mode=0o700)
+ self._uploads += 1
+ try:
suffix = suffix.lower() if suffix.lower() in {".mp3", ".wav", ".flac", ".m4a", ".ogg"} else ".mp3"
audio = directory / ("input" + suffix)
digest = hashlib.sha256()
@@ -107,15 +111,23 @@ class JobManager:
target.write(block)
digest.update(block)
remaining -= len(block)
- request["audio_path"] = str(audio)
- write_json(directory / "request.json", request)
- write_json(directory / "operator.json", self.config)
- write_json(directory / "input.json", {"sha256": digest.hexdigest(), "bytes": size, "path": audio.name})
- queued = result(directory, "queued", stage="queued", progress=0)
- thread = threading.Thread(target=self._run, args=(directory,), daemon=True)
- self._threads[job_id] = thread
- thread.start()
- return queued
+ with self._mutex:
+ if self._closed:
+ result(directory, "failed", reason_code="interrupted", message="Service stopped during upload.")
+ raise ValueError("Service is shutting down")
+ request["audio_path"] = str(audio)
+ write_json(directory / "request.json", request)
+ write_json(directory / "operator.json", self.config)
+ write_json(directory / "input.json", {"sha256": digest.hexdigest(), "bytes": size, "path": audio.name})
+ queued = result(directory, "queued", stage="queued", progress=0)
+ thread = threading.Thread(target=self._run, args=(directory,), daemon=True)
+ self._threads[job_id] = thread
+ thread.start()
+ return queued
+ finally:
+ with self._uploads_changed:
+ self._uploads -= 1
+ self._uploads_changed.notify_all()
def _run(self, directory):
try:
@@ -180,9 +192,12 @@ class JobManager:
def close(self):
with self._mutex:
self._closed = True
+ self._uploads_changed.notify_all()
for job_id, thread in list(self._threads.items()):
if thread.is_alive():
self.cancel(job_id)
+ while self._uploads:
+ self._uploads_changed.wait()
for thread in list(self._threads.values()):
thread.join()
self._lockfile.close()
diff --git a/tests/test_upload_concurrency.py b/tests/test_upload_concurrency.py
new file mode 100644
index 0000000..0630898
--- /dev/null
+++ b/tests/test_upload_concurrency.py
@@ -0,0 +1,93 @@
+"""Job transport synchronization; these byte streams are not audio fixtures."""
+import io
+import threading
+
+import pytest
+
+from dopplergeist.jobs import JobManager
+
+
+class PausedStream(io.BytesIO):
+ def __init__(self):
+ super().__init__(b"upload transport bytes")
+ self.started = threading.Event()
+ self.release = threading.Event()
+
+ def read(self, size=-1):
+ self.started.set()
+ if not self.release.wait(5):
+ raise TimeoutError("upload test did not release stream")
+ return super().read(size)
+
+
+def test_slow_upload_does_not_block_cancel_and_reserves_queue_slot(tmp_path):
+ manager = JobManager(tmp_path, max_pending=2)
+ manager._serial.acquire()
+ stream = PausedStream()
+ upload = None
+ try:
+ first = manager.submit({"schema_version": 1}, io.BytesIO(b"first"), 5)
+ uploaded = []
+ upload = threading.Thread(target=lambda: uploaded.append(manager.submit(
+ {"schema_version": 1}, stream, len(stream.getvalue()))))
+ upload.start()
+ assert stream.started.wait(5)
+ cancelled = threading.Event()
+ cancel = threading.Thread(target=lambda: (manager.cancel(first["job_id"]), cancelled.set()))
+ cancel.start()
+ assert cancelled.wait(1), "cancellation blocked behind upload"
+ cancel.join()
+ with pytest.raises(OverflowError):
+ manager.submit({"schema_version": 1}, io.BytesIO(b"third"), 5)
+ stream.release.set()
+ upload.join(5)
+ assert not upload.is_alive() and uploaded[0]["status"] == "queued"
+ assert manager.get(first["job_id"])["status"] == "cancelled"
+ finally:
+ stream.release.set()
+ if upload:
+ upload.join(5)
+ manager._serial.release()
+ manager.close()
+
+
+def test_shutdown_waits_for_upload_and_does_not_launch_it(tmp_path):
+ manager = JobManager(tmp_path)
+ stream = PausedStream()
+ errors = []
+
+ def submit():
+ try:
+ manager.submit({"schema_version": 1}, stream, len(stream.getvalue()))
+ except ValueError as exc:
+ errors.append(str(exc))
+
+ upload = threading.Thread(target=submit)
+ upload.start()
+ assert stream.started.wait(5)
+ close = threading.Thread(target=manager.close)
+ close.start()
+ try:
+ with manager._uploads_changed:
+ assert manager._uploads_changed.wait_for(lambda: manager._closed, timeout=5)
+ assert close.is_alive()
+ finally:
+ stream.release.set()
+ upload.join(5)
+ close.join(5)
+ assert not upload.is_alive() and not close.is_alive()
+ assert errors == ["Service is shutting down"]
+ assert not manager._threads
+
+
+def test_incomplete_upload_releases_queue_slot(tmp_path):
+ manager = JobManager(tmp_path, max_pending=1)
+ manager._serial.acquire()
+ try:
+ with pytest.raises(ValueError, match="Incomplete upload"):
+ manager.submit({"schema_version": 1}, io.BytesIO(b"short"), 6)
+ job = manager.submit({"schema_version": 1}, io.BytesIO(b"next"), 4)
+ assert job["status"] == "queued"
+ finally:
+ manager._serial.release()
+ manager.close()