fix(map): rate limit station reverse geocoding

This commit is contained in:
lingniu
2026-08-12 12:04:39 +08:00
parent 4c547757a7
commit 5b565d57fc
3 changed files with 13 additions and 1 deletions
+10
View File
@@ -38,12 +38,15 @@ STATION_GEOCODE_CACHE_SECONDS = int(os.getenv("STATION_GEOCODE_CACHE_SECONDS", "
STATION_GEOCODE_CACHE_PATH = Path(os.getenv(
"STATION_GEOCODE_CACHE_PATH", str(ROOT / ".station-geocode-cache.json")
))
AMAP_REGEOCODE_MIN_INTERVAL_SECONDS = float(os.getenv("AMAP_REGEOCODE_MIN_INTERVAL_SECONDS", "0.25"))
_cache_lock = threading.Lock()
_cache = {}
_cache_load_locks = {}
_station_geocode_cache_lock = threading.Lock()
_station_geocode_cache = None
_station_geocode_cache_dirty = False
_station_geocode_rate_lock = threading.Lock()
_station_geocode_next_request_at = 0.0
class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
@@ -142,8 +145,15 @@ def _persist_station_geocode_cache():
def _reverse_geocode_station(longitude, latitude):
global _station_geocode_next_request_at
if not AMAP_REGEOCODE_KEY:
raise RuntimeError("AMAP_REGEOCODE_KEY is not configured")
with _station_geocode_rate_lock:
now = time.monotonic()
wait_seconds = max(0.0, _station_geocode_next_request_at - now)
_station_geocode_next_request_at = max(now, _station_geocode_next_request_at) + AMAP_REGEOCODE_MIN_INTERVAL_SECONDS
if wait_seconds:
time.sleep(wait_seconds)
query = urlencode({
"key": AMAP_REGEOCODE_KEY,
"location": "{:.6f},{:.6f}".format(longitude, latitude),