199 lines
6.6 KiB
Python
199 lines
6.6 KiB
Python
"""Redis 访问层:会话、设备 token、配对码、限流、天气结果缓存。
|
||
|
||
平台配置(settings 表)不在此列——配置一律直读库,见文件内注释。
|
||
键规划见 01-总体设计.md 4.1,键名与文档保持一致,便于运维排查。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
from typing import Any
|
||
|
||
import redis.asyncio as aioredis
|
||
|
||
from app.core.config import settings
|
||
|
||
_client: aioredis.Redis | None = None
|
||
|
||
|
||
def client() -> aioredis.Redis:
|
||
global _client
|
||
if _client is None:
|
||
_client = aioredis.from_url(
|
||
settings.redis_url,
|
||
encoding="utf-8",
|
||
decode_responses=True,
|
||
socket_connect_timeout=3,
|
||
socket_timeout=3,
|
||
)
|
||
return _client
|
||
|
||
|
||
async def close() -> None:
|
||
global _client
|
||
if _client is not None:
|
||
await _client.aclose()
|
||
_client = None
|
||
|
||
|
||
async def ping() -> bool:
|
||
try:
|
||
return bool(await client().ping())
|
||
except Exception:
|
||
return False
|
||
|
||
|
||
# ---------------- 会话(Web) ----------------
|
||
async def save_session(token_hash: str, user_id: str) -> None:
|
||
await client().set(f"sess:{token_hash}", user_id, ex=settings.session_ttl_seconds)
|
||
|
||
|
||
async def load_session(token_hash: str) -> str | None:
|
||
key = f"sess:{token_hash}"
|
||
uid = await client().get(key)
|
||
if uid:
|
||
# 滑动续期:活跃用户不会中途掉线
|
||
await client().expire(key, settings.session_ttl_seconds)
|
||
return uid
|
||
|
||
|
||
async def drop_session(token_hash: str) -> None:
|
||
await client().delete(f"sess:{token_hash}")
|
||
|
||
|
||
async def revoke_sessions_of(user_id: str) -> int:
|
||
"""停用账号时踢掉它所有 Web 会话(sess:* 的 value 就是 user_id)。"""
|
||
n = 0
|
||
async for key in client().scan_iter(match="sess:*", count=200):
|
||
if await client().get(key) == user_id:
|
||
await client().delete(key)
|
||
n += 1
|
||
return n
|
||
|
||
|
||
# ---------------- 设备 token ----------------
|
||
async def save_device_token(device_id: str, token_hash: str) -> None:
|
||
await client().set(f"dtoken:{device_id}:{token_hash}", "1")
|
||
|
||
|
||
async def load_device_token(device_id: str, token_hash: str) -> bool:
|
||
return bool(await client().exists(f"dtoken:{device_id}:{token_hash}"))
|
||
|
||
|
||
async def revoke_device_tokens(device_id: str) -> int:
|
||
"""解绑/停用用户时吊销该设备全部 token。"""
|
||
pattern = f"dtoken:{device_id}:*"
|
||
n = 0
|
||
async for key in client().scan_iter(match=pattern, count=200):
|
||
await client().delete(key)
|
||
n += 1
|
||
return n
|
||
|
||
|
||
# ---------------- 扫码登录票据(设备屏上的二维码 → Web 会话) ----------------
|
||
# 一码一用:设备每次打开二维码都重新申请,手机扫完即作废,
|
||
# 所以码即便被旁人拍到,也只有第一个点开的人能换到会话。
|
||
async def put_web_login(code: str, user_id: str, device_id: str, ttl: int) -> None:
|
||
# 同一台设备只保留最新一张:屏幕上换过码,旧码(哪怕被截图拍下)立刻失效
|
||
prev = await client().get(f"wlogin:dev:{device_id}")
|
||
if prev and prev != code:
|
||
await client().delete(f"wlogin:{prev}")
|
||
await client().set(f"wlogin:{code}", json.dumps({"user_id": user_id, "device_id": device_id}), ex=ttl)
|
||
await client().set(f"wlogin:dev:{device_id}", code, ex=ttl)
|
||
|
||
|
||
async def pop_web_login(code: str) -> dict[str, Any] | None:
|
||
key = f"wlogin:{code}"
|
||
pipe = client().pipeline()
|
||
pipe.get(key)
|
||
pipe.delete(key)
|
||
raw, _ = await pipe.execute()
|
||
return json.loads(raw) if raw else None
|
||
|
||
|
||
# ---------------- 配对码 ----------------
|
||
async def put_pair(code: str, payload: dict[str, Any], ttl: int) -> None:
|
||
await client().set(f"pair:{code}", json.dumps(payload), ex=ttl)
|
||
await client().delete(f"pair:try:{code}")
|
||
|
||
|
||
async def get_pair(code: str) -> dict[str, Any] | None:
|
||
raw = await client().get(f"pair:{code}")
|
||
return json.loads(raw) if raw else None
|
||
|
||
|
||
async def mark_pair_bound(code: str, user_id: str) -> None:
|
||
"""记账消费:码本身保留一小段 claim 窗口,供设备换 token。"""
|
||
raw = await client().get(f"pair:{code}")
|
||
if not raw:
|
||
return
|
||
data = json.loads(raw)
|
||
data["bound_user_id"] = user_id
|
||
await client().set(f"pair:{code}", json.dumps(data), ex=settings.pair_claim_window_seconds)
|
||
await client().set(f"pair:claimed:{code}", user_id, ex=settings.pair_claim_window_seconds)
|
||
|
||
|
||
async def consume_pair(code: str) -> None:
|
||
await client().delete(f"pair:{code}", f"pair:try:{code}")
|
||
|
||
|
||
async def bump_pair_try(code: str) -> int:
|
||
"""每设备限速 5 次/分钟的简单实现。"""
|
||
key = f"pair:try:{code}"
|
||
n = await client().incr(key)
|
||
if n == 1:
|
||
await client().expire(key, 60)
|
||
return int(n)
|
||
|
||
|
||
# ---------------- 平台设置:不入缓存 ----------------
|
||
# 平台配置(qweather.key/host 等)一律直读 settings 表,Redis 不参与。
|
||
# 教训:曾把文档示例 Host 写进 settings:qweather.*,脏缓存压住库和 .env,
|
||
# 导致和风持续 401 且改 .env 无效。运维配置写入频次极低,省这次主键查询不划算。
|
||
|
||
|
||
# ---------------- 通用读缓存(码表等) ----------------
|
||
async def cache_get(key: str) -> Any | None:
|
||
raw = await client().get(f"cache:{key}")
|
||
return json.loads(raw) if raw else None
|
||
|
||
|
||
async def cache_set(key: str, value: Any, ttl: int = 3600) -> None:
|
||
await client().set(f"cache:{key}", json.dumps(value, ensure_ascii=False), ex=ttl)
|
||
|
||
|
||
async def cache_del(*keys: str) -> None:
|
||
if keys:
|
||
await client().delete(*[f"cache:{k}" for k in keys])
|
||
|
||
|
||
# ---------------- 天气缓存 ----------------
|
||
async def get_weather(city: str) -> dict[str, Any] | None:
|
||
raw = await client().get(f"weather:{city}")
|
||
return json.loads(raw) if raw else None
|
||
|
||
|
||
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:
|
||
"""改了 Key/Host 之后清空天气缓存,避免继续吐旧数据。"""
|
||
n = 0
|
||
async for key in client().scan_iter(match="weather:*", count=200):
|
||
await client().delete(key)
|
||
n += 1
|
||
return n
|