Files
inquiry_robot/inquiry-agent/agent/redis_coord/token_cache.py
T

65 lines
1.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
企微 access_token 等短缓存。
本文件职责:GET/SET+TTL;未命中由调用方再打企微,失败可回退。
禁止:把 token 当业务真相;挂了必须能重拉,不要把工单打成「未认证」。
"""
from __future__ import annotations
import logging
from typing import Optional
from agent.redis_coord.client import RedisClient
from agent.redis_coord.keys import TOKEN_WECOM, TOKEN_WSHOTO
logger = logging.getLogger(__name__)
def get_wecom_token(client: RedisClient, *, agent_id: str) -> Optional[str]:
"""读取缓存 token;未命中返回 None。"""
key = client.key(TOKEN_WECOM, agent_id)
val = client.raw.get(key)
if val is None:
return None
return val if isinstance(val, str) else val.decode("utf-8")
def set_wecom_token(
client: RedisClient,
*,
agent_id: str,
token: str,
ttl_seconds: int = 7000,
) -> None:
"""
写入 token(默认 TTL 略短于企微 7200s)。
副作用:覆盖同 agent_id 缓存键。
"""
key = client.key(TOKEN_WECOM, agent_id)
client.raw.set(key, token, ex=ttl_seconds)
logger.info("企微 token 已缓存 agent_id=%s ttl=%s", agent_id, ttl_seconds)
def get_wshoto_token(client: RedisClient, *, app_id: str) -> Optional[str]:
"""读取微盛 access_token 缓存;未命中返回 None。不把 token 当业务真相。"""
key = client.key(TOKEN_WSHOTO, app_id or "default")
val = client.raw.get(key)
if val is None:
return None
return val if isinstance(val, str) else val.decode("utf-8")
def set_wshoto_token(
client: RedisClient,
*,
app_id: str,
token: str,
ttl_seconds: int = 7000,
) -> None:
"""写入微盛 token;TTL 略短于接口 expires_in,避免用过期票去拉群。"""
key = client.key(TOKEN_WSHOTO, app_id or "default")
client.raw.set(key, token, ex=max(60, int(ttl_seconds)))
logger.info("微盛 token 已缓存 ttl=%s", ttl_seconds)