From 96dbdaa71421c2d96c4ab6628c8f879775a982d8 Mon Sep 17 00:00:00 2001 From: "mula.liu" Date: Fri, 13 Nov 2026 21:32:18 +0800 Subject: [PATCH] =?UTF-8?q?=E8=AE=BE=E5=A4=87=E6=8E=A5=E5=8F=A3=EF=BC=9A?= =?UTF-8?q?=E6=97=B6=E5=8C=BA=E6=8C=89=E7=94=A8=E6=88=B7=E7=AE=97=E3=80=81?= =?UTF-8?q?=E5=9B=BE=E7=89=87=E5=BE=85=E5=90=8C=E6=AD=A5=E6=95=B0=E4=BF=AE?= =?UTF-8?q?=E6=AD=A3=E3=80=81=E5=A4=A9=E6=B0=94=E4=B8=8A=E6=B8=B8=E5=A4=B1?= =?UTF-8?q?=E8=B4=A5=E5=9B=9E=E8=90=BD=E6=97=A7=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - /device/v1/ping:ts 按用户居住时区返回(原来 astimezone() 拿的是容器 UTC, 设备照抄 TZ 屏幕上差 8 小时),并给 tz / tz_offset_min / utc。 - UserOut 增加 tz_offset_min(设备没有 tzdata,光有 IANA 名换算不了)。 - /device/v1/media/pending:pending_pic 原来按 kind == "pic" 统计, 而实际取值是 image,所以图片数永远是 0 → 相册弹窗只报总口径。 - 和风上游连不上时,回 24h 内的最后一次成功结果并标 stale, 比让设备显示"暂无数据"有用;错误信息带上 host 便于定位出网问题。 --- docker-compose.yml | 11 ++++++++- docker/nginx.conf | 1 + server/app/api/device_v1.py | 36 +++++++++++++++++++++++++++--- server/app/db/session.py | 3 +++ server/app/schemas/auth.py | 18 +++++++++++++++ server/app/services/redis_store.py | 10 +++++++++ server/app/services/weather.py | 13 +++++++++-- 7 files changed, 86 insertions(+), 6 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index a6d9221..f3f30dc 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -33,7 +33,7 @@ services: - "${BACKEND_PORT:-8000}:8000" restart: unless-stopped healthcheck: - test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/healthz', timeout=3)"] + test: ["CMD", "python", "-c", "import json,urllib.request; d=json.load(urllib.request.urlopen('http://127.0.0.1:8000/healthz', timeout=5)); raise SystemExit(0 if d.get('ok') else 1)"] interval: 10s timeout: 5s retries: 20 @@ -55,3 +55,12 @@ services: api: condition: service_healthy restart: unless-stopped + +networks: + default: + name: nex-buddy_default + ipam: + config: + # 避开办公网 192.168.2.0/24;Docker 自动分配过 192.168.0.0/20, + # 会让容器把客户端当成同网段直连,导致端口映射握手超时。 + - subnet: 172.30.0.0/24 diff --git a/docker/nginx.conf b/docker/nginx.conf index 988a74c..f0aa159 100644 --- a/docker/nginx.conf +++ b/docker/nginx.conf @@ -11,6 +11,7 @@ server { # Docker 内置 DNS:api 容器重建后也能重新解析 resolver 127.0.0.11 valid=10s ipv6=off; set $api_upstream http://api:8000; + proxy_connect_timeout 5s; location /api/ { proxy_pass $api_upstream$request_uri; diff --git a/server/app/api/device_v1.py b/server/app/api/device_v1.py index 6c02357..513e159 100644 --- a/server/app/api/device_v1.py +++ b/server/app/api/device_v1.py @@ -6,7 +6,7 @@ from __future__ import annotations import uuid -from datetime import datetime, timezone +from datetime import datetime, timedelta, timezone from zoneinfo import ZoneInfo, ZoneInfoNotFoundError from fastapi import APIRouter, HTTPException, Query, Request, status @@ -139,9 +139,23 @@ async def pair_claim(body: PairClaimIn, db: SessionDep) -> PairClaimOut: @router.get("/ping") async def ping(device: CurrentDevice, db: SessionDep) -> dict: + """静默心跳:顺带把设备时钟拉正。 + + ``ts`` 按**用户居住时区**给(带偏移),不是按服务器容器时区——容器默认 + UTC,直接 astimezone() 发下去,设备(东八区)就会显示成 UTC 时间。 + """ device.last_active_at = datetime.now(timezone.utc) + user = await user_of_device(device, db) await db.commit() - return {"ok": True, "ts": _now_iso()} + + tz_name, off, local = await _now_for_user(db, user) + return { + "ok": True, + "ts": local.isoformat(timespec="seconds"), + "utc": datetime.now(timezone.utc).isoformat(timespec="seconds"), + "tz": tz_name, + "tz_offset_min": off, + } @router.get("/profile", response_model=UserOut) @@ -188,6 +202,22 @@ async def _user_effective_tz(db, user: User) -> str: return "Asia/Shanghai" +async def _now_for_user(db, user: User | None) -> tuple[str, int, datetime]: + """设备要显示的「现在」:按用户时区算,返回 (IANA 名, 偏移分钟, 本地时间)。 + + 服务器容器默认跑 UTC。以前 ``_now_iso()`` 用 ``astimezone()``(无参), + 拿到的就是容器本地时区,设备照着设 TZ,屏幕上整整差 8 小时。 + """ + tz_name = await _user_effective_tz(db, user) if user is not None else "UTC" + try: + tz = ZoneInfo(tz_name) + except (ZoneInfoNotFoundError, ValueError): + tz_name, tz = "Asia/Shanghai", ZoneInfo("Asia/Shanghai") + local = datetime.now(timezone.utc).astimezone(tz) + off = int((local.utcoffset() or timedelta(0)).total_seconds() // 60) + return tz_name, off, local + + @router.get("/astro") async def device_astro( device: CurrentDevice, @@ -454,7 +484,7 @@ async def media_pending(device: CurrentDevice, db: SessionDep) -> MediaStateOut: seq=device.media_sync_seq, ack=device.media_sync_ack, pending=len(todo), - pending_pic=sum(1 for f in todo if f.kind == "pic"), + pending_pic=sum(1 for f in todo if f.kind == "image"), pending_music=sum(1 for f in todo if f.kind == "music"), rev=media.manifest_rev(files), synced_rev=device.media_synced_rev, diff --git a/server/app/db/session.py b/server/app/db/session.py index 420ebcf..0709759 100644 --- a/server/app/db/session.py +++ b/server/app/db/session.py @@ -28,6 +28,9 @@ engine = create_async_engine( pool_pre_ping=True, pool_size=5, max_overflow=5, + pool_timeout=5, + # 数据库不可达时快速失败,避免登录等请求一直挂起直到浏览器超时。 + connect_args={"timeout": 5, "command_timeout": 15}, echo=False, ) diff --git a/server/app/schemas/auth.py b/server/app/schemas/auth.py index e3c72e8..51dc386 100644 --- a/server/app/schemas/auth.py +++ b/server/app/schemas/auth.py @@ -44,6 +44,9 @@ class UserOut(BaseModel): residence_city: str | None = None residence_place: str | None = None timezone: str | None = None + # 时区偏移(分钟):设备没有 tzdata,光有 IANA 名换算不了本地时间。 + # 服务端算好直接给,夏令时也由服务端负责换。 + tz_offset_min: int | None = None # 星盘:只落 code,名字/符号按码表实时补(见 user_out) sun_sign: str | None = None @@ -69,9 +72,24 @@ def user_out(user: "User", zodiacs: dict[str, dict] | None = None) -> UserOut: if info: setattr(out, f"{kind}_sign_name", info["name_cn"]) setattr(out, f"{kind}_symbol", info["symbol"]) + out.tz_offset_min = _tz_offset_min(user.timezone) return out +def _tz_offset_min(tz_name: str | None) -> int | None: + """IANA 名 → 当前偏移分钟(夏令时按今天算)。算不出来返回 None。""" + from datetime import datetime, timedelta, timezone + from zoneinfo import ZoneInfo, ZoneInfoNotFoundError + + try: + tz = ZoneInfo(tz_name or "Asia/Shanghai") + except (ZoneInfoNotFoundError, ValueError): + return None + off = datetime.now(timezone.utc).astimezone(tz).utcoffset() or timedelta(0) + return int(off.total_seconds() // 60) + + + class LoginOut(BaseModel): token: str user: UserOut diff --git a/server/app/services/redis_store.py b/server/app/services/redis_store.py index 33e908e..7422dd5 100644 --- a/server/app/services/redis_store.py +++ b/server/app/services/redis_store.py @@ -177,6 +177,16 @@ async def set_weather(city: str, payload: dict[str, Any]) -> None: await client().set( f"weather:{city}", json.dumps(payload, ensure_ascii=False), ex=settings.weather_cache_seconds ) + # 再留一份 24 小时的"最后一次成功":上游连不上时宁可发一份旧实况 + # (带 stale 标记),也比让设备显示"暂无数据"强 + await client().set( + f"weather:last:{city}", json.dumps(payload, ensure_ascii=False), ex=86400 + ) + + +async def get_weather_last(city: str) -> dict[str, Any] | None: + raw = await client().get(f"weather:last:{city}") + return json.loads(raw) if raw else None async def clear_weather_cache() -> int: diff --git a/server/app/services/weather.py b/server/app/services/weather.py index 75e5f60..c2eee69 100644 --- a/server/app/services/weather.py +++ b/server/app/services/weather.py @@ -132,8 +132,17 @@ async def now(db: AsyncSession, city: str) -> dict[str, Any]: except WeatherUpstreamError: hourly = [] # 24h 可能是付费套餐,缺了不影响当前天气 except httpx.HTTPError as exc: - # DNS/连接/超时都归到上游不可用,让设备拿到 502 而不是 500 - raise WeatherUpstreamError(f"和风请求失败:{exc.__class__.__name__}") from exc + # DNS/连接/超时都归到上游不可用,让设备拿到 502 而不是 500。 + # 上一次成功的结果(24h)还在就发它——设备上显示一份旧实况, + # 比显示"暂无数据"有用得多,`stale` 让客户端知道它不是实时的。 + last = await redis_store.get_weather_last(city) + if last: + last["cached"] = True + last["stale"] = True + return last + raise WeatherUpstreamError( + f"和风请求失败:{exc.__class__.__name__}({host})" + ) from exc payload = _slim(name or city, loc_id, current.get("now") or {}, hourly) await redis_store.set_weather(city, payload)