Files
cwshed-clone/app/belki/weather.py
T

97 lines
3.9 KiB
Python

"""Small, read-only ULLI weather effect; independent of calculation/storage."""
from __future__ import annotations
import json
import re
import threading
import time
from datetime import datetime, timezone
from http.client import HTTPException
from urllib.request import Request, urlopen
METAR_URL = "https://weather.nyan404.ru/api/v1/metar/raw/ulli"
FALLBACK = {"mode": "none", "intensity": 1, "wind_mps": 0.0}
_WIND = re.compile(r"(?:\d{3}|VRB)(\d{2,3})(?:G(\d{2,3}))?(MPS|KT|KMH)")
_WEATHER = re.compile(r"([+-]?)(?:MI|PR|BC|DR|BL|SH|TS|FZ)?(?:DZ|RA|SN|SG|IC|PL|GR|GS|UP|BR|FG|FU|VA|DU|SA|HZ|PY)+")
def parse_metar(raw: str) -> dict:
"""Read observed wind/precipitation only, ignoring trends, vicinity and remarks."""
result = dict(FALLBACK)
rain = snow = False
for token in raw.upper().split():
if token in {"RMK", "TEMPO", "BECMG", "NOSIG"} or re.fullmatch(r"(?:FM|TL|AT)\d{4}", token):
break
wind = _WIND.fullmatch(token)
if wind:
speed = max(int(wind[1]), int(wind[2] or 0))
result["wind_mps"] = round(min(60, speed * {"KT": 0.514444, "MPS": 1, "KMH": 1 / 3.6}[wind[3]]), 2)
weather = _WEATHER.fullmatch(token)
if not weather:
continue
has_rain = "RA" in token or "DZ" in token
has_snow = "SN" in token or "SG" in token
if not (has_rain or has_snow):
continue
rain |= has_rain
snow |= has_snow
level = 1 if weather[1] == "-" else 3 if weather[1] == "+" else 2
# Showers and blowing snow are visibly fuller, but -SHSN stays light.
if weather[1] != "-" and any(code in token for code in ("SH", "TS", "BL")):
level = 3
result["intensity"] = max(result["intensity"], level)
result["mode"] = "mixed" if rain and snow else "snow" if snow else "rain" if rain else "none"
return result
class WeatherCache:
"""One bounded upstream request per process/5 min; failures retry after 1 min.
Concurrent visitors get the quiet fallback instead of waiting on the lock.
Stale or invalid observations never keep a storm running on the page.
"""
def __init__(self):
self._lock = threading.Lock()
self._expires = 0.0
self._value = dict(FALLBACK)
def get(self) -> dict:
if time.monotonic() < self._expires:
return dict(self._value)
if not self._lock.acquire(blocking=False):
return dict(FALLBACK)
try:
if time.monotonic() < self._expires:
return dict(self._value)
value = dict(FALLBACK)
ttl = 60
try:
request = Request(METAR_URL, headers={"Accept": "application/json"})
with urlopen(request, timeout=3) as response:
body = response.read(65_537)
if len(body) > 65_536:
raise ValueError("oversized METAR")
payload = json.loads(body)
item = payload["item"]
if payload.get("found") is not True or item.get("station_id") != "ULLI":
raise ValueError("missing ULLI")
observed = datetime.fromisoformat(item["observation_time"].replace("Z", "+00:00"))
age = (datetime.now(timezone.utc) - observed).total_seconds()
raw = item["raw_metar"]
if not -600 <= age <= 7200 or not isinstance(raw, str) or not raw.strip():
raise ValueError("stale or invalid METAR")
value = parse_metar(raw)
ttl = min(300, 7200 - max(0, age))
except (OSError, HTTPException, ValueError, KeyError, TypeError, AttributeError):
pass # Decoration must not expose upstream errors or break the form.
self._value = value
self._expires = time.monotonic() + ttl
return dict(value)
finally:
self._lock.release()
weather_cache = WeatherCache()