Files
marqdo/src/host/sys.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

240 lines
7.5 KiB
Rust

//! System / process host primitives.
use crate::host::as_text;
#[cfg(feature = "exec-host")]
use std::process::Command;
use crate::host::HostContext;
use crate::value::Value;
fn as_i64(v: &Value, label: &str) -> Result<i64, String> {
match v {
Value::Int(n) => Ok(*n),
_ => Err(format!("{label} must be int")),
}
}
pub fn env_get(name: &Value) -> Result<Value, String> {
let key = as_text(name, "name")?;
Ok(match std::env::var(key) {
Ok(v) => Value::Text(v),
Err(_) => Value::None,
})
}
pub fn env_set(name: &Value, value: &Value) -> Result<Value, String> {
let key = as_text(name, "name")?;
let val = as_text(value, "value")?;
std::env::set_var(key, val);
Ok(Value::None)
}
/// Load KEY=VALUE pairs from a `.env` file into the process environment.
/// Existing variables are **not** overridden. Default path: `.env` under host cwd.
pub fn dotenv_load(ctx: &HostContext, path: Option<&Value>) -> Result<Value, String> {
let rel = match path {
None | Some(Value::None) => ".env".to_string(),
Some(v) => as_text(v, "path")?.to_string(),
};
let file = if std::path::Path::new(&rel).is_absolute() {
std::path::PathBuf::from(&rel)
} else {
ctx.cwd.join(&rel)
};
let text = match std::fs::read_to_string(&file) {
Ok(t) => t,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Value::Int(0)),
Err(e) => {
return Err(format!("dotenv_load {}: {e}", file.display()));
}
};
let mut loaded = 0i64;
for raw in text.lines() {
let line = raw.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let line = line.strip_prefix("export ").unwrap_or(line).trim();
let Some((k, v)) = line.split_once('=') else {
continue;
};
let key = k.trim();
if key.is_empty() {
continue;
}
if std::env::var_os(key).is_some() {
continue;
}
let mut val = v.trim();
if (val.starts_with('"') && val.ends_with('"'))
|| (val.starts_with('\'') && val.ends_with('\''))
{
val = &val[1..val.len() - 1];
}
std::env::set_var(key, val);
loaded += 1;
}
Ok(Value::Int(loaded))
}
pub fn args(ctx: &HostContext) -> Result<Value, String> {
Ok(Value::List(
ctx.argv.iter().map(|s| Value::Text(s.clone())).collect(),
))
}
pub fn cwd(ctx: &HostContext) -> Result<Value, String> {
Ok(Value::Text(ctx.cwd.display().to_string()))
}
/// Bound entry Artifact Metadata (map).
pub fn meta(ctx: &HostContext) -> Result<Value, String> {
Ok(Value::Map(ctx.entry_metadata.clone()))
}
/// Lookup one metadata key; missing → None.
pub fn meta_get(ctx: &HostContext, key: &Value) -> Result<Value, String> {
let k = as_text(key, "key")?;
Ok(ctx
.entry_metadata
.iter()
.find(|(name, _)| name == k)
.map(|(_, v)| v.clone())
.unwrap_or(Value::None))
}
/// Classify entry Artifact (`web` / `endpoint` / `prompt` / `other`); missing type → None.
pub fn artifact_kind(ctx: &HostContext) -> Result<Value, String> {
Ok(match crate::artifact::classify(&ctx.entry_metadata) {
None => Value::None,
Some(crate::artifact::ArtifactKind::Web) => Value::Text("web".into()),
Some(crate::artifact::ArtifactKind::Endpoint) => Value::Text("endpoint".into()),
Some(crate::artifact::ArtifactKind::Prompt) => Value::Text("prompt".into()),
Some(crate::artifact::ArtifactKind::Other) => Value::Text("other".into()),
})
}
pub fn exit(ctx: &HostContext, code: &Value) -> Result<Value, String> {
let c = as_i64(code, "code")?;
if ctx.soft_side_effects {
return Err(format!("exit {c} (soft mode does not terminate process)"));
}
#[cfg(target_arch = "wasm32")]
{
return Err(format!("exit {c} unavailable in browser wasm"));
}
#[cfg(not(target_arch = "wasm32"))]
{
std::process::exit(c as i32);
}
}
pub fn exec(
ctx: &HostContext,
cmd: &Value,
args: Option<&Value>,
capture: Option<&Value>,
) -> Result<Value, String> {
#[cfg(not(feature = "exec-host"))]
{
let _ = (ctx, cmd, args, capture);
return Err("exec unavailable in browser wasm".into());
}
#[cfg(feature = "exec-host")]
{
use std::process::Stdio;
if !ctx.allow_exec() {
if ctx.sandbox_session.is_some() {
return Err("exec unavailable in sandbox".into());
}
return Err("exec denied by host policy".into());
}
let cmd = as_text(cmd, "cmd")?;
let capture = match capture {
None | Some(Value::None) => false,
Some(v) => crate::host::math::as_bool(v),
};
let mut command = Command::new(cmd);
command.current_dir(&ctx.cwd);
match args {
None | Some(Value::None) => {}
Some(Value::List(xs)) => {
for x in xs {
command.arg(x.as_display());
}
}
Some(Value::Text(s)) => {
command.arg(s);
}
Some(_) => return Err("exec args must be list or text".into()),
}
if capture {
command.stdout(Stdio::piped());
command.stderr(Stdio::piped());
let output = command
.output()
.map_err(|e| format!("exec `{cmd}`: {e}"))?;
let code = output.status.code().unwrap_or(1) as i64;
let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
Ok(Value::Map(vec![
("code".into(), Value::Int(code)),
("stdout".into(), Value::Text(clip_exec_io(&stdout))),
("stderr".into(), Value::Text(clip_exec_io(&stderr))),
]))
} else {
let status = command
.status()
.map_err(|e| format!("exec `{cmd}`: {e}"))?;
Ok(Value::Int(status.code().unwrap_or(1) as i64))
}
}
}
const EXEC_IO_CAP: usize = 256 * 1024;
fn clip_exec_io(s: &str) -> String {
let mut it = s.chars();
let head: String = it.by_ref().take(EXEC_IO_CAP).collect();
if it.next().is_some() {
format!("{head}\n…(truncated)")
} else {
head
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::host::HostContext;
use std::io::Write;
#[test]
fn dotenv_loads_without_override() {
let dir = std::env::temp_dir().join(format!("marqdo-dotenv-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("sample.env");
{
let mut f = std::fs::File::create(&path).unwrap();
writeln!(f, "# comment").unwrap();
writeln!(f, "MARQDO_DOTENV_A=one").unwrap();
writeln!(f, "export MARQDO_DOTENV_B=\"two\"").unwrap();
}
std::env::set_var("MARQDO_DOTENV_A", "keep");
std::env::remove_var("MARQDO_DOTENV_B");
let mut ctx = HostContext::default();
ctx.cwd = dir.clone();
let n = dotenv_load(&ctx, Some(&Value::Text("sample.env".into()))).unwrap();
assert_eq!(n, Value::Int(1));
assert_eq!(std::env::var("MARQDO_DOTENV_A").unwrap(), "keep");
assert_eq!(std::env::var("MARQDO_DOTENV_B").unwrap(), "two");
assert_eq!(
dotenv_load(&ctx, Some(&Value::Text("missing.env".into()))).unwrap(),
Value::Int(0)
);
let _ = std::fs::remove_dir_all(&dir);
}
}