|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Minimal stand-in for NABat's GraphQL API, for local dev/testing. |
| 3 | +
|
| 4 | +BatAI never uses a real GraphQL client: every query is a plain string, |
| 5 | +interpolated with literal IDs and POSTed as {"query": "..."}, with no |
| 6 | +variables and no schema. So instead of running a GraphQL server, this |
| 7 | +dispatches on substrings in the query text and returns canned JSON shaped |
| 8 | +like NABat's real responses. |
| 9 | +
|
| 10 | +Scope (for now): only the single-recording fetch flow, i.e. the query shapes used by: |
| 11 | + - bats_ai/core/tasks/nabat/nabat_data_retrieval.py (fetchAcousticAndSurveyEventInfo) |
| 12 | + - bats_ai/core/views/nabat/nabat_recording.py (bare presignedUrlFromAcousticFile, |
| 13 | + used as an access check by get_email_if_authorized / generate_nabat_recording; |
| 14 | + and the updateAcousticFileVet mutation, used to push an annotation to NABat) |
| 15 | +Anything else (species sync, NABat file lists) returns a GraphQL-shaped error |
| 16 | +rather than crashing, so it's obvious a handler needs to be added rather than |
| 17 | +failing confusingly downstream. |
| 18 | +
|
| 19 | +The combined query's response seeds one already-vetted species for every recording |
| 20 | +fetched (see SEED_ANNOTATION_*), so create_nabat_recording_from_response() picks it |
| 21 | +up and creates a matching NABatRecordingAnnotation automatically on first fetch - |
| 22 | +giving you something to see immediately rather than an empty annotation list. This |
| 23 | +requires a local Species row with a matching pk to already exist (the species-sync |
| 24 | +query isn't mocked); most dev databases already have one from prior real usage. |
| 25 | +
|
| 26 | +Presigned URLs are generated for real against the `minio` service already in |
| 27 | +docker-compose.yml, so the full download + spectrogram-generation pipeline |
| 28 | +runs end-to-end against real infrastructure. Run upload_recording.py to seed |
| 29 | +the object they point at (it also creates the bucket - this service never |
| 30 | +needs a live connection to minio at all, since presigning is pure local |
| 31 | +signing and does no network I/O). |
| 32 | +
|
| 33 | +Whoever downloads a presigned URL (the celery worker) needs to be able to |
| 34 | +resolve the host baked into it, and that host must match what the URL was |
| 35 | +signed with. Set MINIO_ENDPOINT accordingly: the compose-network name |
| 36 | +`minio:9000` if celery also runs in Docker (the default), or `localhost:9000` |
| 37 | +if celery runs natively on the host (see dev/.env.docker-compose-native), |
| 38 | +since only the published port is reachable from there. |
| 39 | +""" |
| 40 | + |
| 41 | +from __future__ import annotations |
| 42 | + |
| 43 | +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer |
| 44 | +import json |
| 45 | +import logging |
| 46 | +import os |
| 47 | +import re |
| 48 | + |
| 49 | +from minio import Minio |
| 50 | + |
| 51 | +logging.basicConfig(level=logging.INFO) |
| 52 | +logger = logging.getLogger("nabat-mock") |
| 53 | + |
| 54 | +MINIO_ENDPOINT = os.environ.get("MINIO_ENDPOINT", "minio:9000") |
| 55 | +MINIO_ACCESS_KEY = os.environ.get("MINIO_ACCESS_KEY", "minioAccessKey") |
| 56 | +MINIO_SECRET_KEY = os.environ.get("MINIO_SECRET_KEY", "minioSecretKey") |
| 57 | +MINIO_BUCKET = os.environ.get("MINIO_BUCKET", "nabat-mock") |
| 58 | +PORT = int(os.environ.get("PORT", "8082")) |
| 59 | + |
| 60 | +# The single shared object every mocked recording_id resolves to. Per-ID fixture |
| 61 | +# files aren't needed: any recording_id "just works" against this one object. |
| 62 | +RECORDING_OBJECT_KEY = "recordings/example.wav" |
| 63 | + |
| 64 | +# Reserved recording_id that always resolves to "not found", to exercise the |
| 65 | +# existing 403 handling in get_email_if_authorized / generate_nabat_recording. |
| 66 | +NOT_FOUND_RECORDING_ID = 0 |
| 67 | + |
| 68 | +# The "already vetted in NABat" species every newly-fetched recording seeds an |
| 69 | +# annotation for. Must be a pk that actually exists in the local Species table |
| 70 | +# (see the module docstring). Email matches dev/nabat_mock/NABAT-realm.json's test |
| 71 | +# user, so the seeded annotation is visible when browsing as them. |
| 72 | +SEED_ANNOTATION_SPECIES_ID = int(os.environ.get("SEED_ANNOTATION_SPECIES_ID", "1")) |
| 73 | +SEED_ANNOTATION_EMAIL = os.environ.get("SEED_ANNOTATION_EMAIL", "testuser@example.com") |
| 74 | + |
| 75 | +ACOUSTIC_FILE_ID_RE = re.compile(r'acousticFileId:\s*"?(\d+)"?') |
| 76 | + |
| 77 | +# Presigning is pure local signing - no network I/O - as long as a region is given |
| 78 | +# (otherwise minio-py falls back to a live GetBucketLocation request). So this never |
| 79 | +# actually needs to connect to minio; it just needs MINIO_ENDPOINT to be whatever host |
| 80 | +# the downloader (celery) can resolve. See the module docstring. |
| 81 | +minio_client = Minio( |
| 82 | + MINIO_ENDPOINT, |
| 83 | + access_key=MINIO_ACCESS_KEY, |
| 84 | + secret_key=MINIO_SECRET_KEY, |
| 85 | + secure=False, |
| 86 | + region="us-east-1", |
| 87 | +) |
| 88 | + |
| 89 | + |
| 90 | +def extract_id(pattern: re.Pattern, query: str) -> int | None: |
| 91 | + match = pattern.search(query) |
| 92 | + return int(match.group(1)) if match else None |
| 93 | + |
| 94 | + |
| 95 | +def presigned_recording_url(recording_id: int) -> str | None: |
| 96 | + if recording_id == NOT_FOUND_RECORDING_ID: |
| 97 | + return None |
| 98 | + return minio_client.presigned_get_object(MINIO_BUCKET, RECORDING_OBJECT_KEY) |
| 99 | + |
| 100 | + |
| 101 | +def build_presigned_only_response(query: str) -> dict: |
| 102 | + """Mirrors nabat_recording.py's QUERY: presignedUrlFromAcousticFile only.""" |
| 103 | + recording_id = extract_id(ACOUSTIC_FILE_ID_RE, query) |
| 104 | + url = presigned_recording_url(recording_id) if recording_id is not None else None |
| 105 | + return {"data": {"presignedUrlFromAcousticFile": {"s3PresignedUrl": url} if url else None}} |
| 106 | + |
| 107 | + |
| 108 | +def build_combined_response(query: str) -> dict: |
| 109 | + """Mirrors nabat_data_retrieval.py's fetchAcousticAndSurveyEventInfo query.""" |
| 110 | + recording_id = extract_id(ACOUSTIC_FILE_ID_RE, query) |
| 111 | + url = presigned_recording_url(recording_id) if recording_id is not None else None |
| 112 | + |
| 113 | + return { |
| 114 | + "data": { |
| 115 | + "presignedUrlFromAcousticFile": {"s3PresignedUrl": url} if url else None, |
| 116 | + "surveyEventById": { |
| 117 | + "createdBy": "mock@nabat.org", |
| 118 | + "createdDate": "2024-01-01T00:00:00", |
| 119 | + "eventGeometryByEventGeometryId": { |
| 120 | + "description": "Mock survey event geometry", |
| 121 | + "geom": {"geojson": None}, |
| 122 | + }, |
| 123 | + "acousticBatchesBySurveyEventId": { |
| 124 | + "nodes": [ |
| 125 | + { |
| 126 | + "id": "mock-batch", |
| 127 | + "acousticFileBatchesByBatchId": { |
| 128 | + "nodes": [ |
| 129 | + { |
| 130 | + "autoId": SEED_ANNOTATION_SPECIES_ID, |
| 131 | + "manualId": SEED_ANNOTATION_SPECIES_ID, |
| 132 | + "vetter": SEED_ANNOTATION_EMAIL, |
| 133 | + "speciesByManualId": None, |
| 134 | + } |
| 135 | + ] |
| 136 | + }, |
| 137 | + } |
| 138 | + ] |
| 139 | + }, |
| 140 | + }, |
| 141 | + "acousticFileById": { |
| 142 | + "fileName": f"mock_recording_{recording_id}.wav", |
| 143 | + "recordingTime": "2024-01-01T00:00:00", |
| 144 | + "s3Verified": True, |
| 145 | + "sizeBytes": 0, |
| 146 | + }, |
| 147 | + } |
| 148 | + } |
| 149 | + |
| 150 | + |
| 151 | +def build_update_vet_response(query: str) -> dict: |
| 152 | + """Mirrors nabat_recording.py's UPDATE_QUERY (updateAcousticFileVet mutation). |
| 153 | +
|
| 154 | + Always succeeds. update_nabat_species only checks for an "errors" key, never |
| 155 | + reads the payload, so no fields here need to reflect what was actually sent. |
| 156 | + """ |
| 157 | + return {"data": {"updateAcousticFileVet": {"acousticFileBatchId": 1}}} |
| 158 | + |
| 159 | + |
| 160 | +def build_response(query: str) -> dict: |
| 161 | + if "updateAcousticFileVet" in query: |
| 162 | + return build_update_vet_response(query) |
| 163 | + if "fetchAcousticAndSurveyEventInfo" in query: |
| 164 | + return build_combined_response(query) |
| 165 | + if "presignedUrlFromAcousticFile" in query: |
| 166 | + return build_presigned_only_response(query) |
| 167 | + return {"errors": [{"message": "nabat-mock has no handler for this query yet"}]} |
| 168 | + |
| 169 | + |
| 170 | +class Handler(BaseHTTPRequestHandler): |
| 171 | + def log_message(self, format_, *args): |
| 172 | + logger.info("%s - %s", self.address_string(), format_ % args) |
| 173 | + |
| 174 | + def do_POST(self): |
| 175 | + length = int(self.headers.get("Content-Length", 0)) |
| 176 | + body = self.rfile.read(length) |
| 177 | + try: |
| 178 | + payload = json.loads(body) |
| 179 | + query = payload.get("query", "") |
| 180 | + except json.JSONDecodeError: |
| 181 | + query = "" |
| 182 | + |
| 183 | + response_body = json.dumps(build_response(query)).encode("utf-8") |
| 184 | + |
| 185 | + self.send_response(200) |
| 186 | + self.send_header("Content-Type", "application/json") |
| 187 | + self.send_header("Content-Length", str(len(response_body))) |
| 188 | + self.end_headers() |
| 189 | + self.wfile.write(response_body) |
| 190 | + |
| 191 | + |
| 192 | +def main(): |
| 193 | + server = ThreadingHTTPServer(("0.0.0.0", PORT), Handler) # noqa: S104 (container-internal) |
| 194 | + logger.info("nabat-mock listening on :%s", PORT) |
| 195 | + server.serve_forever() |
| 196 | + |
| 197 | + |
| 198 | +if __name__ == "__main__": |
| 199 | + main() |
0 commit comments