Files
marqdo/src/host/log.rs
T
cflmy 8b0ea9ed7a refactor: 精简三处重复 — as_text×18、catalog 助手×4、view 路由 34 臂
按审计结论清理冗余(不改变行为):
1. as_text:17 个 host 模块各自复制同一函数(两种措辞),合并为
   crate::host::as_text(统一 "{label} needs text",无测试依赖旧措辞)
2. catalog.rs:extract_fm_field / extract_nested_by / extract_fm_list /
   yaml_escape 与 knowledge::util 逐字相同,改为直接引用
3. view/mod.rs:handle 29 臂 + handle_debug 5 臂折叠成两张路由表
   (Notebook/Debug/Action 三种处理器),每臂原本重复同一 api_debug_post 包装

实测:
- cargo build 零警告;cargo test --release 605 passed / 0 failed
- view 服务实测:GET / → 200;POST /api/debug/continue → 200(真实响应
  {"error":"unknown session"});POST /api/nope → 405

行数:view/mod.rs -99(168 删 69 增);src 合计由 53,276 降至约 53,000
(as_text 18 文件各约 6 行、catalog 4 函数约 70 行)

期间发现并修正一处真实风险:路由臂分布在两个 handler(handle / handle_debug),
首次只替换了一个导致 debug 路由 405;已按 handler 分别建表并由实测覆盖。
2026-10-22 15:39:18 +08:00

110 lines
3.0 KiB
Rust

//! Log level gate for Mid M6 (`lib/log`).
use crate::host::as_text;
use crate::host::HostContext;
use crate::value::Value;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Level {
Debug = 10,
Info = 20,
Warn = 30,
Error = 40,
}
impl Level {
pub fn parse(s: &str) -> Result<Self, String> {
match s.trim().to_ascii_lowercase().as_str() {
"debug" | "调试" => Ok(Self::Debug),
"info" | "信息" => Ok(Self::Info),
"warn" | "warning" | "警告" => Ok(Self::Warn),
"error" | "错误" => Ok(Self::Error),
_ => Err(format!("log: unknown level {s:?}")),
}
}
pub fn label(self) -> &'static str {
match self {
Self::Debug => "DEBUG",
Self::Info => "INFO",
Self::Warn => "WARN",
Self::Error => "ERROR",
}
}
}
pub fn set_level(ctx: &mut HostContext, level: &Value) -> Result<Value, String> {
let s = as_text(level, "level")?;
ctx.log_min_level = Level::parse(s)? as u8;
Ok(Value::None)
}
/// Return a ready-to-print line, or `None` if filtered out.
/// Optional `fields` map is appended as `key=value` pairs (stable map order).
pub fn line(
ctx: &HostContext,
level: &Value,
text: &Value,
fields: Option<&Value>,
) -> Result<Value, String> {
let lvl = Level::parse(as_text(level, "level")?)?;
let msg = as_text(text, "text")?;
if (lvl as u8) < ctx.log_min_level {
return Ok(Value::None);
}
let mut out = format!("{} {}", lvl.label(), msg);
match fields {
None | Some(Value::None) => {}
Some(Value::Map(entries)) => {
for (k, v) in entries {
out.push(' ');
out.push_str(k);
out.push('=');
out.push_str(&v.as_display());
}
}
Some(_) => return Err("log: fields must be a map".into()),
}
Ok(Value::Text(out))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn filters_debug() {
let mut ctx = HostContext::default();
assert_eq!(ctx.log_min_level, Level::Info as u8);
let filtered = line(
&ctx,
&Value::Text("debug".into()),
&Value::Text("x".into()),
None,
)
.unwrap();
assert_eq!(filtered, Value::None);
set_level(&mut ctx, &Value::Text("debug".into())).unwrap();
let shown = line(
&ctx,
&Value::Text("debug".into()),
&Value::Text("x".into()),
None,
)
.unwrap();
assert_eq!(shown, Value::Text("DEBUG x".into()));
let with = line(
&ctx,
&Value::Text("info".into()),
&Value::Text("hi".into()),
Some(&Value::Map(vec![
("user".into(), Value::Text("a".into())),
("n".into(), Value::Int(1)),
])),
)
.unwrap();
assert_eq!(with, Value::Text("INFO hi user=a n=1".into()));
}
}