feat(PR-03): execution controller, cancellable process adapter and budgets
- add src/execution/{request,process,controller,events}.rs implementing RFC-0002
§6.3 request validation, function_id->CLI name resolution, single-job
lifecycle, dedupe by client_request_id+payload digest, 409 busy/conflict,
unique terminal states, idempotent cancel and Trace v2 binding against the
exact pre-run Analysis bytes
- route all Core subprocess spawning through one bounded, cancelable adapter
with process-group TERM->2s->KILL, spawn hook, 4 MiB output caps and explicit
--fuel/--max-output/--timeout/trace budgets; CoreClient check/--version reuse it
- add marqdo.view-run-events v1 event log: 128 frame ring, Last-Event-ID replay
or authoritative snapshot, numeric seq/id, heartbeat constant
- add bounded --run-timeout (default 30s, max 120s
- add ADR-0008 (lifecycle/cancel race/trace-missing semantics) and PR-03
evidence; execution tests use a real fake-Core executable
- unit 58 + contract 41 + integration 42 pass; clippy clean
This commit is contained in:
1 parent
5c9a313424
commit
e13c1828a4
23 files changed
+3312
-158
No files matched your search
+21
@@ -41,6 +41,16 @@ pub struct Cli {
|
||||
#[arg(long, global = true)]
|
||||
pub no_open: bool,
|
||||
|
||||
/// Wall-clock limit for one explicit run, in seconds (RFC-VIEW-0002 §6.7).
|
||||
/// The frozen Core receives the same value via `--timeout`.
|
||||
#[arg(
|
||||
long,
|
||||
default_value_t = 30,
|
||||
global = true,
|
||||
value_parser = clap::value_parser!(u64).range(1..=120)
|
||||
)]
|
||||
pub run_timeout: u64,
|
||||
|
||||
/// Advanced: allow a non-loopback bind. No execution API is opened by it.
|
||||
#[arg(long, global = true, hide = true)]
|
||||
pub unsafe_expose: bool,
|
||||
@@ -97,6 +107,7 @@ pub struct RuntimeOpts {
|
||||
pub port: u16,
|
||||
pub no_open: bool,
|
||||
pub unsafe_expose: bool,
|
||||
pub run_timeout_secs: u64,
|
||||
}
|
||||
|
||||
impl Cli {
|
||||
@@ -108,6 +119,7 @@ impl Cli {
|
||||
port: self.port,
|
||||
no_open: self.no_open,
|
||||
unsafe_expose: self.unsafe_expose,
|
||||
run_timeout_secs: self.run_timeout,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -141,6 +153,7 @@ mod tests {
|
||||
assert!(cli.command.is_none());
|
||||
assert_eq!(cli.host, "127.0.0.1");
|
||||
assert_eq!(cli.port, 7429);
|
||||
assert_eq!(cli.run_timeout, 30);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -187,6 +200,14 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_timeout_is_bounded_to_rfc_range() {
|
||||
assert!(Cli::try_parse_from(["marqdo-view", "--run-timeout", "0"]).is_err());
|
||||
assert!(Cli::try_parse_from(["marqdo-view", "--run-timeout", "121"]).is_err());
|
||||
let cli = Cli::parse_from(["marqdo-view", "--run-timeout", "45"]);
|
||||
assert_eq!(cli.runtime().run_timeout_secs, 45);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bind_policy_is_loopback_by_default() {
|
||||
assert!(validate_bind("127.0.0.1", false).is_ok());
|
||||
|
||||
+67
-114
@@ -10,15 +10,14 @@
|
||||
//! drop.
|
||||
|
||||
use crate::error::{ViewError, ViewResult};
|
||||
use crate::execution::process::{run_bounded, ProcessBudget};
|
||||
use crate::protocol::tool_v1::{self, CoreVersion};
|
||||
use crate::reader::source::{sha256_hex, sha256_prefixed};
|
||||
use crate::reader::source::{Project, SafeRelativePath};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::ffi::OsString;
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
use std::time::Duration;
|
||||
|
||||
/// Default View-level wall clock cap for one Core `run`.
|
||||
pub const DEFAULT_RUN_TIMEOUT: Duration = Duration::from_secs(120);
|
||||
@@ -433,75 +432,27 @@ impl CoreClient {
|
||||
})
|
||||
}
|
||||
|
||||
/// Spawn the core with an explicit argv, private cwd and a wall-clock cap.
|
||||
/// Spawn the core through the single process adapter with an explicit
|
||||
/// argv, private cwd, bounded capture and a wall-clock cap.
|
||||
fn execute(&self, args: &[OsString], cwd: &Path, timeout: Duration) -> ViewResult<ExecOutput> {
|
||||
let mut command = Command::new(&self.bin);
|
||||
command
|
||||
.args(args)
|
||||
.current_dir(cwd)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped());
|
||||
// Put the core in its own process group so a View-level timeout kills
|
||||
// the whole subtree, not just the immediate shell-less child.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
// SAFETY: `setpgid` is async-signal-safe and only touches the child
|
||||
// before exec.
|
||||
unsafe {
|
||||
command.pre_exec(|| {
|
||||
if libc::setpgid(0, 0) != 0 {
|
||||
return Err(std::io::Error::last_os_error());
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let mut child = command.spawn().map_err(|err| ViewError::CoreSpawn {
|
||||
detail: format!("spawn {}: {err}", self.bin.display()),
|
||||
})?;
|
||||
let stdout = child.stdout.take().expect("piped stdout");
|
||||
let stderr = child.stderr.take().expect("piped stderr");
|
||||
let stdout_thread = std::thread::spawn(move || read_all(stdout));
|
||||
let stderr_thread = std::thread::spawn(move || read_all(stderr));
|
||||
|
||||
let deadline = Instant::now() + timeout;
|
||||
let status = loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => break status,
|
||||
Ok(None) => {
|
||||
if Instant::now() >= deadline {
|
||||
kill_process_tree(&mut child);
|
||||
let _ = child.wait();
|
||||
let _ = stdout_thread.join();
|
||||
let _ = stderr_thread.join();
|
||||
return Err(ViewError::CoreTimeout {
|
||||
detail: format!(
|
||||
"core did not finish within {}s and was killed",
|
||||
timeout.as_secs()
|
||||
),
|
||||
});
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
Err(err) => {
|
||||
let _ = child.kill();
|
||||
return Err(ViewError::CoreSpawn {
|
||||
detail: format!("wait for {}: {err}", self.bin.display()),
|
||||
});
|
||||
}
|
||||
}
|
||||
let budget = ProcessBudget {
|
||||
wall_clock: timeout,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let stdout_bytes = stdout_thread.join().unwrap_or_default();
|
||||
let stderr_bytes = stderr_thread.join().unwrap_or_default();
|
||||
let stdout = String::from_utf8_lossy(&stdout_bytes).to_string();
|
||||
let stderr = String::from_utf8_lossy(&stderr_bytes).to_string();
|
||||
let outcome = run_bounded(&self.bin, args, cwd, &budget, None)?;
|
||||
if outcome.timed_out {
|
||||
return Err(ViewError::CoreTimeout {
|
||||
detail: format!(
|
||||
"core did not finish within {}s and was killed",
|
||||
timeout.as_secs()
|
||||
),
|
||||
});
|
||||
}
|
||||
let stdout = outcome.stdout.text_lossy();
|
||||
let stderr = outcome.stderr.text_lossy();
|
||||
Ok(ExecOutput {
|
||||
exit_code: status.code().unwrap_or(-1),
|
||||
stdout_bytes,
|
||||
exit_code: outcome.exit_code.unwrap_or(-1),
|
||||
stdout_bytes: outcome.stdout.bytes,
|
||||
stdout,
|
||||
stderr,
|
||||
})
|
||||
@@ -515,86 +466,88 @@ struct ExecOutput {
|
||||
stderr: String,
|
||||
}
|
||||
|
||||
/// Kill the core and every descendant in its process group (Unix), or just the
|
||||
/// direct child elsewhere. Never leaves a runaway subprocess behind.
|
||||
fn kill_process_tree(child: &mut std::process::Child) {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let pid = child.id() as i32;
|
||||
if pid > 0 {
|
||||
// SAFETY: negative pid targets the process group created by
|
||||
// pre_exec(setpgid); ESRCH is harmless when it already exited.
|
||||
unsafe {
|
||||
libc::kill(-pid, libc::SIGKILL);
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = child.kill();
|
||||
}
|
||||
|
||||
fn read_all(mut reader: impl Read) -> Vec<u8> {
|
||||
let mut bytes = Vec::new();
|
||||
let _ = reader.read_to_end(&mut bytes);
|
||||
bytes
|
||||
}
|
||||
|
||||
/// Build the base `check` arguments. The caller appends `--emit <path>` and
|
||||
/// optionally `--refs`; this function exists so the argv shape is unit-testable.
|
||||
fn build_check_args(entry: &Path) -> Vec<OsString> {
|
||||
vec![OsString::from("check"), entry.as_os_str().to_os_string()]
|
||||
}
|
||||
|
||||
/// Build `run` arguments from an already user-approved request.
|
||||
pub fn build_run_args(entry: &Path, trace_path: &Path, options: &RunOptions) -> Vec<OsString> {
|
||||
let mut args = vec![
|
||||
OsString::from("run"),
|
||||
entry.as_os_str().to_os_string(),
|
||||
OsString::from("--mode"),
|
||||
OsString::from(options.mode.as_str()),
|
||||
OsString::from("--json"),
|
||||
OsString::from("--trace-file"),
|
||||
trace_path.as_os_str().to_os_string(),
|
||||
];
|
||||
/// Common explicit flags shared by `run` and `call`. Budgets are always sent
|
||||
/// explicitly by the execution controller (RFC-VIEW-0002 §6.7).
|
||||
fn append_common_args(args: &mut Vec<OsString>, trace_path: &Path, options: &RunOptions) {
|
||||
fn push_pair(args: &mut Vec<OsString>, flag: &str, value: &str) {
|
||||
args.push(OsString::from(flag));
|
||||
args.push(OsString::from(value));
|
||||
}
|
||||
args.push(OsString::from("--mode"));
|
||||
args.push(OsString::from(options.mode.as_str()));
|
||||
args.push(OsString::from("--json"));
|
||||
args.push(OsString::from("--trace-file"));
|
||||
args.push(trace_path.as_os_str().to_os_string());
|
||||
for glob in &options.grants.allow_read {
|
||||
push_pair(&mut args, "--allow-read", glob);
|
||||
push_pair(args, "--allow-read", glob);
|
||||
}
|
||||
for glob in &options.grants.allow_write {
|
||||
push_pair(&mut args, "--allow-write", glob);
|
||||
push_pair(args, "--allow-write", glob);
|
||||
}
|
||||
for host in &options.grants.allow_net {
|
||||
push_pair(&mut args, "--allow-net", host);
|
||||
push_pair(args, "--allow-net", host);
|
||||
}
|
||||
for name in &options.grants.allow_env {
|
||||
push_pair(&mut args, "--allow-env", name);
|
||||
push_pair(args, "--allow-env", name);
|
||||
}
|
||||
for program in &options.grants.allow_process {
|
||||
push_pair(&mut args, "--allow-process", program);
|
||||
push_pair(args, "--allow-process", program);
|
||||
}
|
||||
if options.grants.allow_random {
|
||||
args.push(OsString::from("--allow-random"));
|
||||
}
|
||||
if let Some(fuel) = options.fuel {
|
||||
push_pair(&mut args, "--fuel", &fuel.to_string());
|
||||
push_pair(args, "--fuel", &fuel.to_string());
|
||||
}
|
||||
if let Some(stack) = options.stack {
|
||||
push_pair(&mut args, "--stack", &stack.to_string());
|
||||
push_pair(args, "--stack", &stack.to_string());
|
||||
}
|
||||
if let Some(max_output) = options.max_output {
|
||||
push_pair(&mut args, "--max-output", &max_output.to_string());
|
||||
push_pair(args, "--max-output", &max_output.to_string());
|
||||
}
|
||||
if let Some(timeout) = options.timeout_seconds {
|
||||
push_pair(&mut args, "--timeout", &timeout.to_string());
|
||||
push_pair(args, "--timeout", &timeout.to_string());
|
||||
}
|
||||
if let Some(max_events) = options.trace_max_events {
|
||||
push_pair(&mut args, "--trace-max-events", &max_events.to_string());
|
||||
push_pair(args, "--trace-max-events", &max_events.to_string());
|
||||
}
|
||||
if let Some(max_bytes) = options.trace_max_bytes {
|
||||
push_pair(&mut args, "--trace-max-bytes", &max_bytes.to_string());
|
||||
push_pair(args, "--trace-max-bytes", &max_bytes.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
/// Build `run` arguments from an already user-approved request.
|
||||
pub fn build_run_args(entry: &Path, trace_path: &Path, options: &RunOptions) -> Vec<OsString> {
|
||||
let mut args = vec![OsString::from("run"), entry.as_os_str().to_os_string()];
|
||||
append_common_args(&mut args, trace_path, options);
|
||||
args
|
||||
}
|
||||
|
||||
/// Build `call` arguments: explicit argv, one `--arg name=expression` per
|
||||
/// parameter, never a shell string and never client-supplied flags.
|
||||
pub fn build_call_args(
|
||||
entry: &Path,
|
||||
function: &str,
|
||||
arguments: &[(String, String)],
|
||||
trace_path: &Path,
|
||||
options: &RunOptions,
|
||||
) -> Vec<OsString> {
|
||||
let mut args = vec![
|
||||
OsString::from("call"),
|
||||
entry.as_os_str().to_os_string(),
|
||||
OsString::from(function),
|
||||
];
|
||||
for (name, expression) in arguments {
|
||||
args.push(OsString::from("--arg"));
|
||||
args.push(OsString::from(format!("{name}={expression}")));
|
||||
}
|
||||
append_common_args(&mut args, trace_path, options);
|
||||
args
|
||||
}
|
||||
|
||||
|
||||
+49
-1
@@ -42,6 +42,22 @@ pub enum ViewError {
|
||||
ResourceLimit { detail: String },
|
||||
/// Core subprocess could not be spawned.
|
||||
CoreSpawn { detail: String },
|
||||
/// The submitted run request failed schema/target/parameter validation.
|
||||
RunInvalid { detail: String },
|
||||
/// The entry document has no resolvable `main`; View never substitutes one.
|
||||
NoEntryFunction { detail: String },
|
||||
/// Another explicit run is already active; View allows one at a time.
|
||||
RunBusy { detail: String },
|
||||
/// The same client request id was reused with a different payload.
|
||||
RunConflict { detail: String },
|
||||
/// The requested run id is unknown, expired or belongs to another session.
|
||||
RunNotFound { detail: String },
|
||||
/// Bounded capture of CLI stdout/stderr/JSON/trace exceeded the budget.
|
||||
OutputLimit { detail: String },
|
||||
/// The CLI exited but its `--json` document was missing or invalid.
|
||||
CoreProtocol { detail: String },
|
||||
/// More than two concurrent SSE observers for one job.
|
||||
SseBusy { detail: String },
|
||||
/// Core subprocess exceeded the View-level timeout and was killed.
|
||||
CoreTimeout { detail: String },
|
||||
/// Local file system / HTTP I/O failure.
|
||||
@@ -67,6 +83,14 @@ impl ViewError {
|
||||
ViewError::ResourceLimit { .. } => "view.resource_limit",
|
||||
ViewError::CoreSpawn { .. } => "view.core_spawn",
|
||||
ViewError::CoreTimeout { .. } => "view.core_timeout",
|
||||
ViewError::RunInvalid { .. } => "view.run_invalid",
|
||||
ViewError::NoEntryFunction { .. } => "view.no_entry_function",
|
||||
ViewError::RunBusy { .. } => "view.run_busy",
|
||||
ViewError::RunConflict { .. } => "view.run_conflict",
|
||||
ViewError::RunNotFound { .. } => "view.run_not_found",
|
||||
ViewError::OutputLimit { .. } => "view.output_limit",
|
||||
ViewError::CoreProtocol { .. } => "view.core_protocol",
|
||||
ViewError::SseBusy { .. } => "view.sse_busy",
|
||||
ViewError::Io { .. } => "view.io",
|
||||
ViewError::Unsupported { .. } => "view.unsupported",
|
||||
}
|
||||
@@ -80,7 +104,15 @@ impl ViewError {
|
||||
| ViewError::PathForbidden { .. }
|
||||
| ViewError::BindDenied { .. }
|
||||
| ViewError::SourceSpanInvalid { .. }
|
||||
| ViewError::Unsupported { .. } => ExitClass::Argument,
|
||||
| ViewError::Unsupported { .. }
|
||||
| ViewError::RunInvalid { .. }
|
||||
| ViewError::NoEntryFunction { .. }
|
||||
| ViewError::RunBusy { .. }
|
||||
| ViewError::RunConflict { .. }
|
||||
| ViewError::RunNotFound { .. }
|
||||
| ViewError::OutputLimit { .. }
|
||||
| ViewError::CoreProtocol { .. }
|
||||
| ViewError::SseBusy { .. } => ExitClass::Argument,
|
||||
_ => ExitClass::Runtime,
|
||||
}
|
||||
}
|
||||
@@ -118,6 +150,14 @@ impl ViewError {
|
||||
"view.resource_limit" => "超过配置的资源上限。",
|
||||
"view.core_spawn" => "无法启动冻结核心。",
|
||||
"view.core_timeout" => "冻结核心执行超时,已终止。",
|
||||
"view.run_invalid" => "运行请求未通过校验(目标、参数、模式或授权不合法)。",
|
||||
"view.no_entry_function" => "文档没有可调用的 main;请改选一个 H2 Exec 函数。",
|
||||
"view.run_busy" => "已有一次运行正在进行;本版本每个 View 服务只允许一个任务。",
|
||||
"view.run_conflict" => "同一客户端请求 ID 携带了不同内容,拒绝执行。",
|
||||
"view.run_not_found" => "运行任务不存在、已过期或不属于当前会话。",
|
||||
"view.core_protocol" => "冻结核心退出但未给出合法的 --json 结果。",
|
||||
"view.sse_busy" => "该运行任务的 SSE 观察连接超过上限,请稍后重试。",
|
||||
"view.output_limit" => "执行输出超过 View 的接收上限,已停止接收。",
|
||||
"view.io" => "本地 I/O 失败。",
|
||||
"view.unsupported" => "当前版本不支持该功能。",
|
||||
_ => "View 内部错误。",
|
||||
@@ -162,6 +202,14 @@ impl ViewError {
|
||||
| ViewError::ResourceLimit { detail }
|
||||
| ViewError::CoreSpawn { detail }
|
||||
| ViewError::CoreTimeout { detail }
|
||||
| ViewError::RunInvalid { detail }
|
||||
| ViewError::NoEntryFunction { detail }
|
||||
| ViewError::RunBusy { detail }
|
||||
| ViewError::RunConflict { detail }
|
||||
| ViewError::RunNotFound { detail }
|
||||
| ViewError::OutputLimit { detail }
|
||||
| ViewError::CoreProtocol { detail }
|
||||
| ViewError::SseBusy { detail }
|
||||
| ViewError::Io { detail }
|
||||
| ViewError::Unsupported { detail } => detail,
|
||||
ViewError::SourceMismatch { expected, actual } => {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,430 @@
|
||||
//! View-owned run event log and SSE frames (`marqdo.view-run-events` v1).
|
||||
//!
|
||||
//! This is View's own protocol, not a CLI protocol (RFC-VIEW-0002 §6.4). It
|
||||
//! only carries four event types and a bounded, sequenced replay buffer; it is
|
||||
//! not an event bus and never carries token streams or per-instruction values.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::mpsc::{self, Receiver, SyncSender, TrySendError};
|
||||
|
||||
/// In-memory replay buffer per job (RFC-VIEW-0002 §6.5).
|
||||
pub const EVENT_RING_CAPACITY: usize = 128;
|
||||
/// Heartbeat comment cadence; not an event and does not use a sequence number.
|
||||
pub const HEARTBEAT_INTERVAL_SECS: u64 = 15;
|
||||
pub const HEARTBEAT_FRAME: &str = ": heartbeat\n\n";
|
||||
|
||||
pub const EVENTS_SCHEMA: &str = "marqdo.view-run-events";
|
||||
pub const EVENTS_SCHEMA_VERSION: u32 = 1;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RunState {
|
||||
Accepted,
|
||||
Running,
|
||||
CancelRequested,
|
||||
Succeeded,
|
||||
Failed,
|
||||
Cancelled,
|
||||
TimedOut,
|
||||
Unavailable,
|
||||
}
|
||||
|
||||
impl RunState {
|
||||
pub fn data_value(&self) -> &'static str {
|
||||
match self {
|
||||
RunState::Accepted => "accepted",
|
||||
RunState::Running => "running",
|
||||
RunState::CancelRequested => "cancel_requested",
|
||||
RunState::Succeeded => "succeeded",
|
||||
RunState::Failed => "failed",
|
||||
RunState::Cancelled => "cancelled",
|
||||
RunState::TimedOut => "timed_out",
|
||||
RunState::Unavailable => "unavailable",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn label(&self) -> &'static str {
|
||||
match self {
|
||||
RunState::Accepted => "已接受",
|
||||
RunState::Running => "运行中",
|
||||
RunState::CancelRequested => "正在取消",
|
||||
RunState::Succeeded => "成功",
|
||||
RunState::Failed => "失败",
|
||||
RunState::Cancelled => "已取消",
|
||||
RunState::TimedOut => "超时",
|
||||
RunState::Unavailable => "不可用",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_terminal(&self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
RunState::Succeeded
|
||||
| RunState::Failed
|
||||
| RunState::Cancelled
|
||||
| RunState::TimedOut
|
||||
| RunState::Unavailable
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum EventKind {
|
||||
State,
|
||||
Complete,
|
||||
Error,
|
||||
Snapshot,
|
||||
}
|
||||
|
||||
impl EventKind {
|
||||
pub fn sse_name(&self) -> &'static str {
|
||||
match self {
|
||||
EventKind::State => "run.state",
|
||||
EventKind::Complete => "run.complete",
|
||||
EventKind::Error => "run.error",
|
||||
EventKind::Snapshot => "run.snapshot",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RunEvent {
|
||||
pub seq: u64,
|
||||
pub kind: EventKind,
|
||||
pub state: RunState,
|
||||
pub at: String,
|
||||
/// Safe parsed CLI result summary (never raw HTML/innerHTML material).
|
||||
pub result: Option<serde_json::Value>,
|
||||
/// Verified Trace v2 summary, only after digest/binding checks.
|
||||
pub trace: Option<serde_json::Value>,
|
||||
/// `{code, message}` for terminal failures.
|
||||
pub error: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
impl RunEvent {
|
||||
pub fn data(&self, run_id: &str) -> serde_json::Value {
|
||||
let mut data = serde_json::json!({
|
||||
"schema": EVENTS_SCHEMA,
|
||||
"schema_version": EVENTS_SCHEMA_VERSION,
|
||||
"run_id": run_id,
|
||||
"seq": self.seq,
|
||||
"state": self.state.data_value(),
|
||||
"at": self.at,
|
||||
});
|
||||
if let Some(result) = &self.result {
|
||||
data["result"] = result.clone();
|
||||
}
|
||||
if let Some(trace) = &self.trace {
|
||||
data["trace"] = trace.clone();
|
||||
}
|
||||
if let Some(error) = &self.error {
|
||||
data["error"] = error.clone();
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
/// One SSE frame with `event:`, numeric `id` equal to `data.seq`, and JSON
|
||||
/// data on a single line.
|
||||
pub fn to_sse(&self, run_id: &str) -> String {
|
||||
let data = serde_json::to_string(&self.data(run_id))
|
||||
.unwrap_or_else(|_| "{\"schema\":\"marqdo.view-run-events\"}".to_string());
|
||||
format!(
|
||||
"event: {}\nid: {}\ndata: {}\n\n",
|
||||
self.kind.sse_name(),
|
||||
self.seq,
|
||||
data
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Result of subscribing: the frames to write first, then a bounded receiver.
|
||||
pub struct Subscription {
|
||||
pub replay: Vec<RunEvent>,
|
||||
pub receiver: Receiver<RunEvent>,
|
||||
/// True when the stream must be closed after writing replay (terminal job).
|
||||
pub terminal: bool,
|
||||
}
|
||||
|
||||
/// Per-job event log. Callers provide the locking (the controller holds the job
|
||||
/// lock while publishing and while snapshot+subscribe to avoid races).
|
||||
pub struct EventLog {
|
||||
next_seq: u64,
|
||||
ring: VecDeque<RunEvent>,
|
||||
subscribers: Vec<SyncSender<RunEvent>>,
|
||||
last_state: RunState,
|
||||
terminal_snapshot: Option<RunEvent>,
|
||||
}
|
||||
|
||||
impl Default for EventLog {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl EventLog {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
next_seq: 1,
|
||||
ring: VecDeque::with_capacity(EVENT_RING_CAPACITY),
|
||||
subscribers: Vec::new(),
|
||||
last_state: RunState::Accepted,
|
||||
terminal_snapshot: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn next_event(&mut self, kind: EventKind, state: RunState) -> RunEvent {
|
||||
let event = RunEvent {
|
||||
seq: self.next_seq,
|
||||
kind,
|
||||
state,
|
||||
at: utc_now(),
|
||||
result: None,
|
||||
trace: None,
|
||||
error: None,
|
||||
};
|
||||
self.next_seq += 1;
|
||||
self.last_state = state;
|
||||
event
|
||||
}
|
||||
|
||||
fn record(&mut self, mut event: RunEvent) -> RunEvent {
|
||||
if self.ring.len() == EVENT_RING_CAPACITY {
|
||||
self.ring.pop_front();
|
||||
}
|
||||
// A single terminal event is the only one ever stored as the final
|
||||
// snapshot; once terminal, later publishes are ignored by the caller.
|
||||
if event.state.is_terminal() {
|
||||
event.kind = match event.kind {
|
||||
EventKind::State => EventKind::State,
|
||||
other => other,
|
||||
};
|
||||
self.terminal_snapshot = Some(event.clone());
|
||||
}
|
||||
self.ring.push_back(event.clone());
|
||||
self.subscribers
|
||||
.retain(|sender| match sender.try_send(event.clone()) {
|
||||
Ok(()) => true,
|
||||
Err(TrySendError::Full(_)) | Err(TrySendError::Disconnected(_)) => false,
|
||||
});
|
||||
event
|
||||
}
|
||||
|
||||
pub fn publish_state(&mut self, state: RunState) -> RunEvent {
|
||||
let event = self.next_event(EventKind::State, state);
|
||||
self.record(event)
|
||||
}
|
||||
|
||||
pub fn publish_complete(
|
||||
&mut self,
|
||||
result: serde_json::Value,
|
||||
trace: Option<serde_json::Value>,
|
||||
) -> RunEvent {
|
||||
let mut event = self.next_event(EventKind::Complete, RunState::Succeeded);
|
||||
event.result = Some(result);
|
||||
event.trace = trace;
|
||||
self.record(event)
|
||||
}
|
||||
|
||||
pub fn publish_error(
|
||||
&mut self,
|
||||
state: RunState,
|
||||
code: &str,
|
||||
message: &str,
|
||||
result: Option<serde_json::Value>,
|
||||
trace: Option<serde_json::Value>,
|
||||
) -> RunEvent {
|
||||
let mut event = self.next_event(EventKind::Error, state);
|
||||
event.error = Some(serde_json::json!({
|
||||
"code": code,
|
||||
"message": message,
|
||||
}));
|
||||
event.result = result;
|
||||
event.trace = trace;
|
||||
self.record(event)
|
||||
}
|
||||
|
||||
pub fn last_state(&self) -> RunState {
|
||||
self.last_state
|
||||
}
|
||||
|
||||
pub fn terminal(&self) -> bool {
|
||||
self.terminal_snapshot.is_some() || self.last_state.is_terminal()
|
||||
}
|
||||
|
||||
pub fn oldest_seq(&self) -> Option<u64> {
|
||||
self.ring.front().map(|event| event.seq)
|
||||
}
|
||||
|
||||
/// Build the current snapshot frame from the latest known state (and the
|
||||
/// terminal result when present). A snapshot always carries the newest
|
||||
/// sequence number, never a fake historical one.
|
||||
pub fn snapshot_event(&mut self) -> RunEvent {
|
||||
// A snapshot always takes a fresh sequence so a client that already saw
|
||||
// earlier frames never mistakes it for a duplicate and skips it.
|
||||
let seq = self.next_seq;
|
||||
self.next_seq += 1;
|
||||
if let Some(terminal) = &self.terminal_snapshot {
|
||||
let mut snapshot = terminal.clone();
|
||||
snapshot.seq = seq;
|
||||
snapshot.kind = EventKind::Snapshot;
|
||||
return snapshot;
|
||||
}
|
||||
RunEvent {
|
||||
seq,
|
||||
kind: EventKind::Snapshot,
|
||||
state: self.last_state,
|
||||
at: utc_now(),
|
||||
result: None,
|
||||
trace: None,
|
||||
error: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Atomically build replay and register the subscriber. The caller must
|
||||
/// hold the job lock (controller's Mutex) across this call.
|
||||
pub fn subscribe(&mut self, last_event_id: Option<u64>) -> Subscription {
|
||||
let (sender, receiver) = mpsc::sync_channel(EVENT_RING_CAPACITY);
|
||||
let terminal = self.terminal();
|
||||
let mut replay: Vec<RunEvent> = Vec::new();
|
||||
|
||||
match last_event_id {
|
||||
Some(cursor) => {
|
||||
let oldest = self.oldest_seq().unwrap_or(self.next_seq);
|
||||
let last = self.next_seq.saturating_sub(1);
|
||||
if cursor > last || cursor + 1 < oldest {
|
||||
// Too old (already evicted) or forged: synchronise with one
|
||||
// authoritative snapshot instead of a discontinuous history.
|
||||
replay.push(self.snapshot_event());
|
||||
} else {
|
||||
replay.extend(self.ring.iter().filter(|event| event.seq > cursor).cloned());
|
||||
}
|
||||
}
|
||||
None => {
|
||||
replay.push(self.snapshot_event());
|
||||
}
|
||||
}
|
||||
|
||||
if !terminal {
|
||||
self.subscribers.push(sender);
|
||||
}
|
||||
Subscription {
|
||||
replay,
|
||||
receiver,
|
||||
terminal,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Minimal RFC3339 UTC timestamp without a date/time dependency.
|
||||
pub fn utc_now() -> String {
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default();
|
||||
format_utc(now.as_secs())
|
||||
}
|
||||
|
||||
fn format_utc(epoch_secs: u64) -> String {
|
||||
let days = (epoch_secs / 86_400) as i64;
|
||||
let seconds = epoch_secs % 86_400;
|
||||
let (year, month, day) = civil_from_days(days);
|
||||
format!(
|
||||
"{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",
|
||||
seconds / 3600,
|
||||
(seconds % 3600) / 60,
|
||||
seconds % 60
|
||||
)
|
||||
}
|
||||
|
||||
/// Howard Hinnant's `civil_from_days`, valid for the Unix epoch range.
|
||||
fn civil_from_days(days: i64) -> (i64, u32, u32) {
|
||||
let z = days + 719_468;
|
||||
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
|
||||
let doe = z - era * 146_097;
|
||||
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
|
||||
let y = yoe + era * 400;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let d = doy - (153 * mp + 2) / 5 + 1;
|
||||
let m = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||
(if m <= 2 { y + 1 } else { y }, m as u32, d as u32)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn states_have_stable_wire_values_and_terminals() {
|
||||
assert_eq!(RunState::CancelRequested.data_value(), "cancel_requested");
|
||||
assert!(!RunState::CancelRequested.is_terminal());
|
||||
for state in [
|
||||
RunState::Succeeded,
|
||||
RunState::Failed,
|
||||
RunState::Cancelled,
|
||||
RunState::TimedOut,
|
||||
RunState::Unavailable,
|
||||
] {
|
||||
assert!(state.is_terminal());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frames_have_event_id_and_matching_data_seq() {
|
||||
let mut log = EventLog::new();
|
||||
let event = log.publish_state(RunState::Running);
|
||||
let frame = event.to_sse("run-1");
|
||||
assert!(frame.starts_with("event: run.state\n"));
|
||||
assert!(frame.contains(&format!("id: {}", event.seq)));
|
||||
let data_line = frame
|
||||
.lines()
|
||||
.find(|line| line.starts_with("data: "))
|
||||
.expect("data line");
|
||||
let data: serde_json::Value =
|
||||
serde_json::from_str(data_line.trim_start_matches("data: ")).expect("json");
|
||||
assert_eq!(data["seq"], event.seq);
|
||||
assert_eq!(data["run_id"], "run-1");
|
||||
assert_eq!(data["state"], "running");
|
||||
assert_eq!(data["schema"], EVENTS_SCHEMA);
|
||||
assert_eq!(data["schema_version"], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ring_is_bounded_and_old_cursor_gets_snapshot() {
|
||||
let mut log = EventLog::new();
|
||||
for _ in 0..(EVENT_RING_CAPACITY + 40) {
|
||||
log.publish_state(RunState::Running);
|
||||
}
|
||||
assert_eq!(log.ring.len(), EVENT_RING_CAPACITY);
|
||||
let subscription = log.subscribe(Some(1));
|
||||
assert_eq!(subscription.replay.len(), 1);
|
||||
assert_eq!(subscription.replay[0].kind, EventKind::Snapshot);
|
||||
assert!(!subscription.terminal);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminal_job_replays_snapshot_and_closes() {
|
||||
let mut log = EventLog::new();
|
||||
log.publish_state(RunState::Running);
|
||||
log.publish_complete(serde_json::json!({"success": true}), None);
|
||||
let subscription = log.subscribe(None);
|
||||
assert!(subscription.terminal);
|
||||
assert_eq!(subscription.replay[0].kind, EventKind::Snapshot);
|
||||
assert_eq!(subscription.replay[0].state, RunState::Succeeded);
|
||||
assert!(subscription.replay[0].result.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn utc_formatting_is_stable() {
|
||||
assert_eq!(format_utc(0), "1970-01-01T00:00:00Z");
|
||||
assert_eq!(format_utc(1_700_000_000), "2023-11-14T22:13:20Z");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn newest_cursor_replays_only_new_events() {
|
||||
let mut log = EventLog::new();
|
||||
let first = log.publish_state(RunState::Accepted);
|
||||
let second = log.publish_state(RunState::Running);
|
||||
let subscription = log.subscribe(Some(first.seq));
|
||||
assert_eq!(subscription.replay.len(), 1);
|
||||
assert_eq!(subscription.replay[0].seq, second.seq);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
//! Execution layer: the only path from an explicit user request to a Core
|
||||
//! subprocess.
|
||||
//!
|
||||
//! `DocumentService` and the renderer never depend on this module; only the
|
||||
//! `POST /api/runs` server handler can reach it (RFC-VIEW-0002 §5.1).
|
||||
//!
|
||||
//! - `request`: schema/target/parameter/mode/grant validation
|
||||
//! - `process`: the one cancellable Core process adapter with bounded capture
|
||||
//! - `events`: bounded, sequenced View-owned run events and SSE frames
|
||||
//! - `controller`: single-job lifecycle, dedupe, cancel, Trace binding
|
||||
|
||||
pub mod controller;
|
||||
pub mod events;
|
||||
pub mod process;
|
||||
pub mod request;
|
||||
@@ -0,0 +1,293 @@
|
||||
//! The one cancellable CLI process adapter.
|
||||
//!
|
||||
//! Every explicit run/call is spawned here as an explicit argv array (never a
|
||||
//! shell), in its own process group, with bounded stdout/stderr capture and a
|
||||
//! View-owned wall-clock cap that does not rely on the Core terminating itself
|
||||
//! (RFC-VIEW-0002 §6.7).
|
||||
//!
|
||||
//! The adapter is also used by `core_client` for read-only `check`/`--version`
|
||||
//! calls so there is exactly one process-spawning implementation in View.
|
||||
|
||||
use crate::error::{ViewError, ViewResult};
|
||||
use std::ffi::OsString;
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Default stdout/JSON budget (4 MiB, RFC-VIEW-0002 §6.7).
|
||||
pub const MAX_STDOUT_BYTES: usize = 4 * 1024 * 1024;
|
||||
/// Default stderr budget retained for display.
|
||||
pub const MAX_STDERR_BYTES: usize = 64 * 1024;
|
||||
/// Grace period between SIGTERM and SIGKILL when cancelling.
|
||||
pub const CANCEL_GRACE: Duration = Duration::from_secs(2);
|
||||
/// Poll interval for child state/cancel/wall-clock checks.
|
||||
const POLL: Duration = Duration::from_millis(20);
|
||||
|
||||
/// Execution budgets sent to the Core and enforced again by View.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ProcessBudget {
|
||||
/// View-owned wall clock. Always <= the Core `--timeout` value.
|
||||
pub wall_clock: Duration,
|
||||
pub max_stdout: usize,
|
||||
pub max_stderr: usize,
|
||||
}
|
||||
|
||||
impl Default for ProcessBudget {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
wall_clock: Duration::from_secs(30),
|
||||
max_stdout: MAX_STDOUT_BYTES,
|
||||
max_stderr: MAX_STDERR_BYTES,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One bounded stream capture. Reading continues past the cap (so the child
|
||||
/// never blocks on a full pipe) but retained bytes stay bounded.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct Captured {
|
||||
pub bytes: Vec<u8>,
|
||||
pub total: usize,
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
impl Captured {
|
||||
pub fn text_lossy(&self) -> String {
|
||||
String::from_utf8_lossy(&self.bytes).to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ProcessOutcome {
|
||||
pub exit_code: Option<i32>,
|
||||
pub stdout: Captured,
|
||||
pub stderr: Captured,
|
||||
pub cancelled: bool,
|
||||
pub timed_out: bool,
|
||||
pub duration: Duration,
|
||||
}
|
||||
|
||||
impl ProcessOutcome {
|
||||
pub fn status_ok(&self) -> bool {
|
||||
self.exit_code == Some(0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Spawn one Core process and wait for it with bounded capture, optional
|
||||
/// cancellation and a hard wall-clock cap. Never uses a shell.
|
||||
pub fn run_bounded(
|
||||
bin: &Path,
|
||||
args: &[OsString],
|
||||
cwd: &Path,
|
||||
budget: &ProcessBudget,
|
||||
cancel: Option<Arc<AtomicBool>>,
|
||||
) -> ViewResult<ProcessOutcome> {
|
||||
run_bounded_with_hook(bin, args, cwd, budget, cancel, Box::new(|| {}))
|
||||
}
|
||||
|
||||
/// Same as [`run_bounded`], with a hook invoked exactly once **after** the
|
||||
/// child process was successfully spawned (used to publish `running`).
|
||||
pub fn run_bounded_with_hook(
|
||||
bin: &Path,
|
||||
args: &[OsString],
|
||||
cwd: &Path,
|
||||
budget: &ProcessBudget,
|
||||
cancel: Option<Arc<AtomicBool>>,
|
||||
on_spawn: Box<dyn FnOnce() + Send>,
|
||||
) -> ViewResult<ProcessOutcome> {
|
||||
let started = Instant::now();
|
||||
let mut command = Command::new(bin);
|
||||
command
|
||||
.args(args)
|
||||
.current_dir(cwd)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped());
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
// SAFETY: async-signal-safe child-only setup before exec.
|
||||
unsafe {
|
||||
command.pre_exec(|| {
|
||||
if libc::setpgid(0, 0) != 0 {
|
||||
return Err(std::io::Error::last_os_error());
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
}
|
||||
let mut child = command.spawn().map_err(|err| ViewError::CoreSpawn {
|
||||
detail: format!("spawn {}: {err}", bin.display()),
|
||||
})?;
|
||||
on_spawn();
|
||||
let stdout = child.stdout.take().expect("piped stdout");
|
||||
let stderr = child.stderr.take().expect("piped stderr");
|
||||
let stdout_cap = budget.max_stdout;
|
||||
let stderr_cap = budget.max_stderr;
|
||||
let stdout_thread = std::thread::spawn(move || read_bounded(stdout, stdout_cap));
|
||||
let stderr_thread = std::thread::spawn(move || read_bounded(stderr, stderr_cap));
|
||||
|
||||
let deadline = started + budget.wall_clock;
|
||||
let mut cancelled = false;
|
||||
let mut timed_out = false;
|
||||
let mut cancel_sent: Option<Instant> = None;
|
||||
let status = loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => break status,
|
||||
Ok(None) => {}
|
||||
Err(err) => {
|
||||
terminate_group(&mut child);
|
||||
return Err(ViewError::CoreSpawn {
|
||||
detail: format!("wait for {}: {err}", bin.display()),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(flag) = cancel.as_deref() {
|
||||
if flag.load(Ordering::SeqCst) && cancel_sent.is_none() {
|
||||
cancel_sent = Some(Instant::now());
|
||||
signal_group(child.id(), libc::SIGTERM);
|
||||
}
|
||||
}
|
||||
if let Some(since) = cancel_sent {
|
||||
if since.elapsed() >= CANCEL_GRACE {
|
||||
signal_group(child.id(), libc::SIGKILL);
|
||||
cancelled = true;
|
||||
}
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
signal_group(child.id(), libc::SIGKILL);
|
||||
timed_out = true;
|
||||
}
|
||||
if cancelled || timed_out {
|
||||
// Keep polling until the child is reaped; the group may take a
|
||||
// moment to die after SIGKILL.
|
||||
std::thread::sleep(POLL);
|
||||
continue;
|
||||
}
|
||||
std::thread::sleep(POLL);
|
||||
};
|
||||
|
||||
// A cancel request that raced with a natural exit must not fabricate a
|
||||
// cancellation: only a kill initiated by this adapter marks it cancelled.
|
||||
if cancel_sent.is_some() && !cancelled && !timed_out {
|
||||
cancelled = false;
|
||||
}
|
||||
let stdout = stdout_thread.join().unwrap_or_default();
|
||||
let stderr = stderr_thread.join().unwrap_or_default();
|
||||
Ok(ProcessOutcome {
|
||||
exit_code: status.code(),
|
||||
stdout,
|
||||
stderr,
|
||||
cancelled,
|
||||
timed_out,
|
||||
duration: started.elapsed(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Signal a whole process group (Unix) or only the child elsewhere.
|
||||
pub fn signal_group(pid: u32, signal: i32) {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let pgid = pid as i32;
|
||||
if pgid > 0 {
|
||||
// SAFETY: negative pid targets the group created by setpgid; ESRCH
|
||||
// is harmless when the process already exited.
|
||||
unsafe {
|
||||
libc::kill(-pgid, signal);
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
let _ = (pid, signal);
|
||||
}
|
||||
}
|
||||
|
||||
fn terminate_group(child: &mut Child) {
|
||||
signal_group(child.id(), kill_signal());
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
|
||||
fn kill_signal() -> i32 {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
libc::SIGKILL
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
9
|
||||
}
|
||||
}
|
||||
|
||||
fn read_bounded(mut reader: impl Read, cap: usize) -> Captured {
|
||||
let mut captured = Captured::default();
|
||||
let mut buffer = [0u8; 16 * 1024];
|
||||
loop {
|
||||
match reader.read(&mut buffer) {
|
||||
Ok(0) => break,
|
||||
Ok(read) => {
|
||||
captured.total += read;
|
||||
let remaining = cap.saturating_sub(captured.bytes.len());
|
||||
if remaining > 0 {
|
||||
let take = remaining.min(read);
|
||||
captured.bytes.extend_from_slice(&buffer[..take]);
|
||||
}
|
||||
if captured.total > cap {
|
||||
captured.truncated = true;
|
||||
}
|
||||
}
|
||||
Err(err) if err.kind() == std::io::ErrorKind::Interrupted => continue,
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
captured
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn bounded_capture_keeps_limit_and_drains() {
|
||||
let captured = read_bounded(std::io::Cursor::new(vec![b'x'; 100]), 10);
|
||||
assert_eq!(captured.bytes.len(), 10);
|
||||
assert_eq!(captured.total, 100);
|
||||
assert!(captured.truncated);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_budget_matches_rfc() {
|
||||
let budget = ProcessBudget::default();
|
||||
assert_eq!(budget.wall_clock, Duration::from_secs(30));
|
||||
assert_eq!(budget.max_stdout, 4 * 1024 * 1024);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn cancellation_terminates_the_process_group() {
|
||||
let flag = Arc::new(AtomicBool::new(true));
|
||||
let start = Instant::now();
|
||||
let outcome = run_bounded(
|
||||
Path::new("/bin/sleep"),
|
||||
&[OsString::from("30")],
|
||||
Path::new("/"),
|
||||
&ProcessBudget {
|
||||
wall_clock: Duration::from_secs(20),
|
||||
..Default::default()
|
||||
},
|
||||
Some(flag),
|
||||
)
|
||||
.expect("spawn sleep");
|
||||
assert_ne!(
|
||||
outcome.exit_code,
|
||||
Some(0),
|
||||
"cancel must not look successful"
|
||||
);
|
||||
assert!(start.elapsed() < Duration::from_secs(10));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,594 @@
|
||||
//! Validation of the two-phase explicit run request (RFC-VIEW-0002 §6.3).
|
||||
//!
|
||||
//! The browser never sends a command: it sends a document, a target selected
|
||||
//! from Analysis v2, constant parameter expressions, the exact Analysis digest
|
||||
//! it rendered, a mode and (for project mode) explicit fs globs. Everything is
|
||||
//! re-validated here and finally by the Core itself; the client cannot inject
|
||||
//! cwd, flags, a binary path or shell text.
|
||||
|
||||
use crate::core_client::Grants;
|
||||
use crate::error::{ViewError, ViewResult};
|
||||
use crate::protocol::analysis_v2::SemanticProjection;
|
||||
use crate::reader::source::SafeRelativePath;
|
||||
use serde::Deserialize;
|
||||
|
||||
/// Bounded request body size accepted before JSON parsing (RFC §6.8).
|
||||
pub const MAX_RUN_BODY_BYTES: usize = 64 * 1024;
|
||||
pub const MAX_PARAMETERS: usize = 32;
|
||||
pub const MAX_EXPRESSION_CHARS: usize = 4096;
|
||||
pub const MAX_GRANT_GLOBS: usize = 16;
|
||||
pub const MAX_GRANT_CHARS: usize = 256;
|
||||
pub const MAX_CLIENT_REQUEST_ID_CHARS: usize = 128;
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct RunRequest {
|
||||
pub document: String,
|
||||
pub target: RunTarget,
|
||||
#[serde(default)]
|
||||
pub parameters: Vec<ParameterInput>,
|
||||
pub analysis_digest: String,
|
||||
#[serde(default = "default_mode")]
|
||||
pub mode: String,
|
||||
#[serde(default)]
|
||||
pub grants: GrantRequest,
|
||||
pub client_request_id: String,
|
||||
}
|
||||
|
||||
fn default_mode() -> String {
|
||||
"pure".to_string()
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(tag = "kind", deny_unknown_fields)]
|
||||
pub enum RunTarget {
|
||||
#[serde(rename = "entry")]
|
||||
Entry,
|
||||
#[serde(rename = "function")]
|
||||
Function { function_id: String },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ParameterInput {
|
||||
pub name: String,
|
||||
pub expression: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct GrantRequest {
|
||||
#[serde(default)]
|
||||
pub read: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub write: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RunMode {
|
||||
Pure,
|
||||
Project,
|
||||
}
|
||||
|
||||
impl RunMode {
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
RunMode::Pure => "pure",
|
||||
RunMode::Project => "project",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A request that passed schema/size/path/mode/grant validation, before the
|
||||
/// read-only `check` and Analysis-digest step performed by the controller.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ValidatedRequest {
|
||||
pub document: SafeRelativePath,
|
||||
pub target: RunTarget,
|
||||
pub parameters: Vec<ParameterInput>,
|
||||
pub analysis_digest: String,
|
||||
pub mode: RunMode,
|
||||
pub grants: Grants,
|
||||
pub client_request_id: String,
|
||||
}
|
||||
|
||||
/// The target resolved against the entry module's verified Analysis.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ExecutionTarget {
|
||||
/// `marqdo run FILE` (entry `main`).
|
||||
Entry,
|
||||
/// `marqdo call FILE NAME --arg ...`.
|
||||
Function {
|
||||
/// Canonical or unique local name accepted by the frozen CLI.
|
||||
cli_name: String,
|
||||
/// Display label from Analysis (`namespace.local_name` when present).
|
||||
label: String,
|
||||
},
|
||||
}
|
||||
|
||||
/// One target/parameter plan for the Core argv builder.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ExecutionPlan {
|
||||
pub document: SafeRelativePath,
|
||||
pub target: ExecutionTarget,
|
||||
pub arguments: Vec<(String, String)>,
|
||||
pub mode: RunMode,
|
||||
pub grants: Grants,
|
||||
pub analysis_digest: String,
|
||||
pub client_request_id: String,
|
||||
}
|
||||
|
||||
impl ValidatedRequest {
|
||||
/// Resolve the target and parameter names against the verified entry-module
|
||||
/// Analysis. Never accepts a dependency-module function id (RFC §6.3).
|
||||
pub fn plan_against(self, projection: &SemanticProjection) -> ViewResult<ExecutionPlan> {
|
||||
let target = match &self.target {
|
||||
RunTarget::Entry => {
|
||||
if resolve_main(projection).is_none() {
|
||||
return Err(ViewError::NoEntryFunction {
|
||||
detail: format!(
|
||||
"{} 没有可调用的 main;请从函数面板选择一个 H2 Exec 函数",
|
||||
self.document
|
||||
),
|
||||
});
|
||||
}
|
||||
ExecutionTarget::Entry
|
||||
}
|
||||
RunTarget::Function { function_id } => {
|
||||
let function = projection
|
||||
.functions
|
||||
.iter()
|
||||
.find(|function| &function.id == function_id)
|
||||
.ok_or_else(|| ViewError::RunInvalid {
|
||||
detail: format!(
|
||||
"function_id {function_id:?} 不在当前入口模块可调用函数中;依赖模块函数不能作为 call 目标"
|
||||
),
|
||||
})?;
|
||||
let canonical = canonical_name(&function.id, &projection.module_id);
|
||||
let cli_name = if unique_local_name(projection, &function.local_name, &function.id)
|
||||
{
|
||||
function.local_name.clone()
|
||||
} else {
|
||||
canonical.clone()
|
||||
};
|
||||
let label = canonical;
|
||||
validate_parameters(&self.parameters, projection, &function.id)?;
|
||||
ExecutionTarget::Function { cli_name, label }
|
||||
}
|
||||
};
|
||||
Ok(ExecutionPlan {
|
||||
document: self.document,
|
||||
target,
|
||||
arguments: self
|
||||
.parameters
|
||||
.into_iter()
|
||||
.map(|parameter| (parameter.name, parameter.expression))
|
||||
.collect(),
|
||||
mode: self.mode,
|
||||
grants: self.grants,
|
||||
analysis_digest: self.analysis_digest,
|
||||
client_request_id: self.client_request_id,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse and validate the raw request against fixed limits. Does not touch the
|
||||
/// file system or the Core; the controller performs the read-only check next.
|
||||
pub fn validate_request(body: &[u8]) -> ViewResult<ValidatedRequest> {
|
||||
if body.len() > MAX_RUN_BODY_BYTES {
|
||||
return Err(ViewError::RunInvalid {
|
||||
detail: format!("运行请求体超过 {MAX_RUN_BODY_BYTES} 字节上限"),
|
||||
});
|
||||
}
|
||||
let request: RunRequest =
|
||||
serde_json::from_slice(body).map_err(|err| ViewError::RunInvalid {
|
||||
detail: format!("运行请求不是合法的 marqdo.view-run-request v1 JSON: {err}"),
|
||||
})?;
|
||||
|
||||
validate_client_request_id(&request.client_request_id)?;
|
||||
validate_digest(&request.analysis_digest)?;
|
||||
let document = SafeRelativePath::parse(&request.document)?;
|
||||
if !document.as_str().ends_with(".mq.md") {
|
||||
return Err(ViewError::RunInvalid {
|
||||
detail: "运行目标必须是受控项目根内的 .mq.md 文档".to_string(),
|
||||
});
|
||||
}
|
||||
match &request.target {
|
||||
RunTarget::Entry => {}
|
||||
RunTarget::Function { function_id } => {
|
||||
if function_id.is_empty()
|
||||
|| function_id.len() > 512
|
||||
|| function_id.chars().any(|ch| ch.is_control() || ch == '\0')
|
||||
{
|
||||
return Err(ViewError::RunInvalid {
|
||||
detail: "function_id 必须来自 Analysis v2 且长度为 1..=512".to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if request.parameters.len() > MAX_PARAMETERS {
|
||||
return Err(ViewError::RunInvalid {
|
||||
detail: format!("参数数量超过 {MAX_PARAMETERS} 个上限"),
|
||||
});
|
||||
}
|
||||
for parameter in &request.parameters {
|
||||
validate_parameter_name(¶meter.name)?;
|
||||
validate_expression(¶meter.expression)?;
|
||||
}
|
||||
|
||||
let (mode, grants) = validate_mode_and_grants(&request.mode, &request.grants)?;
|
||||
|
||||
Ok(ValidatedRequest {
|
||||
document,
|
||||
target: request.target,
|
||||
parameters: request.parameters,
|
||||
analysis_digest: request.analysis_digest,
|
||||
mode,
|
||||
grants,
|
||||
client_request_id: request.client_request_id,
|
||||
})
|
||||
}
|
||||
|
||||
fn validate_client_request_id(value: &str) -> ViewResult<()> {
|
||||
if value.is_empty()
|
||||
|| value.chars().count() > MAX_CLIENT_REQUEST_ID_CHARS
|
||||
|| !value
|
||||
.chars()
|
||||
.all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.' | ':'))
|
||||
{
|
||||
return Err(ViewError::RunInvalid {
|
||||
detail: format!(
|
||||
"client_request_id 必须是不透明的 ASCII 标识(1..={MAX_CLIENT_REQUEST_ID_CHARS},字母/数字/-_ .:)"
|
||||
),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_digest(value: &str) -> ViewResult<()> {
|
||||
let Some(hex) = value.strip_prefix("sha256:") else {
|
||||
return Err(ViewError::RunInvalid {
|
||||
detail: "analysis_digest 必须以 sha256: 开头".to_string(),
|
||||
});
|
||||
};
|
||||
if hex.len() != 64 || !hex.chars().all(|ch| ch.is_ascii_hexdigit()) {
|
||||
return Err(ViewError::RunInvalid {
|
||||
detail: "analysis_digest 必须是 sha256:<64 hex>".to_string(),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_parameter_name(name: &str) -> ViewResult<()> {
|
||||
if name.is_empty()
|
||||
|| name.chars().count() > 128
|
||||
|| name
|
||||
.chars()
|
||||
.any(|ch| ch.is_control() || ch.is_whitespace() || ch == '=')
|
||||
{
|
||||
return Err(ViewError::RunInvalid {
|
||||
detail: "参数名必须非空且不包含控制字符、空白或 '='".to_string(),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_expression(expression: &str) -> ViewResult<()> {
|
||||
if expression.trim().is_empty() {
|
||||
return Err(ViewError::RunInvalid {
|
||||
detail: "参数 expression 不能为空;View 不做隐式裸文本转字符串".to_string(),
|
||||
});
|
||||
}
|
||||
if expression.chars().count() > MAX_EXPRESSION_CHARS {
|
||||
return Err(ViewError::RunInvalid {
|
||||
detail: format!("参数 expression 超过 {MAX_EXPRESSION_CHARS} 字符上限"),
|
||||
});
|
||||
}
|
||||
if expression.chars().any(|ch| ch == '\0' || ch.is_control()) {
|
||||
return Err(ViewError::RunInvalid {
|
||||
detail: "参数 expression 不能包含 NUL/控制字符".to_string(),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_mode_and_grants(mode: &str, grants: &GrantRequest) -> ViewResult<(RunMode, Grants)> {
|
||||
match mode {
|
||||
"pure" => {
|
||||
if !grants.read.is_empty() || !grants.write.is_empty() {
|
||||
return Err(ViewError::RunInvalid {
|
||||
detail: "pure 模式不能携带 fs grants;需要文件访问时请显式选择 project 模式"
|
||||
.to_string(),
|
||||
});
|
||||
}
|
||||
Ok((RunMode::Pure, Grants::default()))
|
||||
}
|
||||
"project" => {
|
||||
if grants.read.len() > MAX_GRANT_GLOBS || grants.write.len() > MAX_GRANT_GLOBS {
|
||||
return Err(ViewError::RunInvalid {
|
||||
detail: format!("每个 fs grant 列表最多 {MAX_GRANT_GLOBS} 项"),
|
||||
});
|
||||
}
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
let mut validated = Grants::default();
|
||||
for glob in &grants.read {
|
||||
validate_glob(glob)?;
|
||||
if seen.insert(glob.clone()) {
|
||||
validated.allow_read.push(glob.clone());
|
||||
}
|
||||
}
|
||||
let mut seen_write = std::collections::BTreeSet::new();
|
||||
for glob in &grants.write {
|
||||
validate_glob(glob)?;
|
||||
if seen_write.insert(glob.clone()) {
|
||||
validated.allow_write.push(glob.clone());
|
||||
}
|
||||
}
|
||||
Ok((RunMode::Project, validated))
|
||||
}
|
||||
"strict" => Err(ViewError::RunDenied {
|
||||
detail: "strict 模式不在 View 首版提供;请改用 pure/project 或直接在终端运行 CLI"
|
||||
.to_string(),
|
||||
}),
|
||||
other => Err(ViewError::RunDenied {
|
||||
detail: format!(
|
||||
"模式 {other:?} 不在首版支持范围;仅允许 pure 或受控 project(fs read/write)"
|
||||
),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_glob(glob: &str) -> ViewResult<()> {
|
||||
if glob.is_empty() || glob.chars().count() > MAX_GRANT_CHARS {
|
||||
return Err(ViewError::RunInvalid {
|
||||
detail: format!("fs grant glob 必须为 1..={MAX_GRANT_CHARS} 字符"),
|
||||
});
|
||||
}
|
||||
if glob.starts_with('/')
|
||||
|| glob.starts_with('\\')
|
||||
|| glob.starts_with('~')
|
||||
|| glob.contains('\\')
|
||||
|| glob.contains('\0')
|
||||
|| glob.chars().any(|ch| ch.is_control())
|
||||
|| glob.split('/').any(|segment| segment == "..")
|
||||
|| glob.contains(':')
|
||||
{
|
||||
return Err(ViewError::RunInvalid {
|
||||
detail: format!(
|
||||
"fs grant {glob:?} 必须是项目根相对 glob(禁止绝对路径、..、反斜杠、盘符/控制字符)"
|
||||
),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Resolve `main` exactly like the frozen CLI does for `run`: canonical name
|
||||
/// first, then a unique local name. No fallback to any other function.
|
||||
fn resolve_main(projection: &SemanticProjection) -> Option<(String, String)> {
|
||||
if let Some(function) = projection.functions.iter().find(|function| {
|
||||
canonical_name(&function.id, &projection.module_id) == "main"
|
||||
|| function.local_name == "main"
|
||||
}) {
|
||||
return Some((
|
||||
canonical_name(&function.id, &projection.module_id),
|
||||
function.local_name.clone(),
|
||||
));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn unique_local_name(projection: &SemanticProjection, local_name: &str, id: &str) -> bool {
|
||||
let matches = projection
|
||||
.functions
|
||||
.iter()
|
||||
.filter(|function| function.local_name == local_name)
|
||||
.count();
|
||||
if matches == 1 {
|
||||
return true;
|
||||
}
|
||||
// If several namespaces define the same local name, only the canonical
|
||||
// qualified name is unambiguous; the CLI resolver has the same rule.
|
||||
let canonical = canonical_name(id, &projection.module_id);
|
||||
canonical == local_name
|
||||
}
|
||||
|
||||
/// Analysis v2 function ids are `<module id>::<canonical name>`.
|
||||
pub fn canonical_name(function_id: &str, module_id: &str) -> String {
|
||||
function_id
|
||||
.strip_prefix(&format!("{module_id}::"))
|
||||
.unwrap_or(function_id)
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn validate_parameters(
|
||||
parameters: &[ParameterInput],
|
||||
projection: &SemanticProjection,
|
||||
function_id: &str,
|
||||
) -> ViewResult<()> {
|
||||
let function = projection
|
||||
.functions
|
||||
.iter()
|
||||
.find(|function| function.id == function_id)
|
||||
.ok_or_else(|| ViewError::RunInvalid {
|
||||
detail: "函数在选择后消失,请刷新页面重新选择".to_string(),
|
||||
})?;
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
for parameter in parameters {
|
||||
if !function
|
||||
.signature
|
||||
.params
|
||||
.iter()
|
||||
.any(|param| param.name == parameter.name)
|
||||
{
|
||||
return Err(ViewError::RunInvalid {
|
||||
detail: format!(
|
||||
"参数 {:?} 不在函数 {} 的签名中",
|
||||
parameter.name, function.local_name
|
||||
),
|
||||
});
|
||||
}
|
||||
if !seen.insert(parameter.name.clone()) {
|
||||
return Err(ViewError::RunInvalid {
|
||||
detail: format!("参数 {:?} 重复提交", parameter.name),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stable digest of the exact request bytes, used for `client_request_id`
|
||||
/// idempotency (same id + same bytes => same run; different bytes => 409).
|
||||
pub fn payload_digest(bytes: &[u8]) -> String {
|
||||
crate::reader::source::sha256_hex(bytes)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn projection() -> SemanticProjection {
|
||||
let source = "x".repeat(200);
|
||||
let digest = crate::reader::source::sha256_hex(source.as_bytes());
|
||||
let analysis = serde_json::json!({
|
||||
"schema": "marqdo.analysis",
|
||||
"schema_version": 2,
|
||||
"producer": {"name": "marqdo", "version": "3.0.0-beta.1", "markdown_profile": "marqdo.md.v1"},
|
||||
"project": {"root_id": "root:t@0.1.0", "identity_kind": "manifest", "lock_digest": "", "stdlib": null},
|
||||
"modules": [{
|
||||
"id": "root:t@0.1.0::index.mq.md",
|
||||
"package_instance_id": "root:t@0.1.0",
|
||||
"relative_path": "index.mq.md",
|
||||
"source_digest": digest,
|
||||
"units": [],
|
||||
"functions": [
|
||||
{"id": "root:t@0.1.0::index.mq.md::main", "unit_id": "u1", "local_name": "main",
|
||||
"namespace": null, "span": {"start": 0, "end": 10}, "heading_span": {"start": 0, "end": 10},
|
||||
"signature": {"kind": "inferred", "params": []}, "body": [], "effects": ["unknown"]},
|
||||
{"id": "root:t@0.1.0::index.mq.md::N.f", "unit_id": "u2", "local_name": "f",
|
||||
"namespace": "N", "span": {"start": 20, "end": 30}, "heading_span": {"start": 20, "end": 30},
|
||||
"signature": {"kind": "explicit", "params": [
|
||||
{"name": "n", "required": true, "type": "Int", "default": null, "span": null}
|
||||
]}, "body": [], "effects": ["unknown"]}
|
||||
],
|
||||
"imports": [], "references": [], "calls": [], "resources": []
|
||||
}],
|
||||
"diagnostics": []
|
||||
})
|
||||
.to_string();
|
||||
let source = "x".repeat(200);
|
||||
let index = crate::reader::source::SourceIndex::new(&source);
|
||||
crate::protocol::analysis_v2::verify_analysis(
|
||||
analysis.to_string().as_bytes(),
|
||||
&source,
|
||||
&index,
|
||||
"index.mq.md",
|
||||
)
|
||||
.map(|verified| verified.projection)
|
||||
.unwrap_or_else(|err| panic!("fixture analysis must verify: {err}"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_unknown_fields_and_bad_modes() {
|
||||
let base = serde_json::json!({
|
||||
"document": "index.mq.md",
|
||||
"target": {"kind": "entry"},
|
||||
"analysis_digest": format!("sha256:{}", "a".repeat(64)),
|
||||
"mode": "pure",
|
||||
"client_request_id": "req-1"
|
||||
});
|
||||
let mut with_unknown = base.clone();
|
||||
with_unknown["cwd"] = serde_json::json!("/tmp");
|
||||
assert!(validate_request(with_unknown.to_string().as_bytes()).is_err());
|
||||
let mut strict = base.clone();
|
||||
strict["mode"] = serde_json::json!("strict");
|
||||
assert_eq!(
|
||||
validate_request(strict.to_string().as_bytes())
|
||||
.unwrap_err()
|
||||
.code(),
|
||||
"view.run_denied"
|
||||
);
|
||||
let mut project_without_globs = base;
|
||||
project_without_globs["mode"] = serde_json::json!("project");
|
||||
assert!(validate_request(project_without_globs.to_string().as_bytes()).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_absolute_and_parent_globs() {
|
||||
let request = serde_json::json!({
|
||||
"document": "index.mq.md",
|
||||
"target": {"kind": "entry"},
|
||||
"analysis_digest": format!("sha256:{}", "a".repeat(64)),
|
||||
"mode": "project",
|
||||
"grants": {"read": ["../secret"], "write": []},
|
||||
"client_request_id": "req-1"
|
||||
});
|
||||
assert!(validate_request(request.to_string().as_bytes()).is_err());
|
||||
let request = serde_json::json!({
|
||||
"document": "index.mq.md",
|
||||
"target": {"kind": "entry"},
|
||||
"analysis_digest": format!("sha256:{}", "a".repeat(64)),
|
||||
"mode": "project",
|
||||
"grants": {"read": ["/etc/passwd"], "write": []},
|
||||
"client_request_id": "req-1"
|
||||
});
|
||||
assert!(validate_request(request.to_string().as_bytes()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_names_and_targets_resolve() {
|
||||
let projection = projection();
|
||||
let request = serde_json::json!({
|
||||
"document": "index.mq.md",
|
||||
"target": {"kind": "function", "function_id": "root:t@0.1.0::index.mq.md::N.f"},
|
||||
"parameters": [{"name": "n", "expression": "5"}],
|
||||
"analysis_digest": format!("sha256:{}", projection.analysis_sha256),
|
||||
"mode": "pure",
|
||||
"client_request_id": "req-2"
|
||||
});
|
||||
let validated = validate_request(request.to_string().as_bytes()).expect("valid");
|
||||
let plan = validated.plan_against(&projection).expect("plan");
|
||||
match plan.target {
|
||||
ExecutionTarget::Function { cli_name, .. } => assert_eq!(cli_name, "f"),
|
||||
ExecutionTarget::Entry => panic!("expected function"),
|
||||
}
|
||||
assert_eq!(plan.arguments, vec![("n".to_string(), "5".to_string())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entry_without_main_is_explicitly_rejected() {
|
||||
let mut projection = projection();
|
||||
projection
|
||||
.functions
|
||||
.retain(|function| function.local_name != "main");
|
||||
let request = serde_json::json!({
|
||||
"document": "index.mq.md",
|
||||
"target": {"kind": "entry"},
|
||||
"analysis_digest": format!("sha256:{}", projection.analysis_sha256),
|
||||
"mode": "pure",
|
||||
"client_request_id": "req-3"
|
||||
});
|
||||
let validated = validate_request(request.to_string().as_bytes()).expect("valid");
|
||||
assert_eq!(
|
||||
validated.plan_against(&projection).unwrap_err().code(),
|
||||
"view.no_entry_function"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_parameter_names_are_rejected_before_execution() {
|
||||
let projection = projection();
|
||||
let request = serde_json::json!({
|
||||
"document": "index.mq.md",
|
||||
"target": {"kind": "function", "function_id": "root:t@0.1.0::index.mq.md::N.f"},
|
||||
"parameters": [{"name": "bogus", "expression": "5"}],
|
||||
"analysis_digest": format!("sha256:{}", projection.analysis_sha256),
|
||||
"mode": "pure",
|
||||
"client_request_id": "req-4"
|
||||
});
|
||||
let validated = validate_request(request.to_string().as_bytes()).expect("valid");
|
||||
assert_eq!(
|
||||
validated.plan_against(&projection).unwrap_err().code(),
|
||||
"view.run_invalid"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ pub mod cli;
|
||||
pub mod config;
|
||||
pub mod core_client;
|
||||
pub mod error;
|
||||
pub mod execution;
|
||||
pub mod export;
|
||||
pub mod protocol;
|
||||
pub mod reader;
|
||||
|
||||
+88
-1
@@ -11,7 +11,7 @@ use crate::reader::markdown::{DocumentIdentity, DocumentModel};
|
||||
use crate::reader::model::{
|
||||
Navigation, OutlineEntry, OutlineKind, PresentationModel, SourceStatus,
|
||||
};
|
||||
use crate::reader::source::{Project, SafeRelativePath};
|
||||
use crate::reader::source::{sha256_hex, Project, SafeRelativePath};
|
||||
|
||||
use crate::core_client::{
|
||||
CheckOptions, CheckResponse, CoreClient, RawCheckDiagnostic, RunOptions, SandboxMode,
|
||||
@@ -186,6 +186,10 @@ impl DocumentService {
|
||||
self.core.as_ref()
|
||||
}
|
||||
|
||||
pub fn core_client(&self) -> Option<&CoreClient> {
|
||||
self.core.as_ref()
|
||||
}
|
||||
|
||||
pub fn core_version(&self) -> Option<&str> {
|
||||
self.core_version.as_deref()
|
||||
}
|
||||
@@ -430,3 +434,86 @@ fn diagnostic_to_view(
|
||||
hints: diagnostic.hints.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// One read-only, byte-verified static view of a document, used by explicit
|
||||
/// run validation and Trace binding. Nothing here executes the document.
|
||||
#[derive(Debug)]
|
||||
pub struct StaticDocument {
|
||||
pub relative: SafeRelativePath,
|
||||
pub source: String,
|
||||
pub source_index: crate::reader::source::SourceIndex,
|
||||
pub source_sha256: String,
|
||||
/// Exact bytes written by `marqdo check --emit`.
|
||||
pub analysis_bytes: Vec<u8>,
|
||||
pub analysis_digest: String,
|
||||
pub verified: crate::protocol::analysis_v2::VerifiedAnalysis,
|
||||
}
|
||||
|
||||
impl DocumentService {
|
||||
/// Re-run the read-only `check --emit` and verify Analysis v2 against the
|
||||
/// current exact source bytes. This is the only static truth used before an
|
||||
/// explicit run is accepted.
|
||||
pub fn static_document(&self, relative: &SafeRelativePath) -> ViewResult<StaticDocument> {
|
||||
let client = self.core.as_ref().ok_or_else(|| ViewError::RunDenied {
|
||||
detail: "没有可用的冻结核心(MARQDO_BIN);无法验证运行请求".to_string(),
|
||||
})?;
|
||||
let source_bytes = self.project.read_source(relative)?;
|
||||
let source_sha256 = sha256_hex(&source_bytes);
|
||||
let source = String::from_utf8(source_bytes).map_err(|err| ViewError::Io {
|
||||
detail: format!("{relative} is not valid UTF-8: {err}"),
|
||||
})?;
|
||||
let source_index = crate::reader::source::SourceIndex::new(&source);
|
||||
let response = client.check(
|
||||
&self.project,
|
||||
relative,
|
||||
&CheckOptions {
|
||||
refs: false,
|
||||
timeout: Some(std::time::Duration::from_secs(30)),
|
||||
},
|
||||
)?;
|
||||
let check = match response {
|
||||
CheckResponse {
|
||||
success: true,
|
||||
analysis: Some(check),
|
||||
..
|
||||
} => check,
|
||||
CheckResponse {
|
||||
success: false,
|
||||
diagnostics,
|
||||
exit_code,
|
||||
..
|
||||
} => {
|
||||
let first = diagnostics
|
||||
.first()
|
||||
.map(|diagnostic| format!("{}: {}", diagnostic.code, diagnostic.message))
|
||||
.unwrap_or_else(|| "no diagnostic detail".to_string());
|
||||
return Err(ViewError::AnalysisFailed {
|
||||
detail: format!(
|
||||
"Core 检查失败(exit {exit_code}, {} diagnostic(s));拒绝执行。first: {first}",
|
||||
diagnostics.len()
|
||||
),
|
||||
});
|
||||
}
|
||||
CheckResponse { analysis: None, .. } => {
|
||||
return Err(ViewError::AnalysisFailed {
|
||||
detail: "Core 声称检查成功但没有产出 Analysis".to_string(),
|
||||
});
|
||||
}
|
||||
};
|
||||
let verified = crate::protocol::analysis_v2::verify_analysis(
|
||||
&check.analysis_bytes,
|
||||
&source,
|
||||
&source_index,
|
||||
relative.as_str(),
|
||||
)?;
|
||||
Ok(StaticDocument {
|
||||
relative: relative.clone(),
|
||||
source,
|
||||
source_index,
|
||||
source_sha256,
|
||||
analysis_digest: check.analysis_digest,
|
||||
analysis_bytes: check.analysis_bytes,
|
||||
verified,
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user