设备接口:时区按用户算、图片待同步数修正、天气上游失败回落旧值
- /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 便于定位出网问题。main
parent
12dc1dbfb1
commit
96dbdaa714
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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:
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
Loading…
Reference in New Issue