feat: stream verified Core execution events over the View SSE channel
This commit is contained in:
1 parent
4cf500fb58
commit
37291137eb
13 files changed
+593
-39
No files matched your search
Generated
+7
@@ -58,6 +58,12 @@ version = "1.1.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16"
|
checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "base64"
|
||||||
|
version = "0.22.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "block-buffer"
|
name = "block-buffer"
|
||||||
version = "0.10.4"
|
version = "0.10.4"
|
||||||
@@ -265,6 +271,7 @@ checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
|
|||||||
name = "marqdo-view"
|
name = "marqdo-view"
|
||||||
version = "0.2.0"
|
version = "0.2.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"base64",
|
||||||
"clap",
|
"clap",
|
||||||
"comrak",
|
"comrak",
|
||||||
"libc",
|
"libc",
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ name = "integration"
|
|||||||
path = "tests/integration/main.rs"
|
path = "tests/integration/main.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
base64 = "0.22"
|
||||||
clap = { version = "4.5", features = ["derive"] }
|
clap = { version = "4.5", features = ["derive"] }
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
|
|||||||
+28
-2
@@ -372,12 +372,13 @@
|
|||||||
case "cancelled": return "已取消";
|
case "cancelled": return "已取消";
|
||||||
case "timed_out": return "超时";
|
case "timed_out": return "超时";
|
||||||
case "unavailable": return "不可用";
|
case "unavailable": return "不可用";
|
||||||
|
case "incomplete": return "事件流不完整";
|
||||||
default: return String(state || "未知");
|
default: return String(state || "未知");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function isTerminalState(state) {
|
function isTerminalState(state) {
|
||||||
return ["succeeded", "failed", "cancelled", "timed_out", "unavailable"].indexOf(state) >= 0;
|
return ["succeeded", "failed", "cancelled", "timed_out", "unavailable", "incomplete"].indexOf(state) >= 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
function runPanel() {
|
function runPanel() {
|
||||||
@@ -650,6 +651,7 @@
|
|||||||
setRunStatus("浏览器不支持 EventSource,无法接收运行状态;请使用现代浏览器。");
|
setRunStatus("浏览器不支持 EventSource,无法接收运行状态;请使用现代浏览器。");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
var decoders = { stdout: new TextDecoder(), stderr: new TextDecoder() };
|
||||||
var source = new EventSource(job.events_url, { withCredentials: true });
|
var source = new EventSource(job.events_url, { withCredentials: true });
|
||||||
activeRun.source = source;
|
activeRun.source = source;
|
||||||
function apply(event) {
|
function apply(event) {
|
||||||
@@ -668,9 +670,13 @@
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
activeRun.lastSeq = data.seq;
|
activeRun.lastSeq = data.seq;
|
||||||
|
if (data.observation) {
|
||||||
|
renderObservation(data.observation, decoders);
|
||||||
|
return;
|
||||||
|
}
|
||||||
updateRunView(data);
|
updateRunView(data);
|
||||||
}
|
}
|
||||||
["run.state", "run.complete", "run.error", "run.snapshot"].forEach(function (kind) {
|
["run.state", "run.complete", "run.error", "run.snapshot", "run.observation"].forEach(function (kind) {
|
||||||
source.addEventListener(kind, apply);
|
source.addEventListener(kind, apply);
|
||||||
});
|
});
|
||||||
source.onerror = function () {
|
source.onerror = function () {
|
||||||
@@ -680,6 +686,26 @@
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function renderObservation(observation, decoders) {
|
||||||
|
var stream = observation.kind === "stdout.chunk" ? "stdout"
|
||||||
|
: observation.kind === "stderr.chunk" ? "stderr" : null;
|
||||||
|
if (stream) {
|
||||||
|
var output = $("#mq-run-" + stream);
|
||||||
|
if (!output) return;
|
||||||
|
var bytes = Uint8Array.from(atob(observation.data_base64), function (value) {
|
||||||
|
return value.charCodeAt(0);
|
||||||
|
});
|
||||||
|
output.append(document.createTextNode(decoders[stream].decode(bytes, { stream: true })));
|
||||||
|
output.hidden = false;
|
||||||
|
} else if (/^(branch|loop|control|call)\./.test(observation.kind)) {
|
||||||
|
var events = $("#mq-run-events");
|
||||||
|
if (events && events.childElementCount < 100) {
|
||||||
|
appendLine(events, "li", "", observation.kind +
|
||||||
|
(observation.decision === undefined ? "" : " · " + observation.decision));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function updateRunView(data) {
|
function updateRunView(data) {
|
||||||
var panel = runPanel();
|
var panel = runPanel();
|
||||||
if (panel) {
|
if (panel) {
|
||||||
|
|||||||
+10
-1
@@ -66,6 +66,7 @@ pub struct CheckOptions {
|
|||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct RunOptions {
|
pub struct RunOptions {
|
||||||
|
pub event_stream: bool,
|
||||||
pub mode: SandboxMode,
|
pub mode: SandboxMode,
|
||||||
pub grants: Grants,
|
pub grants: Grants,
|
||||||
pub fuel: Option<u64>,
|
pub fuel: Option<u64>,
|
||||||
@@ -80,6 +81,7 @@ pub struct RunOptions {
|
|||||||
impl Default for RunOptions {
|
impl Default for RunOptions {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
|
event_stream: false,
|
||||||
mode: SandboxMode::Pure,
|
mode: SandboxMode::Pure,
|
||||||
grants: Grants::default(),
|
grants: Grants::default(),
|
||||||
fuel: None,
|
fuel: None,
|
||||||
@@ -481,7 +483,13 @@ fn append_common_args(args: &mut Vec<OsString>, trace_path: &Path, options: &Run
|
|||||||
}
|
}
|
||||||
args.push(OsString::from("--mode"));
|
args.push(OsString::from("--mode"));
|
||||||
args.push(OsString::from(options.mode.as_str()));
|
args.push(OsString::from(options.mode.as_str()));
|
||||||
args.push(OsString::from("--json"));
|
if options.event_stream {
|
||||||
|
push_pair(args, "--event-stream", "jsonl");
|
||||||
|
push_pair(args, "--observe-max-events", "10000");
|
||||||
|
push_pair(args, "--observe-max-bytes", "4194304");
|
||||||
|
} else {
|
||||||
|
args.push(OsString::from("--json"));
|
||||||
|
}
|
||||||
args.push(OsString::from("--trace-file"));
|
args.push(OsString::from("--trace-file"));
|
||||||
args.push(trace_path.as_os_str().to_os_string());
|
args.push(trace_path.as_os_str().to_os_string());
|
||||||
for glob in &options.grants.allow_read {
|
for glob in &options.grants.allow_read {
|
||||||
@@ -758,6 +766,7 @@ mod tests {
|
|||||||
Path::new("/p/index.mq.md"),
|
Path::new("/p/index.mq.md"),
|
||||||
Path::new("/t/trace.json"),
|
Path::new("/t/trace.json"),
|
||||||
&RunOptions {
|
&RunOptions {
|
||||||
|
event_stream: false,
|
||||||
mode: SandboxMode::Pure,
|
mode: SandboxMode::Pure,
|
||||||
grants: Grants {
|
grants: Grants {
|
||||||
allow_read: vec!["data/**".into()],
|
allow_read: vec!["data/**".into()],
|
||||||
|
|||||||
+126
-11
@@ -8,8 +8,11 @@
|
|||||||
use crate::core_client::{build_call_args, build_run_args, RunOptions, SandboxMode, ScratchDir};
|
use crate::core_client::{build_call_args, build_run_args, RunOptions, SandboxMode, ScratchDir};
|
||||||
use crate::error::{ViewError, ViewResult};
|
use crate::error::{ViewError, ViewResult};
|
||||||
use crate::execution::events::{EventLog, RunEvent, RunState, Subscription};
|
use crate::execution::events::{EventLog, RunEvent, RunState, Subscription};
|
||||||
use crate::execution::process::{run_bounded_with_hook, ProcessBudget, ProcessOutcome};
|
use crate::execution::process::{
|
||||||
|
run_bounded_with_hook, Captured, ProcessBudget, ProcessHooks, ProcessOutcome,
|
||||||
|
};
|
||||||
use crate::execution::request::{self, payload_digest, ExecutionPlan, ExecutionTarget, RunMode};
|
use crate::execution::request::{self, payload_digest, ExecutionPlan, ExecutionTarget, RunMode};
|
||||||
|
use crate::protocol::execution_events_v1 as core_events;
|
||||||
use crate::protocol::trace_v2::{verify_trace, TraceVerificationInput};
|
use crate::protocol::trace_v2::{verify_trace, TraceVerificationInput};
|
||||||
use crate::reader::assemble::{DocumentService, StaticDocument};
|
use crate::reader::assemble::{DocumentService, StaticDocument};
|
||||||
use crate::reader::source::{sha256_hex, sha256_prefixed};
|
use crate::reader::source::{sha256_hex, sha256_prefixed};
|
||||||
@@ -171,6 +174,12 @@ struct ControllerState {
|
|||||||
dedupe: HashMap<String, DedupeEntry>,
|
dedupe: HashMap<String, DedupeEntry>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct CoreRun {
|
||||||
|
process: ProcessOutcome,
|
||||||
|
trace: Option<Vec<u8>>,
|
||||||
|
stream: Option<core_events::Stream>,
|
||||||
|
}
|
||||||
|
|
||||||
pub struct ExecutionController {
|
pub struct ExecutionController {
|
||||||
service: Arc<DocumentService>,
|
service: Arc<DocumentService>,
|
||||||
config: ExecutionConfig,
|
config: ExecutionConfig,
|
||||||
@@ -282,7 +291,7 @@ impl ExecutionController {
|
|||||||
plan: ExecutionPlan,
|
plan: ExecutionPlan,
|
||||||
) {
|
) {
|
||||||
let started = Instant::now();
|
let started = Instant::now();
|
||||||
let outcome = self.run_core(&job, &plan);
|
let outcome = self.run_core(&job, &plan, &static_doc);
|
||||||
let cancel_requested = job.cancel.load(Ordering::SeqCst);
|
let cancel_requested = job.cancel.load(Ordering::SeqCst);
|
||||||
eprintln!(
|
eprintln!(
|
||||||
"JOB_DEBUG id={} run_core elapsed={:?} cancel={cancel_requested}",
|
"JOB_DEBUG id={} run_core elapsed={:?} cancel={cancel_requested}",
|
||||||
@@ -336,7 +345,8 @@ impl ExecutionController {
|
|||||||
&self,
|
&self,
|
||||||
job: &Arc<Job>,
|
job: &Arc<Job>,
|
||||||
plan: &ExecutionPlan,
|
plan: &ExecutionPlan,
|
||||||
) -> Result<(ProcessOutcome, Option<Vec<u8>>), ViewError> {
|
static_doc: &StaticDocument,
|
||||||
|
) -> ViewResult<CoreRun> {
|
||||||
let client = self
|
let client = self
|
||||||
.service
|
.service
|
||||||
.core_client()
|
.core_client()
|
||||||
@@ -346,7 +356,13 @@ impl ExecutionController {
|
|||||||
let entry = self.service.project().absolute_for(&plan.document)?;
|
let entry = self.service.project().absolute_for(&plan.document)?;
|
||||||
let scratch = ScratchDir::create("run")?;
|
let scratch = ScratchDir::create("run")?;
|
||||||
let trace_path = scratch.file("trace.json");
|
let trace_path = scratch.file("trace.json");
|
||||||
let options = self.run_options(plan);
|
let mut options = self.run_options(plan);
|
||||||
|
let projection = &static_doc.verified.projection;
|
||||||
|
options.event_stream =
|
||||||
|
semver::Version::parse(&projection.producer_version).is_ok_and(|version| {
|
||||||
|
version >= semver::Version::new(3, 0, 0)
|
||||||
|
|| version >= semver::Version::parse("3.0.0-rc.2").expect("valid Core version")
|
||||||
|
});
|
||||||
let args = match &plan.target {
|
let args = match &plan.target {
|
||||||
ExecutionTarget::Entry => build_run_args(&entry, &trace_path, &options),
|
ExecutionTarget::Entry => build_run_args(&entry, &trace_path, &options),
|
||||||
ExecutionTarget::Function { cli_name, .. } => {
|
ExecutionTarget::Function { cli_name, .. } => {
|
||||||
@@ -365,20 +381,60 @@ impl ExecutionController {
|
|||||||
wall_clock: self.config.run_timeout,
|
wall_clock: self.config.run_timeout,
|
||||||
..self.config.budget.clone()
|
..self.config.budget.clone()
|
||||||
};
|
};
|
||||||
|
let (send_stream, receive_stream) = std::sync::mpsc::channel();
|
||||||
|
let mut hooks = ProcessHooks {
|
||||||
|
on_spawn: Some(Box::new(hook)),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
if options.event_stream {
|
||||||
|
let entry = match &plan.target {
|
||||||
|
ExecutionTarget::Entry => "main",
|
||||||
|
ExecutionTarget::Function { cli_name, .. } => cli_name,
|
||||||
|
};
|
||||||
|
let binding = core_events::Binding {
|
||||||
|
digest: static_doc.analysis_digest.clone(),
|
||||||
|
root: projection.project_root_id.clone(),
|
||||||
|
entry: format!("{}::{entry}", projection.module_id),
|
||||||
|
function: plan.function_id.clone(),
|
||||||
|
mode: plan.mode.as_str().to_string(),
|
||||||
|
producer: projection.producer_version.clone(),
|
||||||
|
modules: projection
|
||||||
|
.modules
|
||||||
|
.iter()
|
||||||
|
.map(|module| module.id.clone())
|
||||||
|
.collect(),
|
||||||
|
max_output: DEFAULT_MAX_OUTPUT as usize,
|
||||||
|
};
|
||||||
|
let observed_job = Arc::clone(job);
|
||||||
|
hooks.stdout = Some(Box::new(move |stdout| {
|
||||||
|
let stream = core_events::read(stdout, &binding, |observation| {
|
||||||
|
if let Ok(mut inner) = observed_job.inner.lock() {
|
||||||
|
inner.log.publish_observation(observation);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let _ = send_stream.send(stream);
|
||||||
|
Captured::default()
|
||||||
|
}));
|
||||||
|
}
|
||||||
let outcome = run_bounded_with_hook(
|
let outcome = run_bounded_with_hook(
|
||||||
client.bin(),
|
client.bin(),
|
||||||
&args,
|
&args,
|
||||||
self.service.project().root(),
|
self.service.project().root(),
|
||||||
&budget,
|
&budget,
|
||||||
Some(Arc::clone(&job.cancel)),
|
Some(Arc::clone(&job.cancel)),
|
||||||
Box::new(hook),
|
hooks,
|
||||||
)?;
|
)?;
|
||||||
let trace = read_trace_limited(&trace_path)?;
|
let trace = read_trace_limited(&trace_path)?;
|
||||||
Ok((outcome, trace))
|
Ok(CoreRun {
|
||||||
|
process: outcome,
|
||||||
|
trace,
|
||||||
|
stream: receive_stream.try_recv().ok(),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn run_options(&self, plan: &ExecutionPlan) -> RunOptions {
|
fn run_options(&self, plan: &ExecutionPlan) -> RunOptions {
|
||||||
RunOptions {
|
RunOptions {
|
||||||
|
event_stream: false,
|
||||||
mode: match plan.mode {
|
mode: match plan.mode {
|
||||||
RunMode::Pure => SandboxMode::Pure,
|
RunMode::Pure => SandboxMode::Pure,
|
||||||
RunMode::Project => SandboxMode::Project,
|
RunMode::Project => SandboxMode::Project,
|
||||||
@@ -399,7 +455,7 @@ impl ExecutionController {
|
|||||||
plan: &ExecutionPlan,
|
plan: &ExecutionPlan,
|
||||||
static_doc: &StaticDocument,
|
static_doc: &StaticDocument,
|
||||||
started: Instant,
|
started: Instant,
|
||||||
outcome: Result<(ProcessOutcome, Option<Vec<u8>>), ViewError>,
|
outcome: ViewResult<CoreRun>,
|
||||||
cancel_requested: bool,
|
cancel_requested: bool,
|
||||||
) -> (
|
) -> (
|
||||||
RunState,
|
RunState,
|
||||||
@@ -410,7 +466,11 @@ impl ExecutionController {
|
|||||||
Option<String>,
|
Option<String>,
|
||||||
) {
|
) {
|
||||||
let duration_ms = started.elapsed().as_millis() as u64;
|
let duration_ms = started.elapsed().as_millis() as u64;
|
||||||
let (outcome, trace_bytes) = match outcome {
|
let CoreRun {
|
||||||
|
process: outcome,
|
||||||
|
trace: trace_bytes,
|
||||||
|
stream,
|
||||||
|
} = match outcome {
|
||||||
Ok(value) => value,
|
Ok(value) => value,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
let state = match err.code() {
|
let state = match err.code() {
|
||||||
@@ -486,7 +546,40 @@ impl ExecutionController {
|
|||||||
)),
|
)),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
let json: serde_json::Value =
|
let json: serde_json::Value = if let Some(stream) = &stream {
|
||||||
|
let Some(mut terminal) = stream
|
||||||
|
.terminal
|
||||||
|
.clone()
|
||||||
|
.filter(|terminal| terminal["success"].as_bool() == Some(outcome.status_ok()))
|
||||||
|
else {
|
||||||
|
let mut result = base_result(plan, static_doc, duration_ms);
|
||||||
|
result["stdout"] = serde_json::json!(String::from_utf8_lossy(&stream.stdout));
|
||||||
|
result["stderr"] = serde_json::json!(String::from_utf8_lossy(&stream.stderr));
|
||||||
|
result["output_complete"] = serde_json::json!(false);
|
||||||
|
return (
|
||||||
|
RunState::Incomplete,
|
||||||
|
result,
|
||||||
|
None,
|
||||||
|
"unavailable".into(),
|
||||||
|
Some("view.core_protocol".into()),
|
||||||
|
Some(
|
||||||
|
if stream.invalid {
|
||||||
|
"CLI 事件流无效"
|
||||||
|
} else {
|
||||||
|
"CLI 事件流缺少可信终态"
|
||||||
|
}
|
||||||
|
.into(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
terminal["command"] = serde_json::json!(match plan.target {
|
||||||
|
ExecutionTarget::Entry => "run",
|
||||||
|
ExecutionTarget::Function { .. } => "call",
|
||||||
|
});
|
||||||
|
terminal["stdout"] = serde_json::json!(String::from_utf8_lossy(&stream.stdout));
|
||||||
|
terminal["stderr"] = serde_json::json!(String::from_utf8_lossy(&stream.stderr));
|
||||||
|
terminal
|
||||||
|
} else {
|
||||||
match serde_json::from_slice::<serde_json::Value>(&outcome.stdout.bytes) {
|
match serde_json::from_slice::<serde_json::Value>(&outcome.stdout.bytes) {
|
||||||
Ok(value) if value.is_object() => value,
|
Ok(value) if value.is_object() => value,
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
@@ -512,7 +605,8 @@ impl ExecutionController {
|
|||||||
)),
|
)),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
};
|
||||||
|
|
||||||
// Re-read the source after the run: a changed source makes the result
|
// Re-read the source after the run: a changed source makes the result
|
||||||
// stale and forbids anchoring events to the current text.
|
// stale and forbids anchoring events to the current text.
|
||||||
@@ -523,7 +617,7 @@ impl ExecutionController {
|
|||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
let stale = sha256_hex(¤t_source) != static_doc.source_sha256;
|
let stale = sha256_hex(¤t_source) != static_doc.source_sha256;
|
||||||
|
|
||||||
let (trace, trace_status) = build_trace_summary(
|
let (mut trace, mut trace_status) = build_trace_summary(
|
||||||
trace_bytes.as_deref(),
|
trace_bytes.as_deref(),
|
||||||
static_doc,
|
static_doc,
|
||||||
&json,
|
&json,
|
||||||
@@ -532,6 +626,26 @@ impl ExecutionController {
|
|||||||
);
|
);
|
||||||
let mut result = build_cli_result(plan, static_doc, duration_ms, &json, &outcome);
|
let mut result = build_cli_result(plan, static_doc, duration_ms, &json, &outcome);
|
||||||
result["stale"] = serde_json::json!(stale);
|
result["stale"] = serde_json::json!(stale);
|
||||||
|
if let Some(stream) = stream {
|
||||||
|
result["event_protocol"] = serde_json::json!(1);
|
||||||
|
result["core_run_id"] = serde_json::json!(stream.id);
|
||||||
|
result["source_verified"] = serde_json::json!(stream.verified && !stale);
|
||||||
|
result["observation_truncated"] = serde_json::json!(stream.truncated);
|
||||||
|
result["stdout_bytes"] = serde_json::json!(stream.stdout.len());
|
||||||
|
result["stderr_bytes"] = serde_json::json!(stream.stderr.len());
|
||||||
|
result["output_complete"] = serde_json::json!(!json["error"]["code"]
|
||||||
|
.as_str()
|
||||||
|
.is_some_and(|code| code.contains("output_limit")));
|
||||||
|
if trace_status == "verified"
|
||||||
|
&& trace
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|trace| trace["core_run_id"].as_str())
|
||||||
|
!= Some(&stream.id)
|
||||||
|
{
|
||||||
|
trace = None;
|
||||||
|
trace_status = "invalid".into();
|
||||||
|
}
|
||||||
|
}
|
||||||
let success = json
|
let success = json
|
||||||
.get("success")
|
.get("success")
|
||||||
.and_then(serde_json::Value::as_bool)
|
.and_then(serde_json::Value::as_bool)
|
||||||
@@ -692,6 +806,7 @@ fn base_result(
|
|||||||
) -> serde_json::Value {
|
) -> serde_json::Value {
|
||||||
serde_json::json!({
|
serde_json::json!({
|
||||||
"document": plan.document.as_str(),
|
"document": plan.document.as_str(),
|
||||||
|
"function_id": plan.function_id,
|
||||||
"target": match &plan.target {
|
"target": match &plan.target {
|
||||||
ExecutionTarget::Entry => serde_json::json!({"kind": "entry"}),
|
ExecutionTarget::Entry => serde_json::json!({"kind": "entry"}),
|
||||||
ExecutionTarget::Function { cli_name, label } => serde_json::json!({
|
ExecutionTarget::Function { cli_name, label } => serde_json::json!({
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ pub enum RunState {
|
|||||||
Cancelled,
|
Cancelled,
|
||||||
TimedOut,
|
TimedOut,
|
||||||
Unavailable,
|
Unavailable,
|
||||||
|
Incomplete,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RunState {
|
impl RunState {
|
||||||
@@ -39,6 +40,7 @@ impl RunState {
|
|||||||
RunState::Cancelled => "cancelled",
|
RunState::Cancelled => "cancelled",
|
||||||
RunState::TimedOut => "timed_out",
|
RunState::TimedOut => "timed_out",
|
||||||
RunState::Unavailable => "unavailable",
|
RunState::Unavailable => "unavailable",
|
||||||
|
RunState::Incomplete => "incomplete",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -52,6 +54,7 @@ impl RunState {
|
|||||||
RunState::Cancelled => "已取消",
|
RunState::Cancelled => "已取消",
|
||||||
RunState::TimedOut => "超时",
|
RunState::TimedOut => "超时",
|
||||||
RunState::Unavailable => "不可用",
|
RunState::Unavailable => "不可用",
|
||||||
|
RunState::Incomplete => "事件流不完整",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -63,6 +66,7 @@ impl RunState {
|
|||||||
| RunState::Cancelled
|
| RunState::Cancelled
|
||||||
| RunState::TimedOut
|
| RunState::TimedOut
|
||||||
| RunState::Unavailable
|
| RunState::Unavailable
|
||||||
|
| RunState::Incomplete
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -73,6 +77,7 @@ pub enum EventKind {
|
|||||||
Complete,
|
Complete,
|
||||||
Error,
|
Error,
|
||||||
Snapshot,
|
Snapshot,
|
||||||
|
Observation,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EventKind {
|
impl EventKind {
|
||||||
@@ -82,6 +87,7 @@ impl EventKind {
|
|||||||
EventKind::Complete => "run.complete",
|
EventKind::Complete => "run.complete",
|
||||||
EventKind::Error => "run.error",
|
EventKind::Error => "run.error",
|
||||||
EventKind::Snapshot => "run.snapshot",
|
EventKind::Snapshot => "run.snapshot",
|
||||||
|
EventKind::Observation => "run.observation",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -98,6 +104,7 @@ pub struct RunEvent {
|
|||||||
pub trace: Option<serde_json::Value>,
|
pub trace: Option<serde_json::Value>,
|
||||||
/// `{code, message}` for terminal failures.
|
/// `{code, message}` for terminal failures.
|
||||||
pub error: Option<serde_json::Value>,
|
pub error: Option<serde_json::Value>,
|
||||||
|
pub observation: Option<serde_json::Value>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RunEvent {
|
impl RunEvent {
|
||||||
@@ -119,6 +126,9 @@ impl RunEvent {
|
|||||||
if let Some(error) = &self.error {
|
if let Some(error) = &self.error {
|
||||||
data["error"] = error.clone();
|
data["error"] = error.clone();
|
||||||
}
|
}
|
||||||
|
if let Some(observation) = &self.observation {
|
||||||
|
data["observation"] = observation.clone();
|
||||||
|
}
|
||||||
data
|
data
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -180,6 +190,7 @@ impl EventLog {
|
|||||||
result: None,
|
result: None,
|
||||||
trace: None,
|
trace: None,
|
||||||
error: None,
|
error: None,
|
||||||
|
observation: None,
|
||||||
};
|
};
|
||||||
self.next_seq += 1;
|
self.next_seq += 1;
|
||||||
self.last_state = state;
|
self.last_state = state;
|
||||||
@@ -213,6 +224,12 @@ impl EventLog {
|
|||||||
self.record(event)
|
self.record(event)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn publish_observation(&mut self, observation: serde_json::Value) {
|
||||||
|
let mut event = self.next_event(EventKind::Observation, self.last_state);
|
||||||
|
event.observation = Some(observation);
|
||||||
|
self.record(event);
|
||||||
|
}
|
||||||
|
|
||||||
pub fn publish_complete(
|
pub fn publish_complete(
|
||||||
&mut self,
|
&mut self,
|
||||||
result: serde_json::Value,
|
result: serde_json::Value,
|
||||||
@@ -276,6 +293,7 @@ impl EventLog {
|
|||||||
result: None,
|
result: None,
|
||||||
trace: None,
|
trace: None,
|
||||||
error: None,
|
error: None,
|
||||||
|
observation: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -85,7 +85,15 @@ pub fn run_bounded(
|
|||||||
budget: &ProcessBudget,
|
budget: &ProcessBudget,
|
||||||
cancel: Option<Arc<AtomicBool>>,
|
cancel: Option<Arc<AtomicBool>>,
|
||||||
) -> ViewResult<ProcessOutcome> {
|
) -> ViewResult<ProcessOutcome> {
|
||||||
run_bounded_with_hook(bin, args, cwd, budget, cancel, Box::new(|| {}))
|
run_bounded_with_hook(bin, args, cwd, budget, cancel, ProcessHooks::default())
|
||||||
|
}
|
||||||
|
|
||||||
|
type StdoutReader = Box<dyn FnOnce(std::process::ChildStdout) -> Captured + Send>;
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct ProcessHooks {
|
||||||
|
pub on_spawn: Option<Box<dyn FnOnce() + Send>>,
|
||||||
|
pub stdout: Option<StdoutReader>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Same as [`run_bounded`], with a hook invoked exactly once **after** the
|
/// Same as [`run_bounded`], with a hook invoked exactly once **after** the
|
||||||
@@ -96,7 +104,7 @@ pub fn run_bounded_with_hook(
|
|||||||
cwd: &Path,
|
cwd: &Path,
|
||||||
budget: &ProcessBudget,
|
budget: &ProcessBudget,
|
||||||
cancel: Option<Arc<AtomicBool>>,
|
cancel: Option<Arc<AtomicBool>>,
|
||||||
on_spawn: Box<dyn FnOnce() + Send>,
|
hooks: ProcessHooks,
|
||||||
) -> ViewResult<ProcessOutcome> {
|
) -> ViewResult<ProcessOutcome> {
|
||||||
let started = Instant::now();
|
let started = Instant::now();
|
||||||
let mut command = Command::new(bin);
|
let mut command = Command::new(bin);
|
||||||
@@ -122,12 +130,17 @@ pub fn run_bounded_with_hook(
|
|||||||
let mut child = command.spawn().map_err(|err| ViewError::CoreSpawn {
|
let mut child = command.spawn().map_err(|err| ViewError::CoreSpawn {
|
||||||
detail: format!("spawn {}: {err}", bin.display()),
|
detail: format!("spawn {}: {err}", bin.display()),
|
||||||
})?;
|
})?;
|
||||||
on_spawn();
|
if let Some(on_spawn) = hooks.on_spawn {
|
||||||
|
on_spawn();
|
||||||
|
}
|
||||||
let stdout = child.stdout.take().expect("piped stdout");
|
let stdout = child.stdout.take().expect("piped stdout");
|
||||||
let stderr = child.stderr.take().expect("piped stderr");
|
let stderr = child.stderr.take().expect("piped stderr");
|
||||||
let stdout_cap = budget.max_stdout;
|
let stdout_cap = budget.max_stdout;
|
||||||
let stderr_cap = budget.max_stderr;
|
let stderr_cap = budget.max_stderr;
|
||||||
let stdout_thread = std::thread::spawn(move || read_bounded(stdout, stdout_cap));
|
let stdout_thread = std::thread::spawn(move || match hooks.stdout {
|
||||||
|
Some(read_stdout) => read_stdout(stdout),
|
||||||
|
None => read_bounded(stdout, stdout_cap),
|
||||||
|
});
|
||||||
let stderr_thread = std::thread::spawn(move || read_bounded(stderr, stderr_cap));
|
let stderr_thread = std::thread::spawn(move || read_bounded(stderr, stderr_cap));
|
||||||
|
|
||||||
let deadline = started + budget.wall_clock;
|
let deadline = started + budget.wall_clock;
|
||||||
|
|||||||
+26
-17
@@ -111,6 +111,7 @@ pub enum ExecutionTarget {
|
|||||||
pub struct ExecutionPlan {
|
pub struct ExecutionPlan {
|
||||||
pub document: SafeRelativePath,
|
pub document: SafeRelativePath,
|
||||||
pub target: ExecutionTarget,
|
pub target: ExecutionTarget,
|
||||||
|
pub function_id: String,
|
||||||
pub arguments: Vec<(String, String)>,
|
pub arguments: Vec<(String, String)>,
|
||||||
pub mode: RunMode,
|
pub mode: RunMode,
|
||||||
pub grants: Grants,
|
pub grants: Grants,
|
||||||
@@ -122,17 +123,17 @@ impl ValidatedRequest {
|
|||||||
/// Resolve the target and parameter names against the verified entry-module
|
/// Resolve the target and parameter names against the verified entry-module
|
||||||
/// Analysis. Never accepts a dependency-module function id (RFC §6.3).
|
/// Analysis. Never accepts a dependency-module function id (RFC §6.3).
|
||||||
pub fn plan_against(self, projection: &SemanticProjection) -> ViewResult<ExecutionPlan> {
|
pub fn plan_against(self, projection: &SemanticProjection) -> ViewResult<ExecutionPlan> {
|
||||||
let target = match &self.target {
|
let (target, function_id) = match &self.target {
|
||||||
RunTarget::Entry => {
|
RunTarget::Entry => {
|
||||||
if resolve_main(projection).is_none() {
|
let Some(function) = resolve_main(projection) else {
|
||||||
return Err(ViewError::NoEntryFunction {
|
return Err(ViewError::NoEntryFunction {
|
||||||
detail: format!(
|
detail: format!(
|
||||||
"{} 没有可调用的 main;请从函数面板选择一个 H2 Exec 函数",
|
"{} 没有可调用的 main;请从函数面板选择一个 H2 Exec 函数",
|
||||||
self.document
|
self.document
|
||||||
),
|
),
|
||||||
});
|
});
|
||||||
}
|
};
|
||||||
ExecutionTarget::Entry
|
(ExecutionTarget::Entry, function.id.clone())
|
||||||
}
|
}
|
||||||
RunTarget::Function { function_id } => {
|
RunTarget::Function { function_id } => {
|
||||||
let function = projection
|
let function = projection
|
||||||
@@ -153,12 +154,16 @@ impl ValidatedRequest {
|
|||||||
};
|
};
|
||||||
let label = canonical;
|
let label = canonical;
|
||||||
validate_parameters(&self.parameters, projection, &function.id)?;
|
validate_parameters(&self.parameters, projection, &function.id)?;
|
||||||
ExecutionTarget::Function { cli_name, label }
|
(
|
||||||
|
ExecutionTarget::Function { cli_name, label },
|
||||||
|
function.id.clone(),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
Ok(ExecutionPlan {
|
Ok(ExecutionPlan {
|
||||||
document: self.document,
|
document: self.document,
|
||||||
target,
|
target,
|
||||||
|
function_id,
|
||||||
arguments: self
|
arguments: self
|
||||||
.parameters
|
.parameters
|
||||||
.into_iter()
|
.into_iter()
|
||||||
@@ -201,7 +206,7 @@ pub fn validate_request(body: &[u8]) -> ViewResult<ValidatedRequest> {
|
|||||||
|| function_id.chars().any(|ch| ch.is_control() || ch == '\0')
|
|| function_id.chars().any(|ch| ch.is_control() || ch == '\0')
|
||||||
{
|
{
|
||||||
return Err(ViewError::RunInvalid {
|
return Err(ViewError::RunInvalid {
|
||||||
detail: "function_id 必须来自 Analysis v2 且长度为 1..=512".to_string(),
|
detail: "function_id 必须来自 Analysis 且长度为 1..=512".to_string(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -364,17 +369,21 @@ fn validate_glob(glob: &str) -> ViewResult<()> {
|
|||||||
|
|
||||||
/// Resolve `main` exactly like the frozen CLI does for `run`: canonical name
|
/// Resolve `main` exactly like the frozen CLI does for `run`: canonical name
|
||||||
/// first, then a unique local name. No fallback to any other function.
|
/// first, then a unique local name. No fallback to any other function.
|
||||||
fn resolve_main(projection: &SemanticProjection) -> Option<(String, String)> {
|
fn resolve_main(
|
||||||
if let Some(function) = projection.functions.iter().find(|function| {
|
projection: &SemanticProjection,
|
||||||
canonical_name(&function.id, &projection.module_id) == "main"
|
) -> Option<&crate::protocol::analysis_v2::SemanticFunction> {
|
||||||
|| function.local_name == "main"
|
projection
|
||||||
}) {
|
.functions
|
||||||
return Some((
|
.iter()
|
||||||
canonical_name(&function.id, &projection.module_id),
|
.find(|function| canonical_name(&function.id, &projection.module_id) == "main")
|
||||||
function.local_name.clone(),
|
.or_else(|| {
|
||||||
));
|
let mut candidates = projection
|
||||||
}
|
.functions
|
||||||
None
|
.iter()
|
||||||
|
.filter(|function| function.local_name == "main");
|
||||||
|
let first = candidates.next()?;
|
||||||
|
candidates.next().is_none().then_some(first)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn unique_local_name(projection: &SemanticProjection, local_name: &str, id: &str) -> bool {
|
fn unique_local_name(projection: &SemanticProjection, local_name: &str, id: &str) -> bool {
|
||||||
|
|||||||
@@ -0,0 +1,355 @@
|
|||||||
|
//! Decode the CLI's bounded, source-bound NDJSON stream. The browser only
|
||||||
|
//! receives projections selected by this decoder.
|
||||||
|
|
||||||
|
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||||
|
use serde::Deserialize;
|
||||||
|
use serde_json::{json, Value};
|
||||||
|
use std::io::{BufRead, BufReader, Read};
|
||||||
|
|
||||||
|
const SCHEMA: &str = "marqdo.execution-events";
|
||||||
|
const MAX_LINE: usize = 4 * 1024 * 1024;
|
||||||
|
const MAX_CHUNK: usize = 64 * 1024;
|
||||||
|
const MAX_TRANSPORT: usize = 16 * 1024 * 1024;
|
||||||
|
|
||||||
|
pub struct Binding {
|
||||||
|
pub digest: String,
|
||||||
|
pub root: String,
|
||||||
|
pub entry: String,
|
||||||
|
pub function: String,
|
||||||
|
pub mode: String,
|
||||||
|
pub producer: String,
|
||||||
|
pub modules: Vec<String>,
|
||||||
|
pub max_output: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct Stream {
|
||||||
|
pub id: String,
|
||||||
|
pub verified: bool,
|
||||||
|
pub truncated: bool,
|
||||||
|
pub stdout: Vec<u8>,
|
||||||
|
pub stderr: Vec<u8>,
|
||||||
|
pub terminal: Option<Value>,
|
||||||
|
pub invalid: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct Event {
|
||||||
|
schema: String,
|
||||||
|
schema_version: u32,
|
||||||
|
run_id: String,
|
||||||
|
seq: u64,
|
||||||
|
kind: String,
|
||||||
|
payload: serde_json::Map<String, Value>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn read(input: impl Read, binding: &Binding, mut publish: impl FnMut(Value)) -> Stream {
|
||||||
|
let mut input = BufReader::new(input);
|
||||||
|
let mut stream = Stream::default();
|
||||||
|
let mut line = Vec::new();
|
||||||
|
let mut total = 0;
|
||||||
|
let mut seq = 0;
|
||||||
|
let mut entry_frame_seen = false;
|
||||||
|
loop {
|
||||||
|
line.clear();
|
||||||
|
let size = match input
|
||||||
|
.by_ref()
|
||||||
|
.take(MAX_LINE as u64 + 1)
|
||||||
|
.read_until(b'\n', &mut line)
|
||||||
|
{
|
||||||
|
Ok(0) => break,
|
||||||
|
Ok(size) => size,
|
||||||
|
Err(_) => {
|
||||||
|
stream.invalid = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
total += size;
|
||||||
|
if total > MAX_TRANSPORT || size > MAX_LINE {
|
||||||
|
stream.invalid = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if line.last() != Some(&b'\n') {
|
||||||
|
stream.invalid = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let Ok(event) = serde_json::from_slice::<Event>(&line) else {
|
||||||
|
stream.invalid = true;
|
||||||
|
break;
|
||||||
|
};
|
||||||
|
match consume(&mut stream, binding, event, seq, &mut entry_frame_seen) {
|
||||||
|
Ok(Some(projection)) => publish(projection),
|
||||||
|
Ok(None) => {}
|
||||||
|
Err(()) => {
|
||||||
|
stream.invalid = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
seq += 1;
|
||||||
|
}
|
||||||
|
if stream.invalid {
|
||||||
|
// Drain without keeping bytes so a malformed child cannot block on its pipe.
|
||||||
|
let _ = std::io::copy(&mut input, &mut std::io::sink());
|
||||||
|
stream.terminal = None;
|
||||||
|
}
|
||||||
|
stream
|
||||||
|
}
|
||||||
|
|
||||||
|
fn consume(
|
||||||
|
stream: &mut Stream,
|
||||||
|
binding: &Binding,
|
||||||
|
event: Event,
|
||||||
|
seq: u64,
|
||||||
|
entry_frame_seen: &mut bool,
|
||||||
|
) -> Result<Option<Value>, ()> {
|
||||||
|
if event.schema != SCHEMA
|
||||||
|
|| event.schema_version != 1
|
||||||
|
|| event.seq != seq
|
||||||
|
|| event.run_id.is_empty()
|
||||||
|
|| event.run_id.len() > 128
|
||||||
|
|| stream.terminal.is_some()
|
||||||
|
{
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
let payload = &event.payload;
|
||||||
|
let kind = event.kind.as_str();
|
||||||
|
if seq == 0 {
|
||||||
|
if kind != "stream.opened"
|
||||||
|
|| payload.get("protocol") != Some(&json!({"name": SCHEMA, "schema_version": 1}))
|
||||||
|
|| payload
|
||||||
|
.get("producer")
|
||||||
|
.and_then(|value| value["name"].as_str())
|
||||||
|
!= Some("marqdo")
|
||||||
|
|| payload
|
||||||
|
.get("producer")
|
||||||
|
.and_then(|value| value["version"].as_str())
|
||||||
|
!= Some(&binding.producer)
|
||||||
|
|| !payload.get("limits").is_some_and(Value::is_object)
|
||||||
|
|| !payload.get("observation").is_some_and(Value::is_object)
|
||||||
|
{
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
stream.id = event.run_id;
|
||||||
|
return Ok(Some(json!({"seq": seq, "kind": kind})));
|
||||||
|
}
|
||||||
|
if stream.id != event.run_id {
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
let mut projection = json!({"seq": seq, "kind": kind});
|
||||||
|
if seq == 1 {
|
||||||
|
match kind {
|
||||||
|
"run.rejected" => {
|
||||||
|
if text(payload, "status") != Some("rejected") || text(payload, "phase").is_none() {
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
stream.terminal = Some(failure(payload)?);
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
"run.started" => {
|
||||||
|
let source = payload.get("source").ok_or(())?;
|
||||||
|
if source["analysis_digest"].as_str() != Some(&binding.digest)
|
||||||
|
|| source["root_id"].as_str() != Some(&binding.root)
|
||||||
|
|| text(payload, "entry") != Some(&binding.entry)
|
||||||
|
|| text(payload, "mode") != Some(&binding.mode)
|
||||||
|
{
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
stream.verified = true;
|
||||||
|
return Ok(Some(projection));
|
||||||
|
}
|
||||||
|
_ => return Err(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
match kind {
|
||||||
|
"stream.opened" | "run.started" | "run.rejected" => return Err(()),
|
||||||
|
"stdout.chunk" | "stderr.chunk" => {
|
||||||
|
let data = text(payload, "data_base64").ok_or(())?;
|
||||||
|
if text(payload, "encoding") != Some("base64") || data.len() > MAX_CHUNK.div_ceil(3) * 4
|
||||||
|
{
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
let bytes = STANDARD.decode(data).map_err(|_| ())?;
|
||||||
|
if bytes.len() > MAX_CHUNK
|
||||||
|
|| payload.get("byte_count").and_then(Value::as_u64) != Some(bytes.len() as u64)
|
||||||
|
{
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
if stream.stdout.len() + stream.stderr.len() + bytes.len() > binding.max_output {
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
if kind == "stdout.chunk" {
|
||||||
|
stream.stdout.extend_from_slice(&bytes);
|
||||||
|
} else {
|
||||||
|
stream.stderr.extend_from_slice(&bytes);
|
||||||
|
}
|
||||||
|
projection["data_base64"] = json!(data);
|
||||||
|
}
|
||||||
|
"run.completed" => {
|
||||||
|
let value = payload
|
||||||
|
.get("value")
|
||||||
|
.filter(|value| value["type"].is_string())
|
||||||
|
.ok_or(())?;
|
||||||
|
if text(payload, "status") != Some("ok") || (!*entry_frame_seen && !stream.truncated) {
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
stream.terminal = Some(json!({"success": true, "value": value}));
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
"run.failed" => {
|
||||||
|
if text(payload, "status") != Some("error") {
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
stream.terminal = Some(failure(payload)?);
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
"observation.truncated" => {
|
||||||
|
if stream.truncated
|
||||||
|
|| !matches!(
|
||||||
|
text(payload, "reason"),
|
||||||
|
Some("event_budget" | "byte_budget")
|
||||||
|
)
|
||||||
|
|| payload.get("limit").and_then(Value::as_u64).is_none()
|
||||||
|
|| payload.get("written").and_then(Value::as_u64).is_none()
|
||||||
|
|| !payload
|
||||||
|
.get("dropped")
|
||||||
|
.is_some_and(|value| value.is_null() || value.is_u64())
|
||||||
|
{
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
stream.truncated = true;
|
||||||
|
}
|
||||||
|
"call.enter" | "call.exit" | "return" | "branch.eval" | "loop.iteration"
|
||||||
|
| "control.break" | "control.continue" | "effect" => {
|
||||||
|
let module = text(payload, "module_id").ok_or(())?;
|
||||||
|
let span = payload.get("span").ok_or(())?;
|
||||||
|
let span_ok = span["start"]
|
||||||
|
.as_u64()
|
||||||
|
.zip(span["end"].as_u64())
|
||||||
|
.is_some_and(|(start, end)| start < end);
|
||||||
|
if !binding.modules.iter().any(|known| known == module)
|
||||||
|
|| !(span_ok
|
||||||
|
|| span.is_null() && !matches!(kind, "control.break" | "control.continue"))
|
||||||
|
|| kind != "effect" && text(payload, "frame_id").is_none()
|
||||||
|
{
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
match kind {
|
||||||
|
"call.enter" => {
|
||||||
|
let function = text(payload, "function_id").ok_or(())?;
|
||||||
|
match payload.get("parent_frame_id") {
|
||||||
|
Some(Value::Null) if !*entry_frame_seen && function == binding.function => {
|
||||||
|
*entry_frame_seen = true
|
||||||
|
}
|
||||||
|
Some(Value::String(_)) if *entry_frame_seen => {}
|
||||||
|
_ => return Err(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"call.exit" if text(payload, "status").is_none() => return Err(()),
|
||||||
|
"return" if text(payload, "value_type").is_none() => return Err(()),
|
||||||
|
"branch.eval" => {
|
||||||
|
projection["decision"] =
|
||||||
|
json!(payload.get("result").and_then(Value::as_bool).ok_or(())?)
|
||||||
|
}
|
||||||
|
"loop.iteration" => {
|
||||||
|
let decision = text(payload, "decision")
|
||||||
|
.filter(|decision| matches!(*decision, "continue" | "exit"))
|
||||||
|
.ok_or(())?;
|
||||||
|
projection["decision"] = json!(decision);
|
||||||
|
}
|
||||||
|
"effect"
|
||||||
|
if text(payload, "operation").is_none()
|
||||||
|
|| text(payload, "result_code").is_none() =>
|
||||||
|
{
|
||||||
|
return Err(())
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Values and additive kinds are never emitted as browser observations.
|
||||||
|
_ => return Ok(None),
|
||||||
|
}
|
||||||
|
Ok(Some(projection))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn text<'a>(payload: &'a serde_json::Map<String, Value>, key: &str) -> Option<&'a str> {
|
||||||
|
payload
|
||||||
|
.get(key)?
|
||||||
|
.as_str()
|
||||||
|
.filter(|text| !text.is_empty() && text.len() <= MAX_LINE)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn failure(payload: &serde_json::Map<String, Value>) -> Result<Value, ()> {
|
||||||
|
let error = payload.get("error").ok_or(())?;
|
||||||
|
let code = error["code"].as_str().ok_or(())?;
|
||||||
|
let message = error["message"].as_str().ok_or(())?;
|
||||||
|
Ok(json!({"success": false, "error": {"code": code, "message": message}}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn sample() -> (Binding, Vec<Value>) {
|
||||||
|
let binding = Binding {
|
||||||
|
digest: "sha256:expected".into(),
|
||||||
|
root: "root:p".into(),
|
||||||
|
entry: "root:p::index.mq.md::main".into(),
|
||||||
|
function: "root:p::index.mq.md::main".into(),
|
||||||
|
mode: "pure".into(),
|
||||||
|
producer: "3.0.0-rc.2".into(),
|
||||||
|
modules: vec!["root:p::index.mq.md".into()],
|
||||||
|
max_output: 100,
|
||||||
|
};
|
||||||
|
let event = |seq, kind, payload| {
|
||||||
|
json!({"schema": SCHEMA, "schema_version": 1, "run_id": "r", "seq": seq,
|
||||||
|
"kind": kind, "payload": payload})
|
||||||
|
};
|
||||||
|
let events = vec![
|
||||||
|
event(
|
||||||
|
0,
|
||||||
|
"stream.opened",
|
||||||
|
json!({"protocol": {"name": SCHEMA, "schema_version": 1},
|
||||||
|
"producer": {"name": "marqdo", "version": binding.producer}, "limits": {}, "observation": {}}),
|
||||||
|
),
|
||||||
|
event(
|
||||||
|
1,
|
||||||
|
"run.started",
|
||||||
|
json!({"entry": binding.entry, "mode": binding.mode,
|
||||||
|
"source": {"analysis_digest": binding.digest, "root_id": binding.root}}),
|
||||||
|
),
|
||||||
|
event(
|
||||||
|
2,
|
||||||
|
"stdout.chunk",
|
||||||
|
json!({"data_base64": "NAo=", "encoding": "base64", "byte_count": 2}),
|
||||||
|
),
|
||||||
|
event(
|
||||||
|
3,
|
||||||
|
"run.failed",
|
||||||
|
json!({"status": "error", "error": {"code": "runtime.test", "message": "test"}}),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
(binding, events)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn decode(binding: &Binding, events: &[Value]) -> Stream {
|
||||||
|
let ndjson = events
|
||||||
|
.iter()
|
||||||
|
.map(|value| format!("{value}\n"))
|
||||||
|
.collect::<String>();
|
||||||
|
read(ndjson.as_bytes(), binding, |_| {})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn validates_stream_identity_bytes_and_terminal_boundary() {
|
||||||
|
let (binding, mut events) = sample();
|
||||||
|
let stream = decode(&binding, &events);
|
||||||
|
assert!(stream.verified && !stream.invalid);
|
||||||
|
assert_eq!(stream.stdout, b"4\n");
|
||||||
|
assert!(stream.terminal.is_some());
|
||||||
|
assert!(decode(&binding, &events[..3]).terminal.is_none());
|
||||||
|
events[2]["payload"]["byte_count"] = json!(1);
|
||||||
|
assert!(decode(&binding, &events).invalid);
|
||||||
|
events[1]["payload"]["source"]["analysis_digest"] = json!("wrong");
|
||||||
|
assert!(!decode(&binding, &events).verified);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,5 +4,6 @@
|
|||||||
//! second publisher or implementation of them (RFC-VIEW-0002 §5.3).
|
//! second publisher or implementation of them (RFC-VIEW-0002 §5.3).
|
||||||
|
|
||||||
pub mod analysis_v2;
|
pub mod analysis_v2;
|
||||||
|
pub mod execution_events_v1;
|
||||||
pub mod tool_v1;
|
pub mod tool_v1;
|
||||||
pub mod trace_v2;
|
pub mod trace_v2;
|
||||||
+1
-1
@@ -62,7 +62,7 @@ pub fn serve(service: DocumentService, opts: &RuntimeOpts) -> ViewResult<i32> {
|
|||||||
.unwrap_or(0)
|
.unwrap_or(0)
|
||||||
);
|
);
|
||||||
if let Some(version) = state.service.core_version() {
|
if let Some(version) = state.service.core_version() {
|
||||||
eprintln!("core: marqdo {version} (Analysis v2, Trace v2)");
|
eprintln!("core: marqdo {version} (Analysis v2/v3, Trace v2)");
|
||||||
} else if let Some(note) = state.service.core_note() {
|
} else if let Some(note) = state.service.core_note() {
|
||||||
eprintln!("core: unavailable ({note})");
|
eprintln!("core: unavailable ({note})");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -249,13 +249,13 @@ fn cli_verify_end_to_end_against_fake_core() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn cli_verify_rejects_schema_v3_and_digest_mismatch() {
|
fn cli_verify_rejects_schema_v4_and_digest_mismatch() {
|
||||||
let (project, core) = fixture("verify_negative");
|
let (project, core) = fixture("verify_negative");
|
||||||
let source = std::fs::read(project.path("index.mq.md")).unwrap();
|
let source = std::fs::read(project.path("index.mq.md")).unwrap();
|
||||||
let script = core.script.to_str().unwrap().to_string();
|
let script = core.script.to_str().unwrap().to_string();
|
||||||
let dir = project.dir.to_str().unwrap().to_string();
|
let dir = project.dir.to_str().unwrap().to_string();
|
||||||
|
|
||||||
core.set_analysis(&minimal_analysis("index.mq.md", &sha256_hex(&source), 3));
|
core.set_analysis(&minimal_analysis("index.mq.md", &sha256_hex(&source), 4));
|
||||||
let output = common::run_view(
|
let output = common::run_view(
|
||||||
&["verify", "index.mq.md", "--marqdo-bin", &script],
|
&["verify", "index.mq.md", "--marqdo-bin", &script],
|
||||||
std::path::Path::new(&dir),
|
std::path::Path::new(&dir),
|
||||||
|
|||||||
@@ -58,7 +58,7 @@ fn source_digest_mismatch_degrades_instead_of_misbinding() {
|
|||||||
fn unknown_analysis_schema_is_a_hard_protocol_error() {
|
fn unknown_analysis_schema_is_a_hard_protocol_error() {
|
||||||
let (project, core) = project("state-protocol");
|
let (project, core) = project("state-protocol");
|
||||||
let source = std::fs::read(project.path("index.mq.md")).unwrap();
|
let source = std::fs::read(project.path("index.mq.md")).unwrap();
|
||||||
core.set_analysis(&minimal_analysis("index.mq.md", &sha256_hex(&source), 3));
|
core.set_analysis(&minimal_analysis("index.mq.md", &sha256_hex(&source), 4));
|
||||||
let context = DocumentService::open(&project.dir, Some(&core.script)).unwrap();
|
let context = DocumentService::open(&project.dir, Some(&core.script)).unwrap();
|
||||||
let relative = context.project().entry().relative.clone();
|
let relative = context.project().entry().relative.clone();
|
||||||
let err = context.load(&relative).unwrap_err();
|
let err = context.load(&relative).unwrap_err();
|
||||||
|
|||||||
Reference in new issue
Block a user