File size: 7,446 Bytes
d15f07c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
"""
Server-side proxy for OpenStreetMap Nominatim geocoding.

Why this exists: the SPA used to call ``nominatim.openstreetmap.org`` directly
from the browser. That fails in two ways:

  1. CORS — Nominatim does not reliably send ``Access-Control-Allow-Origin``,
     and the custom ``User-Agent`` the frontend tried to set is a *forbidden
     header* the browser silently drops, so requests arrive unidentified.
  2. Policy — Nominatim's usage policy caps clients at ~1 req/s and requires a
     real identifying User-Agent / contact. Per-keystroke browser calls trip
     the rate limiter, which then returns header-less error pages → the CORS
     error the user sees.

Proxying through the API fixes both: it's same-origin (no CORS), sets a proper
identifying User-Agent server-side, throttles to <=1 req/s globally, and caches
recent queries so autocomplete bursts collapse to a single upstream call.

Responses are passed through unchanged so the existing frontend parsing
(``lat``, ``lon``, ``display_name``, ``address``, ``osm_type``, ``osm_id``)
keeps working.

NOTE: for production scale, self-host Nominatim or use a paid geocoder — a
single shared 1 req/s budget is a courtesy limit, not a throughput guarantee.
"""
from __future__ import annotations

import asyncio
import os
import time
from typing import Any, Optional

import httpx
from fastapi import APIRouter, HTTPException, Query
from loguru import logger

router = APIRouter(prefix="/geocode", tags=["geocode"])

_NOMINATIM_BASE = "https://nominatim.openstreetmap.org"

# Nominatim's policy requires an identifying User-Agent with contact info.
# Override via env in deploys (e.g. "OpenNavigator/1.0 (ops@example.org)").
_USER_AGENT = os.getenv(
    "NOMINATIM_USER_AGENT",
    "OpenNavigator/1.0 (https://github.com/getcommunityone/open-navigator)",
)

# Global throttle: never issue upstream calls faster than this.
_MIN_INTERVAL_S = 1.05
_throttle_lock = asyncio.Lock()
_last_call_ts = 0.0

# Tiny in-memory TTL cache. Autocomplete fires several near-identical queries;
# caching collapses them and shields Nominatim. Keyed by the full request path.
_CACHE_TTL_S = 300.0
_CACHE_MAX = 512
_cache: dict[str, tuple[float, Any]] = {}


def _cache_get(key: str) -> Optional[Any]:
    hit = _cache.get(key)
    if not hit:
        return None
    ts, payload = hit
    if time.monotonic() - ts > _CACHE_TTL_S:
        _cache.pop(key, None)
        return None
    return payload


def _cache_put(key: str, payload: Any) -> None:
    if len(_cache) >= _CACHE_MAX:
        # Cheap eviction: drop the oldest entry.
        oldest = min(_cache.items(), key=lambda kv: kv[1][0])[0]
        _cache.pop(oldest, None)
    _cache[key] = (time.monotonic(), payload)


async def _throttled_get(path: str, params: dict[str, str]) -> Any:
    """GET ``{base}{path}`` through the global throttle, with caching + UA."""
    cache_key = f"{path}?{httpx.QueryParams(params)}"
    cached = _cache_get(cache_key)
    if cached is not None:
        return cached

    global _last_call_ts
    async with _throttle_lock:
        # Another coroutine may have populated this key while we waited for the
        # lock. Re-checking here coalesces concurrent identical lookups into one
        # upstream request instead of sending the same query once per waiter.
        cached = _cache_get(cache_key)
        if cached is not None:
            return cached

        wait = _MIN_INTERVAL_S - (time.monotonic() - _last_call_ts)
        if wait > 0:
            await asyncio.sleep(wait)
        try:
            async with httpx.AsyncClient(timeout=10.0) as client:
                resp = await client.get(
                    f"{_NOMINATIM_BASE}{path}",
                    params=params,
                    headers={
                        "User-Agent": _USER_AGENT,
                        "Accept": "application/json",
                    },
                )
        except httpx.TimeoutException as exc:
            logger.warning("Nominatim timeout for {}", path)
            raise HTTPException(status_code=502, detail="Geocoder request timed out.") from exc
        except httpx.RequestError as exc:
            logger.warning("Nominatim request failed for {}: {}", path, exc)
            raise HTTPException(status_code=502, detail="Geocoder is unavailable.") from exc
        finally:
            # Failed upstream calls still consume the shared request budget.
            # Recording the attempt prevents a transient outage from causing a
            # tight retry loop that violates Nominatim's usage policy.
            _last_call_ts = time.monotonic()

        # Cache the validated response before releasing the lock so identical
        # requests waiting above can reuse it instead of calling upstream.
        if resp.status_code == 429:
            retry_after = resp.headers.get("Retry-After", "1")
            # Only forward the integer form. This keeps the response predictable and
            # avoids reflecting an arbitrary upstream header value.
            if not retry_after.isdigit():
                retry_after = "1"
            raise HTTPException(
                status_code=429,
                detail="Geocoder rate-limited; retry shortly.",
                headers={"Retry-After": retry_after},
            )
        if resp.status_code >= 400:
            logger.warning("Nominatim {} for {}: {}", resp.status_code, path, resp.text[:200])
            raise HTTPException(status_code=502, detail=f"Geocoder error ({resp.status_code}).")
        try:
            payload = resp.json()
        except ValueError as exc:
            raise HTTPException(status_code=502, detail="Geocoder returned non-JSON.") from exc

        _cache_put(cache_key, payload)
        return payload


@router.get("/search")
async def geocode_search(
    q: str = Query(..., min_length=3, description="Free-text address / place query."),
    limit: int = Query(6, ge=1, le=20),
    countrycodes: str = Query(
        "us",
        pattern=r"^[A-Za-z]{2}(?:,[A-Za-z]{2})*$",
        description="Comma-separated ISO alpha-2 country codes to restrict results to.",
    ),
):
    """
    Forward-geocode a free-text query. Returns Nominatim's JSON array verbatim
    (each item has ``lat``, ``lon``, ``display_name``, ``address``,
    ``osm_type``, ``osm_id`` …). Empty array means no match.
    """
    query = q.strip()
    if len(query) < 3:
        # FastAPI's min_length validates the raw string, so whitespace-only
        # input needs an explicit post-normalization check.
        raise HTTPException(status_code=422, detail="Query must contain at least 3 characters.")

    normalized_countrycodes = ",".join(
        code.strip().lower() for code in countrycodes.split(",")
    )
    return await _throttled_get(
        "/search",
        {
            "q": query,
            "format": "json",
            "addressdetails": "1",
            "countrycodes": normalized_countrycodes,
            "limit": str(limit),
        },
    )


@router.get("/reverse")
async def geocode_reverse(
    lat: float = Query(..., ge=-90, le=90),
    lon: float = Query(..., ge=-180, le=180),
):
    """Reverse-geocode a lat/lng to its nearest address (Nominatim JSON object)."""
    return await _throttled_get(
        "/reverse",
        {
            "lat": str(lat),
            "lon": str(lon),
            "format": "json",
            "addressdetails": "1",
        },
    )