Files
api_health/utils/user_service.js
T
likandtrae-solo-agent 68faf840cf fix: 写接口限流、WS 有界与 token 不再进日志
新增进程内限流并挂到订单/档案写接口;WS 设 maxPayload、同连接串行处理、按用户限频;鉴权只读请求头并区分登录失效与用户服务故障;访问日志只记路径,避免 token 落盘;陪诊师列表分页夹紧。
2026-10-24 22:24:50 +08:00

85 lines
2.7 KiB
JavaScript
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.
import fetch from "node-fetch";
const USER_SERVICE_URL = process.env.USER_SERVICE_URL || "http://127.0.0.1:9010";
const CACHE_TTL = 5 * 60 * 1000; // 成功结果缓存 5 分钟
const NEGATIVE_TTL = 60 * 1000; // 无效 token 短缓存,防止打爆 user 服务
const MAX_CACHE_SIZE = 2000;
const LOOKUP_TIMEOUT = 5000; // user 服务偶发无响应时不能拖住 health 的全部请求
// key -> { user, expiresAt },Map 按插入序实现简易 LRU
const cache = new Map();
function cacheGet(key) {
const hit = cache.get(key);
if (!hit) return undefined;
if (Date.now() > hit.expiresAt) {
cache.delete(key);
return undefined;
}
// 重新插入以更新 LRU 顺序
cache.delete(key);
cache.set(key, hit);
return hit.user;
}
function cacheSet(key, user, ttl) {
cache.set(key, { user, expiresAt: Date.now() + ttl });
if (cache.size > MAX_CACHE_SIZE) {
cache.delete(cache.keys().next().value);
}
}
async function lookup(body) {
const res = await fetch(`${USER_SERVICE_URL}/user/userInfo`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
signal: AbortSignal.timeout(LOOKUP_TIMEOUT),
});
const data = await res.json();
return data?.data?.user || null;
}
/**
* 仅按 token 获取用户信息(带 5 分钟进程内缓存,token→user)
*
* 注意:缓存期内登出/账户锁定/用户信息变更最多延迟 5 分钟生效
* (user 服务自身接口即时生效)
*
* 只保留 token 路径:user 服务已不再接受按 userId 明文查询,
* 故不存在 userId 兜底,避免凭 userId 冒充他人身份。
*
* @param {string} token 登录 token
* @param {Object} [options]
* @param {boolean} [options.strict] 严格模式:user 服务不可用时不返回 null,
* 而是抛出 code = USER_SERVICE_UNAVAILABLE 的错误,供接口区分「登录失效」与「服务故障」
* @returns {Promise<Object|null>} 用户信息或 null
*/
export async function getUserByToken(token, options = {}) {
if (!token) return null;
const key = `tk:${token}`;
const cached = cacheGet(key);
if (cached !== undefined) return cached;
try {
const user = await lookup({ token });
if (user) {
cacheSet(key, user, CACHE_TTL);
return user;
}
// 无效 token 短缓存,保护 user 服务
cacheSet(key, null, NEGATIVE_TTL);
} catch (err) {
// 网络异常不缓存,避免把故障期内的问题固化 5 分钟
console.error("getUserByToken error:", err.message);
if (options.strict) {
const unavailable = new Error("用户服务暂不可用");
unavailable.code = "USER_SERVICE_UNAVAILABLE";
throw unavailable;
}
}
return null;
}