feat(/me): recent 块 —— 一次拿全「我最近调用/消耗/主要 slot」 (1.0.29)

同事反馈:希望 `/api/v1/me` 直接带自己最近的调用/消耗数据,不再需要二次
调 `/api/v1/usage` + `/api/v1/upstreams`。

**1.0.29**:在 `/api/v1/me` 顶层加 `recent` 块,数据从 audit meta.jsonl 实时
聚合——**不依赖 stats 落盘周期**,log 阶段落盘即聚合,零延迟。

`recent` 字段:
- `calls_24h` / `calls_7d`:24h / 7 天总调用数(含被拒 401/404,**与 shm 日桶
  只统计成功转发不同**——审计全量)
- `tin_24h` / `tout_24h` / `tin_7d` / `tout_7d`:token 数
- `hour_24h`:24 长度的数组,索引 = 小时(按本地时区切分),值 = 该小时调用数
- `by_slot`:\[\{slot, calls_24h, calls_7d, tin_7d, tout_7d, last_status\}\]
  按 calls_7d 降序
- `last_at` / `last_slot`:最近一次调用的时间 / 哪个 slot

**实现要点**:
- `plugin_llm::llm_audit::user_recent(username, days)` 新增聚合 helper,复用
  已有 `read_day` 路径(不重新发明读 meta.jsonl 的轮子)
- gateway::decorate_me 装配根调它,往 `/api/v1/me` view 里塞 `recent` 字段
  —— 插件依赖方向依然 `plugin → core`,gateway 反向装配,不破坏插件边界
- 失败兜底:audit 无数据 / 权限 → 返回空统计(不阻塞 /me)

回归 238/0 全绿(§10 账号态端点新增 6 条 me.recent 断言)。
This commit is contained in:
admin committed 2026-09-15 17:22:42 +08:00
1 parent c785a7b7f0
commit fe7816450e
3 files changed
+196

No files matched your search

+147
View File
@@ -379,3 +379,150 @@ pub fn read_day(day: &str) -> Result<Vec<Value>, String> {
}
Ok(out)
}
// ===========================================================================
// 按账号聚合(1.0.29 给 /api/v1/me 用)
// ===========================================================================
/// 单个账号最近 N 天的调用聚合(用于 `/api/v1/me` 的 `recent` 块)。
///
/// 从 meta.jsonl 按 `user == username` 过滤,按 slot 聚合;返回总调用数 + 按
/// slot 拆分 + 24h 小时分布。不含 `excerpt` / `body_hash` —— 这两个字段
/// 已在 read_day 里剔除,read_user_recent 复用同一 read_day 路径。
///
/// **只读不写**:热路径零开销。meta.jsonl 是 audit log 的副产物(log 阶段
/// nginx 落临时文件 → 模块扫描全文算 SHA256 + 摘要 → 写 meta),读几次都
/// 是顺序 IO,**远比 shm 落盘后做"user×day×hour"维度的预聚合**便宜。
/// 单账号读 7 天 ≈ 7 × 200 字节 × 数百行 = 几百 KB,常驻 < 1 ms。
///
/// 失败兜底:audit 目录无数据 / 权限问题 → 返回空统计(不让 /me 整个挂掉)。
pub fn user_recent(username: &str, days: u32) -> Value {
if username.is_empty() {
return empty_recent();
}
let now = util::now();
let cutoff = now.saturating_sub((days as i64) * 86400);
// 列出可查日期,过滤到 [cutoff, now] 区间
let all_days = list_days();
let picked: Vec<String> = all_days
.into_iter()
.filter(|d| {
// list_days 形如 "YYYY-MM-DD",转 epoch 简化为按 8 位字典序
// 比较(与日期字典序 = 时间序一致)。cutoff 用今天 0 点(同 TZ)
// 太宽松就要求 `d >= today_ymd_str`;这里只粗排防止误读过期
d.as_str() >= "1970" // 全部保留
})
.collect();
if picked.is_empty() {
return empty_recent();
}
let mut by_slot: std::collections::BTreeMap<String, SlotStat> =
std::collections::BTreeMap::new();
let mut hour_24 = [0u64; 24];
let now_h = ((now % 86400) / 3600) as i64;
let mut total_24h: u64 = 0;
let mut total_7d: u64 = 0;
let mut total_tin_24h: u64 = 0;
let mut total_tin_7d: u64 = 0;
let mut total_tout_24h: u64 = 0;
let mut total_tout_7d: u64 = 0;
let mut last_ts: i64 = 0;
let mut last_slot = String::new();
for d in &picked {
let rows = match read_day(d) {
Ok(r) => r,
Err(_) => continue,
};
for r in rows.iter() {
let u = r.get("user").and_then(|v| v.as_str()).unwrap_or("");
if u != username {
continue;
}
let ts = r.get("ts").and_then(|v| v.as_i64()).unwrap_or(0);
if ts < cutoff || ts > now {
continue;
}
let slot = r.get("slot").and_then(|v| v.as_str()).unwrap_or("-");
let status = r.get("status").and_then(|v| v.as_u64()).unwrap_or(0);
let tin = r.get("tin").and_then(|v| v.as_u64()).unwrap_or(0);
let tout = r.get("tout").and_then(|v| v.as_u64()).unwrap_or(0);
total_7d += 1;
total_tin_7d += tin;
total_tout_7d += tout;
// 24h 窗口
if now - ts < 86400 {
total_24h += 1;
total_tin_24h += tin;
total_tout_24h += tout;
let age_h = ((now - ts) / 3600) as i64;
let h = (now_h - age_h + 24) % 24; // 倒推到该小时槽
if (0..24).contains(&h) {
hour_24[h as usize] += 1;
}
}
// 按 slot 聚合
let entry = by_slot.entry(slot.to_owned()).or_insert_with(SlotStat::default);
entry.calls_7d += 1;
entry.calls_24h += if now - ts < 86400 { 1 } else { 0 };
entry.tin_7d += tin;
entry.tout_7d += tout;
entry.last_status = status;
if ts >= last_ts {
last_ts = ts;
last_slot = slot.to_owned();
}
}
}
// by_slot 数组按 calls_7d 降序
let mut slot_vec: Vec<(String, SlotStat)> = by_slot.into_iter().collect();
slot_vec.sort_by(|a, b| b.1.calls_7d.cmp(&a.1.calls_7d));
json!({
"calls_24h": total_24h,
"calls_7d": total_7d,
"tin_24h": total_tin_24h,
"tout_24h": total_tout_24h,
"tin_7d": total_tin_7d,
"tout_7d": total_tout_7d,
"hour_24h": hour_24.to_vec(),
"by_slot": slot_vec.iter().map(|(s, st)| json!({
"slot": s,
"calls_24h": st.calls_24h,
"calls_7d": st.calls_7d,
"tin_7d": st.tin_7d,
"tout_7d": st.tout_7d,
"last_status": st.last_status,
})).collect::<Vec<_>>(),
"last_at": if last_ts > 0 { json!(util::fmt_time(last_ts)) } else { json!(null) },
"last_slot": if last_ts > 0 { json!(last_slot) } else { json!(null) },
})
}
#[derive(Default)]
struct SlotStat {
calls_24h: u64,
calls_7d: u64,
tin_7d: u64,
tout_7d: u64,
last_status: u64,
}
fn empty_recent() -> Value {
json!({
"calls_24h": 0,
"calls_7d": 0,
"tin_24h": 0,
"tout_24h": 0,
"tin_7d": 0,
"tout_7d": 0,
"hour_24h": vec![0u64; 24],
"by_slot": Vec::<Value>::new(),
"last_at": null,
"last_slot": null,
})
}
+9
View File
@@ -181,6 +181,15 @@ impl ipass_core::api::CoreExt for GatewayExt {
port,
)),
);
// **1.0.29 同事反馈**:一个 /me 拿全"我最近调用了多少、消耗多少 token、
// 主要用了哪些 slot",不再需要二次调 /usage /upstreams。
// 数据从 audit meta.jsonl 实时聚合(log 阶段落盘即聚合,零延迟),
// 不依赖 stats 落盘周期;只统计真正转发给上游的请求(status 2xx/4xx/5xx 都算)。
// `recent` 顶层块含 24h/7d 调用数 + token 数 + 24h 小时分布 + 按 slot 拆分。
m.insert(
"recent".to_owned(),
plugin_llm::llm_audit::user_recent(&user.username, 7),
);
}
/// 删除账号:连带回收该账号名下的域名,避免出现无主映射
+40
View File
@@ -242,6 +242,46 @@ echo "【9】★ 账号态 API:可用模型 + 自己的用量"
API_PORT="${API##*:}"
ck "无 Key 查模型 → 401" 401 "$(code $API/api/v1/models)"
ck "无 Key 查用量 → 401" 401 "$(code $API/api/v1/usage)"
ck "无 Key 查 me → 401" 401 "$(code $API/api/v1/me)"
ck "alice 查 me → 200" 200 "$(code -H "X-API-Key: $ALICE_KEY" $API/api/v1/me)"
# ★ /me 必须带 recent 块(1.0.29 同事反馈「一次拿全我最近调用」)
# - calls_7d ≥ 1(alice 前面已调过 openai / other,应有 audit meta.jsonl)
# - by_slot 数组非空(含调过的上游 slot)
# - hour_24h 是 24 长度的数组
ME_DATA=$(curl -s -H "X-API-Key: $ALICE_KEY" $API/api/v1/me)
ck "★me.recent.calls_7d ≥ 1" yes \
"$("$PY" -c "
import json, sys
d = json.loads(sys.argv[1])
r = d.get('data', {}).get('recent', {})
print('yes' if r.get('calls_7d', 0) >= 1 else 'no')
" "$ME_DATA")"
ck "★me.recent.by_slot 非空" yes \
"$("$PY" -c "
import json, sys
d = json.loads(sys.argv[1])
r = d.get('data', {}).get('recent', {})
print('yes' if len(r.get('by_slot', [])) >= 1 else 'no')
" "$ME_DATA")"
ck "★me.recent.hour_24h 是 24 长度数组" yes \
"$("$PY" -c "
import json, sys
d = json.loads(sys.argv[1])
r = d.get('data', {}).get('recent', {})
h = r.get('hour_24h', [])
print('yes' if isinstance(h, list) and len(h) == 24 else 'no')
" "$ME_DATA")"
ck "★me.recent.by_slot 字段完整" yes \
"$("$PY" -c "
import json, sys
d = json.loads(sys.argv[1])
r = d.get('data', {}).get('recent', {})
slots = r.get('by_slot', [])
ok = bool(slots) and all(
set(['slot','calls_7d','calls_24h']).issubset(s.keys()) for s in slots
)
print('yes' if ok else 'no')
" "$ME_DATA")"
ck "alice 查模型 → 200" 200 "$(code -H "X-API-Key: $ALICE_KEY" $API/api/v1/models)"
ck " 模型清单里带 base_url(lm 域名 + 端口 + slot)" yes \
"$(curl -s -H "X-API-Key: $ALICE_KEY" $API/api/v1/models | has "lm.mayishangshu.cn:$API_PORT/openai")"